Пример #1
0
    def test_multiple_interval_calculation(self):
        day = WorkDay()
        day.clear_interval()

        time_one = Time(12, 30, Meridian.PM)
        time_two = Time(2, 30, Meridian.PM)

        date_one = Date(4, 29, 2021)
        date_two = Date(4, 29, 2021)

        date_time_one = DateTime(date_one, time_one)
        date_time_two = DateTime(date_two, time_two)

        day.set_interval_start(date_time_one)
        day.end_current_interval(date_time_two)

        time_one = Time(2, 30, Meridian.PM)
        time_two = Time(4, 30, Meridian.PM)

        date_time_one = DateTime(date_one, time_one)
        date_time_two = DateTime(date_two, time_two)

        day.set_interval_start(date_time_one)
        day.end_current_interval(date_time_two)

        self.assertEqual(str(day.get_total_hours_worked()), "4:00")
def main():
    roll = RollBook("CSCI220", "Programming I", "Spring 2008")
    print("When roll book is empty...")
    print(roll)
    print("Class Average:", roll.classAverage())
    print("\n*****\n")

    d1 = Date()
    d1.setDate(8, 15, 2006)
    stu1 = Student(123, "Tenessee", "Williams", [90, 93], d1)
    roll.addStudent(stu1)

    d2 = Date()
    d2.setDate(5, 12, 2000)
    stu2 = Student(234, "Bob", "Marley", [95, 90, 92], d2)
    roll.addStudent(stu2)

    d3 = Date()
    d3.setDate(12, 1, 2004)
    stu3 = Student(345, "Diana", "Ross", [], d3)
    roll.addStudent(stu3)

    d4 = Date()
    d4.setDate(3, 9, 2007)
    stu4 = Student(456, "Peter", "Townshend", [87, 92, 98, 94, 92], d4)
    roll.addStudent(stu4)

    print(roll)

    print("Class Average:", roll.classAverage())
Пример #3
0
    def test_multiple_interval_not_hanging(self):
        day = WorkDay()
        day.clear_interval()

        time_one = Time(12, 30, Meridian.PM)
        time_two = Time(2, 30, Meridian.PM)

        date_one = Date(4, 29, 2021)
        date_two = Date(4, 29, 2021)

        date_time_one = DateTime(date_one, time_one)
        date_time_two = DateTime(date_two, time_two)

        day.set_interval_start(date_time_one)
        day.end_current_interval(date_time_two)

        time_one = Time(2, 30, Meridian.PM)
        time_two = Time(4, 30, Meridian.PM)

        date_time_one = DateTime(date_one, time_one)
        date_time_two = DateTime(date_two, time_two)

        day.set_interval_start(date_time_one)
        day.end_current_interval(date_time_two)

        self.assertEqual(day.check_for_incomplete_interval(), False)
Пример #4
0
def time_expression(Hour=None,
                    Minute=None,
                    Second=None,
                    AMPM=None,
                    SpecialTimeText=None):
    if SpecialTimeText:
        if SpecialTimeText.lower() == "noon":
            return Date(hour=12)
        if SpecialTimeText.lower() == "midnight":
            return Date(hour=0)
    d = Date()
    if Hour:
        d = d._replace(hour=int(Hour))
    if Minute:
        d = d._replace(minute=int(Minute))
    if Second:
        d = d._replace(second=int(Second))
    if AMPM is not None:
        if d.hour:
            if noon(d.hour, AMPM):
                d = d._replace(hour=12)
            elif midnight(d.hour, AMPM):
                d = d._replace(hour=0)
            else:
                d = d._replace(hour=d.hour + AMPM)
        d = d._replace(am_pm=AMPM)
    if (d.hour, d.minute, d.second) != (None, None, None):
        return d
