Ejemplo n.º 1
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv, 'hlcr')
        if len(opts) == 0:
            print "type python crawlplayers.py -h for help"
            sys.exit(2)
    except getopt.GetoptError:
        print "To run the file use python crawlplayers.py -l -c as options"
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-h":
            print "To run the file use python crawlplayers.py with -h or -i or both as options"
            sys.exit()
        elif opt == "-l":
            for letter in string.ascii_lowercase:
                html = getHtmlForPlayers(letter)
                filename = letter + "-list.txt"
                print "writing file for: " + letter
                writeFile(playerListsFolder + filename, html)
                sleepForAWhile()
        elif opt == "-c":
            getPlayerUsingBs4(playerListsFolder)
        elif opt == "-r":
            getPlayerUsingRegEx(playerListsFolder)
        else:
            print "type python crawlplayers.py -h for help"
            sys.exit()
Ejemplo n.º 2
0
 def run(self, update, packager, distRelease):
     content = ""
     
     # one mail by update
     reminderStr = packager.id + "-" + distRelease.tag + "-" + update.packageName \
             + "-" +  update.bundles[0].version  
     reminders = []
     try:
         if not os.path.exists(config.REMINDER_FILE):
             utils.writeFile(config.REMINDER_FILE, "# Remove this file if you will re-send mail alerts\n", "w")
         content = utils.readFile(config.REMINDER_FILE);
         reminders = content.splitlines()
     except:
         pass
     for r in reminders:
         if r == reminderStr:
             return "skipped"
     content += reminderStr + "\n"
     utils.writeFile(config.REMINDER_FILE, content, 'w')
     
     toaddrs  = packager.mail + "\n"
     subject = "Updates are available for %s \n" % update.packageName
     msg = "To: " + toaddrs + "\n"\
         + "From: " + config.FROM_ADRS + "\n" \
         + "Subject: " + subject + "\n" \
         + "PACKAGE INFO:\n" \
         + str(update) \
         + "\nRELEASE INFO:\n" \
         + str(distRelease)
     server = smtplib.SMTP(config.SMTP_HOSTNAME)
     server.sendmail(config.FROM_ADRS, toaddrs, msg)
     server.quit()
     return "done"
Ejemplo n.º 3
0
    def AddToPlaylist(self, playlistIndex, songIndex):
        if self.playlistDat[playlistIndex][
                "PlaylistName"] == self.currentlyPlayingPlaylist:
            self.AddToQueue(songIndex)

        songIndex = self.fixIndexIfFiltered(songIndex)
        # playlist element format: songName\artistName\albumName\songURL
        if self.state == self.LIBRARY_STATE:
            lineToWrite = self.songDat[songIndex][
                "SongName"] + '\\' + self.artistDat[
                    self.selectedArtist]["ArtistName"] + '\\' + self.albumDat[
                        self.selectedAlbum]["AlbumName"] + '\\' + self.songDat[
                            songIndex]["AudioPath"]
        else:
            lineToWrite = self.playlistSongDat[songIndex][
                "SongName"] + '\\' + self.playlistSongDat[songIndex][
                    "ArtistName"] + '\\' + self.playlistSongDat[songIndex][
                        "AlbumName"] + '\\' + self.playlistSongDat[songIndex][
                            "AudioPath"]

        playlistContent = utils.readFile(
            self.playlistDat[playlistIndex]["PlaylistPath"],
            forceLastVersion=True)
        playlistContent += "\n" if len(
            playlistContent) > 0 and playlistContent[-1] != "\n" else ""
        playlistContent += lineToWrite + '\n'
        utils.writeFile(self.playlistDat[playlistIndex]["PlaylistPath"],
                        playlistContent)
Ejemplo n.º 4
0
 def run(self, update, packager, distRelease):
     result = self._applyTemplate(update, packager, distRelease)
     self.outputFile = os.path.join(
             config.OUTPUT_DIR, packager.dist.ID, 
             packager.name.replace(" ", "_"), distRelease.tag, update.packageName + ".spec")
     
     utils.writeFile(self.outputFile, result, 'w')
     return "done"
Ejemplo n.º 5
0
def init():
    '''Handles command line calls'''
    path = os.getcwd()
    cipherText = utils.openFile(path + '/' + sys.argv[1])
    cipherText = utils.stripWhiteSpace(cipherText)
    key = getKey(cipherText)
    plainText = decryptText(cipherText, key)
    utils.writeFile(path + '/caesar_plain.txt', plainText)
Ejemplo n.º 6
0
def main():
    print("#===== Cifragem RSA =====#")

    plain_text_path = input("Caminho do texto claro: ")
    plain_text = readFile(plain_text_path)
    cipher_text = cipher(plain_text)
    print(f"Texto cifrado escrito para ./textos/texto-cifrado.txt")
    writeFile("./textos/texto-cifrado.txt", cipher_text)
Ejemplo n.º 7
0
def main():
    messages = readFile('plaintexts.txt')
    assert messages, "Empty 'plaintext.txt' file!"
    messagesBytes = [msg.encode() for msg in messages]
    key = randomBytes(max(len(msg) for msg in messagesBytes))
    ciphertexts = [encrypt(key, msg).hex() for msg in messagesBytes]
    writeFile('ciphertexts.txt', ciphertexts)
    writeFile('keys.txt', [key.hex()])
Ejemplo n.º 8
0
def init():
    '''Handles command line calls'''
    path = os.getcwd()
    cipherText = utils.openFile(path + '/' + sys.argv[1])
    cipherText = utils.stripWhiteSpace(cipherText)
    key = getKey(cipherText)
    plainText = decryptText(cipherText, key)
    utils.writeFile(path + '/caesar_plain.txt', plainText)
Ejemplo n.º 9
0
def testIgnoreInput():
    for (progName, inString, solution) in [
            ('containsGAGA.py', 'GAGAGAGAG', 'yes'), \
            ('containsGAGA.py', 'TTTTGGCCGGT', 'no') ]:
        utils.writeFile('progString.txt', rf(progName))
        utils.writeFile('inString.txt', inString)
        val = ignoreInput('irrelevant input')
        utils.tprint((progName, inString), ":", val)
        assert val == solution
Ejemplo n.º 10
0
def runner(packet_names_chunk):
    uid = str(uuid.uuid4())
    file_path = os.path.join(statPath, uid + ".log")
    m = MinioWrapper()
    coui = 1
    for packet_name in packet_names_chunk:
        migrate(m, packet_name)
        writeFile(file_path,
                  str(coui) + " out of " + str(len(packet_names_chunk)) + "\n")
        coui = coui + 1
Ejemplo n.º 11
0
def main():
    messages = readFile('plaintexts.txt')
    assert messages, "Empty 'plaintext.txt' file!"
    messagesBytes = [msg.encode() for msg in messages]
    keys = [randomBytes(len(msg)) for msg in messagesBytes]
    ciphertexts = [
        encrypt(key, msg).hex() for key, msg in zip(keys, messagesBytes)
    ]
    writeFile('ciphertexts.txt', ciphertexts)
    writeFile('keys.txt', [key.hex() for key in keys])
