def main():
    '''This Job runs every day at noon and should give the list of stocks announcing the next day'''
    subject = 'Your Companies Earnings Announcements Tomorrow'

    # 0. get current day
    day = Time.get_time_for_delta('days', 1)
    day = Time.time_to_str_time(day)

    # 1. Get all the list of users
    users = base.managers.user_manager.get_many()

    # 2. for each user, get the list of stocks they are following
    for user in users:
        announcing_stocks = []
        stocks = user.get_stocks_for_user()

        # 3. for each stock, check if the announcement date matches the day
        for stock in stocks:
            announcement_date = stock.get('time')

            if not announcement_date:
                continue

            announcement_date = Time.time_to_str_time(announcement_date)

            if announcement_date == day:
                announcing_stocks.append(stock.get('ticker'))

        # 4. list is not empty, send user a notification email
        if len(announcing_stocks) > 0:
            print "-->user, date, stocks: %s:%s:%s" % (user.get('email'), day, announcing_stocks)
            html_content = print_table(announcing_stocks, 3)
            email.send_email(user.get('email'), None, subject, '', html_content)
    def _serialize(cls, user):
        if user:
            return (Time.get_utc_time(), user.get('username'), user.get('first_name'),
                    user.get('last_name'), user.get('email'), password_utils.encrypt_password(user.get('password')),
                    user.get('about'), user.get('location'), user.get('website'), user.get('image_url'),
                    user.get('gender'), user.get('birthday'), json.dumps(user.get('body')))

        return ()
    def _serialize(cls, stock, serialize_id=False):
        if stock:
            about = stock.get('about')
            if about:
                about = about.encode('ascii', errors='ignore')

            name = stock.get('name')
            if name:
                name = name.encode('ascii', errors='ignore')

            if serialize_id:
                return (stock.get('id'), Time.get_utc_time(), stock.get('ticker'), name, about, stock.get('time'),
                        stock.get('followers'), json.dumps(stock.get('body')), stock.get('interest_id', 1))

            return (Time.get_utc_time(), stock.get('ticker'), name, about, stock.get('time'),
                    stock.get('followers'), json.dumps(stock.get('body')), stock.get('interest_id', 1))

        return ()
Exemple #4
0
    def __init__(self):

        self.help = "[INFO]"
        self.user = "******"
        self.fail = "[FAIL]"
        self.message_encode = "utf-8"
        self.lennyfaces = self.get_lennyfaces()
        self.eightBall = self.get_eightball()
        self.starttime = datetime.now()
        self.time = Time()
        self.web = Web()
def start():
    truck1 = Truck()
    truck2 = Truck()
    get_packages()
    get_distances()

    truck1.time = Time(8, 00)  # Truck 1 start time 8:00 am
    truck2.time = Time(9, 30)  # Truck 2 start time 9:30 a

    delivery(truck1, early_deliveries)
    delivery(truck2, truck_2)
    delivery(truck1, left_over)

    print('\n********** Delivery Information **********')
    print('Truck 1 distance traveled: ' + str(truck1.distance) + ' miles.')
    print('Truck 2 distance traveled: ' + str(round(truck2.distance, 2)) +
          ' miles.')
    print('\nTotal distance traveled to deliver packages is ' +
          str(round(truck1.distance + truck2.distance, 2)) + ' miles.')

    user_interface()
Exemple #6
0
def construct_response(result, response_data=None):
    response_dict = collections.OrderedDict()

    if isinstance(result, exceptions.ApiError):
        status = result.error_code.http_status
        message = result.error_code.message
    else:
        message = "ok"
        status = result

    response_dict.update({"status": status})
    response_dict.update({"host": socket.gethostname()})
    response_dict.update({"generated_at": Time.get_utc_time()})
    response_dict.update({"message": message})
    response_dict.update({"data": response_data})

    return jsonify(response_dict), status
Exemple #7
0
    def get_price(self, date=None):
        if not self.body:
            return None

        if date:
            price_dict = self.body.get(date).get('price')
        else:
            if self.body.get(self.day):
                price_dict = self.body.get(self.day).get('price')
            else:
                price_dict = None

        labels = []
        values = []

        if not price_dict:
            return labels, values

        keys = price_dict.keys()

        # sort labels by ascending time
        keys.sort()

        # now sort the values list
        prices = []

        for key in keys:
            current_column = []
            # convert times to local time
            offset = Time.get_utc_offset()
            local_time = float(key.replace(':', '.')) + offset

            current_column.append(str(local_time))
            if not price_dict.get(key):
                current_column.append(0)
            else:
                current_column.append(float(price_dict.get(key)))
            prices.append(current_column)

        return prices
 def __init__(self):
     self._date = Date()
     self._time = Time()
