コード例 #1
0
ファイル: installer.py プロジェクト: FreeNest/freenest-core
def read_config(config_path):
    """
    Reads a config file and returns a Config instance
    """
    config = Config()
    config.read(config_path)
    return config
コード例 #2
0
    def __init__(self):
        config = Config(__file__)
        self.data = config.get()
        self.app = Tk()

        self.setWindow()
        self.setTaps()
        self.app.mainloop()
コード例 #3
0
ファイル: installer.py プロジェクト: FreeNest/freenest-core
def load_config(args, installermodules):
    """
    Puts the settings user has given via debconf to conf object
    """
    conf = Config()
    for i in args:
	#print(i)
	section, option, value = i.split(";")
	conf.set_value(section, option, value)
    return conf
コード例 #4
0
ファイル: api_data.py プロジェクト: ramawardhanaa/samsi
    def __init__(self):
        self.config = Config()
        self.config_data = self.config.get_config_data()
        self.dht22 = DHT22(self.config_data['DHT22']['pin'])
        self.DS18B20 = DS18B20()
        self.json_data = {}
        self.log = Log()

        self.ds18b20_temp = []
        self.dht22_data = []
コード例 #5
0
ファイル: scale.py プロジェクト: ramawardhanaa/samsi
 def __init__(self):
     self.config = Config()  # config init
     self.config_data = self.config.get_config_data()
     self.hx = HX711(5, 6)  # initialize scale
     self.is_calibrated = self.config_data['SCALE'].getboolean(
         "calibrated")  # check config if scale is calibrated
     self.ratio = 0  # scale ratio for calibration
     self.offset = 0
     self.value = 0
     self.result = 0
     self.data = 0
     if self.is_calibrated:
         self.hx.set_offset(float(self.config_data["SCALE"]['offset']))
         self.config_ratio = self.config_data["SCALE"][
             'ratio']  # get scale ratio of config
         self.hx.set_scale(float(self.config_ratio))
コード例 #6
0
 def __init__(self, buffer, config_path=None):
     self.buffer = buffer
     self.config = Config.setup_main_config(
         os.path.join(config_path, 'yandex.yml'))
     self.result = []
     self._cleaner = None
     self._logger = logging.getLogger('crawler')
コード例 #7
0
class labelTool(QtGui.QMainWindow):
    # Constructor
    def __init__(self):
        # Construct base class
        super(labelTool, self).__init__()

        # Toolbar
        self.toolBars = toolBars(self)
        self.toolBars.prepareToolBar()

        centralWidget = QtGui.QWidget()
        self.setCentralWidget(centralWidget)

        self.paintArea = paintWidget(self)

        self.scrollArea = QtGui.QScrollArea()
        # self.scrollArea.setVerticalScrollBarPolicy( QtCore.Qt.ScrollBarAlwaysOn )
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setAutoFillBackground(True)
        self.scrollArea.setWidget(self.paintArea)

        # Looking for label tool configuration file under the same directory with this file
        configDir = os.path.dirname(__file__)
        self.configFile = os.path.join(configDir, "labelTool.conf")
        self.configObj = Config()
        message = self.configObj.load(self.configFile)
        # self.statusBar().showMessage(message)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.scrollArea)
        centralWidget.setLayout(vbox)

        # Open in full screen
        self.screenShape = QtGui.QDesktopWidget().screenGeometry()
        self.resize(self.screenShape.width(), self.screenShape.height())

        self.applicationTitle = 'Label Tool v0.1'
        self.setWindowTitle(self.applicationTitle)

    # Destructor
    def __del__(self):
        self.checkAndSave()
        self.configObj.save(self.configFile)

    # Disable the popup menu on right click
    def createPopupMenu(self):
        pass
コード例 #8
0
def main():
    # Register signal handlers
    signal.signal(signal.SIGINT, sigint_handler)

    # Register exception handler
    sys.excepthook = except_hook

    # Read the important options first
    args, unparsed = get_options()
    cfg_f = args.config
    verbose = args.verbose

    # Read the config file,
    cfg = Config(cfg_f, verbose)
    cfg.parse()
    cfg.check()

    # Print out the config
    if verbose:
        printv('Contents: ')
        printoff(str(cfg), CBEIGE2)

    # Overwrite the output directory
    if os.path.isdir(args.outdir):
        printw('Overwriting output directory: ' + args.outdir)
        shutil.rmtree(args.outdir)
    elif os.path.isfile(args.outdir):
        printw('Overwriting output directory: ' + args.outdir)
        os.remove(args.outdir)

    run_lcov(args.indir, args.outdir, cfg, verbose)
コード例 #9
0
    def __init__(self, config=None, postgres=None):
        if config == None:
            self.config = Config()
        else:
            self.config = config

        if postgres == None:
            self.postgres = Postgres(self.config)
        else:
            self.postgres = postgres
        self.execution_datas = []
        self.order_datas = []
        self.save_cnt = 10
