def report_gp_deltas(conn, end, start='now'): params = {'start': maya.when(start).date.strftime('%Y-%m-%d'), 'end': maya.when(end).date.strftime('%Y-%m-%d')} delta_sql = """SELECT DISTINCT DATE(dl_date, 'unixepoch') as date, name, total_gp, char_gp, ship_gp, MAX(total_gp) - MIN(total_gp) as Total, MAX(char_gp) - MIN(char_gp) as character, MAX(ship_gp) - MIN(ship_gp) as ship FROM gp g JOIN users u ON u.uid = g.u_id WHERE date == :start OR date = :end GROUP BY name HAVING MAX(date) and Total > 0 ORDER BY name """ # conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute(delta_sql, params) rows = cursor.fetchall() return rows
def test_add_command(app): """Add some chores.""" assert app assert Chore.query.count() == 0 right_now = arrow.now() tomorrow_10 = maya.when("tomorrow 10:00") yesterday_9am = maya.when("yesterday 9am") yesterday_2pm = maya.when("yesterday 2pm") with TelegramAppMock(app) as telegram: telegram.type_command("add My first chore , tomorrow 10:00", "The chore was added.") telegram.type_command("add Do it now", "The chore was added.") telegram.type_command("add Wash clothes , yesterday 9am , weekly ", "The chore was added.") telegram.type_command("add Shopping , yesterday 2pm , every 2 months ", "The chore was added.") # Add in 2 steps. help_message = ( "To add a new chore, enter the following info (one per line or comma separated):\n" "\u2022 Title\n" "\u2022 (optional) First alarm. E.g.: today 10am, tomorrow 9pm, 20 Jan 2017...\n" "\u2022 (optional) Repetition. E.g.: once, weekly, every 3 days...\n" "Or choose /cancel to stop adding a new chore." ) telegram.type_command("add", help_message) telegram.type_text("Christmas;25 Dec 2016,yearly", "The chore was added.") telegram.type_command("add", help_message) telegram.type_command("cancel", "Okay, no new chore then.") assert Chore.query.count() == 5 assert Alarm.query.count() == 0 first, do_it, wash, shopping, christmas = Chore.query.all() assert first.title == "My first chore" assert arrow.get(first.alarm_start).to("utc") == tomorrow_10.datetime() assert first.repetition is None assert do_it.title == "Do it now" # Both dates should have less than 10 seconds difference (the time of the test). assert (arrow.get(do_it.alarm_start).to("utc") - right_now).seconds < 10 assert do_it.repetition is None assert wash.title == "Wash clothes" assert arrow.get(wash.alarm_start).to("utc") == yesterday_9am.datetime() assert wash.repetition == "weekly" assert shopping.title == "Shopping" assert arrow.get(shopping.alarm_start).to("utc") == yesterday_2pm.datetime() assert shopping.repetition == "every 2 months" assert christmas.title == "Christmas" assert arrow.get(christmas.alarm_start).to("utc") == maya.when("25 Dec 2016").datetime() assert christmas.repetition == "yearly"
def _str_to_datetime(datestr): """Convert `str` to `datetime.datetime`. """ # try known string try: return DATE_STRINGS[str(datestr).lower()]() except KeyError: # any other string pass # use maya try: import maya return maya.when(datestr).datetime() except ImportError: pass # use dateutil.parse with warnings.catch_warnings(): # don't allow lazy passing of time-zones warnings.simplefilter("error", RuntimeWarning) try: return dateparser.parse(datestr) except RuntimeWarning: raise ValueError("Cannot parse date string with timezone " "without maya, please install maya") except (ValueError, TypeError) as exc: # improve error reporting exc.args = ("Cannot parse date string {0!r}: {1}".format( datestr, exc.args[0]),) raise
class RepoInfoParser(CommonParser): per_branch: int = 25 max_age: maya.MayaDT = maya.when("24 months ago") only: str = None def add_arguments(self): super().add_arguments() self.add_argument("-n", "--per-branch", dest="per_branch", type=int) self.add_argument("-m", "--max-age", dest="max_age", type=maya.when)
def test_maya_datetimes(): if not maya: raise SkipTest("maya is optional since it's not supported for " "enough python versions") with freeze_time(maya.when("October 2nd, 1997")): assert datetime.datetime.now() == datetime.datetime(year=1997, month=10, day=2)
def getSeries(startD, endD, stepSeconds=3600): #startD = maya.when(startD, timezone='US/Eastern') # initiating T I M E Z O N E headache startD = maya.when(startD) #endD = maya.when(endD, timezone='US/Eastern') endD = maya.when(endD) timeseries = maya.intervals(start=startD, end=endD, interval=stepSeconds) output = [] for d in timeseries: s = "%d-%02d-%02d %02d:%02d:%02d" % (d.year, d.month, d.day, d.hour, d.minute, d.second) output.append(s) # .intervals() doesn't produce the last entry, so here it is-- # this could make it wacky if your start/ step/ end combo is wacky last = maya.when(s).add(seconds=stepSeconds) output.append( "%d-%02d-%02d %02d:%02d:%02d" % (last.year, last.month, last.day, last.hour, last.minute, last.second)) return output
def _parse_order(self, order: Dict, order_type: OrderType=None): order_id = order.get('id') datetime_str = order.get('datetime') if datetime_str: maya_dt = maya.when(datetime_str) timestamp = maya_dt.epoch datetime = maya_dt.datetime() else: timestamp = None datetime = None market = Market.from_code(order['currency_pair'].upper()) assert market == self.market side = order.get('type') if side is not None: side = side_mapping[side] amount = order.get('amount') filled = None fee = None cost = None transactions = order.get('transactions') if transactions and isinstance(transactions, list): fee = Money(0, self.market.quote) filled = Money(0, self.market.base) for trade in transactions: trade = self._parse_trade(trade) filled += trade.amount fee += trade.fee if cost is None: cost = 0 cost += trade.cost status = self._parse_order_status(order.get('status')) if status == 'Finished' and amount is None: amount = filled remaining = None if amount is not None and filled is not None: remaining = amount - filled price = order.get('price') if cost is None and price: cost = price * filled.amount elif price is None and filled: price = cost / filled.amount return Order( id=order_id, market=market, type=order_type, side=side, status=status, amount=amount, remaining=remaining, filled=filled, cost=cost, fee=fee, price=price, info=order, timestamp=timestamp, datetime=datetime, )
def test_random_date(): d = maya.when('11-17-11 08:09:10') assert d.year == 2011 assert d.month == 11 assert d.day == 17 assert d.hour == 8 assert d.minute == 9 assert d.second == 10 assert d.microsecond == 0
def get_midnight(timezone): now = maya.now() local_now = now.datetime(to_timezone=timezone, naive=True) year = local_now.year month = local_now.month day = local_now.day midnight = maya.when('-'.join(map(str, [year, month, day])), timezone=timezone) return midnight
def test_get_notifications_since_yesterday(self, testapp, authenticated_user): authenticated_user.add_notification(name='panda', data='bear') authenticated_user.save() yesterday = maya.when('yesterday').datetime().date() response = testapp.get( url_for('user.notifications') + f'?since={yesterday}') assert len(response.json) == 1
def json2doc(fpath): with fpath.open() as f: doc = json.load(f) pages = doc["pages"] texts: List[str] = ["".join(page["lines"]) for page in pages] return { "exported": maya.when(str(doc["exported"])).iso8601(), "pages": len(doc["pages"]), "volume[k]": len("".join(texts)) / 1e3, }
def james_date_to_epoch(james_date): parts = james_date.split('-') if len(parts) != 4: raise ValueError(bad_time_syntax) month = parts[0] day = parts[1] year = parts[2] hour, minute = time_of_day(parts[3]) maya_format = '{}-{}-{} {}:{}'.format(year, month, day, hour, minute) return maya.when(maya_format, timezone=timezone)
def test_get_notifications_since_tomorrow(self, testapp, authenticated_user): authenticated_user.add_notification(name='panda', data='bear') authenticated_user.save() tomorrow = maya.when('tomorrow').datetime().date() response = testapp.get( url_for('user.notifications') + f'?since={tomorrow}') assert len(response.json) == 0
def as_maya(ctx, param, value): # noqa if not value: return None try: dt = maya.when(value) return dt.snap("@d") if value == "today" else dt except ValueError as exc: ctx.fail(f"{exc.args[0][:-1]}: {value}")
def get_iso_time_str(timestamp: Union[int, float, str, datetime]=None) -> str: """Get the ISO time string from a timestamp or date obj. Returns current time str if no timestamp is passed""" if isinstance(timestamp, (int, float)): maya_dt = maya.MayaDT(timestamp) elif isinstance(timestamp, str): maya_dt = maya.when(timestamp) elif timestamp is None: maya_dt = maya.now() else: raise ValueError(f'`{type(timestamp)}` is not supported') return maya_dt.iso8601()
def test_maya_datetimes(): if not maya: raise skip.SkipTest("maya is optional since it's not supported for " "enough python versions") with freeze_time(maya.when("October 2nd, 1997")): assert datetime.datetime.now() == datetime.datetime( year=1997, month=10, day=2 )
def get_predictions(coin, render=False): """Returns a list of predictions, unless render is True. Otherwise, returns the path of a rendered image. """ c = Coin(coin) q = "SELECT date as ds, value as y from api_coin WHERE name=:coin" db = records.Database() rows = db.query(q, coin=c.name) df = rows.export('df') df['y_orig'] = df[ 'y'] # to save a copy of the original data..you'll see why shortly. # log-transform y df['y'] = np.log(df['y']) model = Prophet(weekly_seasonality=True, yearly_seasonality=True) model.fit(df) periods = PERIODS if not render else GRAPH_PERIODS future_data = model.make_future_dataframe(periods=periods, freq='d') forecast_data = model.predict(future_data) if render: matplotlib.pyplot.gcf() fig = model.plot(forecast_data, xlabel='Date', ylabel='log($)') return mpld3.fig_to_html(fig) forecast_data_orig = forecast_data # make sure we save the original forecast data forecast_data_orig['yhat'] = np.exp(forecast_data_orig['yhat']) forecast_data_orig['yhat_lower'] = np.exp(forecast_data_orig['yhat_lower']) forecast_data_orig['yhat_upper'] = np.exp(forecast_data_orig['yhat_upper']) df['y_log'] = df['y'] #copy the log-transformed data to another column df['y'] = df['y_orig'] #copy the original data to 'y' # print(forecast_data_orig) d = forecast_data_orig['yhat'].to_dict() predictions = [] for i, k in enumerate(list(d.keys())[-PERIODS:]): w = maya.when(f'{i+1} days from now') predictions.append({ 'when': w.slang_time(), 'timestamp': w.iso8601(), 'usd': convert_to_decimal(d[k]), }) return predictions
def __to_maya(date): mapping = { str: lambda date: maya.when(date), int: lambda date: maya.MayaDT(epoch=date), maya.MayaDT: lambda date: date, datetime: lambda date: maya.MayaDT.from_datetime(date) } try: return mapping[type(date)](date) except KeyError: return maya.now()
def test_interval_flatten_adjacent(): step = 2 max_hour = 20 base = maya.when("jan/1/2011") intervals = [ maya.MayaInterval(start=base.add(hours=hour), duration=timedelta(hours=step)) for hour in range(0, max_hour, step) ] random.shuffle(intervals) assert maya.MayaInterval.flatten(intervals) == [ maya.MayaInterval(start=base, duration=timedelta(hours=max_hour)) ]
def get_valid_date(date, msg="Enter transaction date"): dateval = date while True: try: if dateval is None: dateval = click.prompt(msg, default="today") date = maya.when(dateval).datetime().date() except ValueError: continue else: break return date
async def ffevent(self, ctx: commands.Context, *, info): # Check the user entered the expected amount of inputs info_list = info.split('\n') if len(info_list) == 3: # Make sure the event name is unique (for the purpose ot the cancel command) for raid in self.watched_raids.values(): if raid['info']['title'] == info_list[0]: await ctx.send("An event with that name already exists") return # Attempt to parse the users date time try: parsed_date = maya.when(info_list[2], timezone="GMT") except: await ctx.send( "I didn't understand the date and time you entered") return # Create raid info raid = { 'tank': [], 'healer': [], 'dps': [], 'info': { 'title': info_list[0], 'description': info_list[1] }, 'datetime': parsed_date, 'channel': None, 'reminded': False } # Create a rich embed and post it embed = build_raid_embed(raid) message = await ctx.send(content=TAG, embed=embed) # Update the channel id in the raid now the message is sent raid['channel'] = message.channel.id # Add the new raid to the tracked raids list and save the file self.watched_raids.update({message.id: raid}) with open('cogs/ffevents/raids.pickle', 'wb') as f: pickle.dump(self.watched_raids, f) # Add the linked emoji reactions to the message and pin the message to the channel await message.add_reaction(TANK_EMOJI) await message.add_reaction(HEALER_EMOJI) await message.add_reaction(DPS_EMOJI) await message.pin() else: await ctx.send( "You made a mistake. Make sure to enter a title, description and time on separate lines" )
def get_filter(filter_text): comp = re.compile( r'(?P<key>[\w+ *]+) (?P<filter>([egln][qte]) (?P<values>\w+,* *)+') re_filter = comp.match(filter_text) key = re_filter.group('key') filter_value = '$' + re_filter.group('filter') values = re_filter.group('values') if key in ('event_start', 'event_end'): values = maya.when(re_filter.group('values')).datetime() return {key: {filter_value: values}}
def log(self, date=None, num_of_days=None, details=False): """ Returns the current watering log """ if details: api_route = 'watering/log/details' else: api_route = 'watering/log' if date and num_of_days: parser = maya.when(date) date = parser.datetime().strftime('%Y-%m-%d') api_route = '{}/{}/{}'.format(api_route, date, num_of_days) return self.get(api_route).object.json()
def trailing_periods(step, units, periods): """ Args: step (int): units (str): periods (int): Yields: datetime.datetime """ for count in range(0, (step * periods) + 1, step): when = '{count} {units} ago'.format(count=count, units=units) yield maya.when(when).datetime(naive=True)
def active_rate_field(measurement): if series == 'gas': return 'unit_rate' elif not rate_data['unit_rate_low_zone']: # no low rate return 'unit_rate_high' low_start_str = rate_data['unit_rate_low_start'] low_end_str = rate_data['unit_rate_low_end'] low_zone = rate_data['unit_rate_low_zone'] measurement_at = maya.parse(measurement['interval_start']) low_start = maya.when(measurement_at.datetime( to_timezone=low_zone).strftime(f'%Y-%m-%dT{low_start_str}'), timezone=low_zone) low_end = maya.when(measurement_at.datetime( to_timezone=low_zone).strftime(f'%Y-%m-%dT{low_end_str}'), timezone=low_zone) low_period = maya.MayaInterval(low_start, low_end) return \ 'unit_rate_low' if measurement_at in low_period \ else 'unit_rate_high'
def date_to_epoch(date): """Convert a date to epoch representation""" rv = None if isinstance(date, int): rv = date if isinstance(date, datetime.datetime): _ = maya.parse(date) rv = _.epoch if isinstance(date, str): _ = maya.when(date) rv = _.epoch if rv is None: raise TypeError('date must be epoch int, datetime obj or the string') return rv
def create_sql_dict(time_block_dict, year=2020, quarter=1): sql_dict = {} sql_dict["CRN"] = int(time_block_dict["CRN"]) sql_dict["building"] = time_block_dict["building"][0:2] sql_dict["campus"] = time_block_dict["campus"][0:2] sql_dict["course_num"] = time_block_dict["course_num"][0:7] sql_dict["course_title"] = time_block_dict["course_title"] sql_dict["day"] = time_block_dict["day"] sql_dict["department"] = time_block_dict["department"][0:4] sql_dict["instructor_first_name"] = time_block_dict["instructor_first_name"] sql_dict["instructor_last_name"] = time_block_dict["instructor_last_name"] if time_block_dict["room_number"] == "Web": sql_dict["room_number"] = None else: sql_dict["room_number"] = int(time_block_dict["room_number"]) sql_dict["instructor_first_name"] = time_block_dict["instructor_first_name"] try: maya_t1 = maya.when(time_block_dict["start_time"]) sql_dict["start_time"] = datetime.time( maya_t1.hour, maya_t1.minute, maya_t1.second ) maya_t2 = maya.when(time_block_dict["stop_time"]) sql_dict["stop_time"] = datetime.time( maya_t2.hour, maya_t2.minute, maya_t2.second ) except: sql_dict["start_time"] = None sql_dict["stop_time"] = None # insert end time sql_dict["year"] = year sql_dict["quarter"] = quarter #if sql_dict["building"] in ["we","We"] or sql_dict["campus"] in ["we","We"] or not sql_dict['building'] or not sql_dict['campus']: # sql_dict["in_person"] = False # # sql_dict["web"] = True return sql_dict
def test_alice_verifies_ursula_just_in_time(fleet_of_highperf_mocked_ursulas, highperf_mocked_alice, highperf_mocked_bob): # Patch the Datastore PolicyArrangement model with the highperf # NotAPublicKey not_public_key_record_field = RecordField(NotAPublicKey, encode=bytes, decode=NotAPublicKey.from_bytes) _umbral_pubkey_from_bytes = UmbralPublicKey.from_bytes def actual_random_key_instead(*args, **kwargs): _previous_bytes = args[0] serial = _previous_bytes[-5:] pubkey = NotAPublicKey(serial=serial) return pubkey def mock_set_policy(id_as_hex): return "" def mock_receive_treasure_map(): return Response(bytes(), status=201) with NotARestApp.replace_route("receive_treasure_map", mock_receive_treasure_map): with NotARestApp.replace_route("set_policy", mock_set_policy): with patch('umbral.keys.UmbralPublicKey.__eq__', lambda *args, **kwargs: True): with patch('umbral.keys.UmbralPublicKey.from_bytes', new=actual_random_key_instead): with patch( "nucypher.datastore.models.PolicyArrangement._alice_verifying_key", new=not_public_key_record_field): with mock_cert_loading, mock_metadata_validation, mock_message_verification: with mock_secret_source(): policy = highperf_mocked_alice.grant( highperf_mocked_bob, b"any label", m=20, n=30, expiration=maya.when('next week'), publish_treasure_map=False) # TODO: Make some assertions about policy. total_verified = sum(node.verified_node for node in highperf_mocked_alice.known_nodes) # Alice may be able to verify more than `n`, but certainly not less, # otherwise `grant()` would fail. assert total_verified >= 30 _POLICY_PRESERVER.append(policy)
def accomplishment(date: str = "now", overwrite: bool = False): parsed_date = maya.when(date, timezone="US/Central").datetime(naive=True) day_of_month = parsed_date.day week_number = (day_of_month - 1) // 7 + 1 output_filename = f"{parsed_date.year}-{parsed_date.month:02}-week{week_number}.md" output_filename = Path( str(OUTPUT_FOLDER.joinpath(output_filename)).format( year=parsed_date.year)) typer.echo(str(output_filename)) if not output_filename.parent.exists(): output_filename.parent.mkdir() if TASKS_DATA.exists(): data = yaml.load(TASKS_DATA.read_text(), Loader=yaml.FullLoader) else: data = dict() context_data = data.copy() context_data["date"] = parsed_date # Handle Accomplishments post = frontmatter.loads(ACCOMPLISHMENT_TEMPLATE.read_text()) t = jinja2.Template(post.content) contents = t.render(context_data) post["date"] = parsed_date post.content = contents if not output_filename.exists() or overwrite: output_filename.write_text(frontmatter.dumps(post)) # Handle README output_filename = Path("README.md") post = frontmatter.loads(README_TEMPLATE.read_text()) t = jinja2.Template(post.content) contents = t.render(context_data) post["date"] = parsed_date post.content = contents # output_filename.write_text(frontmatter.dumps(post)) output_filename.write_text(post.content)
def get_window(self, start, stop, return_type="epoch", field_name="timestamp"): # both start and stop should be datetime or a string start_maya = None start_timestamp = None stop_maya = None stop_timestamp = None if isinstance(start, str): start_maya = maya.when(start) start_timestamp = start_maya.datetime().timestamp() if isinstance(stop, str): stop_maya = maya.when(stop) stop_timestamp = stop_maya.datetime().timestamp() if isinstance(start, float): start_maya = maya.MayaDT(start) start_timestamp = start_maya.datetime().timestamp() if isinstance(stop, float): stop_maya = maya.MayaDT(stop) stop_timestamp = stop_maya.datetime().timestamp() if isinstance(start, dt): start_maya = maya.MayaDT(start) start_timestamp = start_maya.datetime().timestamp() if isinstance(stop, dt): stop_maya = maya.MayaDT(stop) stop_timestamp = stop_maya.datetime().timestamp() assert (start_timestamp < stop_timestamp), "The start time isn't less than the end time. The end should be closest to the present" return {'{}'.format(field_name):{'$lt':stop_timestamp, '$gt': start_timestamp}}
def _parse_chore_info(self, info: str): """Parse chore info from the message.""" if self.command == "/cancel": self.send_message("Okay, no new chore then.") return args = list(map(str.strip, info.translate(self.TRANSLATION_TABLE).split("|"))) arg_title, arg_due_at, arg_repetition = args + [None] * (3 - len(args)) # type: ignore alarm_at = (maya.when(arg_due_at) if arg_due_at else maya.now()).datetime() fields = {"title": arg_title, "due_at": alarm_at, "alarm_at": alarm_at, "repetition": arg_repetition} db.session.add(Chore(**fields)) db.session.commit() self.send_message("The chore was added.")
def insert_in_calendar(request): if request.POST: date = request.POST['date'] SCOPES = 'https://www.googleapis.com/auth/calendar' store = file.Storage('./hack/token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('./hack/credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) s = maya.when(date) date = s.datetime().strftime("%Y-%m-%d") event = { 'description': 'VoiceX Meeting Notes', 'start': { 'date': date, 'timeZone': 'Asia/Kolkata', }, 'end': { 'date': date, 'timeZone': 'Asia/Kolkata', }, 'recurrence': ['RRULE:FREQ=DAILY;COUNT=2'], 'reminders': { 'useDefault': False, 'overrides': [ { 'method': 'email', 'minutes': 24 * 60 }, { 'method': 'popup', 'minutes': 10 }, ], }, } event = service.events().insert(calendarId='primary', body=event).execute() print('Event created: %s' % (event.get('htmlLink'))) return JsonResponse({"foo": "booked"}) return JsonResponse({"foo": "bar"})
def _parse_withdrawal(self, withdrawal: Dict) -> Withdrawal: currency = withdrawal.get('currency', self.currency).upper() maya_dt = maya.when(withdrawal['datetime']) if 'datetime' in withdrawal else maya.now() return Transaction( id=withdrawal['id'], type=TxType.WITHDRAWAL, currency=currency, amount=Money(withdrawal['amount'], currency), status=self._parse_withdrawal_status(withdrawal['status']), address=withdrawal.get('address'), tx_hash=withdrawal.get('transaction_id'), fee=None, info=withdrawal, timestamp=maya_dt.epoch, datetime=maya_dt.datetime(), )
def _parse_withdrawal(self, withdrawal: Dict) -> Withdrawal: currency = withdrawal.get("currency", self.currency).upper() maya_dt = (maya.when(withdrawal["datetime"]) if "datetime" in withdrawal else maya.now()) return Transaction( id=withdrawal["id"], type=TxType.WITHDRAWAL, currency=currency, amount=Money(withdrawal["amount"], currency), status=self._parse_withdrawal_status(withdrawal["status"]), address=withdrawal.get("address"), tx_hash=withdrawal.get("transaction_id"), fee=None, info=withdrawal, timestamp=maya_dt.epoch, datetime=maya_dt.datetime(), )
def parse_with_maya(text, timezone=None): if timezone is None: timezone = 'UTC' try: maya_dt = maya.when(text, timezone=timezone) except ValueError as e: print('## Maya parsing failed.') maya_dt = None pass if maya_dt: timee_dt = Timee.from_maya(maya_dt) return timee_dt return None