class EmployeeJiraDataParser(object):

    def __init__(self):
        self._date = Date()
        self._time = Time()

    @staticmethod
    def _get_task_components_as_string(components_list):
        components_string = ""
        for component in components_list:
            if components_string != "":
                components_string = "{};{}".format(components_string, component['name'])
            else:
                components_string = component['name']
        return components_string

    def get_jira_issues(self, employee_timesheet_data):
        jira_issues = list()
        for issue in employee_timesheet_data['issues']:
            issue_dict = dict()
            issue_dict['summary'] = issue['fields']['summary']
            issue_dict['key'] = issue['key']
            issue_dict['issue_id'] = issue['id']
            issue_dict['issue_type'] = issue['fields']['issuetype']['name']
            issue_dict['issue_priority'] = issue['fields']['priority']['name']
            issue_dict['issue_components'] = self._get_task_components_as_string(issue['fields']['components'])
            jira_issues.append(issue_dict)
        return jira_issues

    def parse_employe_worklog_data(self, employee_worklog_data, employee_jira_name, issue_worklog_data):
        worklogs = issue_worklog_data['worklogs']
        for worklog in worklogs:
            if worklog['author']['name'] == employee_jira_name:
                worklog_data = dict()
                worklog_data['worklog_date'] = dict()
                worklog_year, worklog_month, worklog_day = self._date.parse_worklog_date_time(worklog['started'])
                worklog_data['worklog_date']['year'] = worklog_year
                worklog_data['worklog_date']['month'] = worklog_month
                worklog_data['worklog_date']['day'] = worklog_day
                time_spend_hours = float(self._time.parse_seconds_to_hours(worklog['timeSpentSeconds']))
                worklog_data['time_spent'] = time_spend_hours
                employee_worklog_data.append(worklog_data)
        return employee_worklog_data

    def parse_employe_worklog_data_2(self, employee_worklog_data, employee_jira_name, issue_worklog_data):
        worklogs = issue_worklog_data['worklogs']
        time_spent_per_date = dict()
        for worklog in worklogs:
            if worklog['author']['name'] == employee_jira_name:
                worklog_data = dict()
                worklog_data['worklog_date'] = dict()
                worklog_year, worklog_month, worklog_day = self._date.parse_worklog_date_time(worklog['started'])
                worklog_data['worklog_date']['year'] = worklog_year
                worklog_data['worklog_date']['month'] = worklog_month
                worklog_data['worklog_date']['day'] = worklog_day
                time_spend_hours = float(self._time.parse_seconds_to_hours(worklog['timeSpentSeconds']))
                time_spent_per_date_key = "{0}-{1}-{2}".format(worklog_year, worklog_month, worklog_day)
                if time_spent_per_date_key in time_spent_per_date.keys():
                    time_spent_per_date[time_spent_per_date_key] += time_spend_hours
                else:
                    time_spent_per_date[time_spent_per_date_key] = time_spend_hours
                worklog_data['time_spent'] = time_spent_per_date[time_spent_per_date_key]
                employee_worklog_data.append(worklog_data)
        return employee_worklog_data
Exemple #10
0
 def timer_report(self):
     local_passed = Time.passed(self.local_timer)
     global_passed = Time.passed(self.global_timer)
     self.local_timer = Time.now()
     return local_passed, global_passed