Ejemplo n.º 12
0
def init():
    '''Handles command line calls'''
    path = os.getcwd()
    cypherTxt = utils.openFile(path + '/' + sys.argv[1])
    cypherTxt = utils.stripWhiteSpace(cypherTxt)
    # cypherText = ''.join(reversed(cypherTxt))
    keyLength = ioc.estimateKeyLength(cypherTxt)
    key = findKey(cypherTxt, keyLength)
    print "Final Key: %s of length %d" % (key, keyLength)
    plainText = decryptText(cypherTxt, key)
    utils.writeFile(path + '/vigenere_plain.txt', plainText)
Ejemplo n.º 13
0
def testAlterYoEToEoE():
    testvals = [
        ('containsGAGA.py', 'a non-empty string'),
        ('isEmpty.py', ''),
    ]
    for (progName, solution) in testvals:
        progString = rf(progName)
        utils.writeFile('progString.txt', progString)
        val = alterYoEToEoE('')
        utils.tprint(progName, ":", val)
        assert val == solution
Ejemplo n.º 14
0
def testAlterYesToComputesF():
    from F import F
    from G import G  # G is any computable function different to F
    F_input = 'xxxx'
    for (progName, inString,
         solution) in [('containsGAGA.py', 'GAGAGAGAG', F(F_input)),
                       ('containsGAGA.py', 'TTTTGGCCGGT', G(F_input))]:
        utils.writeFile('progString.txt', rf(progName))
        utils.writeFile('inString.txt', inString)
        val = utils.runWithTimeout(None, alterYesToComputesF, F_input)
        utils.tprint((progName, inString), ":", val)
        assert val == solution
Ejemplo n.º 15
0
    def start(self):
        n_jobs = len(self.jobs)
        print("Worker {} started with {} jobs".format(str(self.wid),
                                                      str(n_jobs)))

        last_day = datetime.now().day
        last_timestamp = int(time.time())
        first = True
        while True:
            curr_day = datetime.now().day
            if curr_day != last_day:
                break

            if first == False:
                curr_timestamp = int(time.time())

                time_diff = curr_timestamp - last_timestamp
                if time_diff > self.min_wait:
                    mag_late = "- Late! " + str(time_diff)
                    print(mag_late)
                    logging.info(mag_late)

                while curr_timestamp - last_timestamp < self.min_wait:
                    time.sleep(1)
                    curr_timestamp = int(time.time())
                last_timestamp = curr_timestamp
            else:
                first = False

            msg = "- Worker {} : new check at {}".format(
                str(self.wid),
                datetime.now().strftime("%H:%M:%S"))
            print(msg)
            logging.info(msg)

            for isin, link in self.jobs:

                if link in ["#N/A", '']:
                    continue

                content, content_html = self.getRequestSelenium(link)
                if content == '':
                    continue

                now = datetime.now()
                current_time = now.strftime("%H_%M_%S")
                fname = "results/{}/{}_{}.html".format(self.out_dir, isin,
                                                       current_time)
                utils.writeFile(fname, content_html)

        self.driver.quit()
Ejemplo n.º 16
0
    def createLdifs(self):
        utils.writeFile("Creating the schema as a ldif file (user.ldif)", "user.ldif", """
dn: cn=user,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: user
olcAttributeTypes: ( 1.1.2.1.1 NAME '%(owner)s' DESC 'Owner ID' SUP name )
olcAttributeTypes: ( 1.1.2.1.2 NAME '%(alias)s' DESC 'Alias DN' SUP name )
olcObjectClasses: ( 1.1.2.2.1 NAME 'user' DESC 'Define user' SUP top STRUCTURAL MUST ( %(uid)s $ %(owner)s ) MAY ( %(alias)s ) )
""" % {"uid": self.cget("user_id"), "owner": self.cget("attribute_owner"), "alias": self.cget("attribute_alias")})
        group_value = self.cget("user_group").split("=")[-1]
        utils.writeFile("Creating the user group as a ldif file (usergroup.ldif)", "usergroup.ldif", """
dn: %(group)s,%(dn)s
objectclass: top
objectclass: organizationalUnit
ou: %(group_val)s
description: users
""" % {"group": self.cget("user_group"), "group_val": group_value, "dn": self.cget("base_dn")} )
        utils.writeFile("Creating the user 'superadmin' as a ldif file (superadmin.ldif)", "superadmin.ldif", """
dn: %(uid)s=superadmin,%(group)s,%(dn)s
objectclass: top
objectclass: user
%(uid)s: superadmin
%(owner)s: superadmin
""" % {"uid": self.cget("user_id"), "group": self.cget("user_group"), "dn": self.cget("base_dn"), "owner": self.cget("attribute_owner")} )
        utils.writeFile("Creating the user '%(anonymous)s' as ldif file (anonymous.ldif)", "anonymous.ldif", """
dn: %(uid)s=%(anonymous)s,%(group)s,%(dn)s
objectclass: top
objectclass: user
%(uid)s: %(anonymous)s
%(owner)s: anonymous
""" % {"anonymous": CONFIG.get("global", "anonymous_user"), "uid": self.cget("user_id"), "group": self.cget("user_group"), "dn": self.cget("base_dn"), "owner": self.cget("attribute_owner")} )
Ejemplo n.º 17
0
    def CreatePlaylist(self, text):
        playlistFolder = utils.config["playlistFolder"]
        playlistFolder += "/" if playlistFolder[-1] != "/" else ""
        pathToNewPlaylist = playlistFolder + utils.nameToDirectoryName(
            text) + ".dat"
        utils.writeFile(pathToNewPlaylist, "")

        playlistRoot = utils.config["playlistRoot"]
        playlistRootContent = utils.readFile(playlistRoot,
                                             forceLastVersion=True)
        playlistRootContent += "\n" if len(
            playlistRootContent
        ) > 0 and playlistRootContent[-1] != "\n" else ""
        playlistRootContent += text + "\\" + pathToNewPlaylist
        utils.writeFile(playlistRoot, playlistRootContent)