Пример #5
0
    def calculateTprFprRate(self, evaluation, dataset, testSet) -> dict:
        date = Date()
        Logger.Info("Starting TPR/FPR calculations : " + str(date))

        # trpFprRates = {}

        # we convert the results into a format that's more comfortable to work with
        classificationItems = self.getClassificationItemList(
            testSet, evaluation)
        # for (Prediction prediction: evaluation.predictions()) {
        #     ClassificationItem ci = new ClassificationItem((int)prediction.actual(),((NominalPrediction)prediction).distribution());
        #     classificationItems.add(ci);
        # }

        # now we need to know what is the minority class and the number of samples for each class
        minorityClassIndex = dataset.getMinorityClassIndex()
        numOfNonMinorityClassItems = 0  #all non-minority class samples are counted together (multi-class cases)
        for cls in dataset.getNumOfRowsPerClassInTestSet().keys():
            if cls != minorityClassIndex:
                numOfNonMinorityClassItems += dataset.getNumOfRowsPerClassInTestSet(
                )[cls]

        # sort all samples by their probability of belonging to the minority class
        classificationItems.sort(
            reverse=True,
            key=lambda x: x.getProbabilitiesOfClass(minorityClassIndex))
        # Collections.sort(classificationItems, new ClassificationItemsComparator(minorityClassIndex));
        # Collections.reverse(classificationItems);

        tprFprValues = {}
        tprFprValues[0.0] = 0.0
        minoritySamplesCounter = 0
        majoritySamplesCounter = 0
        currentProb = 2
        for ci in classificationItems:
            currentSampleProb = ci.getProbabilitiesOfClass(minorityClassIndex)
            # if the probability is different, time to update the TPR/FPR statistics
            if currentSampleProb != currentProb:
                tpr = minoritySamplesCounter / dataset.getNumOfRowsPerClassInTestSet(
                )[minorityClassIndex]
                fpr = majoritySamplesCounter / numOfNonMinorityClassItems
                tprFprValues[tpr] = fpr
                currentProb = currentSampleProb

            if ci.getTrueClass() == minorityClassIndex:
                minoritySamplesCounter += 1
            else:
                majoritySamplesCounter += 1

        tprFprValues[1.0] = 1.0
        tprFprValues[1.0001] = 1.0
        date = Date()
        Logger.Info("Done : " + str(date))
        return tprFprValues
    def __init__(self, firstName, lastName, birthMonth, birthDay, birthYear,
                 hireMonth, hireDay, hireYear):
        """Constructor for class Employee"""

        self.birthDate = Date(birthMonth, birthDay, birthYear)
        self.hireDate = Date(hireMonth, hireDay, hireYear)

        self.lastName = lastName
        self.firstName = firstName

        print "Employee constructor: %s, %s" \
           % ( self.lastName, self.firstName )
Пример #7
0
def main():
    name = input()
    month = int(input())
    day = int(input())
    year = int(input())
    #   d1=Date()

    s1 = Student("John", Date(6, 1, 1999), 90)
    s2 = Student("Marry", Date(10, 8, 1997), 80)

    s1.setName(name)
    s2.setDate(month, day, year)

    s1.toString()
    s2.toString()
Пример #8
0
def basic_text(time=None,
               first_second=None,
               weekday=None,
               month=None,
               day=None,
               year=None):
    if not day:
        day = 1
    if not time:
        return Date(year=year, month=month, day=day)
    if time:
        date = Date(year=year, month=month, day=day)
        return date._replace(hour=time.hour,
                             minute=time.minute,
                             second=time.second,
                             am_pm=time.am_pm)
Пример #9
0
 def get_date_from_timestamp(self, timestamp):
     year = int(timestamp[0:4])
     month = int(timestamp[4:6])
     day = int(timestamp[6:8])
     hour = int(timestamp[8:10])
     minute = int(timestamp[10:12])
     return Date(year, month, day, hour, minute)
        def validateDateWrapper(emp, date):
            try:

                day, month, year = date.split(".")
                date = Date(day, month, year)
            except ValueError:
                raise ValueError("Incorrect date format.")
            return func(emp, date)
Пример #11
0
 def __init__(self, userID, userName, lastDate, allMoney):
     self.userID = userID
     self.userName = userName
     self.firstDate = Date(1,2,2020)
     self.lastDate = lastDate
     self.allMoney = allMoney
     self.yearOfVip = 0
     self.bonusPercentMoney = 0
Пример #12
0
 def __decrypt(self):
     tokens = Entry.__c.decrypt(self.__hash, Entry.userKey).split()
     if len(tokens) != 3:
         raise Exception("Decryption cannot be done")
     self.__text = Entry.__c.decrypt(tokens[0], Entry.__KEY)
     self.__date = Date(tokens[1])
     self.__number = int(tokens[2])
     self.__state = EntryState.DECRYPTED
Пример #13
0
    def __init__(self, firstname, lastname, date):
        self.Firstname = firstname
        self.Lastname = lastname

        if isinstance(date, Date):
            self.Birthday = date
        else:
            self.Birthday = Date()
