def build_submission_metadata_context(survey_type: str, submitted_at: datetime, tx_id: str) -> dict: submitted_on = { "term": lazy_gettext("Submitted on:"), "descriptions": [{ "description": lazy_gettext("{date} at {time}").format( date=format_datetime(submitted_at, format="dd LLLL yyyy"), time=format_datetime(submitted_at, format="HH:mm"), ) }], } submission_reference = { "term": lazy_gettext("Submission reference:"), "descriptions": [{ "description": convert_tx_id(tx_id) }], } if survey_type == "social": return { "data-qa": "metadata", "termCol": 3, "descriptionCol": 9, "itemsList": [submitted_on], } return { "data-qa": "metadata", "termCol": 5, "descriptionCol": 7, "itemsList": [submitted_on, submission_reference], }
def preview(): if request.method == 'POST': if 'title' in request.form: title = request.form['title'] else: title = "" if 'message' in request.form: message = request.form['message'] else: message = "" if 'end_date' in request.form: try: end_date = format_datetime( datetime.strptime(request.form['end_date'], '%Y-%m-%dT%H:%M')) except: end_date = format_datetime(datetime.now()) else: end_date = format_datetime(datetime.now()) choices = [] for param, value in request.form.items(): if param.startswith('choice_'): choices.append(value) return render_template('preview.html', title=title, message=message, end_date=end_date, choices=choices) else: return render_template('error.html', message=gettext(u'Error: preview without data'))
def group_to_json(group): group_dict = group._asdict() group_dict['createTimestamp'] = format_datetime(group.createTimestamp) group_dict['modifyTimestamp'] = format_datetime(group.modifyTimestamp) group_dict.update(actions={ 'edit': url_for('.edit_group', cn=group.cn), 'delete': url_for('.delete_group', cn=group.cn), }) return group_dict
def user_to_json(user): user_dict = user._asdict() user_dict['createTimestamp'] = format_datetime(user.createTimestamp) user_dict['modifyTimestamp'] = format_datetime(user.modifyTimestamp) user_dict.update(actions={ 'edit': url_for('.edit_user', uid=user.uid), 'delete': url_for('.delete_user', uid=user.uid), }) return user_dict
def format_date_time(dt) -> str: dt_format = DATETIME_FORMATS.get_or_404(current_user.language) if not dt_format: return format_datetime(dt, "EEEE, MMM dd, HH:mm").title() now = datetime.datetime.now() if dt.year == now.year: return format_datetime(dt, dt_format[0]).title() else: return format_datetime(dt, dt_format[1]).title()
def test_refreshing(self): app = flask.Flask(__name__) b = babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna' babel.refresh() assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM'
def test_refreshing(self): app = flask.Flask(__name__) babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna' babel.refresh() assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM'
def user_to_json(user): user_dict = user._asdict() user_dict['createTimestamp'] = format_datetime(user.createTimestamp) user_dict['modifyTimestamp'] = format_datetime(user.modifyTimestamp) user_dict.update( actions={ 'edit': url_for('.edit_user', uid=user.uid), 'delete': url_for('.delete_user', uid=user.uid), }) return user_dict
def group_to_json(group): group_dict = group._asdict() group_dict['createTimestamp'] = format_datetime(group.createTimestamp) group_dict['modifyTimestamp'] = format_datetime(group.modifyTimestamp) group_dict.update( actions={ 'edit': url_for('.edit_group', cn=group.cn), 'delete': url_for('.delete_group', cn=group.cn), }) return group_dict
def handle(self): clusters = self.kqueen_request('cluster', 'list') provisioners = self.kqueen_request('provisioner', 'list') deployed_clusters = 0 healthy_clusters = 0 healthy_provisioners = 0 # sort clusters by date if isinstance(clusters, list): clusters.sort(key=lambda k: (k['created_at'], k['name'])) for cluster in clusters: if 'state' in cluster: if app.config['CLUSTER_PROVISIONING_STATE'] != cluster['state']: deployed_clusters = deployed_clusters + 1 if app.config['CLUSTER_OK_STATE'] == cluster['state']: healthy_clusters = healthy_clusters + 1 if 'created_at' in cluster: cluster['created_at'] = format_datetime(cluster['created_at']) # sort provisioners by date if isinstance(provisioners, list): provisioners.sort(key=lambda k: (k['created_at'], k['name'])) for provisioner in provisioners: if 'state' in provisioner: if app.config['PROVISIONER_ERROR_STATE'] != provisioner[ 'state']: healthy_provisioners = healthy_provisioners + 1 if 'created_at' in provisioner: provisioner['created_at'] = format_datetime( provisioner['created_at']) cluster_health = 0 if healthy_clusters and deployed_clusters: cluster_health = int((healthy_clusters / deployed_clusters) * 100) provisioner_health = 0 if healthy_provisioners and provisioners: provisioner_health = int( (healthy_provisioners / len(provisioners)) * 100) overview = { 'cluster_count': len(clusters), 'cluster_max': len(clusters) if len(clusters) else 1, 'cluster_health': cluster_health, 'provisioner_count': len(provisioners), 'provisioner_max': len(provisioners) if len(provisioners) else 1, 'provisioner_health': provisioner_health, } return render_template('ui/index.html', overview=overview, clusters=clusters, provisioners=provisioners)
def report_site(site): try: with open( os.path.join(flask.current_app.config["data_dir"], site + ".json") ) as f: data = json.load(f) except FileNotFoundError: flask.abort(404) data["meta"]["last_update"] = format_datetime( datetime.datetime.fromisoformat(data["meta"]["last_update"]) ) data["meta"]["active_since"] = format_datetime( datetime.datetime.fromisoformat(data["meta"]["active_since"]) ) return flask.render_template("report_site.html", site=site, d=data)
def date_age(dt, now=None): # Fail silently for now XXX if not dt: return "" formatted_date = babel.format_datetime(dt, format="yyyy-MM-dd HH:mm") return "{} ({})".format(formatted_date, age(dt, now))
def datetimeformat(dt_value: Optional[datetime.datetime] = None, dt_format: Optional[str] = None, rebase: bool = True) -> Optional[str]: """ Return a datetime formatted according to format. This function is needed, because `flask_babel.format_datetime` formats the current datetime, if `datetime` is None. """ if not dt_value: return None dt_value = utc2local(dt_value) if dt_format == "iso-short": return cast( str, format_datetime(dt_value, "YYYY-MM-dd HH:mm", rebase=False)) return cast(str, format_datetime(dt_value, dt_format, rebase))
def format_dt(dt, sep=' '): s = (datetime.now() - dt).total_seconds() if s > (7*60*60*24): # 7 days return format_datetime(dt) ret = [] if s < 0: neg = True s *= -1 else: neg = False if s >= (24*60*60): days = int(s//(24*60*60)) ret.append('%dd' % days) s -= days*(24*60*60) if s >= 60*60: hours = int(s//(60*60)) ret.append('%dh' % hours) s -= hours*(60*60) if s >= 60: minutes = int(s//60) ret.append('%dm' % minutes) s -= minutes*60 if s >= 1: seconds = int(s) ret.append('%ds' % seconds) s -= seconds if not ret: return '0s' return ('-' if neg else '') + _('%(ret)s ago', ret=sep.join(ret))
def hello(): """ render html file """ login = False if g.get('user') is not None: login = True nowis = format_datetime(datetime.now()) return render_template('index.html', login=login, current_time=nowis)
def hello_world() -> str: """Renders a Basic Template for Babel Implementation""" timezone = get_timezone() tz = pytz.timezone(timezone) current_time = datetime.now(tz) current_time = format_datetime(datetime=current_time) return render_template("index.html", current_time=current_time)
def get_vax_trends(area=None): """ Return the vax-trends array :param area: optional, str :return: list of dicts """ data = get_vax_trends_data(area) trends = [] for d in VAX_DOSES: last_week_dt = data[6]['_id'] count = data[0][d] last_week_count = data[6][d] diff = count - last_week_count if diff > 0: status = 'increase' elif diff < 0: status = 'decrease' else: status = 'stable' try: perc = f'{round(diff / last_week_count * 100)}%' except (ValueError, ZeroDivisionError): perc = 'n/a' trends.append({ 'id': d, 'last_week_count': format_number(last_week_count), 'percentage': perc, 'title': VARS[d]['title'], 'colour': VARS[d][status]['colour'], "icon": VARS[d]['icon'], 'status_icon': VARS[d][status]['icon'], 'count': format_number(count), 'last_week_dt': format_datetime(last_week_dt, DOW_FMTY) }) return trends
def void_transaction(): if flask.request.is_json: data = flask.request.get_json() else: data = flask.request.args try: transaction_id = data['transaction_id'] except (KeyError, TypeError): flask.abort(400) transaction = models.Transaction.query.get(transaction_id) if not transaction or transaction.voided: flask.abort(400) transaction.void_and_refund() if flask.request.is_json: return flask.jsonify(transaction_id=transaction.id, user_id=transaction.user.id, value=transaction.value, balance=transaction.user.balance) else: flask.flash( "Ångrade {type} \"{text}\", {value} den {date} på {user}.".format( type=transaction.type, text=transaction.text, value=transaction.formatted_value, date=flask_babel.format_datetime(transaction.timestamp, "dd MMMM yyyy, HH:mm"), user=transaction.user.full_name, ), 'success') return flask.redirect(flask.url_for('strequeadmin.transactions'))
def translate_series_lang(series): """ Return a modified version of the series input dict with the "name" values babel translated :param series: dict :return: dict """ dates_series = series.get("dates") daily_series = series.get("daily") current_series = series.get("current") cum_series = series.get("cum") if daily_series is not None: for s in daily_series: s["name"] = gettext(s["name"]) if current_series is not None: for s in current_series: s["name"] = gettext(s["name"]) if cum_series is not None: for s in cum_series: s["name"] = gettext(s["name"]) if dates_series is not None: series["dates"] = [ format_datetime(dt, SERIES_DT_FMT) for dt in dates_series ] return series
def get_admins_timeseries_chart_data(): """ Return admins timeseries data to frontend :return: dict """ chart_data = {} try: pipe = [{'$sort': {VAX_DATE_KEY: 1}}] cursor = vax_admins_summary_coll.aggregate(pipeline=pipe) data = list(cursor) df = pd.DataFrame(data) dates = df[VAX_DATE_KEY].apply( lambda x: format_datetime(x, SERIES_DT_FMT)).unique().tolist() data = [{ 'name': OD_TO_PC_MAP[r], 'data': (df[df[VAX_AREA_KEY] == r][VAX_SECOND_DOSE_KEY].cumsum() / df[df[VAX_AREA_KEY] == r][POP_KEY] * 100).round(2).to_list() } for r in sorted(df[VAX_AREA_KEY].unique())] chart_data = { "title": gettext('Vaccination trend'), "yAxisTitle": gettext('Pop. vaccinated (2nd dose) [%]'), "dates": dates, "data": data } app.logger.debug(f"Time series chart data {chart_data}") except Exception as e: app.logger.error(f"While getting vax timeseries chart data {e}") return chart_data
def filter_format_datetime(dt, format=None, rebase=True): """Return a date formatted according to the given pattern. The format parameter can either be ``short``, ``medium``, ``long`` or ``full``. """ return format_datetime(dt, format=format, rebase=rebase)
def macro(self, content, arguments, page_url, alternative): if arguments is None: tm = time.time() # always UTC else: stamp = arguments[0] tm = self.parse_time(stamp) return format_datetime(datetime.utcfromtimestamp(tm))
def get_latest_commits(repo_dir, commit_count): """ :param repo_dir: path of repo :type repo_dir: str :param commit_count: number of commits to return :type commit_count: int :return: commit information (hash, message, author, date) about commit_count last commits :rtype: list of dicts """ try: sipa_repo = git.Repo(repo_dir) commits = sipa_repo.iter_commits(max_count=commit_count) return [{ 'hexsha': commit.hexsha, 'message': commit.summary, 'author': commit.author, 'date': format_datetime(datetime.fromtimestamp(commit.committed_date)), } for commit in commits] except (InvalidGitRepositoryError, CacheError, GitCommandError): logger.exception("Could not get latest commits", extra={'data': { 'repo_dir': repo_dir }}) return []
def date_age(dt: Optional[datetime], now: Optional[datetime] = None) -> str: # Fail silently for now XXX if not dt: return "" formatted_date = babel.format_datetime(dt, format="yyyy-MM-dd HH:mm") return f"{formatted_date} ({age(dt, now)})"
def handle(self): # session data organization_id = session['user']['organization']['id'] user_id = session['user']['id'] # backend resources organization = self.kqueen_request('organization', 'get', fnargs=(organization_id,)) users = self.kqueen_request('user', 'list') members = [ u for u in users if u['organization']['id'] == organization_id and u['id'] != user_id ] # sort members by date members.sort(key=lambda k: (k['created_at'], k['username'])) # Patch members until we actually have these data for realsies for member in members: member['state'] = 'Active' if member['active'] else 'Disabled' member['role'] = member['role'].capitalize() if 'email' not in member: member['email'] = '-' if 'created_at' in member: member['created_at'] = format_datetime(member['created_at']) return render_template('ui/organization_manage.html', organization=organization, members=members)
def _(browser=browser): content = ContentFactory.create(name="Introdução ao Flask") browser.visit(url_for("contents.show", content_slug=content.slug)) timestamp = format_datetime(content.updated_on, "medium") assert browser.is_text_present( f"O conteúdo apresentado foi atualizado em {timestamp} e poderá ser modificado a qualquer momento sem aviso prévio." )
def simple_datetime_display(date, timezone=None, format='MMMM d, yyyy hh:mm a'): if not date: return '' if timezone: date = date.astimezone(pytz.timezone(timezone)) return format_datetime(date, format, rebase=False)
def localised_nice_date(datetime_: datetime.datetime, show_date: bool = False, with_hours: bool = False, with_seconds: bool = False, format: Optional[str] = None) -> str: ''' Returns a friendly localised unicode representation of a datetime. e.g. '31 minutes ago' '1 day ago' 'April 24, 2013' (show_date=True) 'October 25, 2017, 16:03 (UTC)' (show_date=True, with_hours=True) 'Apr 3, 2020, 4:00:31 PM' ( show_date=True, with_hours=True, format='medium') 'April 03, 20' (show_date=True, format='MMMM dd, YY') :param datetime_: The date to format :type datetime_: datetime :param show_date: Show 'April 24, 2013' instead of '2 days ago' :type show_date: bool :param with_hours: should the `hours:mins` be shown for dates :type with_hours: bool :param with_seconds: should the `hours:mins:seconds` be shown for dates :type with_seconds: bool :param format: override format of datetime representation using babel date/time pattern syntax of predefined pattern. :type format: str :rtype: sting ''' if datetime_.tzinfo is None: datetime_ = datetime_.replace(tzinfo=pytz.utc) if not show_date: now = datetime.datetime.now(pytz.utc) date_diff = datetime_ - now if abs(date_diff) < datetime.timedelta(seconds=1): return _('Just now') return format_timedelta(date_diff, add_direction=True) if with_seconds: return format_datetime(datetime_, format or 'long') elif with_hours: fmt_str = "MMMM d, YYYY, HH:mm (z)" return format_datetime(datetime_, format or fmt_str) else: return format_date(datetime_, format or 'long')
def hello_world(): """[basic template] Returns: [type]: [template] """ current_time = format_datetime(datetime.now(get_timezone())) user = getattr(g, 'user', None) return render_template('index.html', user=user, current_time=current_time)
def age( dt: Optional[datetime], now: Optional[datetime] = None, add_direction: bool = True, date_threshold: Optional[Any] = None, ) -> str: """ :param dt: :class:`datetime<datetime>` instance to format :param now: :class:`datetime<datetime>` instance to compare to `dt` :param add_direction: if `True`, will add "in" or "ago" (example for `en` locale) to time difference `dt - now`, i.e "in 9 min." or " 9min. ago" :param date_threshold: above threshold, will use a formated date instead of elapsed time indication. Supported values: "day". """ # Fail silently for now XXX if not dt: return "" if not now: now = datetime.utcnow() locale = babel.get_locale() dt = utc_dt(dt) now = utc_dt(now) delta = dt - now if date_threshold is not None: dy, dw, dd = dt_cal = dt.isocalendar() ny, nw, nd = now_cal = now.isocalendar() if dt_cal != now_cal: # not same day remove_year = dy == ny date_fmt = locale.date_formats["long"].pattern time_fmt = locale.time_formats["short"].pattern fmt = locale.datetime_formats["medium"] if remove_year: date_fmt = date_fmt.replace("y", "").strip() # remove leading or trailing spaces, comma, etc... date_fmt = re.sub("^[^A-Za-z]*|[^A-Za-z]*$", "", date_fmt) fmt = fmt.format(time_fmt, date_fmt) return babel.format_datetime(dt, format=fmt) # don't use (flask.ext.)babel.format_timedelta: as of Flask-Babel 0.9 it # doesn't support "threshold" arg. return format_timedelta( delta, locale=locale, granularity="minute", threshold=0.9, add_direction=add_direction, )
def convert_time_to_string(t): """ Converts ``t`` (in Unix time) to a locale-specific string describing the time and date. """ try: return format_datetime(datetime.datetime.fromtimestamp(float(t))) except AttributeError: # testing as opposed to within the Flask app return time.strftime('%B %d, %Y %I:%M %p', time.localtime(float(t)))
def home_page(): """Function: Home Page index.html""" timeZone = timezone(get_timezone()) dateTime = pytz.utc.localize(datetime.utcnow()).astimezone(tz=timeZone) current_time = format_datetime(dateTime) return render_template('index.html', locale=get_locale(), current_time=current_time)
def index(): print(format_datetime(datetime(1987, 3, 5, 17, 12))) print(gettext('Home')) title = current_app.config['RABIANG_SITE_NAME'] return render_template(current_app.config['RABIANG_SITE_THEME'] + '/main/index.html', title=title)
def datetime_filter(dt, format=None): """Format datetime objects using Flask-Babel :param datetime|None dt: a datetime object or None :param str format: format as understood by Flask-Babel's format_datetime :rtype: unicode """ if dt is None: return "k/A" return flask_babel.format_datetime(dt, format)
def datetimeformat(eval_ctx, value, kind='LONG_DATETIME'): language_formats = config.LANGUAGES_FORMATS or {} language = str(get_locale()) format = 'dd/MM/yyyy HH:mm' if language in language_formats: format = language_formats[language][kind] if kind in language_formats[language] else format return format_datetime(value, format)
def datetime_filter(dt, format=None): """Format datetime objects using Flask-Babel :param datetime|None dt: a datetime object or None :param str format: format as understood by Flask-Babel's format_datetime :rtype: unicode """ if dt is None: return u"k/A" return flask_babel.format_datetime(dt, format)
def export_bookmarks(): bookmarks = Bookmark.by_user(current_user.id, include_private=True) today = datetime.now() filename = "qstode-backup-%s.html" % format_datetime(today, "dd-MM-yyyy") resp = make_response(render_template("_export.html", bookmarks=bookmarks, today=today)) resp.headers["Content-Type"] = "application/octet-stream" resp.headers["Cache-Control"] = "no-cache" resp.headers["Content-Disposition"] = "attachment;filename=" + filename return resp
def test_basics(self): app = flask.Flask(__name__) b = babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' assert babel.format_date(d) == 'Apr 12, 2010' assert babel.format_time(d) == '1:46:00 PM' with app.test_request_context(): app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna' assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM' assert babel.format_date(d) == 'Apr 12, 2010' assert babel.format_time(d) == '3:46:00 PM' with app.test_request_context(): app.config['BABEL_DEFAULT_LOCALE'] = 'de_DE' assert babel.format_datetime(d, 'long') == \ '12. April 2010 15:46:00 MESZ'
def export_bookmarks(): bookmarks = model.Bookmark.by_user(current_user.id, include_private=True) today = datetime.now() filename = 'qstode-backup-%s.html' % format_datetime(today, 'dd-MM-yyyy') resp = make_response(render_template('_export.html', bookmarks=bookmarks, today=today)) resp.headers['Content-Type'] = 'application/octet-stream' resp.headers['Cache-Control'] = 'no-cache' resp.headers['Content-Disposition'] = 'attachment;filename=' + filename return resp
def age(dt, now=None, add_direction=True, date_threshold=None): """ :param dt: :class:`datetime<datetime.datetime>` instance to format :param now: :class:`datetime<datetime.datetime>` instance to compare to `dt` :param add_direction: if `True`, will add "in" or "ago" (example for `en` locale) to time difference `dt - now`, i.e "in 9 min." or " 9min. ago" :param date_threshold: above threshold, will use a formated date instead of elapsed time indication. Supported values: "day". """ # Fail silently for now XXX if not dt: return "" if not now: now = datetime.datetime.utcnow() locale = babel.get_locale() dt = utc_dt(dt) now = utc_dt(now) delta = dt - now if date_threshold is not None: dy, dw, dd = dt_cal = dt.isocalendar() ny, nw, nd = now_cal = now.isocalendar() if dt_cal != now_cal: # not same day remove_year = dy == ny date_fmt = locale.date_formats["long"].pattern time_fmt = locale.time_formats["short"].pattern fmt = locale.datetime_formats["medium"] if remove_year: date_fmt = date_fmt.replace("y", "").strip() # remove leading or trailing spaces, comma, etc... date_fmt = re.sub("^[^A-Za-z]*|[^A-Za-z]*$", "", date_fmt) fmt = fmt.format(time_fmt, date_fmt) return babel.format_datetime(dt, format=fmt) # don't use (flask.ext.)babel.format_timedelta: as of Flask-Babel 0.9 it # doesn't support "threshold" arg. return format_timedelta( delta, locale=locale, granularity="minute", threshold=0.9, add_direction=add_direction, )
def test_custom_formats(self): app = flask.Flask(__name__) app.config.update( BABEL_DEFAULT_LOCALE='en_US', BABEL_DEFAULT_TIMEZONE='Pacific/Johnston' ) b = babel.Babel(app) b.date_formats['datetime'] = 'long' b.date_formats['datetime.long'] = 'MMMM d, yyyy h:mm:ss a' d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'April 12, 2010 3:46:00 AM'
def test_custom_locale_selector(self): app = flask.Flask(__name__) b = babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) the_timezone = 'UTC' the_locale = 'en_US' @b.localeselector def select_locale(): return the_locale @b.timezoneselector def select_timezone(): return the_timezone with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' the_locale = 'de_DE' the_timezone = 'Europe/Vienna' with app.test_request_context(): assert babel.format_datetime(d) == '12.04.2010 15:46:00'
def _value(self): if self.raw_data: return ' '.join(self.raw_data) else: locale = get_locale() date_fmt = locale.date_formats['short'].pattern # force numerical months and 4 digit years date_fmt = date_fmt.replace('MMMM', 'MM')\ .replace('MMM', 'MM')\ .replace('yyyy', 'y')\ .replace('yy', 'y')\ .replace('y', 'yyyy') time_fmt = locale.time_formats['short'] dt_fmt = locale.datetime_formats['short'].format(time_fmt, date_fmt) return format_datetime(self.data, dt_fmt) if self.data else ''
def _value(self): if self.raw_data: return " ".join(self.raw_data) else: locale = get_locale() date_fmt = locale.date_formats["short"].pattern # force numerical months and 4 digit years date_fmt = ( date_fmt.replace("MMMM", "MM") .replace("MMM", "MM") .replace("yyyy", "y") .replace("yy", "y") .replace("y", "yyyy") ) time_fmt = locale.time_formats["short"] dt_fmt = locale.datetime_formats["short"].format(time_fmt, date_fmt) return format_datetime(self.data, dt_fmt) if self.data else ""
def get_latest_commits(repo_dir, commit_count): """ :param repo_dir: path of repo :type repo_dir: str :param commit_count: number of commits to return :type commit_count: int :return: commit information (hash, message, author, date) about commit_count last commits :rtype: list of dicts """ try: sipa_repo = git.Repo(repo_dir) commits = sipa_repo.iter_commits(max_count=commit_count) return [{ 'hexsha': commit.hexsha, 'message': commit.summary, 'author': commit.author, 'date': format_datetime(datetime.fromtimestamp( commit.committed_date)), } for commit in commits] except (InvalidGitRepositoryError, CacheError, GitCommandError): logger.exception("Could not get latest commits", extra={'data': { 'repo_dir': repo_dir}}) return []
def plot(self): v = set([]) for idx in self.observation_variable: v.add(self.observation_variable_names[idx]) for n in self.variable_names: v.add(n) numplots = len(v) fig, ax = self.setup_subplots(numplots) data = [] for o in self.observation: d = np.ma.MaskedArray(o['data']) d[np.where(d == '')] = np.ma.masked d = np.ma.masked_invalid(d.filled(np.nan).astype(np.float32)) data.append(d) ureg = pint.UnitRegistry() ax_idx = -1 udepth = ureg.parse_expression(self.observation[0]['depthunit']) axis_map = {} unit_map = {} for idx in self.observation_variable: ax_idx += 1 for d in data: ax[ax_idx].plot( d[:, idx], self.observation[0]['depth'] * udepth.to(ureg.meter) ) ax[ax_idx].xaxis.set_label_position('top') ax[ax_idx].xaxis.set_ticks_position('top') ax[ax_idx].set_xlabel("%s (%s)" % ( self.observation_variable_names[idx], utils.mathtext(self.observation_variable_units[idx]), )) axis_map[self.observation_variable_names[idx]] = ax[ax_idx] try: if "_" in self.observation_variable_units[idx]: u = self.observation_variable_units[idx].lower().split( "_", 1 )[1] else: u = self.observation_variable_units[idx].lower() unit_map[ self.observation_variable_names[idx]] = ureg.parse_units(u) except: unit_map[ self.observation_variable_names[idx]] = ureg.dimensionless for k, v in unit_map.iteritems(): if v == ureg.speed_of_light: unit_map[k] = ureg.celsius for idx, var in enumerate(self.variables): if axis_map.get(self.variable_names[idx]) is not None: axis = axis_map.get(self.variable_names[idx]) showlegend = True destunit = unit_map.get(self.variable_names[idx]) else: ax_idx += 1 axis = ax[ax_idx] showlegend = False try: destunit = ureg.parse_units( self.variable_units[idx].lower()) if destunit == ureg.speed_of_light: destunit = ureg.celsius except: destunit = ureg.dimensionless for j in range(0, self.data.shape[0]): try: u = ureg.parse_units(self.variable_units[idx].lower()) if u == ureg.speed_of_light: u = ureg.celsius quan = ureg.Quantity(self.data[j, idx, :], u) except: quan = ureg.Quantity( self.data[j, idx, :], ureg.dimensionless) axis.plot(quan.to(destunit).magnitude, self.depths[j, idx, :]) showlegend = showlegend or len(self.observation) > 1 if not showlegend: axis.xaxis.set_label_position('top') axis.xaxis.set_ticks_position('top') axis.set_xlabel("%s (%s)" % ( self.variable_names[idx], utils.mathtext(self.variable_units[idx]), )) else: l = [] for j in [ (gettext("Observed"), self.observation_times), (gettext("Modelled"), self.timestamps) ]: for i, name in enumerate(self.names): if len(self.names) == 1: name = "" else: name = name + " " l.append("%s%s (%s)" % ( name, j[0], format_datetime(j[1][i]) )) leg = axis.legend(l, loc='best') for legobj in leg.legendHandles: legobj.set_linewidth(4.0) ax[0].invert_yaxis() ax[0].set_ylabel(gettext("Depth (m)")) if len(self.variables) > 0: plt.suptitle("\n".join( wrap( gettext("Profile for %s, Observed at %s, Modelled at %s") % ( ", ".join(self.names), format_datetime(self.observation_time), format_datetime(self.timestamp) ), 80) )) else: plt.suptitle("\n".join( wrap( gettext("Profile for %s (%s)") % ( ", ".join(self.names), format_datetime(self.observation_time) ), 80) )) fig.tight_layout() fig.subplots_adjust(top=0.88) return super(ObservationPlotter, self).plot()
def data(self, *args, **kw): security = current_app.services['security'] length = int(kw.get("iDisplayLength", 0)) start = int(kw.get("iDisplayStart", 0)) sort_col = int(kw.get("iSortCol_0", 1)) sort_dir = kw.get("sSortDir_0", "asc") echo = int(kw.get("sEcho", 0)) search = kw.get("sSearch", "").replace("%", "").strip().lower() end = start + length q = User.query \ .options(sa.orm.subqueryload('groups'), sa.orm.undefer('photo'), ) \ .filter(User.id != 0) total_count = q.count() if search: # TODO: gérer les accents filter = or_(func.lower(User.first_name).like("%" + search + "%"), func.lower(User.last_name).like("%" + search + "%"), func.lower(User.email).like("%" + search + "%")) q = q.filter(filter) count = q.count() SORT_COLS = { 1: [], # [User.last_name, User.first_name] will be added anyway 2: [func.lower(User.email)], 5: [User.last_active], } columns = list(SORT_COLS.get(sort_col, [])) columns.extend([func.lower(User.last_name), func.lower(User.first_name)]) direction = asc if sort_dir == 'asc' else desc order_by = map(direction, columns) # sqlite does not support 'NULLS FIRST|LAST' in ORDER BY clauses engine = q.session.get_bind(User.__mapper__) if engine.name != 'sqlite': order_by[0] = nullslast(order_by[0]) q = q.order_by(*order_by) users = q.slice(start, end).all() data = [] MUGSHOT_SIZE = 45 for user in users: # TODO: this should be done on the browser. user_url = url_for(".users_user", user_id=user.id) mugshot = user_photo_url(user, size=MUGSHOT_SIZE) name = escape(getattr(user, "name") or "") email = escape(getattr(user, "email") or "") roles = [r for r in security.get_roles(user, no_group_roles=True) if r.assignable] columns = [] columns.append( u'<a href="{url}"><img src="{src}" width="{size}" height="{size}">' u'</a>'.format(url=user_url, src=mugshot, size=MUGSHOT_SIZE) ) columns.append( u'<a href="{url}">{name}</a>'.format(url=user_url, name=name)) columns.append( u'<a href="{url}"><em>{email}</em></a>'.format(url=user_url, email=email)) columns.append(u'\u2713' if user.can_login else u'') columns.append(render_template_string( u'''{%- for g in groups %} <span class="badge badge-default">{{ g.name }}</span> {%- endfor %}''', groups=sorted(user.groups))) columns.append(render_template_string( u'''{%- for role in roles %} <span class="badge badge-default">{{ role }}</span> {%- endfor %}''', roles=roles)) if user.last_active: last_active = format_datetime(user.last_active) else: last_active = _(u'Never logged in') columns.append(last_active) data.append(columns) return { "sEcho": echo, "iTotalRecords": total_count, "iTotalDisplayRecords": count, "aaData": data, }
def parse_query(self, query): quantum = query.get('quantum') if quantum == 'month': self.date_formatter = lambda x: format_date(x, "MMMM yyyy") elif quantum == 'day': self.date_formatter = lambda x: format_date(x, "long") elif quantum == 'hour': self.date_formatter = lambda x: format_datetime(x) else: self.date_formatter = lambda x: format_date(x, "long") def get_time(param): if query.get(param) is None or len(str(query.get(param))) == 0: return -1 else: try: return int(query.get(param)) except ValueError: return query.get(param) self.time = get_time('time') self.starttime = get_time('starttime') self.endtime = get_time('endtime') scale = query.get('scale') if scale is None or 'auto' in scale: scale = None else: scale = [float(x) for x in scale.split(',')] self.scale = scale variables = query.get('variable') if variables is None: variables = ['votemper'] if isinstance(variables, str) or isinstance(variables, unicode): variables = variables.split(',') variables = filter(lambda v: v != '', variables) self.variables_anom = variables self.variables = [re.sub('_anom$', '', v) for v in variables] cmap = query.get('colormap') if cmap is not None: cmap = colormap.colormaps.get(cmap) if cmap is None and self.variables != self.variables_anom: cmap = colormap.colormaps['anomaly'] self.cmap = cmap linearthresh = query.get('linearthresh') if linearthresh is None or linearthresh == '': linearthresh = 200 linearthresh = float(linearthresh) if not linearthresh > 0: linearthresh = 1 self.linearthresh = linearthresh depth = query.get('depth') if depth is None or len(str(depth)) == 0: depth = 0 if isinstance(depth, basestring) and depth.isdigit(): depth = int(depth) if isinstance(depth, list): for i in range(0, len(depth)): if isinstance(depth[i], basestring) and depth[i].isdigit(): depth[i] = int(depth[i]) self.depth = depth self.showmap = query.get('showmap') is None or \ bool(query.get('showmap'))
def datetimeformat(value, format="EEE, d MMM yyyy H:mm:ss"): return format_datetime(value, format)
def my_format_datetime(value, format='medium'): if format == 'full': format="EEEE, d. MMMM y 'at' HH:mm" elif format == 'medium': format="EE dd.MM.y HH:mm" return format_datetime(value, format)
def _jinja2_filter_datetime(date, fmt=None): if fmt: return format_datetime(date, fmt) else: return format_datetime(date, 'dd MMMM YY, HH:mm')
def datetime_filter(datetime, format=None, locale=None): return format_datetime(datetime, format, locale)
def get_dt(fmt='dd MMMM YY'): return format_datetime(datetime.now(), fmt)
def monthly_format(value, format='MMMM yyyy'): year, month = value dt = datetime(year, month, 1, 0, 0) return format_datetime(dt, format)
def datetime_processor(datetime): return format_datetime(datetime, format='medium')
def reformat_datetime(value, format=None): """Converts datetime into string formatted for current locale.""" return format_datetime(value.replace(tzinfo=None), format)
def index(): print(format_datetime(datetime(1987, 3, 5, 17, 12))) print(gettext('Home')) current_app.logger.info('Information: 3 + 2 = %d', 5) return render_template('default/main/index.html')
def render_view(self, field, **kwargs): return (format_datetime(field.object_data) if field.object_data else u'')