def test_approve( create_user, create_reservation, create_blocking, smtp, notify_blocker, colliding_reservation, colliding_occurrence ): blocking = create_blocking(start_date=date.today(), end_date=date.today() + timedelta(days=1)) br = blocking.blocked_rooms[0] other_user = create_user(123) resv = create_reservation( start_dt=datetime.combine(blocking.start_date, time(8)), end_dt=datetime.combine(blocking.start_date, time(10)), created_by_user=other_user if colliding_reservation else blocking.created_by_user, booked_for_user=other_user if colliding_reservation else blocking.created_by_user, ) resv2 = create_reservation( start_dt=datetime.combine(blocking.start_date + timedelta(days=1), time(8)), end_dt=datetime.combine(blocking.end_date + timedelta(days=1), time(10)), repeat_frequency=RepeatFrequency.DAY, created_by_user=other_user if colliding_occurrence else blocking.created_by_user, booked_for_user=other_user if colliding_occurrence else blocking.created_by_user, ) assert br.state == BlockedRoom.State.pending br.approve(notify_blocker=notify_blocker) assert br.state == BlockedRoom.State.accepted assert resv.is_rejected == colliding_reservation assert not resv2.is_rejected for occ in resv2.occurrences: assert occ.is_rejected == (colliding_occurrence and blocking.is_active_at(occ.date)) if notify_blocker: extract_emails(smtp, one=True, to=blocking.created_by_user.email, subject="Room blocking ACCEPTED") assert len(smtp.outbox) == 2 * (colliding_occurrence + colliding_reservation) # 2 emails per rejection
def isValid(self, cart=None): """ Make sure this discount still has available uses and is in the current date range. If a cart has been populated, validate that it does apply to the products we have selected. """ if not self.active: return (False, ugettext('This coupon is disabled.')) if self.startDate > date.today(): return (False, ugettext('This coupon is not active yet.')) if self.endDate < date.today(): return (False, ugettext('This coupon has expired.')) if self.numUses > self.allowedUses: return (False, ugettext('This discount has exceeded the number of allowed uses.')) if not cart: return (True, ugettext('Valid.')) minOrder = self.minOrder or 0 if cart.total < minOrder: return (False, ugettext('This discount only applies to orders of at least %s.' % moneyfmt(minOrder))) #Check to see if the cart items are included validProducts = self.validProducts.all() # Skip validProducts check if validProducts is empty validItems = not bool(validProducts) if validProducts: for cart_item in cart.cartitem_set.all(): if cart_item.product in validProducts: validItems = True break #Once we have 1 valid item, we exit if validItems: return (True, ugettext('Valid.')) else: return (False, ugettext('This discount cannot be applied to the products in your cart.'))
def test_runfolder(self): runs = runfolder.get_runs(self.runfolder_dir) # do we get the flowcell id from the filename? self.assertEqual(len(runs), 1) name = 'run_4286GAAXX_%s.xml' % ( date.today().strftime('%Y-%m-%d'),) self.assertEqual(runs[0].serialization_filename, name) self.assertEqual(runs[0].runfolder_name, '090220_HWI-EAS229_0093_30VR0AAXX') # do we get the flowcell id from the FlowcellId.xml file make_flowcell_id(self.runfolder_dir, '207BTAAXY') runs = runfolder.get_runs(self.runfolder_dir) self.assertEqual(len(runs), 1) name = 'run_207BTAAXY_%s.xml' % ( date.today().strftime('%Y-%m-%d'),) self.assertEqual(runs[0].serialization_filename, name) r1 = runs[0] xml = r1.get_elements() xml_str = ElementTree.tostring(xml) r2 = runfolder.PipelineRun(xml=xml) self.assertEqual(r1.serialization_filename, r2.serialization_filename) self.assertNotEqual(r2.image_analysis, None) self.assertNotEqual(r2.bustard, None) self.assertNotEqual(r2.gerald, None)
def all_messages(start_date=None, end_date=None): start_date = start_date or FIRST_DATE end_date = end_date or (date.today() - timedelta(days=1)) all_tracks = [] request_number = 0 for day in date_range(start_date, end_date): if request_number == 80: # Take a break, don't hit the rate limit print 'Taking a 5 minute break, so we don\'t hit the rate limit!' time.sleep(5 * 60) request_number = 0 request_number = request_number + 1 print 'Checking for %s' % day for message in room_messages(day): tracks = extract_spotify_tracks_from_message(message) if tracks: all_tracks.append({'user': message['from']['name'], 'date': message['date'], 'tracks': tracks}) f = open(LAST_DATE_FILE, 'wb') f.write(datetime.strftime(date.today(), '%Y%m%d')) f.close() return all_tracks
def yahoo(symbol, start_date=None, stop_date=None): """ Loads the prices from the start date for the given symbol Only new quotes are downloaded. """ if not stop_date: stop_date = date.today().strftime("%Y%m%d") if not start_date: query = db.Query(Quote) query.order('-date') query.filter('symbol = ', symbol) latest_quote = query.get() if latest_quote: start_date = latest_quote.date else: start_date = date.today() - timedelta(days=120) if start_date == date.today(): return start_date = start_date.strftime("%Y%m%d") prices = ystockquote.get_historical_prices(symbol, start_date, stop_date) headers = prices[0] try: close = Quote.get_idx(headers, 'Close') date_ = Quote.get_idx(headers, 'Date') open = Quote.get_idx(headers, 'Open') high = Quote.get_idx(headers, 'High') low = Quote.get_idx(headers, 'Low') except Exception, e: logging.warning('Could not download %s:%s', symbol, e) return None
def abuse_detected(phone_number, duration=None, persist=False): """ :param phone_number: a phone number to add to the abuse tracker. :param duration: the duration of the call. :param persist: iff persist is set to True abuse flag will be set permanently :return: true iff abuse is likely """ hashed_phone_number = sha256(bytes(str(phone_number), 'utf-8')).hexdigest() short_calls = 0 if duration is not None and int(duration) <= current_app.config['SHORT_CALL_THRESHOLD']: short_calls = 1 abuse_case = PossibleAbuses().query.filter_by(id=hashed_phone_number).first() if abuse_case is None: abuse_case = PossibleAbuses() abuse_case.id = hashed_phone_number abuse_case.short_calls = 0 + short_calls abuse_case.date = date.today() abuse_case.persistent = persist db.session.add(abuse_case) elif abuse_case.date == date.today(): abuse_case.short_calls += short_calls else: abuse_case.date = date.today() abuse_case.short_calls = short_calls if persist: abuse_case.persistent = True db.session.commit() if abuse_case.persistent or \ abuse_case.short_calls >= current_app.config['SHORT_CALL_MAX_AMOUNT']: return True return False
def test_deadline_datetime(self): meeting = G(Meeting, meeting_date=date.today()) deadline_date = date.today() - timedelta(days=2) deadline_time = time(hour=21, tzinfo=pytz.timezone('Asia/Tokyo')) deadline_datetime = datetime.combine(deadline_date, deadline_time) assert meeting.deadline_datetime() == deadline_datetime
def download_exp_data(request, expId, reportType=''): try: # s = Session.objects.get(sessionToken=sessionToken) e = Experiment.objects.get(pk=int(expId)) except: return render(request, 'Object_not_found.html', {'token': expId, 'type': "Experiment"}) count=0 # for duplicate filenames fn="%s_data_%s.zip" % (e.name,date.today().strftime("%d%b%Y")) output_filename=os.path.join(settings.MEDIA_ROOT, settings.ZIP_TMP, fn) while os.path.exists(output_filename) and count<100: count=count+1 fn="%s_data_%s_%d.zip" % (e.name,date.today().strftime("%d%b%Y"),count) output_filename=os.path.join(settings.MEDIA_ROOT, settings.ZIP_TMP, fn) if count==100: return HttpResponse('Error creating output file') output_zip=zipfile.ZipFile(output_filename, 'w') fn_list=[] # for tracking duplicate filenames in the output zip s = Session.objects.filter(exp=e) for i in s: r = Report.objects.filter(sessionKey=i) for j in r: # reports should match type if set, contents length >0 if (reportType=='' or j.eventType==reportType) and len(j.dataLog.strip())>0: fn=unique_txt(fn_list,e.name,j.eventType) output_zip.writestr(fn,j.dataLog.encode("ascii",'ignore')) fn_list.append(fn) output_zip.close() f=open(output_filename,'rb') response = HttpResponse(File(f),content_type='application/zip') response['Content-Disposition'] = "attachment; filename=%s" % os.path.basename(output_filename) response['Content-Length'] = os.path.getsize(output_filename) return response
def parseDate(st): m = dateControl.match(st) if m: base = m.groupdict()['day'] modifier = m.groupdict()['modifier'] qty = m.groupdict()['qty'] if base == 'today': resDate = date.today() elif base == 'yesterday': resDate = date.today() - timedelta(days=1) elif base == 'tomorrow': resDate = date.today() + timedelta(days=1) elif base == 'week': resDate = date.today() resDate -= timedelta(resDate.weekday()) elif base == 'month': resDate = date.today() resDate -= timedelta(resDate.day - 1) # now modifiers (optional) if modifier and qty: qty = int(qty) if modifier == '+': resDate += timedelta(qty) else: resDate -= timedelta(qty) return resDate # dd/Mmm/aaaa return str2date(st)
def test_grouper_multilevel_freq(self): # GH 7885 # with level and freq specified in a pd.Grouper from datetime import date, timedelta d0 = date.today() - timedelta(days=14) dates = date_range(d0, date.today()) date_index = pd.MultiIndex.from_product( [dates, dates], names=['foo', 'bar']) df = pd.DataFrame(np.random.randint(0, 100, 225), index=date_index) # Check string level expected = df.reset_index().groupby([pd.Grouper( key='foo', freq='W'), pd.Grouper(key='bar', freq='W')]).sum() # reset index changes columns dtype to object expected.columns = pd.Index([0], dtype='int64') result = df.groupby([pd.Grouper(level='foo', freq='W'), pd.Grouper( level='bar', freq='W')]).sum() assert_frame_equal(result, expected) # Check integer level result = df.groupby([pd.Grouper(level=0, freq='W'), pd.Grouper( level=1, freq='W')]).sum() assert_frame_equal(result, expected)
def get_sale_analysis(): """ 总体手机分类每月销售数,不是总评论数,柱状图 'date_list' 'count_list' 'change' 上一月的销售增幅百分比 """ from datetime import date import func start_date = date(2012, 1, 1) s_date = date(2012, 1, 1) date_list = [] count_list = [] from dateutil.relativedelta import relativedelta e_date = date(date.today().year, date.today().month, 1) while s_date < e_date: date_list.append(s_date) count_list.append(0) s_date = s_date + relativedelta(months=1) for c in c_list: for r in c['review']: date = func.get_review_date(r) if date < start_date: continue else: for i in range(len(date_list)): if date_list[i].year == date.year and date_list[i].month == date.month: count_list[i] += 1 break return {'date_list': [[d.year, d.month] for d in date_list], 'count_list': count_list, 'change': round(100 * ((count_list[-1] - count_list[-2]) / float(count_list[-2])), 1) }
def test_conditional_aggregation_example(self): Client.objects.create( name='Jean Grey', account_type=Client.REGULAR, registered_on=date.today(), ) Client.objects.create( name='James Bond', account_type=Client.PLATINUM, registered_on=date.today(), ) Client.objects.create( name='Jane Porter', account_type=Client.PLATINUM, registered_on=date.today(), ) self.assertEqual( Client.objects.aggregate( regular=models.Sum(Case( When(account_type=Client.REGULAR, then=1), output_field=models.IntegerField(), )), gold=models.Sum(Case( When(account_type=Client.GOLD, then=1), output_field=models.IntegerField(), )), platinum=models.Sum(Case( When(account_type=Client.PLATINUM, then=1), output_field=models.IntegerField(), )), ), {'regular': 2, 'gold': 1, 'platinum': 3} )
def test_save(self): # If an object is created signed, signature date must be set signature_value = [{"x": [1, 2], "y": [3, 4]}] i = JSignatureTestModel(signature=signature_value) i.save() i = JSignatureTestModel.objects.get(pk=i.pk) self.assertEqual(date.today(), i.signature_date.date()) # If signature doesn't change, signature date must not be updated i = JSignatureTestModel(signature=signature_value) i.save() i.signature_date = date(2013, 1, 1) i.signature = signature_value i.save() i = JSignatureTestModel.objects.get(pk=i.pk) self.assertEqual(date(2013, 1, 1), i.signature_date.date()) # If signature changes, signature date must be updated too new_signature_value = [{"x": [5, 6], "y": [7, 8]}] i = JSignatureTestModel(signature=signature_value, signature_date=date(2013, 1, 1)) i.save() i.signature_date = date(2013, 1, 1) i.signature = new_signature_value i.save() i = JSignatureTestModel.objects.get(pk=i.pk) self.assertEqual(date.today(), i.signature_date.date()) # If sinature is set to None, it must be the same for signature_date i = JSignatureTestModel(signature=signature_value) i.save() i.signature = None i.save() i = JSignatureTestModel.objects.get(pk=i.pk) self.assertIsNone(i.signature_date)
def makeDate(indate): indate = indate.replace("dzisiaj", (date.today()).strftime('%d %m %Y ')) indate = indate.replace("wczoraj", (date.today()-timedelta(1)).strftime(('%d %m %Y'))) indate = indate.replace('Poniedziałek', 'Monday') indate = indate.replace('Tuesday', 'Wtorek') indate = indate.replace('Wednesday', 'Środa') indate = indate.replace('Thursday', 'Czwartek') indate = indate.replace('Monday', 'Piątek') indate = indate.replace('Saturday', 'Sobota') indate = indate.replace('Sunday', 'Niedziela') indate = indate.replace('stycznia', '01') indate = indate.replace('lutego', '02') indate = indate.replace('marca', '03') indate = indate.replace('kwietnia', '04') indate = indate.replace('maja', '05') indate = indate.replace('czerwca', '06') indate = indate.replace('lipca', '07') indate = indate.replace('sierpnia', '08') indate = indate.replace('września', '09') indate = indate.replace('pażdziernika', '10') indate = indate.replace('listopda', '11') indate = indate.replace('grudnia', '12') return indate
def action_resources(): project = kc.get_project_by_name(options.project) start = himutils.get_date(options.start, date.today() - timedelta(days=1)) stop = himutils.get_date(options.end, date.today() + timedelta(days=1)) logger.debug('=> start date = %s', start) logger.debug('=> stop date = %s', stop) output = dict({'vcpu': 0, 'ram':0}) for region in regions: # instances nc = Nova(options.config, debug=options.debug, log=logger, region=region) gc = Gnocchi(options.config, debug=options.debug, log=logger, region=region) deleted = nc.get_project_instances(project_id=project.id, deleted=True) running = nc.get_project_instances(project_id=project.id) for i in deleted + running: resource = gc.get_resource(resource_type='instance', resource_id=i.id) if not resource: continue metrics = dict() metrics['vcpu'] = gc.get_client().metric.get('vcpus', i.id) metrics['ram'] = gc.get_client().metric.get('memory', i.id) for key, value in metrics.iteritems(): measurement = gc.get_client().metric.get_measures(metric=value['id'], aggregation='max', start=start, stop=stop) if measurement: output[key] += measurement[0][2] printer.output_dict({'header': 'resources used by %s in all regions' % project.name}) printer.output_dict(output)
def test_user_limited_today(self): """ Ability to limit iterations to a user and those which are active today. """ user = self.matt username = self.matt.username pearl = mommy.make('core.Pearl', user=user) # Iterations for today. This `should` show. iterations = [ mommy.make('core.Iteration', date=date.today(), pearl=pearl), ] # Iterations in the past and future. These should `not` show. mommy.make('core.Iteration', date=date.today()-timedelta(5), pearl=pearl) mommy.make('core.Iteration', date=date.today()+timedelta(5), pearl=pearl) url = reverse('edition_today', args=[username]) request = self.factory.get(url) response = TodayEditionView.as_view()(request, user=username) self.assertEqual( list(response.context_data['iteration_list']), list(iterations), )
def _endOfMonth(self, month): month %= 12 eom = date.today().replace(month=month + 1, day=1) - timedelta(days=1) if eom < date.today(): eom = eom.replace(year=eom.year + 1) return 'due:' + eom.strftime('%Y-%m-%d')
def action_whales(): start = himutils.get_date(options.start, date.today() - timedelta(days=1)) stop = himutils.get_date(options.end, date.today() + timedelta(days=1)) if start > stop: himutils.sys_error('start %s must be fore stop %s' % (start, stop)) logger.debug('=> start date = %s', start) logger.debug('=> stop date = %s', stop) for region in regions: nc = Nova(options.config, debug=options.debug, log=logger, region=region) cc = Cinder(options.config, debug=options.debug, log=logger, region=region) project_usage = nc.get_usage(start=start, end=stop) logger.debug('=> threshold for whales filter %s', options.threshold) print_header = True for usage in project_usage: project = kc.get_by_id(obj_type='project', obj_id=usage.tenant_id) if not project: logger.debug('=> project with id %s not found',usage.tenant_id) continue if len(usage.server_usages) < options.threshold: continue cinderusage = cc.get_usage(usage.tenant_id) admin = project.admin if hasattr(project, 'admin') else 'unknown!' output = OrderedDict() output['instances'] = len(usage.server_usages) output['volume_gb'] = cinderusage.gigabytes['in_use'] output['name'] = project.name output['admin'] = admin if print_header: output['header'] = 'project usage %s (instances, volume (GB), name, id)' % region print_header = False printer.output_dict(objects=output, sort=False, one_line=True)
def update_l10n_metric(): """Calculate new l10n coverage numbers and save. L10n coverage is a measure of the amount of translations that are up to date, weighted by the number of visits for each locale. The "algorithm" (see Bug 727084): SUMO visits = Total SUMO visits for the last 30 days; Total translated = 0; For each locale { Total up to date = Total up to date + ((Number of up to date articles in the en-US top 50 visited)/50 ) * (Visitors for that locale / SUMO visits)); } An up to date article is any of the following: * An en-US article (by definition it is always up to date) * The latest en-US revision has been translated * There are only new revisions with TYPO_SIGNIFICANCE not translated * There is only one revision of MEDIUM_SIGNIFICANCE not translated """ if settings.STAGE: # Let's be nice to GA and skip on stage. return # Get the top 60 visited articles. We will only use the top 50 # but a handful aren't localizable so we get some extras. top_60_docs = _get_top_docs(60) # Get the visits to each locale in the last 30 days. end = date.today() - timedelta(days=1) # yesterday start = end - timedelta(days=30) locale_visits = googleanalytics.visitors_by_locale(start, end) # Total visits. total_visits = sum(locale_visits.itervalues()) # Calculate the coverage. coverage = 0 for locale, visits in locale_visits.iteritems(): if locale == settings.WIKI_DEFAULT_LANGUAGE: num_docs = MAX_DOCS_UP_TO_DATE up_to_date_docs = MAX_DOCS_UP_TO_DATE else: up_to_date_docs, num_docs = _get_up_to_date_count( top_60_docs, locale) if num_docs and total_visits: coverage += ((float(up_to_date_docs) / num_docs) * (float(visits) / total_visits)) # Save the value to Metric table. metric_kind = MetricKind.objects.get(code=L10N_METRIC_CODE) day = date.today() Metric.objects.create( kind=metric_kind, start=day, end=day + timedelta(days=1), value=int(coverage * 100)) # Store as a % int.
def enquiry_from_user_dict(self, user, source, referrer): if 'dob' in user: dob = user['dob'] if user['dob'] is not None else date.today() else: dob = date.today() if 'telephone' in user: telephone = user['telephone'] if user['telephone'] is not None else '' else: telephone = '' search_params = { 'email': user['email'] } client = self.get_or_create( search_params=search_params, first_name=user['first_name'], last_name=user['last_name'], email=user['email'], daytime_phone_number=telephone, telephone=[{'number': telephone}], date_of_birth=dob.strftime(u'%Y-%m-%d'), active=False, adviser=None ) RemoteConciergeClientSource().create_source_for_client(client, source, referrer)
def main(): parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__) parser.add_argument('path', nargs='*', default=None, help='Root directory for the Mercurial repository.') args = parser.parse_args() # Get the changelog data from each repository. cl_counts = {} if args.path: for repository_path in args.path: extract_cl_counts(repository_path, cl_counts) else: # Assume that the current path has a repository. extract_cl_counts(os.getcwd(), cl_counts) # Draw the chart and save it in a file. full_file_name = os.path.join(CHART_FILE_PATH, CHART_FILE_NAME) chart = create_empty_chart(full_file_name) start_date = date.today() - timedelta(days=(NUM_DAYS_TO_SHOW - 1)) draw_daily_boxes(chart, start_date, cl_counts) chart.save() # Open the image file and print total count. view_chart(full_file_name) print('Changes as of: ' + str(date.today()) + ': ' + \ str(sum(cl_counts.itervalues())))
def __init__(self,user,analysis_interval = None, a_range = (15,16), **kwargs): self.user = user self.analysis_interval = analysis_interval if analysis_interval == "month": self.visit_freq = dict(user.sort_visit(sort_by = "month")) current_month = int(str(date.today()).split("-")[1]) current_year = int(str(date.today()).split("-")[0][-2:]) for yy in range(a_range[0],a_range[1]+1): for mm in range(1,13): if (yy == current_year) and (mm > current_month): break if mm < 10: mm = ''.join(['0',str(mm)]) exp = '{}/{}'.format(yy,mm) #if there is no visit, then set visit time to 0 if self.visit_freq.get(exp) is None: self.visit_freq[exp] = 0 rl = [] append = rl.append for d,f in self.visit_freq.items(): y = int(d.split("/")[0]) if (y >= a_range[0]) and (y <= a_range[1]): append((d,f)) self.visit_freq = sorted(rl,key = itemgetter(0)) elif analysis_interval is None: self.visit_freq = user.sort_visit() else: self.visit_freq = user.sort_visit(sort_by = analysis_interval) gc.collect()
def process_exit_surveys(): """Exit survey handling. * Collect new exit survey results. * Save results to our metrics table. * Add new emails collected to the exit survey. """ _process_exit_survey_results() # Get the email addresses from two days ago and add them to the survey # campaign (skip this on stage). if settings.STAGE: # Only run this on prod, it doesn't need to be running multiple times # from different places. return startdate = date.today() - timedelta(days=2) enddate = date.today() - timedelta(days=1) for survey in SURVEYS.keys(): if 'email_collection_survey_id' not in SURVEYS[survey]: # Some surveys don't have email collection on the site # (the askers survey, for example). continue emails = get_email_addresses(survey, startdate, enddate) for email in emails: add_email_to_campaign(survey, email) statsd.gauge('survey.{0}'.format(survey), len(emails))
def harvest(self, start_date=None, end_date=None): # Always harvest a 2 day period starting 2 days back to honor time given # to contributors to cancel a public registration start_date = start_date or date.today() - timedelta(4) end_date = end_date or date.today() - timedelta(2) search_url = self.URL.format(start_date.isoformat(), end_date.isoformat()) records = self.get_records(search_url) record_list = [] for record in records: doc_id = record['url'].replace('/', '') record_list.append( RawDocument( { 'doc': json.dumps(record), 'source': self.short_name, 'docID': doc_id, 'filetype': 'json' } ) ) return record_list
def test_data_analytics(self): for domain_name in [self.domain.name, self.domain2.name]: GIRRow.objects.create( domain_name=domain_name, month=date.today(), start_date=date.today(), wams_current=1, active_users=1, using_and_performing=1, not_performing=1, inactive_experienced=1, inactive_not_experienced=1, not_experienced=1, not_performing_not_experienced=1, active_ever=1, possibly_exp=1, ever_exp=1, exp_and_active_ever=1, active_in_span=1, eligible_forms=1, ) MALTRow.objects.create( domain_name=domain_name, month=date.today(), num_of_forms=1, ) self._assert_data_analytics_counts(domain_name, 1) self.domain.delete() self._assert_data_analytics_counts(self.domain.name, 0) self._assert_data_analytics_counts(self.domain2.name, 1)
def calculate_payments(self, sub_offer, cash_flow=False, extraordinary_earnings=False, calculation_for_extraordinary_earnings_report=False): total_paid = sub_offer.total_paid payments_to_do = self._payments_to_do_(sub_offer, cash_flow, extraordinary_earnings) if not extraordinary_earnings and not calculation_for_extraordinary_earnings_report: for payment in sorted(payments_to_do, key=lambda x: x.id): if total_paid <= payment.amount: payment.amount -= total_paid total_paid = 0.0 if payment.date > date.today(): payment.status = 'Futuro' else: payment.status = 'Pendiente' else: total_paid -= payment.amount payment.amount = 0.0 payment.status = 'Realizado' if not extraordinary_earnings and not calculation_for_extraordinary_earnings_report and total_paid > 0.0 and\ date.today() > sub_offer.offer.expiration_date: payments_to_do.append(Payment(sub_offer, original_amount=-total_paid, amount=-total_paid, date=date.today(), description=u'Saldo a favor con proveedor', status=u'Pendiente')) if extraordinary_earnings or calculation_for_extraordinary_earnings_report: for payment in payments_to_do: payment.status = 'Calculado' return filter(lambda p: abs(p.amount) >= 0.01, payments_to_do)
def handle(self, *args, **options): #set the buffer time buffer_time = 5 start = date.today() - timedelta(days=buffer_time) end = date.today() #get the expired requests (that have not already been marked as expired) expired_requests = OncallRequest.objects.filter( date__range=[start, end] ).filter( #filter any requests that already are expired (reduces redundancy) expired=False ) #if no expired requests exist, return if(len(expired_requests) == 0): return #loop each expired request for request in expired_requests: #get the coverage teacher and increment the oncall number for each patron by one teacher = request.coverage_teacher teacher.oncall_count += 1 #save to the database teacher.save() #set request expired boolean to true request.expired = True request.save()
def _make_form(self): start_date = None force_today = False if 'start_date' in request.args: force_today = True try: start_date = datetime.strptime(request.args['start_date'], '%Y-%m-%d').date() except ValueError: pass self.past_date = start_date is not None and start_date < date.today() if start_date is None or start_date <= date.today(): start_dt, end_dt, self.date_changed = get_default_booking_interval( duration=self.DEFAULT_BOOKING_DURATION, precision=self.DEFAULT_START_TIME_PRECISION, force_today=force_today ) self.date_changed = self.date_changed and not self.past_date else: start_dt = datetime.combine(start_date, Location.working_time_start) end_dt = datetime.combine(start_date, Location.working_time_end) self.date_changed = False defaults = FormDefaults(room_id=self._room.id, start_dt=start_dt, end_dt=end_dt, booked_for_id=session.user.id, booked_for_name=session.user.getStraightFullName().decode('utf-8'), contact_email=session.user.getEmail().decode('utf-8'), contact_phone=session.user.getPhone().decode('utf-8')) return self._make_confirm_form(self._room, defaults=defaults, form_class=NewBookingSimpleForm)
def test_process(self): event = Event( name="some event", location="Ballwil", start_time=datetime.combine(date.today(), time(hour=9))) self.plugin.process(event) self.assertEqual(event.departure_time, datetime.combine( date.today(), time(hour=7, minute=38)))
def get(self): """ """ logging.info('in findEvents') distance = float(self.request.get('distance')) lat = float(self.request.get('lat')) lon = float(self.request.get('lon')) #q = Locations.all() #locations = q.filter('date <= ', date.today()).filter('end_date >= ', date.today()) locations = Locations.gql("Where end_date >= :1",date.today()) json_results = [] for loc in locations: if (loc.date <= date.today()): logging.info(loc.location_name) geo_lat = loc.geolocation.lat geo_long = loc.geolocation.lon dist_calc = ( 6371 * acos( cos( radians(lat) ) * cos( radians( geo_lat ) ) * cos( radians( geo_long ) - radians(lon) ) + sin( radians(lat) ) * sin( radians( geo_lat ) ) ) ) logging.info(dist_calc) if dist_calc < distance: logging.info(loc.location_name) json_results.append({"location": loc.location_name,"event": loc.event, "key": str(loc.key())}) self.response.headers['Content-Type'] = 'application/json' response = json.dumps(json_results) self.response.out.write(response)
def test_list(self): response = self.run_command("list") self.assertEqual(response, "{}".format(date.today().year))
def espandi_rubrica_responsabili_autoparco(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def sales_list_margin_items_pdf(request): if request.is_ajax(): q = request.GET.get('q') gid = request.GET.get('gid') if gid: gid = gid else: gid = None sales = [] costPrice = [] if q is not None: allItems = SoldItem.objects.values('product_name', 'product_category', 'sku', 'unit_cost') \ .annotate(Count('sku')) \ .annotate(Sum('total_cost')) \ .annotate(Sum('unit_cost')) \ .annotate(Sum('quantity')).order_by('product_name') all_items = allItems.filter( Q(sku__icontains=q) | Q(product_name__icontains=q) | Q(product_category__icontains=q)) items = all_items total_items = [] for t in items: product = ProductVariant.objects.get(sku=t['sku']) try: itemPrice = product.get_cost_price().gross except: itemPrice = product.get_cost_price() unitSalesCost = t['unit_cost'] totalSalesCost = t['total_cost__sum'] try: grossProfit = unitSalesCost - itemPrice unitMargin = round((grossProfit / unitSalesCost) * 100, 2) salesGrossProfit = totalSalesCost - (itemPrice * t['quantity__sum']) salesMargin = round( (salesGrossProfit / totalSalesCost) * 100, 2) except: grossProfit = 0 unitMargin = 0 salesMargin = 0 t['unitMargin'] = unitMargin t['salesMargin'] = salesMargin total_items.append(t) else: items = SoldItem.objects.values('product_name', 'product_category', 'sku', 'unit_cost') \ .annotate(Count('sku')) \ .annotate(Sum('total_cost')) \ .annotate(Sum('unit_cost')) \ .annotate(Sum('quantity')).order_by('product_name') total_items = [] for t in items: product = ProductVariant.objects.get(sku=t['sku']) try: itemPrice = product.get_cost_price().gross except: itemPrice = product.get_cost_price() unitSalesCost = t['unit_cost'] totalSalesCost = t['total_cost__sum'] try: grossProfit = unitSalesCost - itemPrice unitMargin = round((grossProfit / unitSalesCost) * 100, 2) salesGrossProfit = totalSalesCost - (itemPrice * t['quantity__sum']) salesMargin = round( (salesGrossProfit / totalSalesCost) * 100, 2) except: grossProfit = 0 unitMargin = 0 salesMargin = 0 t['unitMargin'] = unitMargin t['salesMargin'] = salesMargin total_items.append(t) img = image64() data = { 'today': date.today(), 'items': total_items, 'puller': request.user, 'image': img, 'gid': gid } pdf = render_to_pdf( 'dashboard/reports/sales_margin2/pdf/margin_items.html', data) return HttpResponse(pdf, content_type='application/pdf')
def sales_list_tax_pdf(request): if request.is_ajax(): q = request.GET.get('q') gid = request.GET.get('gid') if gid: gid = gid else: gid = None sales = [] costPrice = [] if q is not None: all_sales = Sales.objects.filter( Q(invoice_number__icontains=q) | Q(terminal__terminal_name__icontains=q) | Q(created__icontains=q) | Q(customer__name__icontains=q) | Q(customer__mobile__icontains=q) | Q(solditems__product_name__icontains=q) | Q(user__email__icontains=q) | Q(user__name__icontains=q)).order_by('id').distinct() if gid: csales = all_sales.filter(created__icontains=gid) for sale in csales: quantity = SoldItem.objects.filter(sales=sale).aggregate( c=Count('sku')) setattr(sale, 'quantity', quantity['c']) for i in SoldItem.objects.filter(sales=sale): product = ProductVariant.objects.get(sku=i.sku) try: quantity = product.get_cost_price().gross except: quantity = product.get_cost_price() costPrice.append(quantity) totalCostPrice = sum(costPrice) setattr(sale, 'totalCostPrice', totalCostPrice) try: grossProfit = sale.total_net - totalCostPrice status = 'true' margin = round((grossProfit / sale.total_net) * 100, 2) except: grossProfit = 0 margin = 0 setattr(sale, 'margin', margin) sales.append(sale) else: for sale in all_sales: quantity = SoldItem.objects.filter(sales=sale).aggregate( c=Count('sku')) setattr(sale, 'quantity', quantity['c']) for i in SoldItem.objects.filter(sales=sale): product = ProductVariant.objects.get(sku=i.sku) try: quantity = product.get_cost_price().gross except: quantity = product.get_cost_price() costPrice.append(quantity) totalCostPrice = sum(costPrice) setattr(sale, 'totalCostPrice', totalCostPrice) try: grossProfit = sale.total_net - totalCostPrice status = 'true' margin = round((grossProfit / sale.total_net) * 100, 2) except: grossProfit = 0 margin = 0 setattr(sale, 'margin', margin) sales.append(sale) elif gid: csales = Sales.objects.filter(created__icontains=gid) for sale in csales: quantity = SoldItem.objects.filter(sales=sale).aggregate( c=Count('sku')) setattr(sale, 'quantity', quantity['c']) for i in SoldItem.objects.filter(sales=sale): product = ProductVariant.objects.get(sku=i.sku) try: quantity = product.get_cost_price().gross except: quantity = product.get_cost_price() costPrice.append(quantity) totalCostPrice = sum(costPrice) setattr(sale, 'totalCostPrice', totalCostPrice) try: grossProfit = sale.total_net - totalCostPrice status = 'true' margin = round((grossProfit / sale.total_net) * 100, 2) except: grossProfit = 0 margin = 0 setattr(sale, 'margin', margin) sales.append(sale) else: try: last_sale = Sales.objects.latest('id') gid = DateFormat(last_sale.created).format('Y-m-d') except: gid = DateFormat(datetime.datetime.today()).format('Y-m-d') csales = Sales.objects.filter(created__icontains=gid) for sale in csales: quantity = SoldItem.objects.filter(sales=sale).aggregate( c=Count('sku')) setattr(sale, 'quantity', quantity['c']) for i in SoldItem.objects.filter(sales=sale): product = ProductVariant.objects.get(sku=i.sku) try: quantity = product.get_cost_price().gross except: quantity = product.get_cost_price() costPrice.append(quantity) totalCostPrice = sum(costPrice) setattr(sale, 'totalCostPrice', totalCostPrice) try: grossProfit = sale.total_net - totalCostPrice status = 'true' margin = round((grossProfit / sale.total_net) * 100, 2) except: grossProfit = 0 margin = 0 setattr(sale, 'margin', margin) sales.append(sale) img = image64() data = { 'today': date.today(), 'sales': sales, 'puller': request.user, 'image': img, 'gid': gid } pdf = render_to_pdf( 'dashboard/reports/sales_margin2/pdf/saleslist_pdf.html', data) return HttpResponse(pdf, content_type='application/pdf')
def available_data_range(self, frequency): if frequency != '1m': return super(QUANTAXISKDataSource, self).available_data_range(frequency) return date(2018, 1, 1), date.today() - relativedelta(days=1)
# Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores from datetime import date maior_idade = 0 menor_idade = 0 ano_atual = date.today().year for c in range(0, 7): nascimento = int(input('Digite aqui seu ano de nascimento: ')) idade = ano_atual - nascimento if idade >= 18: maior_idade += 1 if idade < 18: menor_idade += 1 print('Há {} pessoas maiores de idade e {} menores de idade'.format( maior_idade, menor_idade))
def meetingAlert(): logger = getLogger() with requests.Session() as s: loginReq = s.post( 'https://office.hiworks.com/stickint.onhiworks.com/home/ssl_login', data=LOGIN_INFO) if loginReq.status_code != 200: logger.error('hi-works login failed - confirm id/pw') raise Exception('로그인 정보가 일치하지 않습니다.') headers = { 'referer': 'https://board.office.hiworks.com/stickint.onhiworks.com/bbs/board/board_list', 'User-Agent': UserAgent().chrome, 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } reqBody = { 'category_no': 7500, 'resource_type': 'T', 'date': date.today().strftime('%Y-%m-%d'), 'booking_search_name': '', 'page': 1, 'limit': 7 } boardReq = s.post( url= 'https://booking.office.hiworks.com/stickint.onhiworks.com/booking/bookingAjax/getResourceList', headers=headers, data=reqBody) if getCache('list') is None: logger.info('no cached list data : 예약시스템') setCache('list', boardReq.content) exit() prevContent = json.loads(getCache('list')) nextContent = json.loads(boardReq.content) for i, item in enumerate(nextContent['result']['list']): # 리스트의 예약 내용이 증가했으면 ? if 'BKCP' in item['booking_info'] and len( item['booking_info']['BKCP'] ) > len(prevContent['result']['list'][i]['booking_info']['BKCP']): # 새로 들어온예약이 무엇인지 찾아보자 for n in range(len(item['booking_info']['BKCP'])): isContinue = False # 새로운것이 이미 뿌려졌던건지 비교 for c2 in prevContent['result']['list'][i]['booking_info'][ 'BKCP']: if c2['no'] == item['booking_info']['BKCP'][n]['no']: isContinue = True if isContinue: continue else: content = makeMeetingContent({ 'name': item['name'], 'user_name': item['booking_info']['BKCP'][n]['user_name'], 'start': item['booking_info']['BKCP'][n]['start'], 'end': item['booking_info']['BKCP'][n]['end'], }) for url in SEND_LIST: sendMessage(content=content, url=url) # 예약이 없는 상태에서 최초 예약이 들어올경우 elif 'BKCP' not in prevContent['result']['list'][i][ 'booking_info'] and 'BKCP' in item['booking_info']: # 모든게 새로들어온것이다. for n in range(len(item['booking_info']['BKCP'])): content = makeMeetingContent({ 'name': item['name'], 'user_name': item['booking_info']['BKCP'][n]['user_name'], 'start': item['booking_info']['BKCP'][n]['start'], 'end': item['booking_info']['BKCP'][n]['end'], }) for url in SEND_LIST: sendMessage(content=content, url=url) setCache('list', boardReq.content) elif 'BKCP' in item['booking_info'] \ and len(item['booking_info']['BKCP']) < len(prevContent['result']['list'][i]['booking_info']['BKCP']): setCache('list', boardReq.content) setCache('list', boardReq.content)
def genesisBlock(self): return Block(date.today(), {}, "0")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 今天过期的商品打折20% """ __title__ = '' __author__ = 'JWH5566' __mtime__ = '2016/3/24' from datetime import date, timedelta today = date.today() tomorrow = today + timedelta(days=1) products = [ { 'sku': '1', 'expiration_date': today, 'price': 100.0 }, { 'sku': '2', 'expiration_date': tomorrow, 'price': 50 }, { 'sku': '3', 'expiration_date': today, 'price': 20 }, ] print('今天过期的商品打折20%')
def espandi_rubrica_responsabili_formazione(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def espandi_rubrica_referenti_gruppi(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def espandi_rubrica_direttori_corsi(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def espandi_rubrica_delegati_giovani(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def espandi_rubrica_centrali_operative(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def espandi_rubrica_commissari(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def espandi_rubrica_referenti_attivita(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def espandi_rubrica_ufficio_soci_unita(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def espandi_rubrica_delegati_obiettivo_6(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def upload_folder(): folder = settings.UPLOAD_FOLDER % (current_user.get_id(), str(date.today().month)) if os.path.exists(folder) == False: os.makedirs(folder, 0o775) return folder
def espandi_rubrica_presidenti(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def initiate_process(year, collection): ''' ------------------------------------------ Initiates threads. ------------------------------------------ ''' print('--------------------') print('Cleaning up year {}'.format(year)) year_str = str(year) # ############################## # # this version only populates num_of_amendments if it doesn't already exist # records_to_populate = collection.find({'leg_url': {'$regex': 'http'}, 'intro_date': {'$regex': year_str}, 'num_of_amendments': None}) # record_count = collection.count_documents({'leg_url': {'$regex': 'http'}, 'intro_date': {'$regex': year_str}, 'num_of_amendments': None}) # print('--> Number of records with no amendment counts for year {}: {}'.format(year, record_count)) # if record_count > 0: # for rec in records_to_populate: # # get complete url using url_builder # url = url_builder(rec['leg_url']) # # scrape url # soup = get_soup(url) # # get amendment count # amendment_count = get_num_of_amendments(soup) # # update mongo record with bill text # bill_issue = rec['leg_id'] # cong_id = rec['congress_id'] # update_mongo_num_of_amendments(bill_issue, cong_id, amendment_count, collection) # r = collection.count_documents({'leg_url': {'$regex': 'http'}, 'intro_date': {'$regex': year_str}, 'num_of_amendments': None}) # if r%100 == 0: # print('+++++++++') # print('Year {}: {} records remaining with no amendment counts'.format(year, r)) # ############################## # this version checks, logs, and updates num_of_amendments records_to_populate = collection.find({'leg_url': {'$regex': 'http'}, 'intro_date': {'$regex': year_str}}) record_count = collection.count_documents({'leg_url': {'$regex': 'http'}, 'intro_date': {'$regex': year_str}}) print('--> Number of records to check for year {}: {}'.format(year, record_count)) log_path = '/home/ubuntu/galvanize_capstone/data/logs/mongo_updates.jsonl' i = 0 if record_count > 0: for rec in records_to_populate: # get complete url using url_builder url = url_builder(rec['leg_url']) print(url) # scrape url soup = get_soup(url) # get amendment count amendment_count = get_num_of_amendments(soup) print('\tMongo amendment count: {}'.format(rec['num_of_amendments'])) print('\tScraped amendment count: {}'.format(amendment_count)) # update mongo record with bill text if str(amendment_count) != str(rec['num_of_amendments']): leg_id = rec['leg_id'] cong_id = rec['congress_id'] print('\t\tAmendment count for Congress ID {}, {} has changed. Updating...'.format(cong_id, leg_id)) line_to_log = {'congress_id': cong_id, 'leg_id': leg_id, 'num_of_amendments': {'old_value': rec['num_of_amendments'], 'new_value': amendment_count, 'date': str(date.today().isoformat())}} write_json_file(line_to_log, log_path) update_mongo_num_of_amendments(leg_id, cong_id, amendment_count, collection) if i%20 == 0: print('+++++++++') print(rec['leg_id']) print('{:.2f}% complete checking amendment counts'.format(100 * i / record_count)) print('+++++++++') i += 1
def espandi_rubrica_consigliere_giovane(qs_sedi, al_giorno=date.today()): return espandi_rubriche(qs_sedi, al_giorno)
def getData(): tickerData = yf.Ticker('SPY') closePrice = tickerData.history(period='1d')['Close'].values[0] today = date.today() return (today, closePrice)
def graph(companylist, comindex): print("="*20,"Graph Screen","="*20) while True: utils.cls() print("\nSelect option (1-7):") print("1. Last 7 days") print("2. Last 1 month") print("3. Last 3 months") print("4. Last 6 months") print("5. Last 1 year") print("6. Go back to previous menu") print("7. Exit\n") option = input("Your option : ") if option == '1': step = timedelta(days=7) break elif option == '2': step = timedelta(days=30) break elif option == '3': step = timedelta(days=90) break elif option == '4': step = timedelta(days=180) break elif option == '5': step = timedelta(days=365) break elif option == '6': return elif option == '7': print("\nThanks for coming. Please visit again ...") exit() else: input("\nWrong option."+" Press Enter to continue...") tickerName = companylist.iloc[int(comindex)].Symbol #Function to parse and covert date from string to datetime for time series dateparse = lambda dates: pd.datetime.strptime(dates, '%d-%b-%y') #Function to read csv file for time series with additional parameters for parsing date in datetime format company_details = pd.read_csv("http://finance.google.com/finance/historical?q={}&num=30&ei=NGoQWtDQFMGKUIuSsYgF&output=csv"\ .format(tickerName), parse_dates=[0], index_col=[0],date_parser=dateparse) #Sorted the csv data in ascending order of date company_details = company_details.sort_index(ascending=True) print("\n") print("="*20,"Time series option(Price/Volume)","="*20) while True: print("\nSelect options for time series (1-3): ") print("1. Time series for close price ") print("2. Time series for volume ") print("3. Exit ") option2 = input("\nYour option : ") try: if option2 == '1': N = input("\nEnter the window in integer for moving averages : ") if int(N) < 2 or int(N) > int(step.days): print("\nWindow should be less than 2 or more than the selected time period") else: ts = company_details['Close'] tsw = company_details['Volume'] break elif option2 == '2': N = input("\nEnter the window in integer for moving averages : ") if int(N) < 2 or int(N) > int(step.days): print("\nWindow should be less than 2 or more than the selected time period") else: ts = company_details['Volume'] tsw = company_details['Close'] break elif option2 == '3': print("\nThanks for coming. Please visit again ...\n") exit() else: print("\nWrong option. Try again ...") except ValueError: print("\nIncorrect Format!! Please try again ... ") cur_dte = date.today() #converting date from datetime to string cur_date = datetime.strftime(cur_dte, '%Y-%m-%d') #from date = current date - step from_dte = cur_dte - step #converting date from datetime to string from_date = datetime.strftime(from_dte, '%Y-%m-%d') ts = ts[from_date:cur_date] tsw = tsw[from_date:cur_date] N = int(N) #Calculate rolling mean rolmean = pd.Series.rolling(ts, window=N).mean() #Calculate rolling standard rolstd = pd.Series.rolling(ts, window=N).std() #Calculate weighted rolling mean wrolmean = wrolfun(ts,tsw,from_dte,cur_dte, N) #Calculate macd px = macd(ts) #Plotting graph fig = plt.figure() plt.subplot(211) plt.plot(ts, color='blue',label='Original') plt.plot(rolmean, color='red',label='Rolling Mean') plt.plot(wrolmean['Time'],wrolmean['Roll'], color='green',label='Weighted Rolling Mean') if option2 == '1': plt.title('Time Series plot for price') plt.ylabel('Price') elif option2 == '2': plt.title('Time Series plot for volume') plt.ylabel('Volume') plt.xlabel('Time') plt.legend(loc='upper left') plt.figure(1) plt.subplot(212) if option2 == '1': plt.ylabel('Price') elif option2 == '2': plt.ylabel('Volume') plt.xlabel('Time') plt.plot(rolstd, color='black',label='Rolling Standard') plt.plot(px['MACD'], color='green',label='MACD') plt.legend(loc='upper left') plt.show()
def getDaysSince(): today = date.today() ugaDate = date(1981, 1, 1) delta = today - ugaDate return delta.days
@author: jaman """ import pandas as pd import matplotlib.pyplot as plt import yfinance as yf from datetime import date from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates pd.plotting.register_matplotlib_converters() simbolo='MSFT' nome='MICROSOFT' inizio=date(2019,6,1) fine=date.today() data=yf.download(simbolo,inizio,fine) df=pd.DataFrame(data) ritorno_giornaliero = df['Close'].pct_change().fillna(0.0) ret_dat=pd.DataFrame(ritorno_giornaliero) ret_dat.reset_index(level=0, inplace=True) ret_dat['nday'] =ret_dat['Date'].dt.weekday_name.fillna(0.0) def ritorna_segnale (df,nday): segnale=0.0 pos=len(df[(df['nday']==nday) & (df['Close']>0)])/len(df[df['nday']==nday])*100 neg=len(df[(df['nday']==nday) & (df['Close']<0)])/len(df[df['nday']==nday])*100 if pos>=neg: segnale=1.0 else : segnale=0.0
def __init__(self, last_ted_update=None): self.path = get_archives_path() if not last_ted_update: last_ted_update = date.today() self.last_ted_update = last_ted_update
from datetime import date an=int(input('Digite seu ano de nascimento: ')) id=date.today().year - an if 9>=id>0: print('Sua categoria é MIRIM') elif 14>=id>9: print('Sua categoria é INFANTIL') elif 19>=id>14: print('Sua categoria é JUNIOR') elif 20>=id>19: print('Sua categoria é SÊNIOR') else: print('Sua categoria é MASTER') print('O atleta tem {} anos'.format(id))
def add_worker_log(source, tenders_count): log = WorkerLog( source=source, update=date.today(), tenders_count=tenders_count) log.save()
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). from datetime import date from os.path import abspath, dirname from re import sub from subprocess import check_output HUXLEY_ROOT = abspath(dirname(dirname(__file__))) COPYRIGHT_YEAR = '2011-%d' % date.today().year COPYRIGHT_TEXT = '\n'.join(('# Copyright (c) %s Berkeley Model United Nations. All rights reserved.' % COPYRIGHT_YEAR, '# Use of this source code is governed by a BSD License (see LICENSE).\n')) def update_copyright(): '''Add or update copyright headers for python files.''' files = check_output(['find', HUXLEY_ROOT, '-type', 'f']).split('\n') py_files = [f for f in files if f.endswith('.py')] for filename in py_files: with open(filename, 'r+') as f: contents = f.read() f.seek(0) if not contents.startswith('# Copyright'): f.write(COPYRIGHT_TEXT) if len(contents) > 0: f.write('\n') f.write(contents) else: f.write(sub('2011\-\d{4}', COPYRIGHT_YEAR, contents)) if __name__ == '__main__':