Пример #14
0
 def canonical_sale_date(date):
     'return a datetime.date'
     if isinstance(date, datetime.date):
         return date
     elif isinstance(date, float):
         return Date(from_float=date).as_datetime_date()
     else:
         raise ValueError('unsupported date type: %s' % date)
Пример #15
0
def get_date_range(num_day):
    curr_date = datetime.date.today()
    date = Date(str(curr_date.year)+str(curr_date.month).zfill(2)+str(curr_date.day).zfill(2))
    date_list = []

    for i in range(0, num_day+1):
        date_list.append(date.substract_day(i))
    return date_list
Пример #16
0
 def get_date_from_edit_page_entry(self, entry):
     entry = self.cut_off_what_is_no_date(entry)
     year = self.get_year(entry)
     month = self.get_month(entry)
     day = self.get_day(entry)
     hour = self.get_hour(entry)
     minute = self.get_minute(entry)
     return Date(year, month, day, hour, minute)
Пример #17
0
def through_range(time=None,
                  weekday1=None,
                  weekday2=None,
                  month=None,
                  date=None,
                  beginning=None):
    output = []
    if month and date and beginning and weekday1:
        ending = Date(month=month, day=date)
        for day in range(beginning.day, ending.day + 1):
            temp = Date(month=month, day=day)
            if temp.weekday and temp.weekday in range(weekday1, weekday2 + 1):
                if time:
                    output.append(temp.update(time))
                else:
                    output.append(temp)
        return output
Пример #18
0
    def _load_actuals(self, training_data, test):
        'return Dict[(date: datetime.date, apn: int), price:float]'
        'return Dict[date: datetime.date, Dict[apn, price: float]]'
        path = os.path.join(Path.Path().dir_working(), 'samples2', training_data + '.csv')
        if False:
            # I could not get this code to work
            # hence the workaround below
            result = pd.read_csv(
                path,
                usecols=[layout_transactions.price],
                low_memory=False,
                index_col=0,  # the transaction_ids
            )

        if False:
            # this code does not work because the transaction_ids are read as strings, not TransactionId values
            df = pd.read_csv(
                path,
                nrows=10000 if test else None,
                usecols=[
                    layout_transactions.transaction_id,
                    layout_transactions.price,
                ],
                low_memory=False,
            )
            result = pd.DataFrame(
                data={
                    'price': df[layout_transactions.price].values,
                },
                index=df[layout_transactions.transaction_id]
            )
        if True:
            # constructing the transaction_ids directly works
            df = pd.read_csv(
                path,
                nrows=10 if test else None,
                usecols=[
                    layout_transactions.sale_date,
                    layout_transactions.apn,
                    layout_transactions.price
                ],
                low_memory=False,
            )
            # make list of transaction_ids
            transaction_ids = []
            for i, sale_date in enumerate(df[layout_transactions.sale_date]):
                transaction_id = TransactionId2(
                    sale_date=Date(from_float=sale_date).as_datetime_date(),
                    apn=long(df[layout_transactions.apn][i]),
                )
                transaction_ids.append(transaction_id)
            result = pd.DataFrame(
                data={
                    'price': df[layout_transactions.price],
                    'transaction_id': transaction_ids},
                index=range(len(transaction_ids)),
            )
        return result