Exemple #11
0
    def execute(self,
                run_name=None,
                tabs=0,
                x_params=None,
                previous_name=None,
                cache_name: str = None):
        # Every execution should refresh initial params
        params = CachedDict().union(self.initial_params) \
            if isinstance(self.initial_params, CachedDict) \
            else CachedDict(self.initial_params if self.initial_params else {})

        self.local_timer = Time.now()
        self.global_timer = Time.now()

        if not x_params:
            x_params = CachedDict()

        x_params = x_params.union(params)  # Add F to X

        if not previous_name:
            previous_name = cache_dir

        makedir(previous_name)

        if cache_name:
            previous_name = path.join(previous_name, cache_name)
            makedir(previous_name)

        if run_name:
            print("  " * tabs, run_name)

        key_len = max([len(qi.key) for qi in self.queue] + [0]) + 5
        name_len = max([len(qi.name) for qi in self.queue] + [0]) + 5

        for qi in self.queue:
            # key, name, method, load_cache, load_self
            if qi.key != "out" and not isinstance(qi.method, Pipeline):
                print(("  " * (tabs + 1)) +
                      ("%-" + str(key_len) + "s %-" + str(name_len) + "s") %
                      (qi.key, qi.name),
                      end=" ")

            pn = path.join(previous_name, qi.key)
            pnf = pn + "." + qi.ext

            if qi.load_cache and path.isfile(pnf):
                params.add_cache(qi.key, pnf)
                if qi.load_self:
                    params.load_cache(qi.key)
            else:
                if isinstance(qi.method, Pipeline):
                    params[qi.key] = qi.method.execute(
                        run_name=qi.name,
                        tabs=tabs + 1,
                        x_params=x_params.union(params),
                        previous_name=pn)
                    if isinstance(params[qi.key],
                                  CachedDict) and "out" in params[qi.key]:
                        params.copy_key(qi.key, params[qi.key], "out")
                else:
                    if self.mute:
                        Silencer.mute()
                    params[qi.key] = qi.method(params, x_params)
                    if self.mute:
                        Silencer.unmute()

                    f = open(pnf,
                             "wb" if qi.ext not in ["txt", "json"] else "w")
                    if qi.ext == "pkl":
                        pickle.dump(params[qi.key], f)
                    else:
                        if qi.ext in ["png", "jpg", "wav", "mp4"]:
                            params[qi.key] = get_file_bytes(params[qi.key],
                                                            format=qi.ext)
                        f.write(params[qi.key])
                    f.close()

            if qi.key != "out" and not isinstance(qi.method, Pipeline):
                local_passed, global_passed = self.timer_report()
                report = params[qi.key].report() \
                    if qi.key in params.val_dict and hasattr(params[qi.key], "report") else ""
                print(("%-15s\t\t" + report) % (local_passed))

        return params
Exemple #12
0
def main():
    # 1. get the time
    day = Time.get_utc_day()
    hours_mins = Time.get_utc_hours_minutes()

    # 1. Get all the list of stocks
    stocks = base.managers.stock_manager.get_many()

    # 2. go through stock and update the desired values
    for stock in stocks:
        ticker = stock.get('ticker')

        try:
            # 2.1 Get the info from the yahoo API
            updated_stock = Share(ticker)
        except:
            print "-->Failed to update: %s with Yahoo API" % ticker
            continue

        price = updated_stock.get_price()
        open = updated_stock.get_open()
        days_high = updated_stock.get_days_high()
        days_low = updated_stock.get_days_low()
        year_high = updated_stock.get_year_high()
        year_low = updated_stock.get_year_low()
        volume = updated_stock.get_volume()
        market_cap = updated_stock.get_market_cap()
        pe_ratio = updated_stock.get_price_earnings_ratio()
        div_yield = updated_stock.get_dividend_yield()
        change = updated_stock.get_change()
        change_percent = updated_stock.data_set.get('ChangeinPercent')

        # 2.2 Get the stock body
        stock_body = stock.get('body')

        stock_price = {hours_mins: price}

        if stock_body:
            # 1. Get the stock info for the day:
            stock_info = stock_body.get(day)

            if stock_info:
                stock_price = stock_info.get('price')
                stock_price.update({hours_mins: price})
        else:
            stock_body = {}

        # 2.2.4 update the stock info dict
        stock_info = {'price': stock_price}
        stock_info.update({'open': open})
        stock_info.update({'days_high': days_high})
        stock_info.update({'days_low': days_low})
        stock_info.update({'year_high': year_high})
        stock_info.update({'year_low': year_low})
        stock_info.update({'volume': volume})
        stock_info.update({'market_cap': market_cap})
        stock_info.update({'pe_ratio': pe_ratio})
        stock_info.update({'div_yield': div_yield})
        stock_info.update({'change': change})
        stock_info.update({'change_percent': change_percent})

        # update the stock body
        stock_body.update({day: stock_info})

        stock.body = stock_body

        # 3. update the stock in the DB
        try:
            base.managers.stock_manager.update_one(stock)
        except:
            print "-->Failed to update: %s in DB" % ticker
            continue
