Exemple #1
0
def send_through_socket_server_site(socket_path,
                                    command,
                                    destination_address=world.f_cfg.
                                    mgmt_address):
    if type(command) is unicode:
        command = command.encode('ascii', 'ignore')
    command_file = open(world.cfg["dir_name"] + '/command_file', 'w')
    try:
        command_file.write(command)
    except:
        command_file.close()
        command_file = open(world.cfg["dir_name"] + '/command_file', 'wb')
        command_file.write(command)
    command_file.close()
    fabric_send_file(world.cfg["dir_name"] + '/command_file',
                     'command_file',
                     destination_host=destination_address)
    world.control_channel = fabric_sudo_command(
        'socat UNIX:' + socket_path + ' - <command_file',
        hide_all=True,
        destination_host=destination_address)
    fabric_remove_file_command('command_file')
    print json.dumps(json.loads(world.control_channel),
                     sort_keys=True,
                     indent=2,
                     separators=(',', ': '))
 def cookie(self, cookie_file):
     if (os.path.exists(cookie_file)):
         self.cookie_file = cookie_file
     else:
         try:
             open(cookie_file, mode, buffering, encoding, errors, newline, closefd)
             self.cookie_file = cookie_file
         except IOError as ex:
             pass
Exemple #3
0
 def cookie(self, cookie_file):
     if (os.path.exists(cookie_file)):
         self.cookie_file = cookie_file
     else:
         try:
             open(cookie_file, mode, buffering, encoding, errors, newline,
                  closefd)
             self.cookie_file = cookie_file
         except IOError as ex:
             pass
 def extract_text_from_local_file(self,local_filename,folder=None,language=None):
     try:
         #build URI            
         if(local_filename == ""):
             raise "Filename not found."
         
         with open(local_filename , "rb") as file_obj:
             file_data = file_obj.read()
             file_obj.close()
             
                     
         
         str_uri_request = Product.base_product_uri + "/ocr/recognize?useDefaultDictionaries=true"
         
         if(folder != None):
             str_uri_request = str_uri_request + "&folder=" + folder
         
         if(language != None):
             str_uri_request = str_uri_request + "&language=" + language
                     
         
         signed_uri = Utils.sign(Utils(),str_uri_request)
         
         response_stream = Utils.process_command(Utils(),signed_uri, "POST", "JSON", file_data)                       
                     
         json_data = json.loads(response_stream)
         
         if (json_data['Code'] != 200):
             return False
         else:
             return json_data["Text"]
                 
     except:
         raise
Exemple #5
0
def add_variable(variable_name, variable_val, val_type):
    """
    Define variable and add it to temporary list or to init_all.py file. 
    """
    import re
    assert not bool(re.compile('[^A-Z^0-9^_] + ').search(variable_name)),\
        "Variable name contain invalid characters (Allowed are only capital letters, numbers and sign '_')."
    
    if not val_type:
        # temporary
        if variable_name not in world.define:
            tmp = variable_val if variable_val.isdigit() else variable_val  
            world.define.append([variable_name, tmp])
        else:
            world.define[variable_name] = variable_val
    elif val_type:
        # permanent
        # TO: for same name change value
        try:
            imported = getattr(__import__('init_all', fromlist=[variable_name]), variable_name)
        except:
            init_all = open("features/init_all.py", "a")
            init_all.write("\n# USER VARIABLE:\n" + variable_name + " = " +
                           (variable_val if variable_val.isdigit() else '\"' + variable_val + '\"'))
            init_all.close()
Exemple #6
0
def compare_file(step, local_path):
    """
    Compare two files, downloaded and local
    """
    if not os.path.exists(local_path):
        assert False, 'No local file %s' % local_path
    
    outcome = open(world.cfg["dir_name"] + '/file_compare', 'w')
    
    # first remove all commented and blank lines of both files
    downloaded_stripped = strip_file(world.cfg["dir_name"] + '/downloaded_file')
    local_stripped = strip_file(local_path)

    line_number = 1
    error_flag = True
    for i, j in zip(downloaded_stripped, local_stripped):
        if i != j:
            outcome.write('Line number: ' + str(line_number) + ' \n\tDownloaded file line: "' +
                          i.rstrip('\n') + '" and local file line: "' + j.rstrip('\n') + '"\n')
            error_flag = False
        line_number += 1
    if error_flag:
        remove_local_file(world.cfg["dir_name"] + '/file_compare')
        
    assert error_flag, 'Downloaded file is NOT the same as local. Check %s/file_compare for details'\
                       % world.cfg["dir_name"]
    
    if len(downloaded_stripped) != len(local_stripped):
        assert len(downloaded_stripped) > len(local_stripped), 'Downloaded file is part of a local file.'
        assert len(downloaded_stripped) < len(local_stripped), 'Local file is a part of a downlaoded life.'
