Esempio n. 1
0
	def loadArtikels(silent=True):
		webshopProducts = utils.readJson('Resources/Artikelen.json')
		customProducts = utils.readJson('Resources/Custom/custom.json')
		if webshopProducts == {}:
			webshopProducts = api.getArtikels(silent=silent)
			utils.writeJson('Resources/Artikelen.json',webshopProducts)
		for d in webshopProducts:
			item = utils.makeWebshopItem(1,d)
			if item is not None:
				webshopLijst.append(item)
		for d in customProducts:
			item = utils.makePreCustomItem(1,d)
			if item is not None:
				customLijst.append(item)
Esempio n. 2
0
def urenWindowSetup():
	def saveAuto(layout,typeFactuur):
		autoEdit = layout.itemAt(1)
		data['Auto'] = dialogs.getJsonLayout(autoEdit)
		latexfact.startFactuur(data,typeFactuur)

	def kiesAuto(layout):
		fileName = QtGui.QFileDialog.getOpenFileName(customerWindow, 'Open File', 'Resources/Autos')
		if fileName == '':
			return
		autoData = utils.readJson(fileName)
		carEdit = dialogs.controleerJsonLayout(autoData)
		l = layout.takeAt(1)
		for i in reversed(range(l.count())):
			notNeeded = l.takeAt(i).widget().setParent(None)
		layout.insertLayout(1,carEdit)

	leftLayout = QtGui.QVBoxLayout()
	rightLayout = QtGui.QVBoxLayout()

	emptyAuto = utils.readJson('Resources/emptyAuto.json')
	autoEdit = dialogs.controleerJsonLayout(emptyAuto)

	bestaandeAutoKiezen = QtGui.QPushButton("Bestaande Auto Kiezen")
	bestaandeAutoKiezen.clicked.connect(lambda s, edit = rightLayout: kiesAuto(edit))
	bestaandeAutoKiezen.setFixedHeight(100)

	urenButton = QtGui.QPushButton("Werk toevoegen")
	urenButton.setFixedHeight(100)
	urenButton.clicked.connect(addUren)

	scrollGroup = QtGui.QGroupBox()
	scrollGroup.setLayout(werkLayout)
	werkScroll = QtGui.QScrollArea()
	werkScroll.setWidget(scrollGroup)
	werkScroll.setWidgetResizable(True)

	voorbeeldButton = QtGui.QPushButton("Afdrukvoorbeeld Factuur")
	voorbeeldButton.setFixedHeight(100)
	voorbeeldButton.clicked.connect(lambda : saveAuto(rightLayout,utils.TypeFactuur.Afdrukvoorbeeld))

	prijsOpgaveButton = QtGui.QPushButton("Kostenraming")
	prijsOpgaveButton.setFixedHeight(100)
	prijsOpgaveButton.clicked.connect(lambda : saveAuto(rightLayout,utils.TypeFactuur.Kostenraming))

	urenWindow.setOpslaan(lambda : saveAuto(rightLayout,utils.TypeFactuur.Definitief))
	urenWindow.volgendeView.setText("Definitieve Factuur")

	leftLayout.addWidget(urenWindow.vorigeView,1)
	leftLayout.addWidget(werkScroll,4)
	leftLayout.addWidget(urenButton,1)

	rightLayout.addWidget(bestaandeAutoKiezen,1)
	rightLayout.addLayout(autoEdit,4)
	rightLayout.addWidget(voorbeeldButton,1)
	rightLayout.addWidget(prijsOpgaveButton,1)
	rightLayout.addWidget(urenWindow.volgendeView,1)

	urenWindow.totalLayout.insertLayout(1,leftLayout)
	urenWindow.totalLayout.insertLayout(2,rightLayout)
Esempio n. 3
0
 def read(self):
     """
     Read the database and return the data.
     
     :rtype: dict 
     """
     return utils.readJson(self.path())
Esempio n. 4
0
def getCounter(S, typeFactuur):
    counters = utils.readJson('Resources/counters.json')
    c = counters.setdefault(S, 100) + 1
    if typeFactuur != utils.TypeFactuur.Afdrukvoorbeeld:
        counters[S] = c
        utils.writeJson('Resources/counters.json', counters)
    return c