コード例 #10
0
 def _delete(self):
     c = Config()
     self.repo.delete(self.corona_data, data_period=c.DATA_PERIOD)
コード例 #11
0

def app_path():
    ret = None
    """Returns the base application path."""
    if hasattr(sys, 'frozen'):
        # Handles PyInstaller
        ret = os.path.dirname(sys.executable)
    ret = os.path.dirname(__file__)
    return os.path.abspath(ret)


if __name__ == "__main__":
    Globals.app = QApplication([])
    Globals.app_dir = app_path()
    Globals.config = Config("bmfont_toolbox_config.json")
    Globals.config.init(Globals.UserData.images_dir, get_user_picture())
    Globals.config.init(Globals.UserData.output_dir, get_user_document())
    Globals.config.init(Globals.UserData.custom_dir, get_user_document())
    Globals.config.init(Globals.UserData.import_text_dir, get_user_document())
    Globals.config.init(Globals.UserData.font_save_name, "font")
    Globals.config.init(Globals.UserData.font_size, 10)
    Globals.config.init(Globals.UserData.window_width, 640)
    Globals.config.init(Globals.UserData.window_height, 480)
    Globals.config.init(Globals.UserData.max_width_index, 1)
    Globals.main_window = MainWindow()
    Globals.main_window.resize(Globals.config.get(Globals.UserData.window_width),
                               Globals.config.get(Globals.UserData.window_height))
    Globals.main_window.show()
    Globals.main_window.open()
    sys.exit(Globals.app.exec())
コード例 #12
0
def main():
    global parent
    global child_pid

    # Register signal handlers
    signal.signal(signal.SIGINT, sigint_handler)
    signal.signal(signal.SIGUSR1, sigusr1_handler)

    # Register exception handler
    sys.excepthook = except_hook

    # Read the important options first
    args, unparsed = get_options()
    cfg_f = args.config
    verbose = args.verbose

    # Read the config file,
    cfg = Config(cfg_f, verbose)
    cfg.parse()
    cfg.check()

    # Update arguments from config
    update_args_with_cfg(args, cfg)

    # Update rest of the args
    cores1 = args.cores_stage1
    cores2 = args.cores_stage2
    force_resp = args.force_resp
    dry_run = args.dry_run
    tgtcmd = cfg.tgtcmd

    if verbose:
        printv('Updated arguments:')
        printoff(
            "cores1      = " + str(args.cores_stage1) + '\n' + \
            "cores2      = " + str(args.cores_stage2) + '\n' + \
            "force_resp  = " + str(args.force_resp) + '\n' + \
            "dry_run     = " + str(args.dry_run) + '\n' + \
            "disable_st2 = " + str(args.disable_stage2) + '\n' + \
            "prg_file    = " + str(args.progress_file) + '\n' + \
            "tgtcmd      = " + str(cfg.tgtcmd) + '\n' + \
            "prg_int     = " + str(args.progress_interval) + '\n'
        )

    printi('PID: ' + str(os.getpid()))

    # Print out the config
    if verbose:
        printv('Contents: ')
        printoff(str(cfg), CBEIGE2)

    # Check for image marker in the target command
    pm_img_marker = False
    for keywrd in tgtcmd:
        if common.PM_IMG_MRK in keywrd:
            pm_img_marker = True

    if not pm_img_marker:
        parser.error('--wrkld-cmd option needs the marker ' +
                     common.PM_IMG_MRK +
                     ' to mark location of the pool image. e.g., ' +
                     '/mnt/pmem0/__POOL_IMAGE__')

    if force_resp != None:
        force_resp = force_resp[0]

    # Overwrite the output directory
    if os.path.isdir(args.outdir):
        printw('Overwriting output directory: ' + args.outdir)
        shutil.rmtree(args.outdir)
    elif os.path.isfile(args.outdir):
        printw('Overwriting output directory: ' + args.outdir)
        os.remove(args.outdir)

    os.makedirs(args.outdir)

    perform_checks()
    if args.checks_only:
        printi('All checks completed')
        exit(0)

    # Fork here to run pmfuzz in one thread and statistics collection in the
    # other thread
    pid = os.fork()

    if pid != 0:  # Run pmfuzz
        write_child_pid(args, pid)
        pmfuzz.run_pmfuzz(args.indir,
                          args.outdir,
                          cfg,
                          cores1=cores1,
                          cores2=cores2,
                          verbose=verbose,
                          force_yes=force_resp,
                          dry_run=dry_run,
                          disable_stage2=args.disable_stage2)
    else:  # Run statistics collection
        parent = False
        collect_statistics(cfg, args)
コード例 #13
0
from handler.event import EventHandler
from helper.config import Config
from helper.discovery import ChromecastDiscovery
from time import sleep
from helper.mqtt import MqttConnection