def add_variable(variable_name, variable_val, val_type):
    """
    Define variable and add it to temporary list or to init_all.py file.
    """
    assert not bool(re.compile('[^A-Z^0-9^_] + ').search(variable_name)),\
        "Variable name contain invalid characters (Allowed are only capital letters, numbers and sign '_')."

    if not val_type:
        # temporary
        if variable_name not in world.define:
            tmp = variable_val if variable_val.isdigit() else variable_val
            world.define.append([variable_name, tmp])
        else:
            world.define[variable_name] = variable_val
    elif val_type:
        # permanent
        # TO: for same name change value
        # TODO: WTF?
        try:
            imported = getattr(__import__('init_all', fromlist=[variable_name]), variable_name)
        except:
            init_all = open("init_all.py", "a")  # TODO: this should be removed
            init_all.write("\n# USER VARIABLE:\n" + variable_name + " = " +
                           (variable_val if variable_val.isdigit() else '\"' + variable_val + '\"'))
            init_all.close()
def compare_file(local_path):
    """
    Compare two files, downloaded and local
    """
    if not os.path.exists(local_path):
        assert False, 'No local file %s' % local_path

    outcome = open(world.cfg["dir_name"] + '/file_compare', 'w')

    # first remove all commented and blank lines of both files
    downloaded_stripped = strip_file(world.cfg["dir_name"] + '/downloaded_file')
    local_stripped = strip_file(local_path)

    line_number = 1
    error_flag = True
    for i, j in zip(downloaded_stripped, local_stripped):
        if i != j:
            outcome.write('Line number: ' + locale.str(line_number) + ' \n\tDownloaded file line: "' +
                          i.rstrip('\n') + '" and local file line: "' + j.rstrip('\n') + '"\n')
            error_flag = False
        line_number += 1
    if error_flag:
        remove_local_file(world.cfg["dir_name"] + '/file_compare')

    assert error_flag, 'Downloaded file is NOT the same as local. Check %s/file_compare for details'\
                       % world.cfg["dir_name"]

    if len(downloaded_stripped) != len(local_stripped):
        assert len(downloaded_stripped) > len(local_stripped), 'Downloaded file is part of a local file.'
        assert len(downloaded_stripped) < len(local_stripped), 'Local file is a part of a downlaoded life.'
Exemple #9
0
 def save_text(self,r):
     global path_for
     pattern_title=re.compile('<h2 class="zm-item-title zm-editable-content">\n\n([\s\S]*?)\n\n<\/h2>')
     pattern_desc=re.compile('<div class="zm-editable-content">([\s\S]*?)<\/div>')
     pattern_content=re.compile('<div class="zm-editable-content clearfix">([\s\S]*?)<\/div>')
     pattern=re.compile('div [\S\s]*?"count">(.*?)</span>[\s\S]*?clearfix">(.*)[\s\S]*?<\/div>')
     
     title=re.findall(pattern_title,r.text)
     desc=re.findall(pattern_desc,r.text)
     content=re.findall(pattern_content,r.text)
     #print(title,desc)
     #a=re.sub(re.compile('<br>'),'\n',r.text)
     answer_favor_list=re.findall(pattern,r.text)
     pat_sub=re.compile('<br>')
     with open('./'+title[0]+'.txt','w') as f:
         try:
             
             f.write('问题:'+title[0]+'\n\n')
             f.write('描述:'+desc[0]+'\n\n')
             i=0
             for answer in answer_favor_list:
                 if(int(answer[0])>favor_data):
                     f.write('\n-------------------''答案'+str(i)+'(赞同:'+answer[0]+')''---------------------\n')
                     f.write('\n答案'+str(i)+'(赞同:'+answer[0]+')-->'+re.sub(pat_sub,'\n',answer[1]))
                     f.write('\n'+content[i])
                     f.write('\n++++++++++++++++++++++++this answer is over++++++++++++++++++++++++++++++')
                     f.write('\n\n')
                 i+=1
         except Exception:
             print('可能在文件读写的时候出了一点问题。。。')
Exemple #10
0
 def read_cookies(self):
     global _session,path_for
     #_session.cookies.load()
     #_session.headers.update(header_data)
     with open('cookiefile')as f:
         cookie=json.load(f)
         _session.cookies.update(cookie)