Ejemplo n.º 18
0
def build():
    allCtrl = blocks.Ctrl(name='all_ctrl', shape=Ctrl.CIRCLE, radius=20,
                          normal=[0,1,0], color=Ctrl.YELLOW, group=False).ctrl
    rootLoc = pm.PyNode('root_loc')
    rootJoint = utils.placeXform(name="m_root_%s" % defines.BIND, mtype='joint',
                                  matrix=rootLoc.getMatrix(worldSpace=True),
                                  worldSpace=True, parent=allCtrl)
    rootCtrl = InlineOffset(
                     rootJoint, name='m_root_%s' % defines.CTRL,
                     controlShape=Ctrl.CIRCLE, controlRadius=15,
                     controlColor=Ctrl.YELLOW)

    #
    # Inner Tentacles
    #

    innerTentacles(allCtrl, rootCtrl)

    #
    # LOWER BELL
    #
    bell(allCtrl, rootCtrl)
    
    #
    # Outer Tentacles
    #
    outerTentacles(allCtrl)
    
    #
    # SKIN
    #
    skin.bind(skinDict)

    pm.PyNode(u'upperBellLatticeBase').setParent(rootCtrl.controls[0])

    upperBellDefVerts = [MeshVertex(u'headDomeShapeDeformed.vtx[0:421]'), MeshVertex(u'headDomeShapeDeformed.vtx[426:431]'), MeshVertex(u'headDomeShapeDeformed.vtx[433:434]'), MeshVertex(u'headDomeShapeDeformed.vtx[436:437]'), MeshVertex(u'headDomeShapeDeformed.vtx[439:442]'), MeshVertex(u'headDomeShapeDeformed.vtx[444:445]'), MeshVertex(u'headDomeShapeDeformed.vtx[458:461]'), MeshVertex(u'headDomeShapeDeformed.vtx[474:477]'), MeshVertex(u'headDomeShapeDeformed.vtx[480:481]'), MeshVertex(u'headDomeShapeDeformed.vtx[483:486]'), MeshVertex(u'headDomeShapeDeformed.vtx[488:489]'), MeshVertex(u'headDomeShapeDeformed.vtx[491:492]'), MeshVertex(u'headDomeShapeDeformed.vtx[494:496]'), MeshVertex(u'headDomeShapeDeformed.vtx[498]'), MeshVertex(u'headDomeShapeDeformed.vtx[511:514]'), MeshVertex(u'headDomeShapeDeformed.vtx[524:526]'), MeshVertex(u'headDomeShapeDeformed.vtx[528:530]'), MeshVertex(u'headDomeShapeDeformed.vtx[532:535]'), MeshVertex(u'headDomeShapeDeformed.vtx[537:543]'), MeshVertex(u'headDomeShapeDeformed.vtx[545:547]'), MeshVertex(u'headDomeShapeDeformed.vtx[549:553]'), MeshVertex(u'headDomeShapeDeformed.vtx[555:559]'), MeshVertex(u'headDomeShapeDeformed.vtx[561:563]'), MeshVertex(u'headDomeShapeDeformed.vtx[585:595]'), MeshVertex(u'headDomeShapeDeformed.vtx[620:633]'), MeshVertex(u'headDomeShapeDeformed.vtx[636:638]'), MeshVertex(u'headDomeShapeDeformed.vtx[640:644]'), MeshVertex(u'headDomeShapeDeformed.vtx[646:650]'), MeshVertex(u'headDomeShapeDeformed.vtx[652:654]'), MeshVertex(u'headDomeShapeDeformed.vtx[656:660]'), MeshVertex(u'headDomeShapeDeformed.vtx[662:666]'), MeshVertex(u'headDomeShapeDeformed.vtx[668:669]'), MeshVertex(u'headDomeShapeDeformed.vtx[694:705]'), MeshVertex(u'headDomeShapeDeformed.vtx[727:750]'), MeshVertex(u'headDomeShapeDeformed.vtx[760:765]'), MeshVertex(u'headDomeShapeDeformed.vtx[778:801]'), MeshVertex(u'headDomeShapeDeformed.vtx[814:821]'), MeshVertex(u'headDomeShapeDeformed.vtx[834:873]'), MeshVertex(u'headDomeShapeDeformed.vtx[922:953]'), MeshVertex(u'headDomeShapeDeformed.vtx[1002:1105]'), MeshVertex(u'headDomeShapeDeformed.vtx[1154:1177]'), MeshVertex(u'headDomeShapeDeformed.vtx[1214:1296]'), MeshVertex(u'headDomeShapeDeformed.vtx[1339:1362]'), MeshVertex(u'headDomeShapeDeformed.vtx[1411:1414]'), MeshVertex(u'headDomeShapeDeformed.vtx[1417:1427]'), MeshVertex(u'headDomeShapeDeformed.vtx[1430:1441]'), MeshVertex(u'headDomeShapeDeformed.vtx[1444:1449]'), MeshVertex(u'headDomeShapeDeformed.vtx[1452:1463]'), MeshVertex(u'headDomeShapeDeformed.vtx[1466:1477]'), MeshVertex(u'headDomeShapeDeformed.vtx[1480:1485]'), MeshVertex(u'headDomeShapeDeformed.vtx[1490:1517]'), MeshVertex(u'headDomeShapeDeformed.vtx[1566:1587]'), MeshVertex(u'headDomeShapeDeformed.vtx[1630:1635]'), MeshVertex(u'headDomeShapeDeformed.vtx[1638:1649]'), MeshVertex(u'headDomeShapeDeformed.vtx[1652:1663]'), MeshVertex(u'headDomeShapeDeformed.vtx[1666:1671]'), MeshVertex(u'headDomeShapeDeformed.vtx[1674:1691]'), MeshVertex(u'headDomeShapeDeformed.vtx[1694:1701]'), MeshVertex(u'headDomeShapeDeformed.vtx[1704:1709]'), MeshVertex(u'headDomeShapeDeformed.vtx[1712:2583]'), MeshVertex(u'headDomeShapeDeformed.vtx[2632:2663]'), MeshVertex(u'headDomeShapeDeformed.vtx[2712:2823]'), MeshVertex(u'headDomeShapeDeformed.vtx[2872:2895]'), MeshVertex(u'headDomeShapeDeformed.vtx[2932:3361]')]

    pm.skinPercent('skinCluster84', upperBellDefVerts, 
                   transformValue = [(rootJoint,1.0)])
    pm.reorderDeformers(u'upperBellLattice',u'skinCluster84',
                        u'model:headDome')
    pm.reorderDeformers(u'upperBellLattice',u'skinCluster48',
                        u'model:innerDome')

    # save skin dict
    utils.writeFile('rigPirateCaptain_skin.json',skinDict)
Ejemplo n.º 19
0
def main():
    print("\n#===== Decifragem RSA =====#")

    option = None
    while True:
        print("1 - Gerar Chaves")
        print("2 - Decifrar Texto")
        option = input("Escolha: ")
        if (option == "1"):
            # Criar chaves publicas e privadas
            print("#=== Gerando Chaves ===#")
            public_key, private_key = createKeys(151, 139)

            writeFile("./public-key.txt", public_key)
            writeFile("./private-key.txt", private_key)
            print(f"Chave pública escrita em public-key.txt")
            print(f"Chave privada escrita em private-key.txt")
            break
        elif(option == "2"):
            cipher_text_path = input("Caminho do texto cifrado: ")
            cipher_text = readFile(cipher_text_path)
            deciphered_text = decipher(cipher_text)
            print(f"Texto decifrado escrito para ./textos/texto-decifrado.txt")
            writeFile("./textos/texto-decifrado.txt", deciphered_text)
            break
Ejemplo n.º 20
0
def writeDomainMap():
    global excel_data
    domain_map_name = "domain_map.json"

    domain_map_obj = excel_data.getObjBySheetName(rootConfig.SHEET_DOMAIN,
                                                  True)

    real_domain_map = {}  #重新生成一份新的映射表
    for name_key, domain_value in domain_map_obj.items():
        domain_data = {}
        domain_data["server_list"] = {}  #单独存一个,后续进行排序用
        real_domain_map[str(domain_value["domain"].replace(
            " ", ""))] = domain_data  #以域名为key,取出空格
        del domain_value["domain"]  #删掉域名key
        for key, value in domain_value.items():
            key_list = key.split("_")
            if len(key_list) > 1:
                server_list = domain_data["server_list"]
                key_type = key_list[0]
                key_index = int(key_list[1])
                if server_list.has_key(key_index) == False:
                    server_list[key_index] = {"index": key_index}  #加上index用做排序
                temp_dict = server_list[key_index]
                temp_dict[key_type] = value
            else:
                domain_data[key] = value

    for domain_url, domain_list in real_domain_map.items():
        server_list = []
        for server_key, server_data in domain_list["server_list"].items():
            server_list.append(server_data)

        # server_list.sort(reverse=True) #测试排序
        server_list.sort(key=lambda x: x["index"])
        # domain_list["server_list"] = server_list
        real_domain_map[domain_url] = server_list

    utils.writeFile(rootConfig.WRITE_PACK_PATH, domain_map_name,
                    utils.objToJson(real_domain_map))