Esempio n. 5
0
    def writeConfigurations(self, cfgStr, result, pathToConfigurationsFile):
        configurations = {}
        if (os.path.exists(pathToConfigurationsFile)):
            configurations = utils.readJson(pathToConfigurationsFile)
        configurations[cfgStr] = result
        utils.writeJson(pathToConfigurationsFile, configurations)

        return
Esempio n. 6
0
  def __runExternal(self,commandType,value,footer):

       cmd=value
       cmdArgs=cmd.split(" ")

       if ( "run" in commandType ):
         response = slack_client.api_call(
          "chat.postMessage",
          channel=self.channel,
          ts=self.formJson["message_ts"],
          text="*User* `" + self.slackUserName + "`\n*Running command:* " + cmdArgs[0] + " \n*From menu:* " + footer
         )
      

       thr = Thread(target=self.__slackThreadRun , args=[cmd,commandType])
       thr.start()

       if ( commandType == "exec_nomenu" ):
          return
       #load menu after running
       elif commandType == "exec_gomain" or commandType == "run_gomain":
         #load main menu
         menuName=mainMenu
       elif commandType == "exec_goback" or commandType == "run_goback":
         #load previous menu
         menuName=self.callbackMenuName
       elif "exec_gomenu" in commandType or "run_gomenu" in commandType:
         pos=commandType.index("-")
         menuName=commandType[pos+1:]

       else:
         #load current menu
         menuName=self.previousMenuName


       menu=utils.readJson("menu/" + menuName + ".json")
       if ( not "User " in menu[0]["title"] ):
         menu[0]["title"]="User " + self.slackUserName + "\n" + menu[0]['title']

       menu=self.__loadSelectedValues(menu,menuName)
       app.logger.debug(menu)

       if ( "exec_gomenu" in commandType or "run_gomenu" in commandType) :

          menu=self.__loadSelectedValues(menu,menuName)

          response = slack_client.api_call(
           "chat.update",
           channel=self.channel,
           ts=self.formJson["message_ts"],
           attachments=menu
          )
       else:
          response = slack_client.api_call(
           "chat.postMessage",
           channel=self.channel,
           attachments=menu
          )
Esempio n. 7
0
def installLayout(layoutfile, side, prefix, symmetry, mirror):
    data = utils.readJson(layoutfile)
    # Load the data as a dictionary
    info = json.loads(data)
    for key, value in info.iteritems():
        jointInfo = info[key]

    # Now we have all the data we need to build the joints
    jntinfo = utils.createLytJoints(jointInfo, prefix, side, symmetry)

    assetname = 'Layout_' + side + prefix
    lytast = cmds.container(n=assetname)
    cmds.addAttr(lytast,
                 shortName="type",
                 longName="type",
                 dt='string',
                 keyable=False)
    typename = prefix.replace('_', '')
    cmds.setAttr(lytast + '.type', typename.lower(), type='string')

    if symmetry == True:
        mirassetname = 'LayoutMirror_' + side + prefix
        mirrorlytast = cmds.container(n=mirassetname)
        cmds.addAttr(mirrorlytast,
                     shortName="type",
                     longName="type",
                     dt='string',
                     keyable=False)
        cmds.setAttr(mirrorlytast + '.type', prefix, type='string')
        # Add mirror attribute
        cmds.addAttr(lytast,
                     shortName="mirror",
                     longName="mirror",
                     dt='string',
                     keyable=False)
        cmds.setAttr(lytast + '.mirror', mirassetname, type='string')
        """
        If you don't have the symmetry joint option,
        you could add a "mirror attribute here".  
        In rig arm a mirrored arm rig could be created 
        if a layout asset has the mirror attribute.
        """
    if mirror == True:
        mirassetname = 'LayoutMirror_' + side + prefix
        cmds.addAttr(lytast,
                     shortName="mirror",
                     longName="mirror",
                     dt='string',
                     keyable=False)
        cmds.setAttr(lytast + '.mirror', mirassetname, type='string')

    for j in jntinfo:
        cmds.container(lytast, edit=True, an=j[0])
        # Check for symmetry
        if symmetry == True:
            cmds.container(mirrorlytast, edit=True, an=j[1])
Esempio n. 8
0
	def kiesKlant(layout):
		fileName = QtGui.QFileDialog.getOpenFileName(customerWindow, 'Open File', 'Resources/Klanten')
		if fileName == '':
			return
		klantData = utils.readJson(fileName)
		custEdit = dialogs.controleerJsonLayout(klantData)
		l = layout.takeAt(1)
		for i in reversed(range(l.count())):
			notNeeded = l.takeAt(i).widget().setParent(None)
		layout.insertLayout(1,custEdit)