Exemple #11
0
    def __putItemStateToArchive(self, item, archive):
        encoder = memento.Encoder()
        itemState = encoder.encode(item)
        itemStateFilename = "id=" + str(item.id) + "_title=" + item.title

        tmpDir = UserConfig().get("tmp_dir", consts.DEFAULT_TMP_DIR)
        tmpFileName = os.path.join(tmpDir, "item_state.json")
        with open(tmpFileName, "w") as f:
            f.write(itemState)
        archive.add(tmpFileName, arcname=os.path.join(".reggata/items", itemStateFilename))
Exemple #12
0
 def POST(self):
     i = web.input()
     w = open(hostsFile, 'w')
     w.writelines(i.hosts)
     w.close()
     # 响应
     web.header('Content-Type', 'text/html; charset=utf-8', unique=True)
     r = open(hostsFile)
     tmpList = r.readlines()
     r.close()
     responseHtml = '<form method="post" action="/hosts/mod">'
     hosts = ''
     for host in tmpList:
         isMatch = bool(re.match(r'^\#?[0-9]+(\.[0-9]+){3}.*$', host, re.VERBOSE));
         if isMatch: 
             hosts += host
     responseHtml += '<textarea name="hosts" cols="60" rows="15">' + hosts + '</textarea><br/>'
     responseHtml += '<input type="submit" value="Update"></form>'
     return responseHtml
Exemple #13
0
 def POST(self):
     i = web.input()
     w = open(hostsFile, 'w')
     w.writelines(i.hosts)
     w.close()
     # 响应
     web.header('Content-Type', 'text/html; charset=utf-8', unique=True)
     r = open(hostsFile)
     tmpList = r.readlines()
     r.close()
     responseHtml = '<form method="post" action="/hosts/mod">'
     hosts = ''
     for host in tmpList:
         isMatch = bool(
             re.match(r'^\#?[0-9]+(\.[0-9]+){3}.*$', host, re.VERBOSE))
         if isMatch:
             hosts += host
     responseHtml += '<textarea name="hosts" cols="60" rows="15">' + hosts + '</textarea><br/>'
     responseHtml += '<input type="submit" value="Update"></form>'
     return responseHtml
    def __putItemStateToArchive(self, item, archive):
        encoder = memento.Encoder()
        itemState = encoder.encode(item)
        itemStateFilename = "id=" + str(item.id) + "_title=" + item.title

        tmpDir = UserConfig().get("tmp_dir", consts.DEFAULT_TMP_DIR)
        tmpFileName = os.path.join(tmpDir, "item_state.json")
        with open(tmpFileName, "w") as f:
            f.write(itemState)
        archive.add(tmpFileName,
                    arcname=os.path.join(".reggata/items", itemStateFilename))
Exemple #15
0
def TicTacToeTomek():
    f = open("input.txt")
    T = int(f.readline())
    print T

    for i in range(T):
        #        print 'Test Case: ' + str(i)
        status = solveTic(f)
        global answer
        answer = ''
        print 'Case #' + str(i + 1) + ': ' + status
Exemple #16
0
def save(path, gallery, fileName):
    imageName = str(uuid.uuid4()) + fileName[fileName.rfind("."):]
    imagePath = MEDIA_ROOT + os.sep + imageName
    destination = open(imagePath, 'wb+')
    for chunk in path.chunks():
        destination.write(chunk)
    destination.close()
        
    image = gallery.image_set.create()
    image.path = imageName
    image.save()
def strip_file(file_path):
    tmp_list = []
    tmp = open(file_path, 'r')
    for line in tmp:
        line = line.strip()
        if len(line) < 1:
            continue
        elif line[0] == '#':
            continue
        else:
            tmp_list.append(line.strip())
    tmp.close()
    return tmp_list
Exemple #18
0
def strip_file(file_path):
    tmp_list = []
    tmp = open(file_path, 'r')
    for line in tmp:
        line = line.strip()
        if len(line) < 1:
            continue
        elif line[0] == '#':
            continue
        else:
            tmp_list.append(line.strip())
    tmp.close()
    return tmp_list
def send_through_socket_server_site(socket_path, command, destination_address=world.f_cfg.mgmt_address):
    if type(command) is unicode:
        command = command.encode('ascii', 'ignore')
    command_file = open(world.cfg["dir_name"] + '/command_file', 'w')
    try:
        command_file.write(command)
    except:
        command_file.close()
        command_file = open(world.cfg["dir_name"] + '/command_file', 'wb')  # TODO: why 'w' / 'wb'
        command_file.write(command)
    command_file.close()
    fabric_send_file(world.cfg["dir_name"] + '/command_file', 'command_file', destination_host=destination_address)
    world.control_channel = fabric_sudo_command('socat UNIX:' + socket_path + ' - <command_file', hide_all=True,
                                                destination_host=destination_address)
    fabric_remove_file_command('command_file')
    try:
        result = json.loads(world.control_channel)
        log.info(json.dumps(result, sort_keys=True, indent=2, separators=(',', ': ')))
        world.cmd_resp = result
    except:
        log.exception('Problem with parsing json: %s', str(world.control_channel))
        world.cmd_resp = world.control_channel
    return world.cmd_resp