logging.basicConfig(level=logging.DEBUG)
logging.getLogger("pychromecast").setLevel(logging.DEBUG)
logging.getLogger("pychromecast.socket_client").setLevel(logging.INFO)

logger = logging.getLogger(__name__)

logger.debug("~ reading config")
try:
    config = Config()
except Exception:
    logger.error("Could not parse config.ini, please check that file.")
    sys.exit(1)

event_handler = EventHandler()

logger.debug("~ connecting to mqtt")
username = None
password = None
if config.get_mqtt_broker_use_auth():
    logger.debug("~ using username and password to connect to mqtt")
    username = config.get_mqtt_broker_username()
    password = config.get_mqtt_broker_password()

mqtt = MqttConnection(config.get_mqtt_broker_address(),
コード例 #14
0
 def test_getPassword(self):
     config = Config()
     self.assertIsNotNone(config.password)
コード例 #15
0
 def test_getUsername(self):
     config = Config()
     self.assertIsNotNone(config.username)
コード例 #16
0
from helper.config import Config
from helper.discovery import ChromecastDiscovery
from time import sleep
from helper.mqtt import MqttConnection

# logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(filename="chromecast.log", level=logging.DEBUG)
logging.getLogger("pychromecast").setLevel(logging.DEBUG)
logging.getLogger("pychromecast.socket_client").setLevel(logging.INFO)

logger = logging.getLogger(__name__)

logger.debug("~ reading config")
config_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                           'config.ini')
config = Config(config_path)

event_handler = EventHandler()

logger.debug("~ connecting to mqtt")
username = None
password = None
if config.get_mqtt_broker_use_auth():
    logger.debug("~ using username and password to connect to mqtt")
    username = config.get_mqtt_broker_username()
    password = config.get_mqtt_broker_password()

mqtt = MqttConnection(config.get_mqtt_broker_address(),
                      config.get_mqtt_broker_port(), username, password,
                      event_handler)
if not mqtt.start_connection():
コード例 #17
0
import requests
import os, sys
import lxml.html as html
import time
import logging.config
import consul
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from helper.config import Config

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(CURRENT_DIR, '..', 'config')

main_config = Config.setup_main_config(os.path.join(config_path, 'main.yml'))
logging.config.fileConfig(os.path.join(config_path, 'logging.conf'))

class ProxyManager(object):

    def __init__(self):
        self.headers = {
            'User-Agent': 'Lynx/2.8.9dev.8 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.4.9',
            'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'ru,en-US;q=0.7,en;q=0.3',
            'X-Requested-With': 'XMLHttpRequest',
            'Connection': 'Keep-Alive',
            'Host': 'yandex.ru'
        }

        self.url = 'https://yandex.ru/search/?text=qwerty&lr=213'
        self._logger = logging.getLogger(__name__)
        self.download_url = 'http://api.foxtools.ru/v2/Proxy.txt' \
コード例 #18
0
 def test_getOutputDir(self):
     config = Config()
     self.assertIsNotNone(config.outputDir)
コード例 #19
0
import os
import sys
import pika
import json
import redis
from collections import namedtuple
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from mongoengine import connect
from helper.config import Config
from proccess.proccessing import Process
import logging.config
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(CURRENT_DIR, '..', 'config')

main_config = Config.setup_main_config(os.path.join(config_path, 'main.yml'))
logging.config.fileConfig(os.path.join(config_path, 'logging.conf'))
params = Config.setup_main_config(os.path.join(config_path, 'rabbit.yml'))


class RabbitTask:
    def __init__(self):

        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(params.receiver.host))
        self._logger = logging.getLogger(__name__)
        self.queue = params.receiver.queue.social

        self._channel = self.connection.channel()
        self._channel.queue_declare(queue=self.queue, durable=True)
        self._channel.basic_qos(prefetch_count=1)