Ejemplo n.º 21
0
    def myCompile(self, cfg, executionTime):

        # Fetch the configuration
        indexes = utils.getIndexesOfLength(cfg, len(self.designSpace) - 1)

        # Erase parameters that do not make sense
        self.eraseUselessParameters(indexes)

        # Write the configuration to the INDEX_FILE file
        inputName = os.environ['INPUT_NAME']
        outputFile = os.environ['INDEX_FILE']
        utils.writeFile(outputFile, indexes)

        repoPath = os.environ['REPO_PATH']
        if (self.finalConfFlag):
            args = self.args

            hostname = socket.gethostname()
            benchmarkName = args['benchmark']

            configJson = args['configBenchmarkJson']
            numOfCores = configJson['numOfCores']
            htFlag = configJson['HT']
            pwFlag = configJson['PW']

            modeStr = 'REG'
            if (htFlag):
                modeStr = 'HT'
            if (pwFlag):
                modeStr += '/PW'

            bestConfFile = repoPath + '/data/' + benchmarkName + '/' + hostname + '/' + modeStr + '/' + str(
                numOfCores) + '/' + inputName + '/bestConfiguration.json'
            bestConf = {'conf': indexes, 'time': executionTime}
            utils.writeJson(bestConfFile, bestConf)

        return os.system(
            repoPath + '/src/scripts/backEnd'
        )  # generate the binary of the best configuration found
Ejemplo n.º 22
0
    def postConfigure(self):
        if self.cget("create_file"):
            zone = self.cget("vendor_prefix") + "." + self.cget("domain_prefix")
            email = self.cget("email")
            date = datetime.date.today()
            serial = "%04d%02d%02d00" % (date.year, date.month, date.day)
            server = self.cget("server")
            comurl = self.cget("home_page")
            dsurl = CONFIG.get("ds", "url")
            dsetaurl = CONFIG.get("dseta", "url") + "ided_ds/"
            utils.writeFile("Creating ONS zone template", self.cget("filename"),
"""
;; 
$TTL 1d

;; zone
$ORIGIN %s

@ IN SOA localhost %s (
                        %s ; serial
                        3h         ; refresh
                        1h         ; retry
                        1d         ; expire
                        1h         ; cache
                        )

;; this server is the nameserver for this zone
;  IN NS %s.

; NAPTRs for products
;; example product
;;                 order pref flags service    regex                                                   replacement
;2.1.0.9.8  IN NAPTR 0     0    "u"   "epc+html" "!^.*$!%s!"                  .
;           IN NAPTR 1     0    "u"   "epc+ds"   "!^.*$!%s!" .
;           IN NAPTR 2     0    "u"   "epc+ided_ds"   "!^.*$!%s!" .
"""
                            % (zone, email, serial, server, comurl, dsurl, dsetaurl)) 
            utils.putWarning("This is just a template. You need to complete it with products ids.")
Ejemplo n.º 23
0
    def on_done(self, path, name):
        pagePath = os.path.join(path, name)
        if os.path.exists(pagePath):
            sublime.error_message("Unable to create page, page exists.")
        else:
            os.makedirs(pagePath)
            utils.writeFile(os.path.join(pagePath, "%s.js" % name),
                            PAGE_JS.replace('${name}', name))
            utils.writeFile(os.path.join(pagePath, "%s.wxml" % name),
                            PAGE_WXML)
            utils.writeFile(os.path.join(pagePath, "%s.wxss" % name),
                            PAGE_WXSS)

            sublime.active_window().open_file(
                os.path.join(pagePath, "%s.js" % name))
            sublime.status_message("WX page create success!")
Ejemplo n.º 24
0
            jsonNetWork = networks[networkName]
            network = Network(jsonNetWork['type'], jsonNetWork['paraDict'],
                              networkName)
            layer2.addNetwork(network)
        CNN.addLayer(layer2)

        layer3 = Layer(str3['name'])
        networks = str3['networks']
        for networkName in networks:
            jsonNetWork = networks[networkName]
            network = Network(jsonNetWork['type'], jsonNetWork['paraDict'],
                              networkName)
            layer3.addNetwork(network)
        CNN.addLayer(layer3)

        layer4 = Layer(str4['name'])
        networks = str4['networks']
        for networkName in networks:
            jsonNetWork = networks[networkName]
            network = Network(jsonNetWork['type'], jsonNetWork['paraDict'],
                              networkName)
            layer4.addNetwork(network)
        CNN.addLayer(layer4)

        for rule in str5:
            if rule != 'name':
                CNN.addForwardRule(str5[rule])

        sentenceList = CNN.toSentenceList()
        writeFile('./CNN.py', sentenceList)
Ejemplo n.º 25
0
    def report(self):
        '''
        write the values out to files
        
        The values of the monitored EPICS PVs (the "raw data")
        is written to an XML file.  This file is then used
        with one or more XSLT stylesheets to create HTML pages.
        An overall "home page" (index.html) is created to provide
        a table of contents of this static web site.
        '''
        xmlText = self.buildReport()
        utils.writeFile(XML_RAWDATA_FILE_NAME, xmlText)

        # accumulate list of each file written below
        www_site_file_list = []
        xslt_file_list_used = [
            'index.xsl',
        ]  # do the index.xsl file last
        www_site_file_list.append(XML_RAWDATA_FILE_NAME)

        # add pvlist.xml to file list
        pvlist_xml_file_name = self.configuration['PVLIST_FILE']
        www_site_file_list.append(pvlist_xml_file_name)

        # add pvlist.xsl to file list
        xslt_file_name = XSL_PVLIST_FILE_NAME
        if os.path.exists(xslt_file_name):
            _xslt_(xslt_file_name, pvlist_xml_file_name)
            xslt_file_list_used.append(xslt_file_name)

        # add report.xml to file list
        report_xml_file_name = XML_RAWDATA_FILE_NAME
        if os.path.exists(report_xml_file_name):
            # write "report.xml"    : values of monitored EPICS PVs
            www_site_file_list.append(report_xml_file_name)

            xslt_file_name = XSL_RAWDATA_FILE_NAME
            if os.path.exists(xslt_file_name):
                _xslt_(xslt_file_name, report_xml_file_name)
                xslt_file_list_used.append(xslt_file_name)

                # convert all .xsl files
                xslt_files = fnmatch.filter(os.listdir('.'), '*.xsl')
                for xslt_file_name in xslt_files:
                    if xslt_file_name not in xslt_file_list_used:
                        _xslt_(xslt_file_name, report_xml_file_name)

        # finally, write index.html from file list, table of files and descriptions as provided
        xslt_file_name = XSL_INDEX_FILE_NAME
        if os.path.exists(xslt_file_name):
            # TODO: each XSLT file has a "description" attribute
            #  This could be used when building "index.html" file
            #  For now, this is manually copied from .xsl file to the table in index.xsl
            #  To automate this process, a new, temporary XML document will need to be
            #  created with the names and descriptions of all HTML pages.
            #  Then use that XML in the following XSLT.
            #  Also should add a time stamp string.
            _xslt_(xslt_file_name, report_xml_file_name)

        # include any other useful files from the project directory
        local_files = os.listdir('.')
        for file_pattern in self.upload_patterns:
            www_site_file_list += fnmatch.filter(local_files, file_pattern)
            www_site_file_list += fnmatch.filter(local_files,
                                                 file_pattern.upper())

        # only copy files if web_site_path is not the current dir
        www_site_file_list = sorted(set(www_site_file_list))
        www_site_path = os.path.abspath(
            self.configuration['LOCAL_WWW_LIVEDATA_DIR'])
        if www_site_path != os.path.abspath(os.getcwd()):
            for fname in www_site_file_list:
                utils.copyToWebServer(fname, www_site_path)