Exemple #20
0
 def get_img(self,url):
     global  _session
     r=_session.get(url,proxies=proxy)
     pat_img=re.compile('<noscript><img src="([\s\S]*?)"')
     url_list=re.findall(pat_img,r.text)
     i=0
     try :   
         for img_url in url_list:
             with open(str(i)+'.jpg','bw')as f:
                 print('下载第'+str(i)+'张')
                 f.write(_session.get(img_url,proxies=proxy).content)
             i+=1
     except :
         print('可能出了一点问题。。。')
Exemple #21
0
    def try_one(s):
        unlink(file_name)
        f = pyio.open(file_name, "wb")
        try:
            # write once with \n and once without
            f.write(s)
            f.write(b"\n")
            f.write(s)
            f.close()

            f = pyio.open(file_name, "rb")
            line = f.readline()
            assert line == s + b"\n"

            line = f.readline()
            assert line == s

            line = f.readline()
            assert not line  # Must be at EOF

            f.close()
        finally:
            unlink(file_name)
    def get_crosstalk_corrections(self,outputDir):
        fileName = self.get_crosstalk_correction_file_name(outputDir)
        f = open(fileName)
        lines = [line.encode('ascii','replace').replace(':','').replace('%','').split() for line in f.readlines()]
        corrections = [line[1] for line in lines]
#         percentages = [cor.endswith('%')*.01 for cor in corrections]
#         factor  = [cor.strip('%') for cor in corrections]
        corrections = [float(cor) for cor in corrections]
        diamondCor = corrections[-1]
        siliconCor = corrections[:-1]
        print diamondCor
        print siliconCor
        meanSil = sum(siliconCor)/len(siliconCor)
        sigmaSil = math.sqrt(sum([x**2 for x in siliconCor])/len(siliconCor) - meanSil**2)
        print meanSil,sigmaSil
        print corrections
        print lines
        f.close()     
        return meanSil,diamondCor
Exemple #23
0
def test_builtin_open():
    import _pyio as pyio  # Python implementation.
    file_name = "mymodule.py"

    f = pyio.open(file_name, "w")
    f.write('print(42)\n')
    f.close()

    success = True
    try:
        exec(open(file_name).read())
        exec(compile(open(file_name, "r").read(), file_name, "eval"))
    except Exception as e:
        print(e)
        success = False
    finally:
        unlink(file_name)

    assert success
def execute_shell_script(path, arguments):
    result = fabric_sudo_command(path + ' ' + arguments, hide_all=False)

    file_name = path.split("/")[-1] + '_output'
    file_name = generate_file_name(1, file_name)

    # assert False, type(result.stdout)
    if not os.path.exists(world.cfg["dir_name"]):
        os.makedirs(world.cfg["dir_name"])

    myfile = open(world.cfg["dir_name"] + '/' + file_name, 'w')
    myfile.write(unicode('Script: ' + path))
    if arguments == '':
        arguments = "no arguments used!"
    myfile.write(unicode('\nwith arguments: ' + arguments + '\n'))
    if result.failed:
        myfile.write(unicode('\nStatus: FAILED\n'))
    else:
        myfile.write(unicode('\nStatus: SUCCEED\n'))

    myfile.write(unicode('\nScript stdout:\n' + result.stdout))
    myfile.close()
    forge_sleep(3, "seconds")