Пример #19
0
    def __init__(self, p_path):

        configfile = os.path.join(os.environ['AIL_BIN'], 'packages/config.cfg')
        if not os.path.exists(configfile):
            raise Exception('Unable to find the configuration file. \
                            Did you set environment variables? \
                            Or activate the virtualenv.')

        cfg = configparser.ConfigParser()
        cfg.read(configfile)
        self.cache = redis.StrictRedis(
            host=cfg.get("Redis_Queues", "host"),
            port=cfg.getint("Redis_Queues", "port"),
            db=cfg.getint("Redis_Queues", "db"),
            decode_responses=True)
        self.store = redis.StrictRedis(
            host=cfg.get("Redis_Data_Merging", "host"),
            port=cfg.getint("Redis_Data_Merging", "port"),
            db=cfg.getint("Redis_Data_Merging", "db"),
            decode_responses=True)
        self.store_metadata = redis.StrictRedis(
            host=cfg.get("ARDB_Metadata", "host"),
            port=cfg.getint("ARDB_Metadata", "port"),
            db=cfg.getint("ARDB_Metadata", "db"),
            decode_responses=True)

        self.PASTES_FOLDER = os.path.join(os.environ['AIL_HOME'], cfg.get("Directories", "pastes"))
        if self.PASTES_FOLDER not in p_path:
            self.p_rel_path = p_path
            self.p_path = os.path.join(self.PASTES_FOLDER, p_path)
        else:
            self.p_path = p_path
            self.p_rel_path = p_path.replace(self.PASTES_FOLDER+'/', '', 1)

        self.p_name = os.path.basename(self.p_path)
        self.p_size = round(os.path.getsize(self.p_path)/1024.0, 2)
        self.p_mime = magic.from_buffer("test", mime=True)
        self.p_mime = magic.from_buffer(self.get_p_content(), mime=True)

        # Assuming that the paste will alway be in a day folder which is itself
        # in a month folder which is itself in a year folder.
        # /year/month/day/paste.gz

        var = self.p_path.split('/')
        self.p_date = Date(var[-4], var[-3], var[-2])
        self.p_date_path = os.path.join(var[-4], var[-3], var[-2], self.p_name)
        self.p_source = var[-5]
        self.supposed_url = 'https://{}/{}'.format(self.p_source.replace('_pro', ''), var[-1].split('.gz')[0])

        self.p_encoding = None
        self.p_hash_kind = {}
        self.p_hash = {}
        self.p_langage = None
        self.p_nb_lines = None
        self.p_max_length_line = None
        self.array_line_above_threshold = None
        self.p_duplicate = None
        self.p_tags = None
Пример #20
0
def main():
    response = requests.get("https://www.hebcal.com/converter?cfg=json&hy=5749&hm=Kislev&hd=25&h2g=1")
    date = response.json()
    print(date['gy'])
    
    year = input("enter hebrew year:")
    month = input("enter hebrew month:")
    day = input("enter hebrew day:")
    heb_date = Date(year, month, day)
Пример #21
0
def get_date_range(date_from, num_day):
    date = Date(str(date_from[0:4])+str(date_from[4:6]).zfill(2)+str(date_from[6:8]).zfill(2))
    date_list = []

    for i in range(0, num_day+1):
        new_date = date.substract_day(i)
        date_list.append(new_date[0:4] +'-'+ new_date[4:6] +'-'+ new_date[6:8])

    return date_list
Пример #22
0
def get_date_range(num_day):
    curr_date = datetime.date.today()
    date = Date( '{}{}{}'.format(str(curr_date.year), str(curr_date.month).zfill(2), str(curr_date.day).zfill(2)) )
    date_list = []

    for i in range(0, num_day):
        date_list.append(date.substract_day(i))

    return list(reversed(date_list))
def main():
    d1 = Date()
    d1.setDate(8, 15, 2006)
    d2 = Date()
    d2.setDate(5, 12, 2000)
    d3 = Date()
    d3.setDate(12, 1, 2004)
    d4 = Date()
    d4.setDate(3, 9, 2007)

    chad = Student("Tenessee", "Williams", [90, 93], d1)
    chad.addGrade(93)
    chad.addGrade(89)
    chad.addGrade(97)
    print chad.getName() + "'s grades are: " + str(chad.getGrades())
    print "Average: " + str(chad.calcAvg())

    brad = Student("Bob", "Marley", [95, 90, 92], d2)
    print
    print str(brad)  #What is this printing?

    csci220 = []
    csci220.append(chad)
    csci220.append(brad)
    csci220.append(Student("Diana", "Ross", [], d3))
    csci220.append(Student("Peter", "Townsend", [87, 92, 98, 94, 92], d4))

    for student in csci220:
        print
        print student

    print
    for i in range(len(csci220)):
        compare = csci220[0].getEnrollDate().compareTo(
            csci220[i].getEnrollDate())
        if compare == 0:
            print csci220[0].getName(
            ) + " enrolled the same day as " + csci220[i].getName()
        elif compare > 0:
            print csci220[0].getName(
            ) + " enrolled after " + csci220[i].getName()
        else:
            print csci220[0].getName(
            ) + " enrolled before " + csci220[i].getName()