Exemple #13
0
    async def main(self, bot, database, message, arguments):

        interest = 5

        # wealth
        userRR = bot.database.user.get(message.author.id)
        users_points = userRR.points
        users_bank = userRR.bank
        add_dir = ["add", "deposit", "put", "give"]
        take_dir = ["take", "withdraw", "remove"]

        # How many memes in bank
        if len(arguments) == 0:

            # Time from interest
            BANK_INTEREST_DAY = 3
            BANK_INTEREST_TIME = 3000
            time = Time()
            past_time = 604800 - (time.time_untill_weekly(
                BANK_INTEREST_DAY, BANK_INTEREST_TIME))

            # Users interest
            try:
                users_own_interest = mceil(
                    (bot.database.pointhistory.get_min_bank_amount(
                        10, past_time, message.author.id)[0].min_bank) *
                    interest / 100)
            except:
                users_own_interest = mceil(users_bank * interest / 100)

            # Creating message and sending it
            letter = ":bank: **| You have {} memes in your bank! Interest is {}%, Currently: {} memes\n\nInterest is calculated by the amount of memes you've had in the bank for the past week!\nYou receive interest every wednesday @ 00:00 **".format(
                users_bank, interest, users_own_interest)
            await bot.say(message.channel, letter)
            return

        # if all
        if arguments[1] in ["all", "kaikki"]:

            # Check if add or take
            if arguments[0] in add_dir:
                amount = users_points
            elif arguments[0] in take_dir:
                amount = users_bank

        elif arguments[1] in ["half", "puolet", "1/2"]:

            # Check if add or take
            if arguments[0] in add_dir:
                amount = mceil(users_points * 0.5)
            elif arguments[0] in take_dir:
                amount = mceil(users_bank * 0.5)

        elif arguments[1] in ["third", "kolmasosa", "1/3"]:

            # Check if add or take
            if arguments[0] in add_dir:
                amount = mceil(users_points * 0.33333)
            elif arguments[0] in take_dir:
                amount = mceil(users_bank * 0.33333)

        elif arguments[1] in ["quarter", "quad", "neljännes", "1/4"]:

            # Check if add or take
            if arguments[0] in add_dir:
                amount = mceil(users_points * 0.25)
            elif arguments[0] in take_dir:
                amount = mceil(users_bank * 0.25)

        # if not all try to set amount
        else:
            try:
                arguments[1] = arguments[1].replace("k", "000")
                amount = int(arguments[1])
            except:
                await bot.say(message.channel, ":bank: **| Invalid amount!**")
                return

        # Must use atleast 10 memes
        if amount < 10:
            await bot.say(message.channel,
                          ":bank: **| You need to atleast use 10 memes!**")
            return

        # Adding memes
        if arguments[0] in add_dir:

            # Checking if usr has memes
            if amount > int(users_points):
                await bot.say(message.channel,
                              ":bank: **| You don't have enough memes!**")
                return

            # calculating min amount in bank
            minimum = users_bank

            # Add to history
            bot.database.pointhistory.add(message.server.id, message.author.id,
                                          10, "Bank", False, amount, "",
                                          "-" + str(amount), "", "To bank", "",
                                          "", "", minimum, 0, amount)

            # Set stats
            bot.database.user.points_alter(message.author.id, -amount)
            bot.database.user.bank_alter(message.author.id, amount)

            # letter
            await bot.say(
                message.channel,
                ":bank: **| You have transferred {} memes to bank!\n\nYou now have:\n:purse:: {} memes\n:bank:: {} memes**"
                .format(amount, users_points - amount, users_bank + amount))
            return

        # Taking memes
        elif arguments[0] in take_dir:

            # Checking if enough memes in bank
            if amount > int(users_bank):
                await bot.say(
                    message.channel,
                    ":bank: **| You don't have that many memes in bank!**")
                return

            # calculating min amount in bank
            minimum = users_bank - amount

            # Add to history
            bot.database.pointhistory.add(message.server.id, message.author.id,
                                          10, "Bank", False, amount, "",
                                          "+" + str(amount), "", "From bank",
                                          "", "", "", minimum, amount, 0)

            # Set stats

            bot.database.user.points_alter(message.author.id, amount)
            bot.database.user.bank_alter(message.author.id, -amount)

            # letter
            await bot.say(
                message.channel,
                ":bank: **| You have transferred {} memes to your wallet!\n\nYou now have:\n:purse:: {} memes\n:bank:: {} memes**"
                .format(amount, users_points + amount, users_bank - amount))
            return
    def _serialize(cls, interest):
        if interest:
            return (Time.get_utc_time(), interest.get('name'), interest.get('image_url'),
                    json.dumps(interest.get('body')), interest.get('followers'))

        return ()