Exemple #25
0
def execute_shell_script(path, arguments):
    result = fabric_sudo_command(path + ' ' + arguments, False)

    file_name = path.split("/")[-1] + '_output'
    file_name = generate_file_name(1, file_name)

    # assert False, type(result.stdout)
    if not os.path.exists(world.cfg["dir_name"]):
        os.makedirs(world.cfg["dir_name"])

    myfile = open(world.cfg["dir_name"] + '/' + file_name, 'w')
    myfile.write(unicode('Script: ' + path))
    if arguments == '':
        arguments = "no arguments used!"
    myfile.write(unicode('\nwith arguments: ' + arguments + '\n'))
    if result.failed:
        myfile.write(unicode('\nStatus: FAILED\n'))
    else:
        myfile.write(unicode('\nStatus: SUCCEED\n'))

    myfile.write(unicode('\nScript stdout:\n' + result.stdout))
    myfile.close()
    forge_sleep(3, "seconds")
    def test_BendingDisp(self):
        """@brief Test tip disp and plot bending against Murua and Smith."""
        
        # Beam solver options.
        XBOPTS = DerivedTypes.Xbopts(FollowerForce = ct.c_bool(False),
                                     MaxIterations = ct.c_int(50),
                                     PrintInfo = ct.c_bool(True),
                                     NumLoadSteps = ct.c_int(25),
                                     Solution = ct.c_int(112),
                                     MinDelta = ct.c_double(1e-4)    )
        
        # Beam inputs.
        XBINPUT = DerivedTypes.Xbinput(3,20)
        XBINPUT.BeamLength = 16.0
        XBINPUT.BeamStiffness[0,0] = 1.0e+09
        XBINPUT.BeamStiffness[1,1] = 1.0e+09
        XBINPUT.BeamStiffness[2,2] = 1.0e+09
        XBINPUT.BeamStiffness[3,3] = 1.0e+04
        XBINPUT.BeamStiffness[4,4] = 2.0e+04
        XBINPUT.BeamStiffness[5,5] = 5.0e+06
        
        XBINPUT.BeamStiffness[:,:] = 1.0*XBINPUT.BeamStiffness[:,:]
        
        XBINPUT.BeamMass[0,0] = 0.75
        XBINPUT.BeamMass[1,1] = 0.75
        XBINPUT.BeamMass[2,2] = 0.75
        XBINPUT.BeamMass[3,3] = 0.1
        XBINPUT.BeamMass[4,4] = 0.001
        XBINPUT.BeamMass[5,5] = 0.001
        
        XBINPUT.g = 0.0
        
        
        # Aero solver options.
        VMOPTS = DerivedTypesAero.VMopts(M = 10,\
                                         N = XBINPUT.NumNodesTot - 1 ,\
                                         ImageMethod = True,\
                                         Steady = True,\
                                         KJMeth = True)
        
        # Aero inputs.
        VMINPUT = DerivedTypesAero.VMinput(c = 1.0, b = XBINPUT.BeamLength,\
                                           U_mag = 25.0,\
                                           alpha = 4.0*np.pi/180.0,\
                                           theta = 0.0,\
                                           WakeLength = 100.0)
        
        # Aeroelastic options.
        # Density due to US standard atmosphere at 20km.
        AELAOPTS = AeroelasticOps(0.0,0.0,0.08891)
        
        # Run solver.
        XBOUT = Solver.Solve_Py(XBINPUT,XBOPTS, VMOPTS, VMINPUT, AELAOPTS)
        PosDefor = XBOUT.PosDeforStatic                   
        
        self.assertAlmostEqual(PosDefor[-1,2],  5.42492076, None, #5.3856278, None,
                               'Tip deflection wrong.', 0.02)
        
        convergence = False
        if convergence == True:
            
            VMOPTS.KJMeth = ct.c_bool(True)
            
            FileMesh = open(TestDir + 'ConvergenceMesh.dat', "w")
            FileKJ = open(TestDir + 'ConvergenceKJ.dat', "w")
            FileKP = open(TestDir + 'ConvergenceKP.dat', "w")
            
            NumElemsArr = [1,5,10,15,20,30]
            MSectArr = [1,2,5,10,15]
            
            ## Write mesh data corresponding to test.
            FileMesh.write("Num Nodes per Elem = %d\n" % (XBINPUT.NumNodesElem))
            FileMesh.write("Num Nodes Array = [")
            for Bla in NumElemsArr:
                FileMesh.write("%d  " %(Bla))
            FileMesh.write("]\n")
            FileMesh.write("Chordwise Panels Array = [")
            for Bla in MSectArr:
                FileMesh.write("%d  " %(Bla))
            FileMesh.write("]\n")
            FileMesh.close()
            
            for NumElems in NumElemsArr:
                for MSect in MSectArr:
                    
                    # Beam solver options.
                    XBOPTS = DerivedTypes.Xbopts(FollowerForce = ct.c_bool(False),\
                                                 MaxIterations = ct.c_int(20),\
                                                 PrintInfo = ct.c_bool(True),\
                                                 NumLoadSteps = ct.c_int(20),\
                                                 Solution = ct.c_int(112),\
                                                 MinDelta = ct.c_double(1e-4))
                    
                    # Beam inputs.
                    XBINPUT = DerivedTypes.Xbinput(3,NumElems)
                    XBINPUT.BeamLength = 16.0
                    XBINPUT.BeamStiffness[0,0] = 1.0e+09
                    XBINPUT.BeamStiffness[1,1] = 1.0e+09
                    XBINPUT.BeamStiffness[2,2] = 1.0e+09
                    XBINPUT.BeamStiffness[3,3] = 1.0e+04
                    XBINPUT.BeamStiffness[4,4] = 2.0e+04
                    XBINPUT.BeamStiffness[5,5] = 5.0e+06
 
                    XBINPUT.BeamMass[0,0] = 0.75
                    XBINPUT.BeamMass[1,1] = 0.75
                    XBINPUT.BeamMass[2,2] = 0.75
                    XBINPUT.BeamMass[3,3] = 0.1
                    XBINPUT.BeamMass[4,4] = 0.001
                    XBINPUT.BeamMass[5,5] = 0.001
                    
                    
                    # Aero solver options.
                    VMOPTS = DerivedTypesAero.VMopts(M = MSect,\
                                                     N = XBINPUT.NumNodesTot - 1 ,\
                                                     ImageMethod = True,\
                                                     Steady = True,\
                                                     KJMeth = True)
                    
                    # Aero inputs.
                    VMINPUT = DerivedTypesAero.VMinput(c = 1.0, b = XBINPUT.BeamLength,\
                                                       U_mag = 25.0,\
                                                       alpha = 4.0*np.pi/180.0,\
                                                       theta = 0.0)
                    
                    # Aeroelastic opts.
                    # Density due to US standard atmosphere at 20km
                    AELAOPTS = AeroelasticOps(0.0,0.0,0.08891)
                          
                    XBOUT = Solver.Solve_Py(XBINPUT,XBOPTS, VMOPTS, VMINPUT, AELAOPTS)
                    PosDefor = XBOUT.PosDeforStatic 
                    
                    # Delete currently unused objects.
                    del XBOUT
                    
                    # Write tip deflection to file.
                    FileKJ.write("%12.5e  " %(PosDefor[-1,2]))
                    if MSect == MSectArr[-1]:
                        FileKJ.write("\n")
                    
                    
                    # Change to Katz &Plotkin force calculation.
                    VMOPTS.KJMeth = ct.c_bool(False)
                    
                    XBOUT = Solver.Solve_Py(XBINPUT,XBOPTS, VMOPTS, VMINPUT, AELAOPTS)
                    PosDefor = XBOUT.PosDeforStatic 
                    
                    # Delete currently unused objects.
                    del XBOUT
                    
                    # Write tip deflection to file.
                    FileKP.write("%12.5e  "%(PosDefor[-1,2]))
                    if MSect == MSectArr[-1]:
                        FileKP.write("\n")
                    
                # END for MSect
            # END for NumNodes
            FileKJ.close()
            FileKP.close()