コード例 #20
0
ファイル: scale.py プロジェクト: ramawardhanaa/samsi
class Scale:
    def __init__(self):
        self.config = Config()  # config init
        self.config_data = self.config.get_config_data()
        self.hx = HX711(5, 6)  # initialize scale
        self.is_calibrated = self.config_data['SCALE'].getboolean(
            "calibrated")  # check config if scale is calibrated
        self.ratio = 0  # scale ratio for calibration
        self.offset = 0
        self.value = 0
        self.result = 0
        self.data = 0
        if self.is_calibrated:
            self.hx.set_offset(float(self.config_data["SCALE"]['offset']))
            self.config_ratio = self.config_data["SCALE"][
                'ratio']  # get scale ratio of config
            self.hx.set_scale(float(self.config_ratio))

    def setup(self):
        try:
            self.offset = self.hx.read_average()
            self.hx.set_offset(self.offset)
            return True
        except Exception as e:
            return False

    def has_error(self):
        value_list = []
        try:
            for x in range(15):
                self.hx.power_up()
                value_list.append(self.hx.get_grams())
                self.hx.power_down()
                time.sleep(0.1)

            print(value_list)
            median_val = median(value_list)
            print(median_val)
            if value_list[3] == median_val:
                return True
            else:
                return False

        except:
            return True

    def calibrate(self, weight):
        try:
            self.value = int(weight)
            measured_weight = (self.hx.read_average() - self.hx.get_offset())
            self.ratio = int(measured_weight) / self.value
            self.hx.set_scale(self.ratio)
            self.config.set_scale(ratio=self.ratio,
                                  offset=self.hx.get_offset(),
                                  calibrated=1)
            return True
        except ValueError:
            return False

    def get_data(self):
        try:
            self.hx.power_up()
            val = self.hx.get_grams()
            measure_weight = round((val / 1000), 2)
            self.hx.power_down()
            return measure_weight
        except Exception as e:
            pass

    def calibrated(self):
        self.is_calibrated = self.config_data['SCALE'].getboolean("calibrated")

        return self.is_calibrated

    def reset(self):
        self.config.set_scale()

    def tare(self):
        pass

    @staticmethod
    def clean():
        GPIO.cleanup()
コード例 #21
0
ファイル: api_data.py プロジェクト: ramawardhanaa/samsi
class ApiData:
    def __init__(self):
        self.config = Config()
        self.config_data = self.config.get_config_data()
        self.dht22 = DHT22(self.config_data['DHT22']['pin'])
        self.DS18B20 = DS18B20()
        self.json_data = {}
        self.log = Log()

        self.ds18b20_temp = []
        self.dht22_data = []

    def error_message(self, device, exception_msg):
        self.log.write_log(
            "something went wrong by collecting the {0} api data! Error: {1}".
            format(device, exception_msg))

    def get_data(self):
        ds18b20_thread = Thread(target=self.get_ds18b20_data)
        dht22_thread = Thread(target=self.get_dht22_data)

        ds18b20_thread.start()
        dht22_thread.start()

        ds18b20_thread.join()
        dht22_thread.join()

        return self.json_data

    def get_ds18b20_data(self):
        sensor_counter = self.DS18B20.device_count()
        try:
            if sensor_counter != 0:
                for x in range(sensor_counter):
                    self.ds18b20_temp.append(self.DS18B20.tempC(x))

            if len(self.ds18b20_temp) != 0:
                for x in range(len(self.ds18b20_temp)):
                    if not self.ds18b20_temp[x] == 85:
                        self.json_data["DS1820B-{}".format(
                            x)] = "{0} {1}".format(self.ds18b20_temp[x], "°C")
                    elif self.ds18b20_temp[x] == 998:
                        self.json_data["DS1820B-{}".format(x)] = "{0}".format(
                            "VCC not connected")
                    else:
                        self.json_data["DS1820B-{}".format(x)] = "{0}".format(
                            "GND or DATA not connected")

        except Exception as e:
            self.error_message("ds18b20", e)

    def get_dht22_data(self):
        try:
            dht22data = self.dht22.get_data()
            self.json_data["dht22 hum"] = "{0} {1}".format(
                dht22data['hum'], "%")
            self.json_data["dht22 temp"] = "{0} {1}".format(
                dht22data['temp'], "°C")

        except Exception as e:
            self.error_message("dht22", e)
コード例 #22
0
from helper import logging
from helper import router
from helper.config import Config
from adopter.controller import controller_interface
from adopter.controller.line_webhook_controller import LineWebhookController
from usecase.interfaces.make_answer_input_port import MakeAnswerInputPortInterface
from usecase.interfaces.make_answer_presenter import MakeAnswerPresenterInterface
from usecase.interfaces.corona_data_repository import CoronaDataRepositoryInterface
from usecase.impl.make_answer_usecase import MakeAnswerUseCase
from drivers.repositories.datastore import DatastoreRepository
from adopter.presenter.line_presenter import LinePresenter
from adopter.controller.controller_interface import ControllerInterface

app = Flask(__name__)

c = Config()
line_bot_api = LineBotApi(c.LINE_ACCESS_TOKEN)
handler = WebhookHandler(c.LINE_CHANNEL_SECRET)


@app.route("/callback", methods=['POST'])
def callback():
    """
    This function is LINE health check handler.
    """
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
コード例 #23
0
ファイル: main.py プロジェクト: ysslzh/get_kline_data
from helper.config import Config
from KlineConsumer import KlineConsumer
from helper.postgres import Postgres
from helper.logger import INFO
import os

INFO("start to init config pg")
config = Config()
pg = Postgres()
INFO("end to init config pg")
def main():
    INFO("start to run kline_data consumer")
    config.load()
    pg.load(config)
    KlineConsumer(config, pg).run()

main()