def uncompress_pubkey(compressedPubKey):
    """
    Turn a 02/03 prefix public key into an uncompressed 04 key

    pow_mod() and most of this function taken from:
    https://bitcointalk.org/index.php?topic=644919.msg7205689#msg7205689
    """

    try:
        test1 = unhexlify(compressedPubKey)
        test2 = int(compressedPubKey,16)
        tast1,test2 = "",""
    except:
        raise Exception('uncompress_pubkey() input not hex')
    #Sanitize input key
    compressedPubKey = hex_to_hexstr(hexlify(unhexlify(compressedPubKey))).zfill(66)
    if (len(compressedPubKey) != 66) \
     or ((compressedPubKey[:-64] != '02') \
      and (compressedPubKey[:-64] != '03')):
        raise Exception('uncompress_pubkey() Unknown input error')
    y_parity = int(compressedPubKey[:2],16) - 2
    x = int(compressedPubKey[2:],16)
    a = (pow_mod(x, 3, P_CURVE) + 7) % P_CURVE
    y = pow_mod(a, (P_CURVE+1)//4, P_CURVE)
    if y % 2 != y_parity:
        y = -y % P_CURVE
    x = hexstrlify(x,64)
    y = hexstrlify(y,64)
    return hexlify(unhexlify('04' + x + y))
def base58_encode(a,version='',postfix=''):
    """
    Base58 encode input

    Mostly ripped from:
    https://github.com/jgarzik/python-bitcoinlib/blob/master/bitcoin/base58.py
    """

    try:
        a = hexlify(unhexlify(a))
        version = hexlify(unhexlify(version))
        postfix = hexlify(unhexlify(postfix))
    except:
        raise Exception('base58_encode() Invalid input')
    a, version, postfix = hex_to_hexstr(a), hex_to_hexstr(version), hex_to_hexstr(postfix)
    b = version + a + postfix
    b58_digits = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
    n1 = int(b,16)
    res = []
    while n1 > 0:
        n1, r = divmod(n1,58)
        res.append(b58_digits[r])
    res = ''.join(res[::-1])
    pad = 0
    for i in range(len(b) // 2):
        j = int(2*i)
        teststr = str(b[j] + b[j+1])
        if teststr == '00':
            pad += 1
        else:
            break
    return str(b58_digits[0] * pad + res)
예제 #3
0
def handleWritingClassTest():
    from __builtin__ import int
    from __builtin__ import float
    hwLabels = []
    trainingFileList = listdir('trainingDigits')
    numTrainingFiles = len(trainingFileList)
    trainingMatrix = zeros((numTrainingFiles, 1024))
    for i in range(numTrainingFiles):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]
        savedNum = int(fileStr.split('_')[0])
        hwLabels.append(savedNum)
        trainingMatrix[i, :] = image2Vector('trainingDigits/%s' % fileNameStr)

    testFileList = listdir('testDigits')
    errorCount = 0.0
    numTests = len(testFileList)
    for i in range(numTests):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        savedNum = int(fileStr.split('_')[0])
        vectorUnderTest = image2Vector('testDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest, trainingMatrix, hwLabels,
                                     3)
        print 'the classifier came back with: %d, the real answer is: %d' % (
            classifierResult, savedNum)
        if (classifierResult != savedNum):
            errorCount += 1.0
    print('\nthe total number of tests: %d, the total number of errors: %d\n' %
          (numTests, errorCount))
    print('\nthe total error rate is: %s' % (errorCount / float(numTests)))
예제 #4
0
파일: start.py 프로젝트: lenwen/elzecsp
def databasecheck():
    dbcon = None
    try:
        if not os.path.isfile(settings.PathDb):
            debug("the db file don't exist. create db file")
            dbcon = dblite.connect(settings.PathDb)
            with dbcon:
                cur = dbcon.cursor()
                cur.execute("CREATE TABLE settings(name VARCHAR, value TEXT);")
                cur.execute("CREATE UNIQUE INDEX index_Settings_Uni_Name on settings (name);")
                cur.execute("INSERT INTO settings VALUES('dbversion', '1');")
                cur.execute("INSERT INTO settings VALUES('version', '0.0.0');")
                cur.execute("INSERT INTO settings VALUES('autoshutdown', '0');")
        else:
            dbcon = dblite.connect(settings.PathDb)
            debug("db file exist.")

        #   open version of the database schema
        cur = dbcon.cursor()
        cur.execute("select value from settings where name = 'dbversion'")
        settings.dbVersionFromDatabase = cur.fetchone()[0]

        debug('Database version in database: {}'.format(settings.dbVersionFromDatabase))

        if int(settings.dbVersionFromDatabase) == 0:
            debug("Database ERROR.. application will now exit.")
            shutdown()
        if int(settings.dbVersionFromDatabase) < 1:
            debug("Run database upgrade 1")


        print "Connections is OK!"
    except Exception:
        print "error in db"
        shutdown()
예제 #5
0
    def getHtmlData(self,awbNumber):

        try:
            self.outputLog('%s-%s start...' % (self.type,awbNumber))

            headers = self.defaultHeaders()
            urlAirChinaCargoTracking = 'http://www.airchinacargo.com/search_order.php'
            aaCargoPostData = {'trackingPath':'track10'
    ,'orders10':'{0}'.format(self.type)
    ,'orders0':'{0}'.format(awbNumber)
    ,'orders11':''
    ,'orders1[':''
    ,'orders12':''
    ,'orders2':''
    ,'orders13':''
    ,'orders3':''
    ,'orders14':''
    ,'orders4':''
    ,'orders9':''
    ,'section':'0-0001-0003-0081'
    ,'x[6]':'0'
    ,'y[6]':'0'}
       
            self.outputLog('request web.')
            htmlSource = self.httPost(urlAirChinaCargoTracking,aaCargoPostData,'UTF-8',headers)
            pattern = r'<tr.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?</tr>'
            match = re.findall(pattern, htmlSource,re.DOTALL | re.MULTILINE)

            rcsType = 'RCS'
            rcfType = 'RCF'
            rcsNumber = 0
            rcfNumber = 0

            self.outputLog('analyze data...')
            jsonData = {}
            for x in match:
                if rcsType in x[0]:     #状态名称format by RCS(货物收运)
                    rcsNumber = int(str(x[2]).strip())
                    jsonData['ATD'] = str(match[1][5]).strip()
                    jsonData['MAWB_NO'] = '-'.join((self.type,awbNumber))
                if rcfType in x[0]:
                    rcfNumber = rcfNumber + int(str(x[2]).strip())

            if rcsNumber == rcfNumber and rcsNumber != 0 and rcfNumber != 0:   #当两数相等时候ATD时间出现
                jsonHtmlSource = {}
                jsonHtmlSource['htmlSource'] = htmlSource
                jsonData['ATA'] = str(x[5]).strip()
                self.outputLog('save data to the data base')
                self.Insert('air_china_cargo_analyze',json.dumps(jsonData))
                self.Insert('air_china_cargo',json.dumps(jsonHtmlSource))
                self.outputLog('{type}-{awbNumber} done.'.format(type=self.type,awbNumber=awbNumber))
            else:
                return self.errorStatus

        except Exception,e:
            self.outputLog('getHtmlData {0}'.format(e))
            return self.errorStatus
예제 #6
0
 def increaseEmployeeSalary(self, employee, ratio):
     increased_amount = int(
         employee.sallaryPerDay) + int(employee.sallaryPerDay) * ratio / 100
     #assigning new value to employee
     employee.sallaryPerDay = str(increased_amount)
     print("Salary Per Day info has been updated for " + employee.name +
           " " + employee.surname + ". " + employee.sallaryPerDay +
           " will be paid after " + str(datetime.now().strftime('%b')) +
           "/" + str(datetime.now().strftime('%y')))
예제 #7
0
 def change_data(self, stock_dict):
     if isinstance(stock_dict, dict):
         self.current_val = stock_dict['close']
         self.high_val = stock_dict['high']
         self.low_val = stock_dict['low']
         self.close_val = stock_dict['close']
         self.open_val = stock_dict['open']
         self.day_amount = stock_dict['amount']
         time = stock_dict['day'].split('-')
         self.time = datetime.date(int(time[0]), int(time[1]), int(time[2]))
예제 #8
0
    def New_Game(self, gameData):
        Logger.info('New_Game FIRED')

        config = ChicagoApp.get_running_app().config
        pCount = int(config.getdefault("Varients", "playerCount", "2")) + 1
        pInfo = {}
        for index in range(1, pCount):
            #pInfo[index] = {'name': 'Player' + str(index), 'cpu': False}
            pInfo[index] = {
                'name':
                config.getdefault("Players", "PlayerCount" + str(index),
                                  "Player" + str(index)),
                'cpu':
                config.getdefault("Players", "p" + str(index) + "CPU", False)
            }
        gs = Game_Screen(
            name='gameScreen',
            playerCount=pCount,
            handCount=5,
            players=pInfo,
            chicagoTwo=config.getdefault("Varients", "chicagoTwo", True),
            rounds=int(config.getdefault("Varients", "roundCount", "2")),
            pokerRoundScoring=config.getdefault("Varients",
                                                "pokerRoundScoring", False),
            pokerAfterShowdownScoring=config.getdefault(
                "Varients", "pokerAfterShowdownScoring", True),
            cardExchangePointsLimit=config.getdefault(
                "Varients", "cardExchangePointsLimit", "46"),
            negativeScoring=config.getdefault("Varients", "negativeScoring",
                                              True),
            fourOfaKindReset=config.getdefault("Varients", "fourOfaKindReset",
                                               False),
            viewDiscards=config.getdefault("Varients", "viewDiscards", True),
            chicagoDestroy=config.getdefault("Varients", "chicagoDestroy",
                                             False),
            Player1="{:<6}".format(
                config.getdefault("Players", "Player1", False)),
            Player2="{:<6}".format(
                config.getdefault("Players", "Player2", False)),
            Player3="{:<6}".format(
                config.getdefault("Players", "Player3", False)),
            Player4="{:<6}".format(
                config.getdefault("Players", "Player4", False)),
            p1CPU=config.getdefault("Players", "p1CPU", False),
            p2CPU=config.getdefault("Players", "p2CPU", False),
            p3CPU=config.getdefault("Players", "p3CPU", False),
            p4CPU=config.getdefault("Players", "p4CPU", False),
            gameData=gameData)
        if self.root.has_screen('gameScreen'):
            self.root.remove_widget(self.root.get_screen('gameScreen'))
        self.root.add_widget(gs)
        Logger.info('screens = ' + str(self.root.screen_names))
        self.root.transition = FadeTransition()
        self.root.current = 'gameScreen'
예제 #9
0
파일: flex.py 프로젝트: kek-pf-mx/dials
    def __call__(self, reflections):
        '''
    Select the reflections

    :param reflections: The reflections

    :return: The selection as a mask

    '''
        import __builtin__
        if self.column == 'intensity.sum.i_over_sigma':
            I = reflections['intensity.sum.value']
            V = reflections['intensity.sum.variance']
            mask1 = V > 0
            I = I.select(mask1)
            V = V.select(mask1)
            data = I / flex.sqrt(V)
        elif self.column == 'intensity.prf.i_over_sigma':
            I = reflections['intensity.prf.value']
            V = reflections['intensity.prf.variance']
            mask1 = V > 0
            I = I.select(mask1)
            V = V.select(mask1)
            data = I / flex.sqrt(V)
        else:
            mask1 = None
            data = reflections[self.column]
        if isinstance(data, double):
            value = __builtin__.float(self.value)
        elif isinstance(data, int):
            value = __builtin__.int(self.value)
        elif isinstance(data, size_t):
            value = __builtin__.int(self.value)
        elif isinstance(data, std_string):
            value = self.value
        elif isinstance(data, vec3_double):
            raise RuntimeError("Comparison not implemented")
        elif isinstance(data, vec2_double):
            raise RuntimeError("Comparison not implemented")
        elif isinstance(data, mat3_double):
            raise RuntimeError("Comparison not implemented")
        elif isinstance(data, int6):
            raise RuntimeError("Comparison not implemented")
        elif isinstance(data, shoebox):
            raise RuntimeError("Comparison not implemented")
        else:
            raise RuntimeError('Unknown column type')
        mask2 = self.op(data, self.value)
        if mask1 is not None:
            mask1.set_selected(size_t(range(len(mask1))).select(mask1), mask2)
        else:
            mask1 = mask2
        return mask1
예제 #10
0
 def post(self, stuff):
     inUser = self.request.get('user')
     inISBN = self.request.get('isbn')
     inBookmark = self.request.get('bookmark')
     inPagesRead = self.request.get('pagesRead')
     q = db.GqlQuery("SELECT * FROM Stat " + "WHERE owner = :1 AND isbn = :2", inUser, int(inISBN))
     for record in q.run(limit=1):
         record.bookmark = int(inBookmark)
         if(int(inPagesRead) > record.pagesRead):
             record.pagesRead = int(inPagesRead)
         db.put(record)
     return	
예제 #11
0
    def customise_query(self, query, kw):
        start = int(kw['start']) if 'start' in kw else 0
        limit = int(kw['limit']) if 'limit' in kw else 0

        if start > 0:
            query = query.offset(start)

        if limit > 0:
            query = query.limit(limit)

        print str(query)
        return query
예제 #12
0
def merger(dataSet):
    time = dataSet[:, 0]
    duration = dataSet[:, 1]
    for a in range(0, len(time)):
        tempDuration = str(int(duration[a]))
        tempTime = str(int(time[a]))
        if (len(tempDuration) < 6):
            for b in range(len(tempDuration), 6):
                tempDuration = '0' + tempDuration
        tempDuration = tempDuration[0:2]
        dataSet[a,0] = float(tempTime + tempDuration)
    return dataSet
예제 #13
0
파일: flex.py 프로젝트: biochem-fan/dials
  def __call__(self, reflections):
    '''
    Select the reflections

    :param reflections: The reflections

    :return: The selection as a mask

    '''
    import __builtin__
    if self.column == 'intensity.sum.i_over_sigma':
      I = reflections['intensity.sum.value']
      V = reflections['intensity.sum.variance']
      mask1 = V > 0
      I = I.select(mask1)
      V = V.select(mask1)
      data = I / flex.sqrt(V)
    elif self.column == 'intensity.prf.i_over_sigma':
      I = reflections['intensity.prf.value']
      V = reflections['intensity.prf.variance']
      mask1 = V > 0
      I = I.select(mask1)
      V = V.select(mask1)
      data = I / flex.sqrt(V)
    else:
      mask1 = None
      data = reflections[self.column]
    if type(data) == double:
      value = __builtin__.float(self.value)
    elif type(data) == int:
      value = __builtin__.int(self.value)
    elif type(data) == size_t:
      value = __builtin__.int(self.value)
    elif type(data) == std_string:
      value = self.value
    elif type(data) == vec3_double:
      raise RuntimeError("Comparison not implemented")
    elif type(data) == vec2_double:
      raise RuntimeError("Comparison not implemented")
    elif type(data) == mat3_double:
      raise RuntimeError("Comparison not implemented")
    elif type(data) == int6:
      raise RuntimeError("Comparison not implemented")
    elif type(data) == shoebox:
      raise RuntimeError("Comparison not implemented")
    else:
      raise RuntimeError('Unknown column type')
    mask2 = self.op(data, self.value)
    if mask1 is not None:
      mask1.set_selected(size_t(range(len(mask1))).select(mask1), mask2)
    else:
      mask1 = mask2
    return mask1
예제 #14
0
def intermediate_code(password,useLotAndSequence=False,lot=100000,sequence=1, \
                      owner_salt=os.urandom(8)):
    '''
    Generates an intermediate code, as outlined by the BIP0038
    wiki, found at:

    https://github.com/bitcoin/bips/blob/master/bip-0038.mediawiki

    Output is a string, beginning with 'passphrase'. Lot and
    sequence inputs are ints.  Even though the Lot range is only
    recommended to be in the range 100000-999999, that
    recommendation is enforced in this code. Sequence is in the
    range 0-4095. Sequence starts at one instead of zero, as per
    the wiki recommendation.

    Also, note that the wiki test vectors do not include examples
    for compressed keys with EC multiplication. Nor does the 
    Bitcoin Address Utility reference implementation successfully
    identify 'cfrm38' confirmation codes for compressed keys.
    This python implementation works with them, and the Bitcoin
    Address Utility can still decrypt the '6P' encrypted private
    keys for compressed public keys, but for compatibility with
    the reference implementation, it is highly recommended that
    you create encrypted keys and confirmation codes only for
    uncompressed public keys when using an intermediate code to
    create EC multiplied encryped private keys with confirmation
    codes.
    '''

    password = normalize_input(password, False, True)
    assert len(owner_salt) == 8 or \
          (len(owner_salt) == 4 and useLotAndSequence)
    if useLotAndSequence:
        lot, sequence = int(lot), int(sequence)
        assert lot >= 100000 and lot <= 999999
        assert sequence >= 0 and sequence <= 4095
        lotsequence = dechex((lot*4096 + sequence),4)
        owner_salt = owner_salt[:4]
        prefactor = scrypt.hash(password,owner_salt,16384,8,8,32)
        prefactor = hexstrlify(prefactor)
        owner_entropy = hexstrlify(owner_salt) + lotsequence
        passfactor = hash256(prefactor + owner_entropy)
        magicbytes = '2ce9b3e1ff39e251'
    else:
        passfactor = scrypt.hash(password,owner_salt,16384,8,8,32)
        passfactor = hexstrlify(passfactor)
        owner_entropy = hexstrlify(owner_salt)
        magicbytes = '2ce9b3e1ff39e253'
    passpoint = privtopub(passfactor,True)
    return b58e(magicbytes + owner_entropy + passpoint)
예제 #15
0
    def testNodesToCheckForConflictingX(self):
        filePath = Utils.getAssetPath("test/setRelativeXToParent.json")
        nodeList = SaveManager.loadNodeDataListKeyConvertedToInt(filePath)

        reingold = ReingoldTilford()

        name = "3"
        node = nodeList[int(name)]
        self.assertTrue(reingold.checkForConflicts(node, nodeList, True),
                        name + " is not being checked for conflict")

        name = "4"  # Main node
        node = nodeList[int(name)]
        self.assertTrue(reingold.checkForConflicts(node, nodeList, True),
                        name + " is not being checked for conflict")
예제 #16
0
    def post(self, studentID):
        self.setupUser()
       
        fName = self.request.get('firstName')
        lName = self.request.get('lastName')
        UserName = self.request.get('user')
        Password = self.request.get('password')
        teacher = self.request.get('teacher')
        grade = self.request.get('grade')

        newStudent = Student(firstName = fName,
                             lastName = lName,
							 user = UserName,
							 password = Password,
                             teacher = teacher, 
                             grade = int(grade),
                             bookList=[1113,1114],
                             )
        newStudent.put()
        newStat = Stat(parent = newStudent, isbn = 1113, owner = UserName, pagesRead = 0, bookmark = 1)
        newStat.put()
        newStat = Stat(parent = newStudent, isbn = 1114, owner = UserName, pagesRead = 0, bookmark = 1)
        newStat.put()
        self.redirect('/student')            
        return
예제 #17
0
 def form_valid(self, form):
     if not self.request.user.is_authenticated():
         return super(RegisterUserAddOrderView, self).form_invalid(form)
     basket = get_basket(self.request)
     if basket.count() < 1:
         return super(RegisterUserAddOrderView, self).form_invalid(form)
     addr = self.request.POST.get('addr')
     address = DeliveryAddress.objects.get(user=self.request.user, pk=int(addr))
     self.object = form.save(commit=False)
     self.object.address = str(address)
     self.object.ip = self.request.META['REMOTE_ADDR']
     self.object.user_agent = self.request.META['HTTP_USER_AGENT']
     self.object.status = STATUS_WAIT
     self.object.lite = False
     self.object.first_name = address.first_name
     self.object.middle_name = address.middle_name
     self.object.last_name = address.last_name
     self.object.phone = address.phone
     self.object.email = self.request.user.email
     self.object.user = self.request.user
     self.object.save()
     success_add_items = make_order_from_basket(self.object, basket)
     if success_add_items is not True:
         self.object.delete()
         return super(RegisterUserAddOrderView, self).form_invalid(form)
     send_new_order_seller(self.object)
     send_new_order_buyer(self.object, [self.request.user.email])
     return super(RegisterUserAddOrderView, self).form_valid(form)
def read_config():
    if len(sys.argv) < 4:
        print sys.argv
        print 'Missing required parameters. task, conf folder and operation'
        exit(1)

    global task_name, operator, timeout
    config_folder, task_name, operator = sys.argv[1], sys.argv[2], sys.argv[3]

    if len(sys.argv) > 4:
        timeout = int(sys.argv[4])

    if config_folder.find('/') > 0:
        config_file = os.path.dirname(
            os.path.abspath(__file__)) + os.sep + config_folder
    else:
        config_file = os.path.dirname(os.path.abspath(
            __file__)) + os.sep + config_folder + os.sep + 'config.properties'
    print 'task:{}, config file:{}'.format(task_name, config_file)

    conf = common_util.load_properties(config_file)
    task_conf = {}
    for key, value in conf.items():
        if key.find(task_name + '.') == 0:
            task_conf[key.replace(task_name + '.', '')] = value

    return task_conf
예제 #19
0
 def ValidateIdentificationSize(self, objtest, idIdentificationType,
                                identificationNumber):
     #rec = self.GetIdentificationTypeByID(idIdentificationType)
     rec = objtest.search([('id', '=', idIdentificationType)])
     if (len(identificationNumber) == int(rec.charactersAmount)):
         return True
     return False
예제 #20
0
 def __open_serial_port__(self):
     port = self.comboBoxPort.currentIndex()
     self.reg.setPort(port)
     baud = int("%s" % self.comboBoxBaud.currentText(), 10)
     self.reg.setBaud(baud)
     username = self.textEditUsername.toPlainText()
     self.reg.setUsername(username)
     password = self.textEditPassword.text()
     self.reg.setPassword(password)
     email = self.textEditEmail.toPlainText()
     self.reg.setEmail(email)
     self.reg.sDeviceUUID(getserial())
     if self._serial_context_.isRunning():
         self._serial_context_.close()
         self.pushButtonOpenSerial.setText(u'Open/Save')
     else:
         self._serial_context_ = serialportcontext.SerialPortContext(
             port=port, baud=baud)
         self._serial_context_.registerReceivedCallback(
             self.__data_received__)
         self.checkBoxDTR.setChecked(True)
         self._serial_context_.setDTR(True)
         self.checkBoxRTS.setChecked(True)
         self._serial_context_.setRTS(True)
         self._serial_context_.open()
         self.pushButtonOpenSerial.setText(u'Close/Save')
     self.reg.writeDB()
예제 #21
0
def leerFicheros():
    archivoPeliculas = open("../bd/peliculas.txt", "r")
    
    for linea in archivoPeliculas.readlines():
        listaDatosPelicula = linea.split(";")
        pelicula = Pelicula(listaDatosPelicula[0], listaDatosPelicula[1], listaDatosPelicula[2], listaDatosPelicula[3], listaDatosPelicula[4], listaDatosPelicula[5])
        lista_peliculas.append(pelicula)
        
    archivoPeliculas.close()
    
    archivoSeries = open("../bd/series.txt", "r")

    for linea in archivoSeries.readlines():
        listaDatosSerie = linea.split(";")
        
        numeroTemporadas = listaDatosSerie[6];
        numeroCapitulos = listaDatosSerie[7];
        lista_temporadas = []
        
        for contador in range(0, int(numeroTemporadas)):
            lista_temporadas.append(numeroCapitulos)
        
        serie = Serie(listaDatosSerie[0], listaDatosSerie[1], listaDatosSerie[2], listaDatosSerie[3], listaDatosSerie[4], listaDatosSerie[5], lista_temporadas)
        lista_series.append(serie)
    
    archivoSeries.close()
예제 #22
0
파일: main.py 프로젝트: isiomaC/CLoudStore
    def get(self, cwd, type, id):

        user = users.get_current_user()
        myuser = ndb.Key('MyUser', user.user_id()).get()
        workDir = Directory.get_by_id(cwd, myuser.key)

        if user and workDir:
            if type == 'file':
                index = int(id)
                recycle = RecycleBin(parent=myuser.key,
                                     parent_id=workDir.key.id(),
                                     file=workDir.files[index])
                del workDir.files[index]
                recycle.put()
                workDir.put()

            elif type == 'dir':

                dirInWorkDir = Directory.get_by_id(id, myuser.key)

                if dirInWorkDir and dirInWorkDir.parent_id == workDir.key.id():

                    if Directory.query(Directory.parent_id == dirInWorkDir.key.
                                       id()).count() == 0 and len(
                                           dirInWorkDir.files) == 0:

                        RecycleBin(parent_id=dirInWorkDir.parent_id,
                                   parent=myuser.key,
                                   dir=dirInWorkDir,
                                   id=dirInWorkDir.key.id()).put()

                        dirInWorkDir.key.delete()
        self.redirect('/cwd/' + cwd)
예제 #23
0
 def __init__(self,
              dtype_or_func=None,
              default=None,
              missing_values=None,
              locked=False):
     # Defines a lock for upgrade
     self._locked = bool(locked)
     # No input dtype: minimal initialization
     if dtype_or_func is None:
         self.func = str2bool
         self._status = 0
         self.default = default or False
         ttype = np.bool
     else:
         # Is the input a np.dtype ?
         try:
             self.func = None
             ttype = np.dtype(dtype_or_func).type
         except TypeError:
             # dtype_or_func must be a function, then
             if not hasattr(dtype_or_func, '__call__'):
                 errmsg = "The input argument `dtype` is neither a function"\
                          " or a dtype (got '%s' instead)"
                 raise TypeError(errmsg % type(dtype_or_func))
             # Set the function
             self.func = dtype_or_func
             # If we don't have a default, try to guess it or set it to None
             if default is None:
                 try:
                     default = self.func('0')
                 except ValueError:
                     default = None
             ttype = self._getsubdtype(default)
         # Set the status according to the dtype
         _status = -1
         for (i, (deftype, func, default_def)) in enumerate(self._mapper):
             if np.issubdtype(ttype, deftype):
                 _status = i
                 self.default = default or default_def
                 break
         if _status == -1:
             # We never found a match in the _mapper...
             _status = 0
             self.default = default
         self._status = _status
         # If the input was a dtype, set the function to the last we saw
         if self.func is None:
             self.func = func
         # If the status is 1 (int), change the function to smthg more robust
         if self.func == self._mapper[1][1]:
             self.func = lambda x: int(float(x))
     # Store the list of strings corresponding to missing values.
     if missing_values is None:
         self.missing_values = set([''])
     else:
         self.missing_values = set(list(missing_values) + [''])
     #
     self._callingfunction = self._strict_call
     self.type = ttype
     self._checked = False
예제 #24
0
def show_count_stats(
      counts,
      group_size=10,
      label_0="None",
      out=None,
      prefix=""):
  assert counts.size() != 0
  if (out is None): out = sys.stdout
  from __builtin__ import int, max
  counts_sorted = sorted(counts, reverse=True)
  threshold = max(1, int(counts_sorted[0] / group_size) * group_size)
  n = counts_sorted.size()
  wt = max(len(label_0), len(str(threshold)))
  wc = len(str(n))
  fmt_val  = prefix + ">= %%%dd:  %%%dd  %%7.5f" % (wt, wc)
  fmt_zero = prefix + "   %s:  %%%dd  %%7.5f" % (("%%%ds" % wt) % label_0, wc)
  for i,count in enumerate(counts_sorted):
    if (count >= threshold): continue
    assert count >= 0
    if (i > 0):
      print >> out, fmt_val % (threshold, i, i/n)
    if (count == 0):
      print >> out, fmt_zero % (n-i, 1-i/n)
      break
    threshold = max(1, threshold-group_size)
  else:
    print >> out, fmt_val % (threshold, n, 1)
예제 #25
0
    def post(self, stuff):
        newUserName = self.request.get('user')
        newUserPassword = self.request.get('password')
        newUserFirstName = self.request.get('firstName')
        newUserlastName = self.request.get('lastName')
        newUserTeacher = self.request.get('teacher')
        newUserGrade = self.request.get('grade')
        newUserPin = self.request.get('pinNumber')

        q = db.GqlQuery("SELECT * FROM Student " + "WHERE user = :1", newUserName)
        if q.count() >= 1:
            #return error that this invalid
            self.response.out.write("Failure")
            logging.debug("invalid user being added")
        else:
            #if error here, remove the int cast and just let the userpin be a string
            newUser = Student(user = newUserName,
                              firstName = newUserFirstName,
                              lastName = newUserlastName, 
                              password = newUserPassword,
                              teacher = newUserTeacher,
                              grade = int(newUserGrade),
                              bookList = [1113, 1114, 1115, 1116 , 1117, 1119, 1120, 1121, 1123])
            newUser.put()   
            newStat = Stat(parent = newUser, isbn = 1113, owner = newUserName, pagesRead = 0, bookmark = 1)
            newStat.put()
            newStat = Stat(parent = newUser, isbn = 1114, owner = newUserName, pagesRead = 0, bookmark = 1)
            newStat.put()
            
            self.response.out.headers['Content-Type'] = "text"
            self.response.headers.add_header('Access-Control-Allow-Origin', '*')
            self.response.out.write("Success")
예제 #26
0
    def getTiers(self, show, description=None):
        descriptions, description_content = self.getDescriptions(show)
        if not description_content:
            return None
        current_tier_data = {}
        if description:
            if description not in description_content:
                return None
            current_tier_data = {description: description_content[description]}
        else:
            current_tier_data = description_content
        chunks = ['current_show', 'description', 'enabled', 'name']
        tiers = {}
        for des, contents in current_tier_data.items():
            result, index = [], 0
            while index < len(contents) + 1:
                x = 0
                for k, v, in contents.items():

                    if k in chunks:
                        continue
                    if x > len(contents):
                        break
                    order = int(k)
                    if order != index:
                        continue
                    result.append(v.encode())
                    x += 1
                index += 1
            tiers.setdefault(des.encode(), result)
        return tiers
예제 #27
0
 def rowcolframes(f):       
     rows = 0
     cols = 0
     frames = 0
     for line in f:
         split = line.split()
         if len(split) == 2:
             if split[0] == rows_tag:
                 rows = int(split[1])
             elif split[0] == cols_tag:
                 cols = int(split[1])
             elif split[0] == frames_tag:
                 frames = int(split[1])
                 break    
     f.seek(0)
     return rows, cols, frames
예제 #28
0
def merge_sort(A):
    if len(A) <= 1:
        return A
    middle = int(len(A) / 2)
    left = merge_sort(A[:middle])
    right = merge_sort(A[middle:])
    return merge(left, right)
예제 #29
0
def displayDonors(table, headerBoxes, headerToFuncDict, clinicalInformationCheckbox):
    colCounter = 0
    rowCount = int(table.rowCount())
    table.insertRow(rowCount)
    for header in headerBoxes:
        if header == clinicalInformationCheckbox:
            if clinicalInformationCheckbox.isChecked():
                headerList = ['Abnormal Lab Results', 'Clinical Notes', 'Allergies', 'Diet', 'Other' ]
                infoFunc = headerToFuncDict[header] 
                info = infoFunc() 
                for headerString in headerList:
                    item = QtGui.QTableWidgetItem()
                    stringInfo = ''
                    if info.has_key(headerString):
                        stringInfo = info[headerString]
                    item.setText(QtCore.QString(stringInfo))
                    table.setItem(rowCount,colCounter, item)
                    colCounter = colCounter+1
            continue
        item = QtGui.QTableWidgetItem()
        donorFunc = headerToFuncDict[header]
        if isinstance(donorFunc(), int) or isinstance(donorFunc(), float):
            value = donorFunc()
            item.setData(QtCore.Qt.DisplayRole, value)
            item.setText(QtCore.QString(str(value)))
        else:
            displayString = str(donorFunc()) 
            item.setText(QtCore.QString(displayString))
        table.setItem(rowCount, colCounter, item)
        colCounter = colCounter + 1 
    exampleData = table.itemAt(1,0).data(QtCore.Qt.DisplayRole)
    table.resizeColumnsToContents()
예제 #30
0
def div(bitmap, integer):
    n,size = bitmap
    max = 2**abs(size)
    if size < 0:
        sf = 2**(abs(size)-1)
        n = (n-max) if n&sf else n&(sf-1)
    return __builtin__.int(float(n)/integer)&(max-1),size
예제 #31
0
def step(context, button_name):
    if not context.userData:
        context.userData = {}

    if button_name not in top_buttons_calendar_ui.keys():
        app.fail("in calendar, the button '"
                 + button_name
                 + "' is not known!")
        return
    button = top_buttons_calendar_ui[button_name]
    month_delta = 1 if (top_buttons_calendar_ui.keys()[0]
                     == button_name) else -1

    app.switch_to_app('calendar')
    squish.snooze(0.25)

    squish.tapObject(button)

    squish.snooze(0.5)
    grid_for_info = squish.waitForObject(names.topCalendarGrid)

    month_now = __builtin__.int(str(grid_for_info.month))
    month_before = context.userData['month']

    month_change = (month_before + month_delta) % 12
    app.compare(str(month_change + 1), str(month_now + 1), " month changes")
예제 #32
0
def displayHeaders(table, headers, clinicalInformationCheckbox):
    table.setColumnCount(len(headers)-1)
    colCounter = 0
    for header in headers:
        if header == clinicalInformationCheckbox:
            if clinicalInformationCheckbox.isChecked():
                curColCount = int(table.columnCount())
                newColCount = curColCount+5
                table.setColumnCount(newColCount)
                headerList = ['Abnormal Lab Results', 'Clinical Notes', 'Allergies', 'Diet', 'Other' ]
                for headerString in headerList:
                    item = QtGui.QTableWidgetItem()
                    item.setText(QtCore.QString(headerString))
                    table.setHorizontalHeaderItem(colCounter, item)
                    colCounter = colCounter+1
            continue
        item = QtGui.QTableWidgetItem()
        if isinstance(header, str):
            item.setText(QtCore.QString(header))
        elif isinstance(header, QtGui.QCheckBox):
            item.setText(header.text())
        table.setHorizontalHeaderItem(colCounter, item)
        colCounter = colCounter + 1
    
            
    
    
    
        


                
예제 #33
0
파일: bnf.py 프로젝트: flaviojs/pyparse
 def rule_Codepoint(self):
     r"""
     codepoint
         ' ' . '10FFFF'
         hexcode
     """
     # NOTE hexcode must come first because it is longer
     _hexcode = self.maybe(self.token_HEXCODE)
     if _hexcode is not None:
         _value = int(_hexcode, 16)
         return (
             'Codepoint',
             '.value',
             _value,
             '.hex',
             _hexcode,
         )
     _codepoint = self.maybe(self._codepoint, ord(' '), 0x10FFFF)
     if _codepoint is not None:
         _value, _str, = _codepoint
         return (
             'Codepoint',
             '.value',
             _value,
             '.str',
             _str,
         )
     assert False, (self.state, )  # not a rule_Codepoint?
예제 #34
0
파일: views.py 프로젝트: ukaoma/nnmware
 def form_valid(self, form):
     if not self.request.user.is_authenticated():
         return super(RegisterUserAddOrderView, self).form_invalid(form)
     basket = get_basket(self.request)
     if basket.count() < 1:
         return super(RegisterUserAddOrderView, self).form_invalid(form)
     addr = self.request.POST.get('addr')
     address = DeliveryAddress.objects.get(user=self.request.user, pk=int(addr))
     self.object = form.save(commit=False)
     self.object.address = str(address)
     self.object.ip = self.request.META['REMOTE_ADDR']
     self.object.user_agent = self.request.META['HTTP_USER_AGENT']
     self.object.status = STATUS_WAIT
     self.object.lite = False
     self.object.first_name = address.first_name
     self.object.middle_name = address.middle_name
     self.object.last_name = address.last_name
     self.object.phone = address.phone
     self.object.email = self.request.user.email
     self.object.user = self.request.user
     self.object.save()
     success_add_items = make_order_from_basket(self.object, basket)
     if success_add_items is not True:
         self.object.delete()
         return super(RegisterUserAddOrderView, self).form_invalid(form)
     send_new_order_seller(self.object)
     send_new_order_buyer(self.object, [self.request.user.email])
     return super(RegisterUserAddOrderView, self).form_valid(form)
def merge_sort(A):
    if len(A)<=1:
        return A
    middle = int(len(A)/2)
    left = merge_sort(A[:middle])
    right = merge_sort(A[middle:])
    return merge (left,right)
예제 #36
0
def show_count_stats(
      counts,
      group_size=10,
      label_0="None",
      out=None,
      prefix=""):
  assert counts.size() != 0
  if (out is None): out = sys.stdout
  from __builtin__ import int, max
  counts_sorted = sorted(counts, reverse=True)
  threshold = max(1, int(counts_sorted[0] / group_size) * group_size)
  n = counts_sorted.size()
  wt = max(len(label_0), len(str(threshold)))
  wc = len(str(n))
  fmt_val  = prefix + ">= %%%dd:  %%%dd  %%7.5f" % (wt, wc)
  fmt_zero = prefix + "   %s:  %%%dd  %%7.5f" % (("%%%ds" % wt) % label_0, wc)
  for i,count in enumerate(counts_sorted):
    if (count >= threshold): continue
    assert count >= 0
    if (i > 0):
      print(fmt_val % (threshold, i, i/n), file=out)
    if (count == 0):
      print(fmt_zero % (n-i, 1-i/n), file=out)
      break
    threshold = max(1, threshold-group_size)
  else:
    print(fmt_val % (threshold, n, 1), file=out)
    def parseText(self, log_file):
        """Meminfo data format:
           <key>:           <value> kB
           .....
           .....
           ---- ****
           Example:
           
           MemTotal:        3809032 kB
           MemFree:          495404 kB
           MemAvailable:    2133700 kB
           Buffers:            8140 kB
           Cached:          1256828 kB
           SwapCached:        86428 kB
           ....
           .....
           ---- /proc/stat
        """

        end_regexp = re.compile('---- ')
        data_regexp = re.compile(
            '(?P<key>^[a-zA-Z]+):\s+(?P<value>[0-9]+)\s+kB')
        line = log_file.readline()
        while line and not end_regexp.search(line):
            m = data_regexp.match(line)
            if m:
                value_name = m.group('key')
                self.data[value_name] = int(m.group('value'))
            line = log_file.readline()
        return line
예제 #38
0
def aes_decrypt_bip38(encMsg,key,pad='{'):
    """
    Very simple AES decryption, with parameters specifically for
    use in BIP0038.

    # Doctest done this way so it outputs the same for Python 2 and 3
    >>> hexstrlify(aes_decrypt_bip38(unhexlify("8f4b4aa6e27d1669ba5dd6039c16d4f1"),unhexlify("3cfc181482b735941483ec8f158314f9ada2aa0d6e4a5c15bd46515092716d3b")))
    '45e8364d907e802d87d3b29f4b527b49'
    >>> hexstrlify(aes_decrypt_bip38(unhexlify("1e7bddc6f793d4444e61a99f5e57fd44"),unhexlify("3cfc181482b735941483ec8f158314f9ada2aa0d6e4a5c15bd46515092716d3b")))
    '45e8364d907e802d87d3b29f4b7b7b7b'
    """

    pad = pad.encode('utf-8')
    key = hexstrlify(key)
    if len(key) != 64:
        raise Exception('aes_decrypt_bip38() key size must be 32 bytes')
    key = unhexlify(key)
    cipher = AES.new(key)
    msg = cipher.decrypt(encMsg)
    try:
        msg = msg.rstrip(pad)
    except:
        msg = msg.rstrip(bytes(pad,'utf-8'))
    if len(msg) != 16:
        if len(msg) > 16:
            raise Exception('aes_decrypt_bip38() decrypted msg larger than 16 bytes after pad strip')
        else:
            msg = msg + pad * int(16 - len(msg))
    return msg
    def _generate_fibers_in_pattern(self):
        '''
        Generate the number of fibers that will be used for each pattern.
        '''

        self.number_of_selected_fibers = int(self.number_of_fibers *
                                             self.rate_of_fibers_in_pattern)

        self.fibers_in_pattern = numpy.array([
            self.ran_generator.permutation(
                self.number_of_fibers)[0:self.number_of_selected_fibers]
            for _ in range(self.number_of_patterns)
        ])
        self.fibers_in_pattern.sort(axis=1)

        # Show fiber overlapping statistics
        for ind1 in range(self.number_of_patterns):
            for ind2 in range(ind1 + 1, self.number_of_patterns):
                intersect = numpy.intersect1d(self.fibers_in_pattern[ind1],
                                              self.fibers_in_pattern[ind2],
                                              assume_unique=True)
                logger.debug('Pattern %s and %s share %s input cells: %s',
                             ind1, ind2, len(intersect), intersect)

        return
    def _generate_length(self):
        '''
        Generate the length of each stimulation interval.
        '''
        # Generate the length of every frequency (starting from 2*T/mean_time elements)
        number_of_elements = int(self.simulation_time / self.mean_length)
        total_time = 0
        while (total_time < self.simulation_time):
            number_of_elements = 2 * number_of_elements
            # Round to ms the pattern length
            self.pattern_length = numpy.round(self.ran_generator.exponential(
                scale=self.mean_length, size=number_of_elements),
                                              decimals=3)
            # Avoid negative lengths
            self.pattern_length[self.pattern_length < 1.e-3] = 1.e-3
            total_time = self.pattern_length.sum()

        # Calculate the number of elements to include in the simulation
        self.pattern_length_cum = numpy.cumsum(a=self.pattern_length)
        first_index = numpy.where(
            self.pattern_length_cum >= self.simulation_time)[0][0]

        # Select those elements
        self.pattern_length = self.pattern_length[0:(first_index + 1)]
        self.pattern_length_cum = self.pattern_length_cum[0:(first_index + 1)]
        # Adjust the length of the last element to fit exactly the simulation length
        self.pattern_length[-1] = self.pattern_length[-1] - (
            self.pattern_length_cum[first_index] - self.simulation_time)
        self.pattern_length_cum[-1] = self.simulation_time

        return
예제 #41
0
    def get(self):
        self.setupUser(); 
        #Remove this code after dataStore Objects are created		
        query = Book.all();
        #DEMO CODE
        if query.count() == 0:
            newBook = Book(title = "Sleeping Beauty", genre = "Fantasy", isbn = int(1113), cover = "img/book_1.jpg", link = Host+"library/1113/")
            newBook.put()
        
            newBook = Book(title = "Moby Dick", genre = "Fantasy", isbn = int(1114), cover = "img/book_2.jpg", link = Host+"library/1114/")
            newBook.put()
 
            newBook = Book(title = "Where The Wild Things Are", genre = "Fantasy", isbn = int(1115), cover= "img/book_3.jpg" , link = Host+"library/1115/")
            newBook.put()
            		
        self.template_values['title'] = "Administrator View"
        self.render("main.html")    
예제 #42
0
def image2Vector(filename):
    returnVector = zeros((1, 1024))
    fileReader = open(filename)
    for i in range(32):
        lineStr = fileReader.readline()
        for j in range(32):
            returnVector[0, 32 * i + j] = int(lineStr[j])
    return returnVector
예제 #43
0
 def pack_decimal(dec, _=None):
     sign, digits, exponent = dec.as_tuple()
     unscaled = int(''.join(map(str, digits)))
     if sign:
         unscaled *= -1
     scale = _int_packer.pack(-exponent)
     unscaled = encode_int(unscaled)
     return scale + unscaled
예제 #44
0
def int(val):
    if val is None:
        return None
    if isinstance(val, six.string_types):
        val = val.replace(',', '')
        if val.strip() == '':
            return None
    return builtins.int(val)
예제 #45
0
def partitionTrainAndTest(dataSet, testRatio=0.2, shouldShuffle=True):
    dataSize = len(dataSet)
    if shouldShuffle:
        random.shuffle(dataSet)
    trainDataSize = int(dataSize * (1 - testRatio))
    trainData = dataSet[:trainDataSize]
    testData = dataSet[trainDataSize:]
    return (trainData, testData)
예제 #46
0
 def payMonthlySalaryOfEmployee(self, employee):
     #calculate monthly salary
     sallary_amount = employee.workedHours * int(employee.sallaryPerDay)
     print str(
         sallary_amount
     ) + " EUR Salary has been paid to " + employee.name + " " + employee.surname + " on " + str(
         datetime.now().strftime(
             '%Y-%m-%d %H:%M:%S')) + ". by %s location" % (self.location)
예제 #47
0
def int(val):
    if val is None:
        return None
    if isinstance(val, six.string_types):
        val = val.replace(',', '')
        if val.strip() == '':
            return None
    return builtins.int(val)
예제 #48
0
    def get_customer_id_from_uuid(self, uuid):
        result = self.session.connection().scalar(
            "SELECT id from customer WHERE uuid = \"%s\"" % uuid)

        if result:
            return int(result)
        else:
            return None
예제 #49
0
 def get(self,evento_id):
     iden = int(evento_id)
     evento = Eventos.get_by_id(iden)
     tags = Tag.query()
     
     tagsevento = map(lambda tag: tag.nombre, evento.tags) #Devuelve una lista de nombre de eventos (strings)
     
     self.render_template('editarevento.html', {'evento':evento, 'tags':tags, 'tagseventos':tagsevento})
예제 #50
0
    def get(self, bookID): 
                
        self.setupUser()
        
        self.setupJSON(bookID)
        loginUser = self.request.get('user')
        logging.debug("value of my var is %s", str(loginUser))
        query = Student.all()
        if (query.count() == 0):
            newStudent = Student(firstName="temp", lastName="temp", userName="******", password="******", books= [1113,1114])
            newStudent.put()
        q = db.GqlQuery("SELECT * FROM Student " + "WHERE user = :1",loginUser)
        theStudent = Student()
        for p in q.run(limit=1):
            theStudent = p
        if theStudent == None:
            libaryList = [1113,1114,1115]
        else:	
            libaryList = theStudent.bookList

        query = Book.all();
        #DEMO CODE
        if query.count() == 0:
            newBook = Book(title = "Sleeping Beauty", genre = "Fantasy", isbn = int(1113), cover = "img/book_1.jpg", link = Host+"library/1113/")
            newBook.put()
        
            newBook = Book(title = "Moby Dick", genre = "Fantasy", isbn = int(1114), cover = "img/book_2.jpg", link = Host+"library/1114/")
            newBook.put()
 
            newBook = Book(title = "Where The Wild Things Are", genre = "Fantasy", isbn = int(1115), cover= "img/book_3.jpg" , link = Host+"library/1115/")
            newBook.put()
            
            query = Book.all()
        
        if self.json:
            self.response.headers.add_header('Access-Control-Allow-Origin', '*')
            self.response.out.headers['Content-Type'] = "text/json"
            books = []
            #look through the books based on the isbn number
            for isbnN in libaryList:
                q = db.GqlQuery("SELECT * FROM Book " + "WHERE isbn = :1",int(isbnN))
                for book in q.run(limit=1):
                    books.append(book.dict())
            self.response.out.write(json.dumps(books))
            return       
 def parseText(self, log_file):
     """Data format:
        <cpu_id>    <user>  <nice> <system> <idle>    <iowait> <irq>  <softirq> <steal> <guest> <guest_nice>
        
        Example:
        cpu       74608 2520 24433  1117073 6176   4054 0       0     0     0 
     """
     end_regexp = re.compile('---- ')
     data_regexp = re.compile(''.join(
         ('(?P<cpu_id>^cpu[0-9]*) +', '(?P<user>[0-9]+) ',
          '(?P<nice>[0-9]+) ', '(?P<system>[0-9]+) '
          '(?P<idle>[0-9]+) '
          '(?P<iowait>[0-9]+) '
          '(?P<irq>[0-9]+) '
          '(?P<softirq>[0-9]+) '
          '(?P<steal>[0-9]+) '
          '(?P<guest>[0-9]+) '
          '(?P<guest_nice>[0-9]+)')))
     line = log_file.readline()
     while line and not end_regexp.search(line):
         m = data_regexp.match(line)
         if m:
             cpu_id = m.group('cpu_id')
             self.data[cpu_id] = {
                 'user': int(m.group('user')),
                 'nice': int(m.group('nice')),
                 'system': int(m.group('system')),
                 'idle': int(m.group('idle')),
                 'iowait': int(m.group('iowait')),
                 'irq': int(m.group('irq')),
                 'softirq': int(m.group('softirq'))
             }
         line = log_file.readline()
     return line
def base58_check_and_encode(a):
    """Perform base58 check and then encode input and checksum"""
    try:
        abc = unhexlify(a)
        defg = int(a,16)
    except:
        raise Exception('base58_check_and_encode() Invalid input')
    a = hexlify(unhexlify(a))
    return base58_encode(a,'',base58_check(a))
예제 #53
0
def fit(integer):
    '''Returns the number of bits necessary to contain integer'''
    return __builtin__.int(math.log(integer,2))+1

    count = 0
    while integer >= 2:
        count += 1
        integer >>= 1
    return count + 1
예제 #54
0
 def __init__(self, dtype_or_func=None, default=None, missing_values=None,
              locked=False):
     # Defines a lock for upgrade
     self._locked = bool(locked)
     # No input dtype: minimal initialization
     if dtype_or_func is None:
         self.func = str2bool
         self._status = 0
         self.default = default or False
         ttype = np.bool
     else:
         # Is the input a np.dtype ?
         try:
             self.func = None
             ttype = np.dtype(dtype_or_func).type
         except TypeError:
             # dtype_or_func must be a function, then
             if not hasattr(dtype_or_func, '__call__'):
                 errmsg = "The input argument `dtype` is neither a function"\
                          " or a dtype (got '%s' instead)"
                 raise TypeError(errmsg % type(dtype_or_func))
             # Set the function
             self.func = dtype_or_func
             # If we don't have a default, try to guess it or set it to None
             if default is None:
                 try:
                     default = self.func('0')
                 except ValueError:
                     default = None
             ttype = self._getsubdtype(default)
         # Set the status according to the dtype
         _status = -1
         for (i, (deftype, func, default_def)) in enumerate(self._mapper):
             if np.issubdtype(ttype, deftype):
                 _status = i
                 self.default = default or default_def
                 break
         if _status == -1:
             # We never found a match in the _mapper...
             _status = 0
             self.default = default
         self._status = _status
         # If the input was a dtype, set the function to the last we saw
         if self.func is None:
             self.func = func
         # If the status is 1 (int), change the function to smthg more robust
         if self.func == self._mapper[1][1]:
             self.func = lambda x : int(float(x))
     # Store the list of strings corresponding to missing values.
     if missing_values is None:
         self.missing_values = set([''])
     else:
         self.missing_values = set(list(missing_values) + [''])
     #
     self._callingfunction = self._strict_call
     self.type = ttype
     self._checked = False
예제 #55
0
    def docsPath(target):
        qtVersionStr = Qt5Path.__preCheckAndExtractQtVersionStr__(target)
        qtMinorVersion = __builtin__.int(qtVersionStr[1])
        if qtMinorVersion == 2:
            path = "doc"
        else:
            path = "Docs/Qt-5.%d" % qtMinorVersion

        return os.path.join(Qt5Path.__createPlatformQtPath__(qtMinorVersion), path)
예제 #56
0
def hex(bitmap):
    '''Return bitmap as a hex string'''
    n,s = bitmap
    size = abs(s)
    length = __builtin__.int(math.ceil(size/4.0))
    if s < 0:
        max,sf = 2**size,2**(size-1)
        n = (n-max) if n&sf else n&(sf-1)
        return '{:s}{:#0{:d}x}'.format('-' if n < 0 else '+', abs(n)&(max-1), length+2)
    return '{:#0{:d}x}'.format(n&(2**size)-1, length+2)
def compress_pub_key(uncompressedPubKey):
    """Compress an 04 prefix public key to a 02/03 key"""

    try:
        test1 = unhexlify(uncompressedPubKey)
        test2 = int(uncompressedPubKey,16)
        tast1,test2 = "",""
    except:
        raise Exception('compress_pub_key() input not hex')
    #Sanitize input key
    uncompressedPubKey = hex_to_hexstr(hexlify(unhexlify(uncompressedPubKey))).zfill(130)
    if uncompressedPubKey[:2] != '04':
        raise Exception('compress_pub_key() unknown error, key does not begin with 04')
    x_coordStr = uncompressedPubKey[2:66]
    y_coordStr = uncompressedPubKey[66:]
    if int(y_coordStr,16) % 2:
        outputHexStr = '03' + x_coordStr
    else:
        outputHexStr = '02' + x_coordStr
    return hexlify(unhexlify(outputHexStr))
예제 #58
0
def _evalname(name):
    k = 0
    for ch in name:
        if ch in '0123456789':
            break
        k += 1
    try:
        bits = int(name[k:])
    except ValueError:
        bits = 0
    base = name[:k]
    return base, bits
예제 #59
0
 def __init__(self, delimiter=None, comments='#', autostrip=True):
     self.comments = comments
     # Delimiter is a character
     if (delimiter is None) or _is_string_like(delimiter):
         delimiter = delimiter or None
         _handyman = self._delimited_splitter
     # Delimiter is a list of field widths
     elif hasattr(delimiter, '__iter__'):
         _handyman = self._variablewidth_splitter
         idx = np.cumsum([0] + list(delimiter))
         delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
     # Delimiter is a single integer
     elif int(delimiter):
         (_handyman, delimiter) = (self._fixedwidth_splitter, int(delimiter))
     else:
         (_handyman, delimiter) = (self._delimited_splitter, None)
     self.delimiter = delimiter
     if autostrip:
         self._handyman = self.autostrip(_handyman)
     else:
         self._handyman = _handyman
def getRestrictions(params):
	startDate=getDateFromString(params.StartDate)
	endDate=getDateFromString(params.EndDate)
	startLoc=params.StartLoc
	endLoc=params.EndLoc
	restLocs=set()
	if len(params.RestrictedLocations)>0:
		for loc in params.RestrictedLocations.split(","):
			restLocs.add(int(loc.strip(string.punctuation)))
	morningTime=getTimeFromString(params.MorningTime)
	eveningTime=getTimeFromString(params.EveningTime)
	return Restrictions(sd=startDate,ed=endDate,sl=startLoc,el=endLoc,rLocs=restLocs,startDriveTime=morningTime,endDriveTime=eveningTime)