Пример #24
0
def csvParser(filePath):
    """ filePath is where the file is save, and it
    must include the name of the file
    Also, if the file name does not include "Members" or 
    "Fincances", csvParser will throw an Exception
    """

    print(filePath)
    fileName = os.path.split(filePath)[1]
    name = fileName.split(".")[0]
    csvfile = open(filePath, newline='')
    reader = csv.DictReader(csvfile)

    try:
        members = []
        for row in reader:
            m = Member(
                row['name'], row['firstName'], row['surname'], row['eMail'],
                Date(int(row['birthDate'].split('/')[0]),
                     int(row['birthDate'].split('/')[1]),
                     int(row['birthDate'].split('/')[2])),
                bool(row['cotisation']), row['belongingGroups'])
            members.append(m)

        csvfile.close()
        return [Group(name, members), name]
    except:
        pass

    t = Table()
    for row in reader:
        try:
            t.addBalanceVerification(row['name'],
                                     row['iD'], float(row["cumul"]),
                                     float(row["balance"]),
                                     float(row['balanceGap']),
                                     int(row['date'].split('/')[0]),
                                     int(row['date'].split('/')[1]),
                                     int(row['date'].split('/')[2]))
        except:
            pass

        try:
            t.addFlux(row["name"], row['iD'], float(row['value']),
                      row['shortInfo'], row['longInfo'], row['supplier'],
                      float(row['iN']), float(row['out']),
                      int(row['date'].split('/')[0]),
                      int(row['date'].split('/')[1]),
                      int(row['date'].split('/')[2]))
        except:
            pass

        csvfile.close()
        return [t, name]

    raise Exception("The file name or file content is invalid")
Пример #25
0
def main():
    scotts = Date()
    print scotts
    scotts.setDate(3, 30, 1995)
    print "Scott: " + str(scotts)
    print

    averys = Date()
    print "Avery: " + str(averys)
    averys.setDate(4, 31, 2000)
    print "Avery: " + str(averys)
    averys.setDate(2, 29, 2008)
    print "Avery: " + str(averys)
    averys.setDate(2, 29, 2009)
    print "Avery: " + str(averys)
    averys.setDate(14, 29, 2008)
    print "Avery: " + str(averys)
    averys.setDate(11, 13, 2009)
    print "Avery: " + str(averys)
Пример #26
0
def main():
    d1 = Date()
    d1.setDate(4, 13, 2010)
    d2 = Date()
    d2.setDate(4, 1, 2009)
    d3 = Date()
    d3.setDate(1, 1, 2010)

    dates = []
    dates.append(d1)
    dates.append(d2)
    dates.append(d3)

    for date in dates:
        print(date)

    d2.setDate(5, 1, 2010)
    print(d2)
    print(dates[1])
Пример #27
0
    def produceClassificationResults(self, datasets: list) -> list:
        classificationResultsPerFold = []
        for dataset in datasets:
            date = Date()
            Logger.Info("Starting to run classifier " + str(date))
            trainSet = dataset.generateSet(True)
            testSet = dataset.generateSet(False)
            evaluationResults = self.runClassifier(Properties.classifier,
                                                   trainSet, testSet)
            date = Date()
            Logger.Info("Starting to process classification results " +
                        str(date))
            classificationResults = self.getClassificationResults(
                evaluationResults, dataset, testSet)
            date = Date()
            Logger.Info("Done " + str(date))
            classificationResultsPerFold.append(classificationResults)

        return classificationResultsPerFold
Пример #28
0
 def __init__(self, stuNum, firstName, lastName, grades, date):
     self.studentNumber = stuNum
     self.firstName = firstName
     self.lastName = lastName
     self.grades = []
     for grade in grades:
         self.grades.append(grade)
     #clone date for enrollDate instead of setting enrollDate = date
     self.enrollDate = Date()
     self.enrollDate.setDate(date.getMonth(),date.getDay(),date.getYear())
Пример #29
0
    def test_single_interval_hanging(self):
        day = WorkDay()
        day.clear_interval()

        time_one = Time(12, 40, Meridian.PM)
        date_one = Date(4, 29, 2021)
        date_time_one = DateTime(date_one, time_one)

        day.set_interval_start(date_time_one)

        self.assertEqual(day.check_for_incomplete_interval(), True)
 def miningBlock(self, higher):
     stringOfZeros = "0" * int(self.POW)
     d = Date()
     block = NodeMemory._get_new_hash(self, higher, self.POW, d.get_date(),
                                      '')
     # while stringHash not found
     if block[1].startswith(stringOfZeros):
         # On affiche un message
         print('New block mined with hash ' + block[2] + '\n' + block[0] +
               '\n')
         # Retourne l'ID du bloc miné
         return block[2]
     return False