Esempio n. 9
0
def loadWebshopArtikels(silent=True):
    webshopLijst = []
    webshopProducts = utils.readJson('Resources/Artikelen.json')
    if webshopProducts == {}:
        webshopProducts = api.getArtikels(silent=silent)
        utils.writeJson('Resources/Artikelen.json', webshopProducts)
    for d in webshopProducts:
        item = d
        if item is not None:
            webshopLijst.append(item)
    return webshopLijst
Esempio n. 10
0
    def readConfigurations(self):
        pathToFiles = self.getInfoStr()
        configurations = {}
        self.args = self.getArgs()
        configJson = self.args['configBenchmarkJson']
        pathToConfigurationsFile = os.path.join(pathToFiles,
                                                self.configurationsFileName)
        if (os.path.exists(pathToConfigurationsFile)):
            configurations = utils.readJson(pathToConfigurationsFile)

        return configurations, pathToFiles
Esempio n. 11
0
def doRecalculate():
    wbdir = sys.argv[2]
    wsname = sys.argv[3]
    fpath = '{}.json'.format(os.path.join(wbdir, wsname))
    dd = utils.readJson(fpath)
    dd = buildTsort(dd)
    dd = compileFormulas(dd)
    global DD
    DD = dd
    DD = recalculateFormulas(DD)
    dd = DD
Esempio n. 12
0
    def __updateMeta(self, filename):
        print(filename)
        try:
            obj = utils.readJson(filename)
            obj['iterations'] += self.__save_round
        except:
            obj = {}
            obj['name'] = filename
            obj['iterations'] = self.__save_round
            obj['active_func'] = self.__prop.queryAttr('active_func')
            obj['weights_shape'] = self.__prop.queryAttr('weights_shape')

        utils.writeJson(obj, filename)
Esempio n. 13
0
 def __init__(self, pin):
     self.pin = pin
     self.resetConfig()
     self.config = utils.readJson(_CONFIG_FILE) or self.config
     self.powerOffIfNeeded()
     self.animations = []
     self.animations.append(rainbow_animation.RainbowAnimation(pin, self.config['leds']))
     self.animations.append(strip_animation.StripAnimation(pin, self.config['leds']))
     self.animations.append(full_smooth_transition_animation.FullSmoothTransitionAnimation(pin, self.config['leds']))
     self.tickCount = 0
     self.lastChangedAnimation = utime.ticks_ms()
     self.forceRefreshColor = True
     self.forceRefreshLeds = 0
 def __init__(self, temperature_sensor, relay_pin, switch_pin, led_pin):
     utils.printInfo('THERMOSTAT', 'init')
     self._temperature_sensor = temperature_sensor
     self._relay_pin = relay_pin
     self._led_pin = led_pin
     self._config = utils.readJson(_CONFIG_FILE) or self._default_config()
     self._update()
     self._timer = utils.timer()
     self._timer.init(period=_UPDATE_INTERVAL_MS,
                      mode=machine.Timer.PERIODIC,
                      callback=lambda t: self._update())
     switch_pin.irq(trigger=machine.Pin.IRQ_FALLING
                    | machine.Pin.IRQ_RISING,
                    handler=lambda p: self._switch_clicked(p))
     utils.printInfo('THERMOSTAT', 'config:\n%s' % (self._config))