Exemple #27
0
def open(*args, **kwargs):
    return _pyio.open(*args, **kwargs)
_artisan= set(['fumster101', 'sivert17', 'wap'])
_architect= set(['flamin_scotsman', 'stamog', 'eviil'])

host = 'mc.pwegoable.com'
port = 25565
file = 'mc.pwegoable.com.playerlog'

if __name__ == '__main__':
    print('Ctrl-C to exit')
    
    
    print("Connecting...")
    q = mcquery.MCQuery(host, port)
    print("Connected.")
    
    f = open(file=file, mode='r+')
    
    while True:
        query=json.loads(q.full_stat().replace(": ", ":").replace("'", '"').replace("\xa7", "§"))
        lowercasePlayers =  [x.lower() for x in query['players']]
        try:
            tree = ET.parse(file)
        except:
            tree = ET.Element('logfile')
        root = tree.getroot()
        logentry = ET.SubElement ( root, 'logentry' )
        datetime = ET.SubElement( logentry, 'datetime')
        datetime.text = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        players = ET.SubElement( logentry, 'datetime')
        players.text = query['numplayers']
        
Exemple #29
0
# encoding=utf-8
'''
Created on 2012-9-22

@author: wangliang
'''

from urllib import urlopen, urlretrieve, urlcleanup
import re
from _pyio import open

webapp = urlopen("http://www.baidu.com")
print webapp.read()