Ejemplo n.º 26
0
import utils 
import defines
reload(utils)
#reload(blocks)
reload(skin)
reload(defines)

NAMESPACE = 'model:'

#
# Save the locators to file...just in case
#
loc_shapes = pm.ls(exactType='locator')
locs = [x.getParent() for x in pm.ls(exactType='locator')]
json = [utils.genNodeEntry(x) for x in locs]
utils.writeFile('rigPirateCaptain_locs.json',json)


ctrls = []
allCtrl = None
root = None

skinDict = {
        # namespace:{
        #   SMOOTH:{mesh:[joints,],},
        #   RIGID:{joint:[meshes,],}, }

        NAMESPACE:{
            skin.SMOOTH:{ },#SMOOTH
            skin.RIGID:{  },#RIGID
            },#'model:'
Ejemplo n.º 27
0
def writeUpdateInfo():
    global excel_data
    file_name = "update_info.json"
    obj = excel_data.getObjBySheetName(rootConfig.SHEET_UPDATE_INFO, True)
    utils.writeFile(rootConfig.WRITE_PACK_PATH, file_name,
                    utils.objToJson(obj))
Ejemplo n.º 28
0
def writeBaseCfg():
    global excel_data
    file_name = "base_config.json"
    obj = excel_data.getObjBySheetName(rootConfig.SHEET_BASE_CONFIG, True)
    utils.writeFile(rootConfig.WRITE_PACK_PATH, file_name,
                    utils.objToJson(obj))
Ejemplo n.º 29
0
def writeProjCfg():
    global excel_data
    file_name = "project.json"
    obj = excel_data.getObjBySheetName(rootConfig.SHEET_PROJECT, True)
    utils.writeFile(rootConfig.WRITE_PACK_PATH, file_name,
                    utils.objToJson(obj))
Ejemplo n.º 30
0
 def write(self, path, buf, offset, fh):
     path = self._full_path(path)
     print 'Writing with path = {0}, len(buf) = {1}, offset = {2}'.format(
         path, str(len(buf)), str(offset))
     yolo = writeFile(path, offset, buf)
     return yolo
Ejemplo n.º 31
0
def _runHaskellTests(assignment, file, cmdList, logFile, kind: Literal['student', 'instructor']):
    resultScript = runTestScriptIfExisting(assignment, kind)
    if resultScript is None:
        if cmdList is not None:
            result = shell.run(['timeout', '--signal', 'KILL', '10'] + cmdList, onError='ignore',
                               captureStdout=True, stderrToStdout=True)
        else:
            print(red(f'No way to run {kind} tests'))
            return
    else:
        result = resultScript
    outLines = massageTestOutput(result.stdout)
    out = '\n'.join(outLines)
    errMsg = None
    okMsg = None
    resultStr = None
    if result.exitcode in [0, 1]:
        logLines = ["Output of running instructor's tests",
                    "=====================================",
                    ""]
        lastCasesLine = None
        cases = None
        failing = None
        for line in outLines:
            m = haskellTestRe.match(line)
            if m:
                cases = int(m.group(1))
                errors = int(m.group(3))
                failures = int(m.group(4))
                failing = errors + failures
                lastCasesLine = line
            else:
                logLines.append(line)
        logLines.append('')
        if lastCasesLine:
            logLines.append(lastCasesLine)
        utils.writeFile(logFile, removeRedundantNewlines(logLines))
        if cases is None:
            if resultScript is not None:
                if resultScript.exitcode == 0:
                    resultStr = 1.0
                    okMsg = f'Test script executed succesfully'
                else:
                    errMsg = f"Test script returned exit code {resultScript.exitcode}"
                    resultStr = 0.0
            else:
                errMsg = f'No test output found for {file}'
                resultStr = 'no test output'
        elif failing:
            errMsg = f'{failing} failing tests for {file}'
            resultStr = round(1 - failing/cases, 2)
        elif cases == 0:
            errMsg = f'No tests defined in {file}'
            if kind == 'student':
                resultStr = 'no tests'
            else:
                resultStr = 1.0
        else:
            okMsg = f'Tests for {file} OK ({cases} test cases)'
            resultStr = 1.0
    elif result.exitcode in [124, -9]:
        errMsg = f'Test TIMEOUT'
        resultStr = 'timeout'
        utils.writeFile(logFile, out)
    else:
        errMsg = f'Tests for {file} FAILED with exit code {result.exitcode}, see above'
        resultStr = 'run failed'
        utils.writeFile(logFile, out)
    if errMsg:
        if result.exitcode in [0, 1]:
            print(out)
        else:
            print(result.stdout)
        print(red(errMsg))
    elif okMsg:
        print(green(okMsg))
    else:
        abort('BUG: neiter errMsg nor okMsg was set')
    return resultStr
Ejemplo n.º 32
0
    def on_done(self, path, name):
        filePath = path
        # if os.path.exists(filePath):
        # 	sublime.error_message("Unable to create project, project exists.")
        # else:
        # os.makedirs(filePath)

        utils.writeFile(os.path.join(filePath, "app.js"), APP_JS)
        utils.writeFile(os.path.join(filePath, "app.json"),
                        APP_JSON.replace('${projectName}', name))
        utils.writeFile(os.path.join(filePath, "app.wxss"), APP_WXSS)
        # utils
        utilPath = os.path.join(filePath, "utils")
        os.makedirs(utilPath)
        utils.writeFile(os.path.join(utilPath, "utils.js"), UTILS_JS)
        # pages
        pagePath = os.path.join(filePath, "pages")
        # index page
        indexPagePath = os.path.join(pagePath, "index")
        os.makedirs(indexPagePath)
        utils.writeFile(os.path.join(indexPagePath, "index.js"),
                        PAGE_JS.replace('${name}', 'index'))
        utils.writeFile(os.path.join(indexPagePath, "index.wxml"), PAGE_WXML)
        utils.writeFile(os.path.join(indexPagePath, "index.wxss"), PAGE_WXSS)
        # test page
        textPagePath = os.path.join(pagePath, "test")
        os.makedirs(textPagePath)
        utils.writeFile(os.path.join(textPagePath, "test.js"),
                        PAGE_JS.replace('${name}', 'test'))
        utils.writeFile(os.path.join(textPagePath, "test.wxml"), PAGE_WXML)
        utils.writeFile(os.path.join(textPagePath, "test.wxss"), PAGE_WXSS)

        sublime.active_window().open_file(os.path.join(filePath, "app.js"))
        sublime.status_message("WX project create success!")
Ejemplo n.º 33
0
def yesViaEmpty(progString, inString):
    utils.writeFile('progString.txt', progString)
    utils.writeFile('inString.txt', inString)
    return yesOnEmpty(rf('ignoreInput.py'))
    def gestionConnexionClient(self):  # fonction appelée lorsqu'une connexion client entrante survient
        print ("Une connexion entrante est détectée")

        # -- connexion du client --
        self.clientTcpDistant = (
            self.serveurTcp.nextPendingConnection()
        )  # récupère le TcpSocket correspondant au client connecté
        # l'objet client est un  TcpSocket et dispose donc de toutes les fonctions du TcpSocket

        etatConnexion = self.clientTcpDistant.waitForConnected(5000)  # attend connexion pendant 5 secondes maxi

        # message état connexion
        if etatConnexion:  # si la connexion est OK ..
            print ("Connexion au serveur OK !")
            print (
                "IP du client connecté : " + str(self.clientTcpDistant.peerAddress().toString())
            )  # affiche IP du client distant
            self.lineEditIPClientDistant.setText(self.clientTcpDistant.peerAddress().toString())  # MAJ champ IP client
            print (
                "IP du serveur local : " + str(self.clientTcpDistant.localAddress().toString())
            )  # affiche IP du serveur local auquel le client est connecté
            self.lineEditIPServeurLocal.setText(self.clientTcpDistant.localAddress().toString())  # MAJ champ IP serveur
        else:
            print ("Connexion au serveur impossible...")
            # exit # sort du try mais reste dans la fonction def
            return  # sort de def

            # suite si la connexion est ok...

            # -- lecture des données en réception = réception de la requête du client distant
        test = self.clientTcpDistant.waitForReadyRead()  # attendre que client soit prêt pour réception de données
        if test == True:
            print ("Données client distant prêtes")
        else:
            print ("Données client distant pas prêtes")

        chaineTrans = str(
            self.clientTcpDistant.readAll()
        )  # lit les données en réception - première lecture - readAll lit ligne à ligne...
        # chaineTrans =str(self.clientTcpLocal.readData(1024)) # lit les données en réception - première lecture - read() lit ligne à ligne...
        chaineReception = ""
        # print chaineTrans - debug

        # while len(chaineTrans): # tant que chaine Trans pas vide - obligé car réception ligne à ligne
        while chaineTrans != "":  # tant que chaine Trans pas vide - obligé car réception ligne à ligne
            chaineReception = chaineReception + chaineTrans
            chaineTrans = ""  # RAZ chaine Trans

            test = self.clientTcpDistant.waitForReadyRead(
                1000
            )  # attendre que client soit à nouveau prêt pour réception de données
            if test == True:  # si prêt à recevoir données
                # print ("Client prêt à recevoir des données")
                chaineTrans = str(self.clientTcpDistant.readAll())  # lit la suite des données en réception
                # chaineTrans =str(self.clientTcpLocal.readData(1024)) # lit la suite des données en réception - read() lit ligne à ligne...
                # print self.clientTcpLocal.isOpen() # debug
                # print (">"+chaineTrans) # debug
                # else:
                # 	print("Client pas prêt à recevoir des données")

                # -- fin réception réponse client

                # si on veut message erreur si problème, utiliser readData(taillemax)
        print ("Données reçues : ")
        print ("-------------------------------------------")
        print chaineReception
        print ("-------------------------------------------")

        self.textEditReceptionReseau.append(chaineReception)  # ajoute réception à la zone texte

        # -- +/- analyse de la requete reçue --

        # ------> analyse si la chaine reçue est une requete GET avec chaine format /&chaine= càd si requête Ajax--------
        if chaineReception.startswith("GET /&"):
            print ("Requête AJAX reçue")
            reponseAjax = ""  # pour mémoriser éléments de la réponse Ajax au fur et à mesure analyse

            # ----- extraction de la chaine allant de & à =
            indexStart = chaineReception.find("&")  # position debut
            print ("indexStart = " + str(indexStart))  # debug
            indexEnd = chaineReception.find("=")  # position fin
            print ("indexEnd = " + str(indexEnd))  # debug

            chaineAnalyse = chaineReception[
                indexStart + 1 : indexEnd
            ]  # garde chaine fonction(xxxx) à partir de GET /&fonction(xxxx)=
            # [a:b] 1er caractère inclusif (d'où le +1) , dernier exclusif
            print ("Chaine recue : " + chaineAnalyse)  # debug

            # ---------------------->>  +/- ici analyse de la chaine  <<------------------

            # --- ls ( ) --
            # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "ls(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                # if (result=="/"):
                cheminAbsolu = self.lineEditCheminRep.text() + result  # le chemin absolu à utiliser
                contenu = utils.getContentDir(cheminAbsolu)  # getContentDir renvoie chaîne
                print (contenu)  # affiche le contenu du rép -
                self.textEdit.setText(contenu)  # efface le champ texte et affiche le fichier à la zone texte
                reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax

                # --- read ( ) --
                # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "read(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                # if (result=="/"):
                cheminAbsolu = self.lineEditCheminRep.text() + "/" + result  # le chemin absolu à utiliser
                # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne
                contenu = utils.readFile(cheminAbsolu)  # readFile renvoie chaine
                print (contenu)  # affiche le contenu du fichier
                reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax

                # --- lines ( ) --
                # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "lines(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                # if (result=="/"):
                cheminAbsolu = self.lineEditCheminRep.text() + "/" + result  # le chemin absolu à utiliser
                # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne
                contenu = str(utils.getNumberOfLines(cheminAbsolu))  # getNumberOfLines renvoie int - nombre de lignes
                print (contenu)  # affiche le contenu du fichier
                reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax

                # --- size ( fichier) --
                # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "size(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                # if (result=="/"):
                cheminAbsolu = self.lineEditCheminRep.text() + "/" + result  # le chemin absolu à utiliser
                # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne
                contenu = str(utils.sizeFile(cheminAbsolu))  # getNumberOfLines renvoie int - nombre de lignes
                print (contenu)  # affiche le contenu du fichier
                reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax

                # --- write ( ) --
                # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "write(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                subResult = result.split(",")  # sépare les sous chaînes séparées par ,
                print subResult

                if len(subResult) == 2:  # si on a bien 2 sous chaînes
                    # if (result=="/"):
                    cheminAbsolu = self.lineEditCheminRep.text() + "/" + subResult[0]  # le chemin absolu à utiliser
                    # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne
                    contenu = utils.writeFile(cheminAbsolu, str(subResult[1]) + "\n")  # writeFile renvoie chaine
                    print (contenu)  # affiche le contenu du fichier
                    reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax
                else:
                    reponseAjax = reponseAjax + "Erreur format\n"  # ajoute à la réponse Ajax

                    # --- getline ( fichier, ligne) --
                    # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "getline(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                subResult = result.split(",")  # sépare les sous chaînes séparées par ,
                print subResult

                if len(subResult) == 2:  # si on a bien 2 sous chaînes
                    # if (result=="/"):
                    cheminAbsolu = self.lineEditCheminRep.text() + "/" + subResult[0]  # le chemin absolu à utiliser
                    if subResult[1].isalnum():  # si 2ème param est bien en chiffres
                        contenu = utils.getLine(cheminAbsolu, str(subResult[1]))  # getLine renvoie chaine
                        print (contenu)  # affiche le contenu du fichier
                        reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax
                    else:
                        reponseAjax = reponseAjax + "Erreur format\n"  # ajoute à la réponse Ajax

                        # --- testdatalog ( fichier, nombrelignes) --
                        # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "testdatalog(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                subResult = result.split(",")  # sépare les sous chaînes séparées par ,
                print subResult

                if len(subResult) == 2:  # si on a bien 2 sous chaînes
                    # if (result=="/"):
                    cheminAbsolu = self.lineEditCheminRep.text() + "/" + subResult[0]  # le chemin absolu à utiliser
                    if subResult[1].isalnum():  # si 2ème param est bien en chiffres
                        contenu = self.testDatalog(cheminAbsolu, str(subResult[1]))  # testDatalog renvoie chaine
                        print (contenu)  # affiche le contenu du fichier
                        reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax
                    else:
                        reponseAjax = reponseAjax + "Erreur format\n"  # ajoute à la réponse Ajax

                        # --- createfile ( ) --
                        # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "createfile(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                # if (result=="/"):
                cheminAbsolu = self.lineEditCheminRep.text() + "/" + result  # le chemin absolu à utiliser
                # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne
                contenu = utils.createFile(cheminAbsolu)  # readFile renvoie chaine
                print (contenu)  # affiche le contenu du fichier
                reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax

                # --- remove ( ) --
                # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn)
            result = utils.testInstructionString(
                chaineAnalyse, "remove(", True
            )  # appelle fonction test instruction format fonction(chaine)
            if result:
                print ("result = " + result)
                reponseAjax = reponseAjax + result + "\n"  # ajoute à la réponse Ajax

                # if (result=="/"):
                cheminAbsolu = self.lineEditCheminRep.text() + "/" + result  # le chemin absolu à utiliser
                contenu = utils.removeFile(cheminAbsolu)  # readFile renvoie chaine
                print (contenu)  # affiche le contenu du fichier
                reponseAjax = reponseAjax + contenu  # ajoute à la réponse Ajax

                # ----- avec params chiffrés ---
            """
			args=utils.testInstructionLong(chaineAnalyse, "lines(", True) # extrait paramètre chaine au format racine (xx,xx,xx,..)
			if args:  # args est True si 1 ou plusieurs paramètres numériques sont trouvés - None sinon 
				print args
			"""

            # --- construction de la réponse complète
            # reponse=self.plainTextEditReponseHttp.toPlainText() +chaineAnalyse+"\n" # Utf-8
            # reponse=self.enteteHttp+chaineAnalyse+"\n"+result+"\n" # +str(args)+"\n" # Utf-8
            reponse = self.enteteHttp + chaineAnalyse + "\n" + reponseAjax + "\n"

            self.envoiChaineClientTcp(reponse)  # envoi la reponse au client - appelle fonction commune

            """
			self.textEditEnvoiReseau.append(reponse) # ajoute à la zone texte d'envoi 
			
			print reponse.toAscii() # convertit en ascii le String - avec conversion unicode... 
			
			#reponse=QString.fromUtf8(reponse) # 2ers octets UTF-8 seulement 
			
			reponseByteArray=reponse.toAscii() # convertit en ascii le String - avec conversion unicode... 
			#byteArray=QByteArray()
			#byteArray.append(reponse)
			
			test=self.clientTcpDistant.write(reponseByteArray) # écrit les données vers le serveur avec CRLF		
			if test==-1 : print ("Erreur en écriture vers le client")
			else: print (str(test)+ " octets envoyés vers le client")
			
			#self.textEditReceptionReseau.append("Reponse envoyee au client : " + str(reponseByteArray)+"\n")		

			test=self.clientTcpDistant.waitForBytesWritten() # attend fin envoi
			if test==False : print("Problème envoi")
			else: print ("envoi réussi")
			"""

            # -- fin si GET /&

            # ---------> si la chaine recue commence par GET et pas une réponse précédente = on envoie page initiale entiere
        elif chaineReception.startswith("GET"):

            # -- écriture des données vers le client = envoi de la réponse du serveur local --
            # test=self.clientTcpLocal.writeData("GET") # écrit les données vers le serveur
            # test=self.clientTcpDistant.writeData(str(self.lineEditReponse.text())) # écrit les données vers le serveur
            # reponse=str(QString.fromUtf8(self.plainTextEditReponse.toPlainText()))+str("\n")

            # reponse=self.plainTextEditReponseHttp.toPlainText() +self.plainTextEditReponseHtml.toPlainText()+"\n" # Utf-8
            # reponseHtml=self.plainTextEditReponseHtml.toPlainText() # partie Html de la réponse

            # reponseHtml.replace(self.lineEditChaineSubstHtml.text(), "var val = new Array(100,200,300,400,500,600);"); # debug - remplace chaine des valeurs à passer au client
            # typiquement, la réponse html contient du code javascript avec un tableau de valeurs var val = new Array(0,0,0,0,0,0);
            # celui-ci est remplacé par le tableau de nouvelles valeurs

            """
			reponseHtml.replace(self.lineEditChaineSubstHtml.text(), "var val = new Array("
			+str(self.lcdNumber_A0.intValue())+","
			+str(self.lcdNumber_A1.intValue()) +","
			+str(self.lcdNumber_A2.intValue())+","
			+str(self.lcdNumber_A3.intValue())+","
			+str(self.lcdNumber_A4.intValue())+","
			+str(self.lcdNumber_A5.intValue()) +");"); # remplace chaine des valeurs à passer au client - ici les valeurs des lcdNumber
			"""
            # --- la réponse HTML + Javascript
            reponseHtml = ""

            # -- début html + le head avec javascript --
            #### ATTENTION : les sections """ """ qui suivent ne sont pas des commentaires mais du code HTML/Javascript actif envoyé au client
            #### NE PAS EFFACER +++

            reponseHtml = (
                reponseHtml
                + """
<!DOCTYPE html>
<html>

<head>
<meta charset=\"utf-8\" />
<title>Titre</title>

<!-- Debut du code Javascript  -->
<script language=\"javascript\" type=\"text/javascript\">
<!-- 

//-- variables et objets globaux 
var textarea=null;
var textInputX=null;
	
//--- fonction appelée sur clic bouton
function onclickButton() { // click Button ON
	requeteAjax(\"&\"+textInput.value+\"=\", drawData); // envoi requete avec &chaine= et fonction de gestion resultat	
} // fin onclickButton

//--- fonction executee au lancement
window.onload = function () { // au chargement de la page
	textarea = document.getElementById(\"textarea\"); // declare objet canvas a partir id = nom
	textarea.value=\"\";// efface le contenu 
	
	textInput= document.getElementById(\"valeur\"); // declare objet champ text a partir id = nom"
	
	} // fin onload

//--- fonction de requete AJAX	
function requeteAjax(chaineIn, callback) {
	
	var xhr = XMLHttpRequest();
	xhr.open(\"GET\", chaineIn, true); // envoi requete avec chaine personnalisee
	xhr.send(null);
	
	//------ gestion de l'évènement onreadystatechange ----- 
	xhr.onreadystatechange = function() {

		if (xhr.readyState == 4 && xhr.status == 200) {
			//alert(xhr.responseText);
			callback(xhr.responseText);
		} // fin if
		
	}; // fin function onreadystatechange		
		
} // fin fonction requeteAjax

//-- fonction de gestion de la reponse a la requete AJAX --
function drawData(stringDataIn) {
	
	// ajoute la réponse au champ texte 
	textarea.value=textarea.value+stringDataIn; // ajoute la chaine au début - décale vers le bas...
	textarea.setSelectionRange(textarea.selectionEnd-1,textarea.selectionEnd-1); // se place à la fin -1 pour avant saut de ligne
	
} // fin fonction drawData

//-->
</script>
<!-- Fin du code Javascript -->

</head>

"""
            )  # les parenthèses encadrent la chaîne et la variable comme si c'était la même ligne

            # -- le body + fin HTML --
            reponseHtml = (
                reponseHtml
                + """
<body>

Serveur Python

<br/>
<input type=\"text\" id=\"valeur\" size=\"50\" />
<button type=\"button\" onclick=\"onclickButton()\">Envoyer</button>
<br/>
En provenance du serveur :
<br/>
<textarea id=\"textarea\" rows=\"10\" cols=\"50\" > </textarea>
<br/>
</body>

</html>
"""
            )  # les parenthèses encadrent la chaîne et la variable comme si c'était la même ligne

            # --- construction de la réponse complète
            # reponse=self.plainTextEditReponseHttp.toPlainText() +reponseHtml+"\n" # Utf-8
            reponse = self.enteteHttp + reponseHtml + "\n"  # Utf-8

            self.envoiChaineClientTcp(reponse)  # envoi la reponse au client - appelle fonction commune

            """
			self.textEditEnvoiReseau.append(reponse) # ajoute à la zone texte d'envoi 
			
			print reponse.toAscii() # convertit en ascii le String - avec conversion unicode... 
			
			#reponse=QString.fromUtf8(reponse) # 2ers octets UTF-8 seulement 
			
			reponseByteArray=reponse.toAscii() # convertit en ascii le String - avec conversion unicode... 
			#byteArray=QByteArray()
			#byteArray.append(reponse)
			
			test=self.clientTcpDistant.write(reponseByteArray) # écrit les données vers le serveur avec CRLF		
			if test==-1 : print ("Erreur en écriture vers le client")
			else: print (str(test)+ " octets envoyés vers le client")
			
			#self.textEditReceptionReseau.append("Reponse envoyee au client : " + str(reponseByteArray)+"\n")		

			test=self.clientTcpDistant.waitForBytesWritten() # attend fin envoi
			if test==False : print("Problème envoi")
			else: print ("envoi réussi")
			"""

            # -- fin si "GET" = fin envoi page initiale complète

            # -- fin de la connexion --
        self.clientTcpDistant.close()  # fin de la connexion
        print ("Fermeture du client tcp distant effectuée")
        print ("===========================================")
        print ("")
Ejemplo n.º 35
0
def create(service_name, database_name, readonly_role_name,
           readwrite_role_name, user_name, verbose):
    """Create database, roles and user."""

    # -------------------------------------------------------------------------
    # 0. Init
    # -------------------------------------------------------------------------
    utils.configureLogging(verbose)

    # Look for DB credentials in .env file
    logging.debug(f"Looking for DB credentials in .env file...")
    config = utils.loadConfig()

    # -------------------------------------------------------------------------
    # 1. Connect to a default database to create the service database
    # -------------------------------------------------------------------------
    # Connect to db server
    initial_db_conn = db.connect(config["DB_HOST"], config["DB_NAME"],
                                 config["DB_USER"], config["DB_PASS"])

    # Create a db for the service
    service_db_name = database_name if database_name else f"{service_name}"
    logging.info(
        f"Create a database with name={service_db_name} for service={service_name}"
    )
    db.create_database(initial_db_conn, service_db_name)

    # Close the db connection
    db.close(initial_db_conn)

    # -------------------------------------------------------------------------
    # 2. Connect to new service db to create roles and a user for the service
    # -------------------------------------------------------------------------
    # Connect to the new service database
    db_conn = db.connect(config["DB_HOST"], service_db_name, config["DB_USER"],
                         config["DB_PASS"])

    # Revoke default, public permissions from public schema
    logging.info(f"Revoke default, public permissions from public schema")
    db.revoke_public_permissions(db_conn, service_db_name)

    # Create a read-only role
    service_readonly_role = readonly_role_name if readonly_role_name else f"role_{service_name}_readonly"
    logging.info(f"Create a read-only role with name={service_readonly_role}")
    db.create_readonly_role(db_conn, service_db_name, service_readonly_role)

    # Create a read/write role
    service_readwrite_role = readwrite_role_name if readwrite_role_name else f"role_{service_name}_readwrite"
    logging.info(
        f"Create a read/write role with name={service_readwrite_role}")
    db.create_readowrite_role(db_conn, service_db_name, service_readwrite_role)

    # Create a user for the service with read/write role grants
    service_user = user_name if user_name else f"user_{service_name}_app"
    service_pass = utils.getRandomPassword(30)
    logging.info(f"Create a user with name={service_user}")
    db.create_user(db_conn, service_user, service_pass, service_readwrite_role)

    # Output user pass to a file
    utils.writeFile(".pass", service_pass)

    # Close the db connection
    db.close(db_conn)
Ejemplo n.º 36
0
        utils.hexString(keyBank.u8RSAImagePublicKey.N)))
    print("[i] u8RSAImagePublicKey E:\n{}".format(
        utils.hexString(keyBank.u8RSAImagePublicKey.E)))
    print("[i] u8AESBootKey:\n{}".format(utils.hexString(
        keyBank.u8AESBootKey)))
    print("[i] u8AESUpgradeKey:\n{}".format(
        utils.hexString(keyBank.u8AESUpgradeKey)))

    print("[i] u8MagicID:\n{}".format(utils.hexString(keyBank.u8MagicID)))
    print("[i] CRC:\n{}".format(utils.hexString(keyBank.crc)))

# Save keys
print("[i] Save keys")

# RSA Boot
utils.writeFile(os.path.join(outFolder, 'RSAboot_pub.bin'),
                keyBank.u8RSABootPublicKey)
utils.writeRSAPublicKey(os.path.join(outFolder, 'RSAboot_pub.txt'),
                        keyBank.u8RSABootPublicKey)

# RSA Upgrade
utils.writeFile(os.path.join(outFolder, 'RSAupgrade_pub.bin'),
                keyBank.u8RSAUpgradePublicKey)
utils.writeRSAPublicKey(os.path.join(outFolder, 'RSAupgrade_pub.txt'),
                        keyBank.u8RSAUpgradePublicKey)

# RSA Image
utils.writeFile(os.path.join(outFolder, 'RSAimage_pub.bin'),
                keyBank.u8RSAImagePublicKey)
utils.writeRSAPublicKey(os.path.join(outFolder, 'RSAimage_pub.txt'),
                        keyBank.u8RSAImagePublicKey)