Esempio n. 15
0
def customerWindowSetup():
	def saveCustomer(rightLayout):
		customerEdit = rightLayout.itemAt(1)
		data['Klant'] = dialogs.getJsonLayout(customerEdit)

	def kiesKlant(layout):
		fileName = QtGui.QFileDialog.getOpenFileName(customerWindow, 'Open File', 'Resources/Klanten')
		if fileName == '':
			return
		klantData = utils.readJson(fileName)
		custEdit = dialogs.controleerJsonLayout(klantData)
		l = layout.takeAt(1)
		for i in reversed(range(l.count())):
			notNeeded = l.takeAt(i).widget().setParent(None)
		layout.insertLayout(1,custEdit)

	rightLayout = QtGui.QVBoxLayout()

	emptyKlant = utils.readJson('Resources/emptyCustomer.json')
	customerEdit = dialogs.controleerJsonLayout(emptyKlant)

	bestaandeKlantKiezen = QtGui.QPushButton("Bestaande Klant Kiezen")
	bestaandeKlantKiezen.clicked.connect(lambda s, edit = rightLayout: kiesKlant(edit))
	bestaandeKlantKiezen.setFixedHeight(100)

	buttonLayout = QtGui.QHBoxLayout()
	soortLabel = QtGui.QLabel("Soort Factuur:")
	buttonLayout.addWidget(soortLabel)
	buttonLayout.setAlignment(Qt.AlignLeft)

	buttons = []
	for en in utils.SoortFactuur:
		b1 = QtGui.QRadioButton(en.name)
		b1.clicked.connect(lambda s, so = en : data.update({'soortFactuur': so}))
		buttonLayout.addWidget(b1)
		buttons.append(b1)
	buttons[0].click()

	rightLayout.addWidget(bestaandeKlantKiezen)
	rightLayout.addLayout(customerEdit)
	rightLayout.addStretch()
	rightLayout.addLayout(buttonLayout)
	rightLayout.addWidget(customerWindow.volgendeView)

	customerWindow.setOpslaan(lambda : saveCustomer(rightLayout))
	customerWindow.totalLayout.addStretch()
	customerWindow.totalLayout.addLayout(rightLayout)
	customerWindow.totalLayout.addStretch()
Esempio n. 16
0
  def __loadMenu(self,commandType,value,selectName):

       app.logger.debug("__loadMenu:" + commandType + "," + value + "," + selectName + "," + self.slackUserName)
       menuName=value
       menu=utils.readJson("menu/" + menuName + ".json")

       #check menu roles before display
       menu=slack.checkMenuRolesBeforeLoad(menu,self.slackUserName)
       app.logger.debug(menu)

       #check for special values in menu
       if ( "actions" in menu[0] and "value" in menu[0]["actions"][0] ):

         menuValue=menu[0]["actions"][0]["value"]
         if ( ":" in menuValue ):

            pos=menuValue.index(":")
            commandType=menuValue[:pos]
            value=menuValue[pos+1:]
            app.logger.debug(commandType + "," + value)

            #run menu function
            if ( commandType == "function" ):
              function=slack.parseMenuValue(value,self.formJson,self.slackUserName)
              #function=value.encode('utf-8') + "()"
              #output=eval(function)
              app.logger.debug(function)
              output=functions.runFunction(function)
              menu[0]["actions"][0]["options"]=output


       #load menu saved data
       if ( "actions" in menu[0] and "name" in menu[0]["actions"][0] ):
         menu=self.__loadSelectedValues(menu,menuName)

       #display the menu
       app.logger.debug(menu)
       if ( not "User " in menu[0]["title"] ):
          menu[0]["title"]="User " + self.slackUserName + "\n" + menu[0]['title']

       response = slack_client.api_call(
        "chat.update",
        channel=self.channel,
        thread_ts=self.formJson["message_ts"],
        ts=self.formJson["message_ts"],
        attachments=menu
       )
Esempio n. 17
0
def iosLocalizer(args) :
	masterfilePath = "";
	masterData     = "";
	targetLanguage = "";
	envData = [];
	
	# Get the environment variables (Settings data)
	envData = utils.getEnvData();
	targetLanguage = envData["target"];

	if (envData) :
		masterfilePath = utils.getMasterFilePath();
	 	masterData = utils.readJson(masterfilePath);

        # to check if the master string file is loaded or not
        if (masterData) :
            for lang in targetLanguage :
                targetLangugaeCode = utils.getLanguageCode(lang);
                makeString(targetLangugaeCode, args, masterData, envData);