file = open("hello.txt")
p = r'/Users/wangliang/Documents/Aptana Studio 3 Workspace/Python-Fundmental/src/python/Chapter14/hello.txt'  #空格没有关心
data = urlretrieve('http://www.baidu.com', p)
print data
#urlcleanup()
Exemple #30
0
def test_file():
    import _pyio as pyio  # Python implementation.
    file_name = "dump.txt"

    unlink(file_name)
    try:
        # verify weak references
        from array import array
        from weakref import proxy
        from collections import UserList

        f = pyio.open(file_name, "wb")

        p = proxy(f)
        p.write(b'teststring')
        assert f.tell() == p.tell()
        f.close()
        f = None
        # TODO: since weakref is not yet properly implemented this will not work
        # assert_raises(ReferenceError, getattr, p, 'tell')

        # verify expected attributes exist
        f = pyio.open(file_name, "wb")
        f.name  # merely shouldn't blow up
        f.mode  # ditto
        f.closed  # ditto
        f.close()

        # verify writelines with instance sequence
        f = pyio.open(file_name, "wb")
        l = UserList([b'1', b'2'])
        f.writelines(l)
        f.close()
        f = pyio.open(file_name, 'rb')
        buf = f.read()
        assert buf == b'12'
        f.close()

        # verify writelines with integers
        f = pyio.open(file_name, "wb")
        assert_raises(TypeError, f.writelines, [1, 2, 3])
        f.close()

        # verify writelines with integers in UserList
        f = pyio.open(file_name, "wb")
        l = UserList([1, 2, 3])
        assert_raises(TypeError, f.writelines, l)
        f.close()

        # verify writelines with non-string object
        class NonString:
            pass

        f = pyio.open(file_name, "wb")
        assert_raises(TypeError, f.writelines, [NonString(), NonString()])
        f.close()

        f = pyio.open(file_name, "wb")
        assert f.name == file_name
        assert not f.isatty()
        assert not f.closed

        f.close()
        assert f.closed
    finally:
        unlink(file_name)
Exemple #31
0
 def save_captcha(self,url,email):
     global _session
     r=_session.get(url,proxies=proxy)
     with open("./pic/code.gif",'wb') as f:
         f.write(r.content)
Exemple #32
0
# encoding=utf-8
'''
Created on 2012-9-22

@author: wangliang
'''

from urllib import urlopen, urlretrieve, urlcleanup
import re
from _pyio import open

webapp = urlopen("http://www.baidu.com")
print webapp.read()