Exemple #15
0
            tokens.append(chr(self.voc[t]))
        return "".join(tokens)


if __name__ == "__main__":
    g = Graph()
    g.add_edge('A', 'B', 'b1')
    # g.add_edge('A', 'B', 'b2')
    g.add_edge('A', 'C', 'c')
    g.add_edge('A', 'C', 'c2')
    # g.add_edge('C', 'C', 'cd')
    g.add_edge('A', 'D', 'd')
    g.add_edge('D', 'E', 'e')
    g.add_edge('A', 'E', 'e')

    now = Time.now()
    plans = list(g.exhaustive_plan(force_tree=False).linearizations())

    print("exhaustive_plan", len(plans))
    print(plans[0])
    print(plans[-1])
    print(Time.passed(now))

    print("memory size", sys.getsizeof(pickle.dumps(plans)) / 1024)
    plans_str = "\n".join(plans).encode("utf-8")
    compressed = zlib.compress(plans_str, 1)
    print("zlib size", sys.getsizeof(pickle.dumps(compressed)) / 1024)

    compressor = Compressor()
    plans = [compressor.compress(p) for p in plans]
    print("compressor size", sys.getsizeof(pickle.dumps({"p": plans, "c": compressor})) / 1024)
Exemple #16
0
 def __init__(self, *args, **kwargs):
     super(Stock, self).__init__(*args, **kwargs)
     if Time.is_market_open():
         self.day = Time.get_utc_day()
     else:
         self.day = Time.get_business_day()
Exemple #17
0
    def execute(self,
                run_name=None,
                tabs=0,
                x_params=None,
                previous_name=None,
                cache_name: str = None):
        self.local_timer = Time.now()
        self.global_timer = Time.now()

        if not x_params:
            x_params = CachedDict()

        if not previous_name:
            previous_name = cache_dir

        makedir(previous_name)

        if cache_name:
            previous_name = path.join(previous_name, cache_name)
            makedir(previous_name)

        if run_name:
            print("  " * tabs, run_name)

        key_len = max([len(qi.key) for qi in self.queue] + [0]) + 5
        name_len = max([len(qi.name) for qi in self.queue] + [0]) + 5

        for qi in self.queue:
            # key, name, method, load_cache, load_self
            if qi.key != "out" and not isinstance(qi.method, Pipeline):
                print(("  " * (tabs + 1)) +
                      ("%-" + str(key_len) + "s %-" + str(name_len) + "s") %
                      (qi.key, qi.name),
                      end=" ")

            pn = path.join(previous_name, qi.key)
            pnf = pn + "." + qi.ext

            if qi.load_cache and qi.key != "out" and path.isfile(pnf):
                self.params.add_cache(qi.key, pnf)
                if qi.load_self:
                    self.params.load_cache(qi.key)
            else:
                if isinstance(qi.method, Pipeline):
                    self.params[qi.key] = qi.method.execute(
                        run_name=qi.name,
                        tabs=tabs + 1,
                        x_params=x_params.union(self.params),
                        previous_name=pn)
                    if "out" in self.params[qi.key]:
                        self.params.copy_key(qi.key, self.params[qi.key],
                                             "out")
                else:
                    if self.mute:
                        Silencer.mute()
                    self.params[qi.key] = qi.method(self.params, x_params)
                    if self.mute:
                        Silencer.unmute()

                    f = open(pnf, "wb" if qi.ext != "txt" else "w")
                    if qi.ext == "sav":
                        pickle.dump(self.params[qi.key], f)
                    else:
                        f.write(self.params[qi.key])
                    f.close()

            if qi.key != "out" and not isinstance(qi.method, Pipeline):
                local_passed, global_passed = self.timer_report()
                report = self.params[qi.key].report() \
                    if qi.key in self.params.val_dict and hasattr(self.params[qi.key], "report") else ""
                print(("%-15s\t\t" + report) % (local_passed))

        return self.params