Esempio n. 18
0
  def __saveMenu(self,menuName,selectName,value):

    app.logger.debug("Saving menu " + menuName + ",selectName=" + selectName + ",value=" + value)

    selectType="unique"
    text=""

    if ( os.path.isfile("menu/" + menuName + ".json") ):
         menu=utils.readJson("menu/" + menuName + ".json")

         for item in menu[0]["actions"][0]["options"]:
            #app.logger.debug("Menu text: " + item["text"])

            if ( "save" in item ):
               slack.saveMenuVars(item["save"])

            if ( "value" in item and item["value"] == value ):
               text=item["text"]

            #app.logger.debug("Menu text: " + item["text"])

         if ( text == "" ):
            text=value 

         if ( "selectType" in menu[0] ):
            selectType=menu[0]["selectType"]

         #save value
         if ( "save" in menu[0] and menu[0]["save"] == "value" ):
            text=value 

         #save text
         #elif ( "save" in menu[0] and menu[0]["save"] == "text" ):
         #   text=item["text"]


    app.logger.debug("Menu selectType: " + selectType)
    app.logger.debug("Menu text: " + text)
    app.logger.debug("Menu value: " + value)


    if ( "name" in self.formJson["actions"][0] ):
       slack.saveMenuStatus(text,menuName , selectName ,selectType,self.slackUserName, self.shared )
Esempio n. 19
0
def doCompile():
    fpath = sys.argv[2]
    dworkbook = utils.readJson(fpath)
    dworksheets = dworkbook["worksheets"]
    is_using_relative_notation = isUsingRelativeNotation(dworksheets)
    for wsname in dworksheets:
        dworksheet = dworksheets[wsname]
        if is_using_relative_notation:
            translateRelativeToA1Notation(dworksheet["cells"])
        buildRanges(dworksheet)
    mergeWorksheets(dworkbook)  # merge cells and ranges
    mainws = dworkbook["merged"]["data"]
    buildTsort(mainws)
    # DEBUG: Comment next line out to get debug output:
    del dworkbook["worksheets"]
    compileFormulas(mainws)
    ofpath = fpath.replace(".json", ".c.json")
    f = open(ofpath, "w")
    writeZspreadWorkbook(dworkbook, f)
    f.close()
Esempio n. 20
0
  def menu(self,request):

    app.logger.debug("in main menu")
    app.logger.debug(request.form)

    if ( "trigger_id" in request.form ):
       trigger_id=request.form["trigger_id"]
    else:
       trigger_id=""

    if ( "payload" in request.form ):

      formJson = json.loads(request.form["payload"])
      channel=formJson["channel"]["id"]
      if ( formJson["actions"][0]["type"] == "select" ):
        app.logger.debug(formJson["actions"][0]["selected_options"][0]["value"])

    else:
       formJson = request.form
       channel=formJson["channel_id"]
      
    menu=utils.readJson("menu/" + mainMenu + ".json")

    slackUserName=formJson["user_name"]
    self.slackUserName=slackUserName

    if ( not "User " in menu[0]['title'] ):
      menu[0]['title']="User " + slackUserName + "\n" + menu[0]['title']

    message_attachments = menu
    app.logger.debug(menu[0]['text'])
    
    response = slack_client.api_call(
      "chat.postMessage",
      channel=channel,
      attachments=message_attachments
    )

    app.logger.debug(response)

    return make_response("", 200)
Esempio n. 21
0
def installLayout(layoutfile, side, prefix, symmetry, mirror):
    data = utils.readJson(layoutfile)
    # Load the data as a dictionary
    info = json.loads(data)
    for key, value in info.iteritems():
        jointInfo = info[key]

    # Now we have all the data we need to build the joints
    jntinfo = utils.createLytJoints(jointInfo, prefix, side, symmetry)

    assetname = 'Layout_' + side + prefix 
    lytast = cmds.container(n=assetname)
    cmds.addAttr(lytast, shortName="type", longName="type", dt='string', keyable=False)
    typename = prefix.replace('_', '')
    cmds.setAttr(lytast + '.type', typename.lower(), type='string')

    if symmetry == True:
        mirassetname = 'LayoutMirror_' + side + prefix 
        mirrorlytast = cmds.container(n=mirassetname)
        cmds.addAttr(mirrorlytast, shortName="type", longName="type", dt='string', keyable=False)
        cmds.setAttr(mirrorlytast + '.type', prefix, type='string')
        # Add mirror attribute
        cmds.addAttr(lytast, shortName="mirror", longName="mirror", dt='string', keyable=False)
        cmds.setAttr(lytast + '.mirror', mirassetname, type='string')
        """
        If you don't have the symmetry joint option,
        you could add a "mirror attribute here".  
        In rig arm a mirrored arm rig could be created 
        if a layout asset has the mirror attribute.
        """
    if mirror == True:
        mirassetname = 'LayoutMirror_' + side + prefix 
        cmds.addAttr(lytast, shortName="mirror", longName="mirror", dt='string', keyable=False)
        cmds.setAttr(lytast + '.mirror', mirassetname, type='string')
        
    for j in jntinfo:
        cmds.container(lytast, edit=True, an=j[0])
        # Check for symmetry
        if symmetry == True:
            cmds.container(mirrorlytast, edit=True, an=j[1])