file = open("hello.txt")
p = r'/Users/wangliang/Documents/Aptana Studio 3 Workspace/Python-Fundmental/src/python/Chapter14/hello.txt' #空格没有关心
data = urlretrieve('http://www.baidu.com', p)
print data
#urlcleanup()
Exemple #33
0
 def save_cookies(self,email):
     global _session,path_for
     with open('./'+email+"_cookiefile",'w')as f:
         json.dump(_session.cookies.get_dict(),f)
    def test_BendingDisp(self):
        """@brief Test tip disp and plot bending against Murua and Smith."""
        
        # Beam solver options.
        XBOPTS = DerivedTypes.Xbopts(FollowerForce = ct.c_bool(False),
                                     MaxIterations = ct.c_int(50),
                                     PrintInfo = ct.c_bool(True),
                                     NumLoadSteps = ct.c_int(25),
                                     Solution = ct.c_int(112),
                                     MinDelta = ct.c_double(1e-4)     )
        
        # Beam inputs.
        XBINPUT = DerivedTypes.Xbinput(3,20)
        XBINPUT.BeamLength = 16.0
        XBINPUT.BeamStiffness[0,0] = 1.0e+09
        XBINPUT.BeamStiffness[1,1] = 1.0e+09
        XBINPUT.BeamStiffness[2,2] = 1.0e+09
        XBINPUT.BeamStiffness[3,3] = 1.0e+04
        XBINPUT.BeamStiffness[4,4] = 2.0e+04
        XBINPUT.BeamStiffness[5,5] = 5.0e+06
        
        XBINPUT.BeamStiffness[:,:] = 1.0*XBINPUT.BeamStiffness[:,:]
        
        XBINPUT.BeamMass[0,0] = 0.75
        XBINPUT.BeamMass[1,1] = 0.75
        XBINPUT.BeamMass[2,2] = 0.75
        XBINPUT.BeamMass[3,3] = 0.1
        XBINPUT.BeamMass[4,4] = 0.001
        XBINPUT.BeamMass[5,5] = 0.001
        
        XBINPUT.g = 0.0
        
        
        # Aero solver options.
        VMOPTS = DerivedTypesAero.VMopts(M = 1,\
                                         N = XBINPUT.NumNodesTot - 1 ,\
                                         ImageMethod = True,\
                                         Steady = True,\
                                         KJMeth = True)
        
        # Aero inputs.
        VMINPUT = DerivedTypesAero.VMinput(c = 1.0, b = XBINPUT.BeamLength,\
                                           U_mag = 25.0,\
                                           alpha = 4.0*np.pi/180.0,\
                                           theta = 0.0,\
                                           WakeLength = 100.0)
        
        # Aeroelastic options.
        # Density due to US standard atmosphere at 20km.
        AELAOPTS = AeroelasticOps(0.0,0.0,0.08891)
        
        # Run solver.
        PosDefor = Solver.Solve_Py(XBINPUT,XBOPTS,
                                             VMOPTS,VMINPUT,
                                             AELAOPTS)[0]
        
        self.assertAlmostEqual(PosDefor[-1,2], 5.3856278, None,
                               'Tip deflection wrong.', 0.02)
        
        convergence = False
        if convergence == True:
            
            VMOPTS.KJMeth = ct.c_bool(True)
            
            FileMesh = open(TestDir + 'ConvergenceMesh.dat', "w")
            FileKJ = open(TestDir + 'ConvergenceKJ.dat', "w")
            FileKP = open(TestDir + 'ConvergenceKP.dat', "w")
            
            NumElemsArr = [1,5,10,15,20,30]
            MSectArr = [1,2,5,10,15]
            
            # Write mesh data corresponding to test.
            FileMesh.write("Num Nodes per Elem = %d\n" % (XBINPUT.NumNodesElem))
            FileMesh.write("Num Nodes Array = [")
            for Bla in NumElemsArr:
                FileMesh.write("%d  " %(Bla))
            FileMesh.write("]\n")
            FileMesh.write("Chordwise Panels Array = [")
            for Bla in MSectArr:
                FileMesh.write("%d  " %(Bla))
            FileMesh.write("]\n")
            FileMesh.close()
            
            for NumElems in NumElemsArr:
                for MSect in MSectArr:
                    
                    # Beam solver options.
                    XBOPTS = DerivedTypes.Xbopts(FollowerForce = ct.c_bool(False),\
                                                 MaxIterations = ct.c_int(50),\
                                                 PrintInfo = ct.c_bool(True),\
                                                 NumLoadSteps = ct.c_int(25),\
                                                 Solution = ct.c_int(112),\
                                                 MinDelta = ct.c_double(1e-4))
                    
                    # Beam inputs.
                    XBINPUT = DerivedTypes.Xbinput(3,NumElems)
                    XBINPUT.BeamLength = 16.0
                    XBINPUT.BeamStiffness[0,0] = 1.0e+09
                    XBINPUT.BeamStiffness[1,1] = 1.0e+09
                    XBINPUT.BeamStiffness[2,2] = 1.0e+09
                    XBINPUT.BeamStiffness[3,3] = 1.0e+04
                    XBINPUT.BeamStiffness[4,4] = 2.0e+04
                    XBINPUT.BeamStiffness[5,5] = 5.0e+06
                    
                    XBINPUT.BeamStiffness[:,:] = 1.0*XBINPUT.BeamStiffness[:,:]
                    
                    XBINPUT.BeamMass[0,0] = 0.75
                    XBINPUT.BeamMass[1,1] = 0.75
                    XBINPUT.BeamMass[2,2] = 0.75
                    XBINPUT.BeamMass[3,3] = 0.1
                    XBINPUT.BeamMass[4,4] = 0.001
                    XBINPUT.BeamMass[5,5] = 0.001
                    
                    
                    # Aero solver options.
                    VMOPTS = DerivedTypesAero.VMopts(M = MSect,\
                                                     N = XBINPUT.NumNodesTot - 1 ,\
                                                     ImageMethod = True,\
                                                     Steady = True,\
                                                     KJMeth = True)
                    
                    # Aero inputs.
                    VMINPUT = DerivedTypesAero.VMinput(c = 1.0, b = XBINPUT.BeamLength,\
                                                       U_mag = 25.0,\
                                                       alpha = 4.0*np.pi/180.0,\
                                                       theta = 0.0)
                    
                    # Aeroelastic opts.
                    # Density due to US standard atmosphere at 20km
                    AELAOPTS = AeroelasticOps(0.0,0.0,0.08891)
                    
                           
                    PosDefor, PsiDefor = Solver.Solve_Py(XBINPUT,XBOPTS,\
                                                         VMOPTS,VMINPUT,\
                                                         AELAOPTS)
                    
                    # Delete currently unused objects.
                    del PsiDefor
                    
                    # Write tip deflection to file.
                    FileKJ.write("%12.5e  " %(PosDefor[-1,2]))
                    if MSect == MSectArr[-1]:
                        FileKJ.write("\n")
                    
                    
                    # Change to Katz &Plotkin force calculation.
                    VMOPTS.KJMeth = ct.c_bool(False)
                    
                    PosDefor, PsiDefor = Solver.Solve_Py(XBINPUT,XBOPTS,\
                                                         VMOPTS,VMINPUT,\
                                                         AELAOPTS)

                    # Delete currently unused objects.
                    del PsiDefor
                    
                    # Write tip deflection to file.
                    FileKP.write("%12.5e  "%(PosDefor[-1,2]))
                    if MSect == MSectArr[-1]:
                        FileKP.write("\n")
                    
                # END for MSect
            # END for NumNodes
            FileKJ.close()
            FileKP.close()