Esempio n. 22
0
  def __slackThreadRun(self,cmd,commandType):

       status=0
       (output,status)=utils.runCmd(cmd)
       output=str(output).replace("\\n","\n")

       if ( "run" in commandType ):

         if ( status == 0 ):
           output+=":white_check_mark: *Submit command finished successfully*"
         else:
           output+=":x: *Submit command Failed*"

         response = slack_client.api_call(
           "chat.postMessage",
           channel=self.formJson["channel"]["id"],
           text=output
         )

       return
       #load menu after running
       if commandType == "exec_gomain" or commandType == "run_gomain":
         #load main menu
         menuName=mainMenu
       elif commandType == "exec_goback" or commandType == "run_goback":
         #load previous menu
         menuName=self.callbackMenuName
       else:
         #load current menu
         menuName=self.previousMenuName

       menu=utils.readJson("menu/" + menuName + ".json")
       menu[0]['title']="User " + self.slackUserName + "\n" + menu[0]['title']
       app.logger.debug(menu)

       response = slack_client.api_call(
           "chat.postMessage",
           channel=self.formJson["channel"]["id"],
           attachments=menu
       )
Esempio n. 23
0
    def restart(self):
        logging.info("restart {} {}".format(self.service, self.env))
        self.__slackPost("@{} restarting {} , environment ,{}".format(
            self.user, self.service, self.env))
        servicesMap = utils.readJson("services_map.json")
        teletraanServices = ""

        services = self.service.split(",")
        for service in services:
            for serviceMap in servicesMap["services"]:

                if (service.lower() == serviceMap["name"]):
                    if (self.env in serviceMap
                            and len(serviceMap[self.env]) > 0):

                        if (serviceMap["type"] == "teletraan"):
                            if (self.env in serviceMap):
                                for envs in serviceMap[self.env]:
                                    if ("envs" in envs):
                                        for env in envs["envs"].split(","):
                                            (output, status) = utils.runCmd(
                                                "./teletraan.py restart \"{}\" {} {} {}"
                                                .format(
                                                    self.formJson, env,
                                                    service.lower(),
                                                    "restart"))
                            else:
                                (output, status) = utils.runCmd(
                                    "./teletraan.py restart \"{}\" {} {} {}".
                                    format(self.formJson, self.env,
                                           service.lower(), "restart"))

                    elif (serviceMap["type"] == "ecs"):
                        self.__ecsRestart(self.env, service)

        self.clearHistory()
        self.__slackPost("@{} restart of {} , environment ,{} finished".format(
            self.user, self.service, self.env))
Esempio n. 24
0
    def getArgs(self):
        hostname = socket.gethostname()
        args = {}
        args['argsSet'] = os.environ['ARGS_TMP']

        configPath = os.environ['REPO_PATH'] + '/config/' + hostname + '.json'
        configJson = utils.readJson(configPath)
        args['configJson'] = configJson

        benchmark = os.environ['BENCHMARK_NAME']
        args['benchmark'] = benchmark

        numOfCores = int(os.environ['NUM_OF_CORES'])
        numOfIterations = int(os.environ['MAX_ITERATIONS'])
        htFlag = bool(int(os.environ['HT_FLAG']))
        pwFlag = bool(int(os.environ['PW_FLAG']))
        args['configBenchmarkJson'] = {
            'numOfCores': numOfCores,
            'numOfIterations': numOfIterations,
            'HT': htFlag,
            'PW': pwFlag
        }

        return args
Esempio n. 25
0
import os
import sys
import re

sys.path.append('/scratch/stimela')
import utils

CONFIG = os.environ['CONFIG']
INPUT = os.environ['INPUT']
OUTPUT = os.environ['OUTPUT']
MSDIR = os.environ['MSDIR']

cab = utils.readJson(CONFIG)
params = cab['parameters']
args = []

# new interface as of WSCLEAN v2.5
# make the transition transparent

npix = filter(lambda x: x['name'] == 'size', params)[0]['value']

if isinstance(npix, int):
    npix = [npix, npix]
elif isinstance(npix, list) and len(npix) == 1:
    npix = npix * 2
elif not (isinstance(npix, list) and all([isinstance(px, int)
                                          for px in npix]) and len(npix) == 2):
    raise ValueError("Npix only accepts single int or list[2] of int")

trdefault = int(max(npix[0], npix[1]) * 0.75)
trim = filter(lambda x: x['name'] == 'trim', params)[0]['value']
Esempio n. 26
0
 def getJson(self):
     return utils.readJson(self.path)
Esempio n. 27
0
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.simplefilter(action='ignore', category=UserWarning)

import sys
import utils

from crossasr import CrossASR

if __name__ == "__main__":

    config = utils.readJson(sys.argv[1])  # read json configuration file

    tts = utils.getTTS(config["tts"])
    asrs = utils.getASRS(config["asrs"])

    crossasr = CrossASR(tts=tts,
                        asrs=asrs,
                        output_dir=config["output_dir"],
                        recompute=True)

    text = "software engineering conference"
    filename = "software_engineering_conference"

    crossasr.processText(text=text, filename=filename)
    crossasr.printResult(text=text, filename=filename)
Esempio n. 28
0
import config
import esp
import machine
import utils
import ubinascii

utils.printLog('ANIMATOR', 'fast set leds')
_config = utils.readJson('animator.data')
if _config and _config['powered_on'] and _config['use_color']:
    pin = machine.Pin(config.D4, machine.Pin.OUT)
    bytes = ubinascii.unhexlify(_config['color'])
    color = [bytes[1], bytes[0], bytes[2]]
    esp.neopixel_write(pin, bytearray(color * _config['leds']), 1)
utils.printLog('ANIMATOR', 'finish')
Esempio n. 29
0
import tvmovieDB

# count = 1;
# with open('extractor\srottentomatoes.txt') as f:
#     lines = f.readlines()
#     f.close()
# for site in lines:
#     rottentomatoes.get_data(site, str(count))
#     count+=1

# data = utils.readJson('extractor\stvMovieDB2.json')
# for site in data:
#     tvmovieDB.get_data(site[1],str(site[0]))

# with open('extractor\stvmovieDB.txt') as f:
#     lines = f.readlines()
#     f.close()
# for site in lines:
#     tvmovieDB.get_data(site,str(count))
#     count+=1
path = "extractor/tvmovidDB"
name_series = []
for filename in os.listdir(path):
    fullpath = os.path.join(path, filename)
    data = utils.readJson(fullpath)
    for i in data['cast']:
        if i not in name_series:
            name_series.append(i)
data = {}
data['cast_names'] = name_series
utils.writeToJson("cast_series", "extractor/", data)
Esempio n. 30
0
import aws
import utils

from reqasync import run_async
from sys import exit
from time import sleep
from datetime import datetime
from datetime import timedelta

if __name__ == '__main__':
    args = utils.parser()

    print('Reading configuration file')
    benchmark_params = utils.readJson(args.config)

    print('Starting AWS session')
    session = aws.session(benchmark_params['region'],
                          benchmark_params['access_key_id'],
                          benchmark_params['secret_access_key'])

    print('All the AWS services will be created at ' +
          benchmark_params['region'])

    print('Starting AWS S3 client')
    s3_client = session.client('s3')

    bucket_list = s3_client.list_buckets()
    bucket = None

    bucket = aws.createBucket(bucket_list['Buckets'],
                              benchmark_params['bucket_name'], s3_client,
Esempio n. 31
0
def standardBedrijfInfo():
    company = utils.readJson('Resources/company.json')
    if company != {}:
        return company
    return utils.writeJson('Resources/company.json', utils.makeCompany())
Esempio n. 32
0
  def menuProcess(self,request):

    app.logger.debug("in index")
    app.logger.debug(request.form)

    self.request=request
    commandType="menu"
    callback=""
    self.previousMenuName=""
    self.callbackMenuName=""
    roles=[]
    footer=""
    value=""
    self.channel=""
    self.ts=""
    buttonValue=""
    buttonName=""
    valueBeforeParse=""

    self.formJson = json.loads(request.form["payload"])
    self.slackUserName=slack.getSlackUserName(self.formJson)

    if ( "trigger_id" in self.formJson ):
       self.triggerId=self.formJson["trigger_id"]
    else:
       self.triggerId=""

    self.channel=self.formJson["channel"]["id"]
    if ( "message_ts" in self.formJson ):
      self.ts=self.formJson["message_ts"]

    if ( "callback_id" in self.formJson ):
       self.callbackMenuName=self.formJson["callback_id"].split(":")[0]
       self.previousMenuName=self.formJson["callback_id"].split(":")[1]

    if ( "submission" in self.formJson and "type" in self.formJson and self.formJson["type"] == "dialog_submission" ):
       commandType="dialog"

    #load callback menu data
    callbackMenu=utils.readJson("menu/" + self.callbackMenuName + ".json")

    #load previous menu data
    self.previousMenu=utils.readJson("menu/" + self.previousMenuName + ".json")
    app.logger.debug(self.previousMenu)

    if ( isinstance(self.previousMenu , list) and len(self.previousMenu) > 0 and  "footer" in self.previousMenu[0] ):
       footer=self.previousMenu[0]["footer"]

    if ( isinstance(self.previousMenu , list) and not self.previousMenu == {} and "name" in self.previousMenu[0]["actions"][0] ):
      selectName=self.previousMenu[0]["actions"][0]["name"]
    else:
      selectName=""

    if ( isinstance(self.previousMenu , list) and len(self.previousMenu) > 0 and "shared" in self.previousMenu[0] ):
      self.shared=self.previousMenu[0]["shared"]

    if ( "actions" in self.formJson and self.formJson["actions"][0]["type"] == "select" ):

      selectValue=self.formJson["actions"][0]["selected_options"][0]["value"]
      valueBeforeParse=selectValue

      if ( "save:" in selectValue ):
         commandType="menu"
         values=selectValue.split(":")
         value=values[2]
         selectValue=values[1]

      elif ( ":" in selectValue ):
         pos=selectValue.index(":")
         commandType=selectValue[:pos]
         value=selectValue[pos+1:]
      else:
         value=selectValue
 

      if ( self.__checkMenuPermissions(selectValue) == False ):
         return make_response("", 200)

      self.__saveMenu(self.previousMenuName,selectName,selectValue)


    if ( "actions" in self.formJson and self.formJson["actions"][0]["type"] == "button" ):

      buttonValue=self.formJson["actions"][0]["value"]
      buttonName=self.formJson["actions"][0]["name"]
      valueBeforeParse=buttonValue

      userHasRoles=slack.checkSelectedMenuRoles(self.previousMenu,buttonName,"button",self.slackUserName)
      if ( not userHasRoles ):
        response = slack_client.api_call(
          "chat.postMessage",
          channel=self.channel,
          text="@" + self.slackUserName + " *Alert*: `You dont have permission for that operation!`"
        )
        return make_response("", 200)


      if ( ":" in buttonValue ):
         pos=buttonValue.index(":")
         commandType=buttonValue[:pos]
         value=buttonValue[pos+1:]
      elif ( buttonValue == "back" ):
         commandType="menu"
         value=self.callbackMenuName
      elif ( buttonValue == "main" ):
         commandType="menu"
         value=mainMenu
      else:
         value=buttonValue

    value=slack.parseMenuValue(value,self.formJson,self.slackUserName,self.shared)
    app.logger.debug("Post data:" + commandType + "," + value + "," + valueBeforeParse)


    #load menu selection from json
    if ( commandType == "menu" and os.path.isfile( "menu/" + value + ".json" ) ):

       self.__loadMenu(commandType,value,selectName)

    #dialog
    elif ( commandType == "dialog" ):
       self.__dialog(value)

    elif ( commandType == "clearSelect" ):
       self.__clearSelect(value)


    #menu value selected and no menu json file
    elif ( commandType == "menu" and not os.path.isfile( "menu/" + value + ".json" ) ):

       self.__processSelected(commandType,value,selectName)

    #run external script
    elif ( "run" in commandType or "exec" in commandType ):

       validate=slack.validateCommand(valueBeforeParse,self.previousMenu,buttonValue)
       if ( validate == True ):
          self.__runExternal(commandType,value,footer)
       else:
          response = slack_client.api_call(
            "chat.postMessage",
            channel=self.channel,
            text="@" + self.slackUserName + " *Alert*: `Running command is not the same as server command!`"
          )
 
    return make_response("", 200)