def validate_sprint(self, attrs, source): sprint = attrs[source] if self.object and self.object.pk: if sprint != self.object.sprint: if self.object.status == TASK.STATUS_DONE: msg = "Cannot change sprint of a completed task" raise serializers.ValidationError(msg) if sprint.end < date.today(): msg = "Cannot assign to an already ended sprint" raise serializers.ValidationError(msg) else: if sprint.end < date.today(): msg = "Cannot assign to an already ended sprint" raise serializers.ValidationError(msg) return attrs
def process(sub_formula, year): ''' Преобразуем смарт фунцию ''' if sub_formula == 'be': formula_obj = DiapasonFormula('01.01~31.12', year) elif sub_formula == 'b': formula_obj = SimpleDateFormula('01.01', year) elif sub_formula == 'e': formula_obj = SimpleDateFormula('31.12', year) elif sub_formula == 'Pascha': pascha = date.Pascha(year) formula_obj = SimpleDateFormula( '{0:02d}.{1:02d}.{2:02d}'.format(*pascha), year ) elif sub_formula == 't': formula_obj = SimpleDateFormula( '{0:02d}.{1:02d}.{2:02d}'.format(*date.today()), year ) else: raise FormulaException( 'Неопределенная формула {0}'.format(sub_formula) ) return formula_obj
def error(data): with open('%s/%s.%s.log' % (LOG_DIR, 'error', today()), 'a') as f: f.write(now() + " <<< dump\n"); pprint(data, f) f.write(">>>\n"); # debug({'test': 1})
def all_stage(self): # Birth Date self.plcm_df['PERSON_BIRTH_DATE'] = self.plcm_df[ 'PERSON_BIRTH_DATE'].apply(lambda x: str(x).split()[0]) self.plcm_df['PERSON_BIRTH_DATE'] = self.plcm_df[ 'PERSON_BIRTH_DATE'].apply( lambda x: dt.date(int(x.split('-')[0]), int(x.split('-')[1]), int(x.split('-')[2]))) # Age self.plcm_df[ 'AGE_AT_ACTIVITY_DATE_(CONTRACT_MONITORING)'] = date.today( ) - self.plcm_df['PERSON_BIRTH_DATE'] self.plcm_df[ 'AGE_AT_ACTIVITY_DATE_(CONTRACT_MONITORING)'] = self.plcm_df[ 'AGE_AT_ACTIVITY_DATE_(CONTRACT_MONITORING)'].apply( lambda x: math.floor(x.days / 365.2425)) # ============================================================================= # plcm_df['PERSON_BIRTH_DATE'] = plcm_df['PERSON_BIRTH_DATE'].apply(lambda x: str(x).split()[0]) # plcm_df['PERSON_BIRTH_DATE'] = plcm_df['PERSON_BIRTH_DATE'].apply(lambda x: dt.date(int(x.split('-')[0]), int(x.split('-')[1]), int(x.split('-')[2]))) # ============================================================================= all = {} for k, v in all.items(): self.plcm_df.loc[self.plcm_df['LOCAL_POINT_OF_DELIVERY_CODE'] == self.stage, self.plcm_df[k]] = v
def __init__(self, name, pass): self.name = name self.password = pass self.createdOn = date.today() #untested but should work self.entity = None self.privalege = 'player' #other options: 'gm', 'admin', ? self.active = True self.lastSeen = date.today() self.warnings = 0 self.warnReasons = [] self.banned = False self.bannedOn = [] #list of date strings of all bans
def validate_end(self, attrs, source): end_date = attrs[source] new = self.object changed = self.object and self.object.end != end_date if (new or changed) and end_date < date.today() : msg = "End date cannot be in the past" raise serializers.ValidationError(msg) return attrs
def get_datetime_range(): endtime = date.today() starttime = date.beginning_of_month(endtime) if starttime == endtime: starttime = date.prevday(starttime) starttime = date.beginning_of_month(starttime) return starttime, endtime
def age(): yob = int(input('enter your year:')) today_date = date.today().year age = today_date-yob if age < 18: print('minor') elif age >=18 and age <= 36: print('youth') else: print('elder')
def find_current_release(self): rel_dates = [rel.get_date() for rel in self.get_releases()] rel_date_upcoming = [d for d in rel_dates if date.today() <= d] if len(rel_date_upcoming) > 0: latest = min(rel_date_upcoming) else: latest = max(rel_dates) for rel in self.get_releases(): if rel.get_date() == latest: return rel return None
def getMean(investors): nbrOfDays = [] dayItem = operator.itemgetter(*[1]) invItem = operator.itemgetter(*[2]) dates = map(dayItem,investors) dates[:] = [date.today() - x for x in dates] for x in dates: nbrOfDays.append(x.days) invest = map(invItem,investors) inv = map(invItem, investors) return [sum(nbrOfDays)/float(len(nbrOfDays)), sum(inv)/float(len(inv))]
class TestWizard(TransactionCase): def setUp(self, *args, **kwargs): super(TestWizard, self).setUp(*args, **kwargs) # close any open todo tasks self.env['todo.task']\ .search([('is_done', '=', False)]) .write({'is_done': True}) # Demo user demo_user = self.env.ref('base.user_demo') # Create two todo task t0 = date.today() Todo = self.env['todo.task'].sudo(demo_user) self.todo1 = Todo.create({'name': 'Todo1', 'date_deadline': fields.Date.to_string(t0)}) self.todo2 = Todo.create({'name': 'Todo2'}) # create wizard instance to use in test wizard = self.env['todo.wizard'].sudo(demo_user) self.wizard = Wizard.create({})
def parse(): parser = command_line_parser() args = parser.parse_args() if args.month is None and args.date_start is not None: (args.month, _, _) = date.parse(args.date_start) if args.month is None and args.date_end is not None: (args.month, _, _) = date.parse(args.date_end) if args.month is None: args.month = date.this_month() if args.year is None and args.date_start is not None: (_, _, args.year) = date.parse(args.date_start) if args.year is None and args.date_end is not None: (_, _, args.year) = date.parse(args.date_end) if args.year is None: args.year = date.this_year() if not (0 <= args.month and args.month <= 12): raise ValueError("Invalid month: " + args.month) if not (0 <= args.year and args.year <= 3000): raise ValueError("Invalid year: " + args.year) args.month_name = date.month_name(args.month) if args.date_start is None: args.date_start = date.month_start(month=args.month, year=args.year) if args.date_end is None: args.date_end = date.today() if args.posted_start is None: args.posted_start = args.date_start args.date_start = date.fmt(args.date_start) args.date_end = date.fmt(args.date_end) args.posted_start = date.fmt(args.posted_start) if args.all_reports: args.material_report = True args.ministry_report = True args.unassigned_report = True args.vendor_report = True args.subfund_report = True return args
def validate_timing(self, timing): if timing is None: logging.info('Lacking of timeframe for uptake!') return False d = date.parseProjectDate(timing) if d is None: logging.info('Unknown format of timeframe "%s" for uptake!' % timing) return False if d < date.projectbegin: logging.info('Timeframe for uptake "%s" out of project duration!' % timing) return False if date.projectend < d: logging.info('Timeframe for uptake "%s" out of project duration!' % timing) return False if d < date.today(): logging.info('Timeframe for uptake "%s" has passed!' % timing) return False return True
def send_email(in_query, target): import smtplib, date, datetime from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText src = '*****@*****.**' pw = 'B30ptimus!' msg = MIMEMultipart() msg['From'] = src msg['To'] = target msg['Subject'] = 'TV Ad Buy Summary for {}'.format(date.today().strftime('%m-%d-%Y')) message = 'Currently placeholder text; put the query results (new inserts) here.' msg.attach(MIMEText(message)) server = smtplib.SMTP('smtp.gmail.com',587) server.ehlo() server.starttls() server.ehlo() server.login(src, pw) server.sendmail(src, target, msg.as_string()) server.quit()
def getDistance(investor,avg): datediff = date.today() - investor[1] investValue = pow(pow(datediff.days,2)/float(avg[0]) + pow(investor[2],2),0.5)/float(avg[1]) investor.append(investValue)
def fromBirthYear(cls, name, year): return cls(name, date.today().year - year)
We can only import date class from the datetime module. Here's how: from datetime import date a = date(2019, 4, 13) print(a) Example 4: Get current date You can create a date object containing the current date by using a classmethod named today(). Here's how: from datetime import date today = date.today() print("Current date =", today) change = 0 i=0
def create_sample_company(): # instatiate Company: company = Company(name="Eric BLABLA KGB") company.set_founder_password("aaa") company.set_joining_password("bbb") # update database and query the ID of the new company: try: db.session.add(company) db.session.commit() except: db.session.rollback() flash( "Any error occured when created the sample company registration. Please try again.", "error") return redirect(url_for("register_company")) registered_company = Company.query.filter_by( name="Eric BLABLA KGB").first() # instatiate Jhon Do: colleague = Colleagues(user_name="jhon_do", email="*****@*****.**", first_name="Jhon", last_name="Do", position="Founder", confirmed=1) colleague.set_password("aaa") data = { "company_id": registered_company.id, "colleague": colleague, "sample_avatar": "john_do.jpg" } create_sample_colleague(data) # set the founder as Admin with full privilegs: registered_colleague = Colleagues.query.filter_by( email="*****@*****.**").first() # instatiate Admins: admin = instatiate_admin(True) admin.colleague_id = registered_colleague.id try: db.session.add(admin) db.session.commit() except: db.session.rollback() flash( "Any error occured when created sample admin registration. Please try again.", "error") return redirect(url_for("register_company")) # copy logo: location = "static/sample_logo/blabla.png" destination = f"static/logo/{registered_colleague.company_id}.png" shutil.copy2(location, destination) # update database: company.logo = "png" try: db.session.commit() print("Company logo copied.") except: db.session.rollback() print("An error occured when copied logo.") # instatiate Jane Do: colleague = Colleagues(user_name="jane_do", email="*****@*****.**", first_name="Jane", last_name="Do", position="Co-Founder", confirmed=1) colleague.set_password("aaa") data = { "company_id": registered_company.id, "colleague": colleague, "sample_avatar": "jane_do.png" } create_sample_colleague(data) # instatiate Do Do: colleague = Colleagues(user_name="dodo", email="*****@*****.**", first_name="Do", last_name="Do", position="dodo", confirmed=1) colleague.set_password("aaa") data = { "company_id": registered_company.id, "colleague": colleague, "sample_avatar": "dodo.svg" } create_sample_colleague(data) # instatiate x more colleagues: x_more = 20 usernames = open("fake_dataset/username.txt").readlines() emails = open("fake_dataset/fake_email.txt").readlines() first_names = open("fake_dataset/first_name.txt").readlines() last_names = open("fake_dataset/last_name.txt").readlines() positions = open("fake_dataset/position.txt").readlines() for x in range(x_more): colleague = Colleagues( user_name=get_random_item(usernames).strip(), email=get_random_item(emails), first_name=get_random_item(first_names), last_name=get_random_item(last_names).lower().title(), position=get_random_item(positions), confirmed=1) colleague.set_password("aaa") data = { "company_id": registered_company.id, "colleague": colleague, "sample_avatar": None } create_sample_colleague(data) # create sample Idea Box: admin = Admins.query.filter( Admins.colleague_id == registered_colleague.id).first() for x in range(2): new_box = Boxes(name=lorem.sentence().replace(".", ""), description=lorem.paragraph(), close_at=str_to_date( add_day(str_to_date(today()), x).strftime('%Y-%m-%d')), admin_id=admin.id) try: print("Trying to add new Idea Box to the database...") db.session.add(new_box) db.session.commit() except SQLAlchemyError as e: error = str(e.__dict__['orig']) print("**************************************") print(error) print("New Idea Box not created!") print("new_box.name: ", new_box.name) print("new_box.description: ", new_box.description) print("new_box.close_at: ", new_box.close_at) print("new_box.admin_id: ", new_box.admin_id) db.session.rollback() # create sample Idea: colleagues = Colleagues.query.filter( Colleagues.company_id == registered_company.id).all() boxes = db.session.query( Boxes, Admins, Colleagues).filter(Boxes.admin_id == admin.id).all() for x in range(7): colleague = get_random_item(colleagues) sign = [ "incognito", colleague.user_name, colleague.first_name, colleague.fullname() ] idea = Ideas(idea=lorem.paragraph(), sign=get_random_item(sign), box_id=get_random_item(boxes).Boxes.id, colleague_id=colleague.id) db.session.add(idea) try: db.session.commit() except: db.session.rollback() print("The sample company registered successfully!")
try: # This borks sdist. os.remove('.SELF') except: pass data_files = [] # Copy static UI files for dir, dirs, files in os.walk('static'): data_files.append((dir, [os.path.join(dir, file_) for file_ in files])) # Copy translation files for dir, dirs, files in os.walk('locale'): data_files.append((dir, [os.path.join(dir, file_) for file_ in files])) setup( name="mailpile", version=APPVER.replace('github', 'dev'+date.today().isoformat().replace('-', '')), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="*****@*****.**", url="http://www.mailpile.is/", description="""\ Mailpile is a personal tool for searching and indexing e-mail.""", long_description="""\ Mailpile is a tool for building and maintaining a tagging search engine for a personal collection of e-mail. It can be used as a simple web-mail client. """, packages=find_packages(), data_files=data_files, install_requires=[ 'lxml>=2.3.2',
def get_videofile(id): curs = conn.cursor() data = request.get_json() try: if not urllib.request.urlopen(data["url"]).status == 200: return jsonify({"message": "invalid url", "status": 400}) video_file = wget.download(data["url"]) cap = cv2.VideoCapture('video_file') time_tracker = 0 sleeping_cnt = 0 is_sleep = 0 focus_count = 0 frame_count = 0 phone_count = 0 try: while cap.isOpened(): _, frame = cap.read() tensor = tf.image.convert_image_dtype(frame, tf.uint8) tensor = tf.expand_dims(tensor, axis=0) detector_output = detector(tensor) class_ids = detector_output["detection_classes"] class_ids = list(np.int64(class_ids.numpy().squeeze())) scores = detector_output["detection_scores"] class_scores = list(np.float64(scores.numpy().squeeze())) try: id = class_ids.index(77) except: if class_scores[id] > 0.85: phone_count += 1 gaze.refresh(frame) frame_count += 1 if sleeping_cnt > 20: is_sleep += 1 if gaze.is_center(): text = "focusing" focus_count += 1 sleeping_cnt = 0 else: if gaze.is_blinking(): sleeping_cnt += 1 else: pass except: pass sql = """insert into CONCENTRATION_TB(id,phone,sleep,concentration,all_frame,created_at) values (%s, %s, %s, %s, %s, %s)""" curs.execute(id, phone_count, is_sleep, focus_count, frame_count, date.today()) #focus_persentage = fo1cus_count/length #sleep_persentage = is_sleep/length '''return frame_count, focus_count, is_sleep phone_count''' # video_file 처리 return jsonify({"status": 200}) except Exception as err: return jsonify({"status": 400, "message": "Fail"})
def update_store(self): last_trading_day = pd.Timestamp(date.today(), tz=pytz.UTC) while last_trading_day.weekday() > 4: last_trading_day = last_trading_day - DateOffset(days=1)
28 >>> #the size is increasing because of the additional information caused due conversion of encoding & decoding >>> >>> import urllib2 >>> f = urllib.urlopen ("http://www.labs.forsk.in/") Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> f = urllib.urlopen ("http://www.labs.forsk.in/") NameError: name 'urllib' is not defined >>> f = urllib2.urlopen ("http://www.labs.forsk.in/") >>> f.read(1000) '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n <title>Forsk - Learn Code Today</title>\r\n\t<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">\r\n\t<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\r\n <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">\r\n <link href="css/bootstrap.css" rel=\'stylesheet\' type=\'text/css\' />\r\n <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>\r\n<script src="js/bootstrap.min.js"></script>\r\n\t<script src="js/navcall.js"></script>\r\n <link href="css/camera.css" rel="stylesheet" />\r\n <link href="css/Reset.css" rel="stylesheet" type="text/css" />\r\n <link href="css/style.css" rel="stylesheet" type="text/css" media="all" />\r\n <link href="css/owl.carousel.css" rel="stylesheet" />\r\n\r\n <script src="js/owl.carousel.js"></script>\r\n\r\n\t<script language="javascript">\r\n\tfunction send_message(){\r\n\tvar name = document.getElementById("name").value;\r\n\tvar ' >>> #useful for web-scraping >>> >>> from datetime import date >>> date.today() datetime.date(2018, 2, 7) >>> import math >>> math.sqrt(16) 4.0 >>> from math import sqrt >>> sqrt (6) 2.449489742783178 >>> from math import sqrt as ml >>> ml(6) 2.449489742783178 >>> #IMPORTANT FILES >>> >>>
def debug(data): with open('%s/%s.%s.log' % (LOG_DIR, 'debug', today()), 'a') as f: f.write(now() + " <<< dump\n"); pprint(data, f) f.write(">>>\n");
$9����~Uy]�\�� (zM��ޢi�̘Ri��|ͭߤ�R4�[�Y�����2ľ���E�p�e��{3����sK�ഢ%m�SC��c`{L9Ra4�������jV�Y��N�Nq&��t[탱��m��0K�\�iM�2�o��n _�*p^�&-��H���d�"z%;b>�v4�f8�z5Sx�-d0��Qa�łf� �Ȃ�����H�fVn� �Q�F�R~i�7�4���GVi�g^>4�*M'����>���@y`�k���G�l[|_�e��� �������QY���Z-��c�*��?w���ir_�@��l^p�'�i��{Wњ>]\c)}��s��j�ym� z���;�PP0�o?����j��aI��(��Asyƒ)~�����aqz+2M ZF�=����ZjQo��r�E%���*tT�@ü��:��؟��&rj��j�[cl&[� ����`E�ĨAP��m}��.�����8�}��|���ʽN��2�94�U��7d��ߗ���D��iQ�;�?���X�2Q��u�|/�I�G|gKP�ڹ��BmG�p���������p���1��h��N�{�p����Z�7�>Ywϙ�E�b^��O^ȝ���.�Oj��8��]ef�ݟ��CK��?�쪾'���h�R��?u�k(�v�b��a6u&.�=׀�8��-6�~V�^��jv>��N�{��eq��q735CNm[(�`I�Yf���_�A#�&�,�s����},��oj#B�V���f�?[�%�1�r�� ?�'������Qr3��#sp>h�38��zG� ;�o�|����ɧ��I W�)f�S���XCg�p0� �c���5a�J<�aK��0'�a96T?��P���=��e|s�nw�?m�\C�ӯ�.LLm�l��^S��H�]�����?��ƃdY-S�+��eW���h�κ�SwT��<�1�I���-�%ǰoy+D��8>��u��W������`��0�_�0���"�\�LI���4,�3�\C����I�v���ss}:���u�"�y^��b�n2u�Y��P;w����HJ�4wR���ue�|�Z����� �j���:'��G�V�^��.J���X����ǁ�r}������'�-`�y���~��-&(e�7V �C_�S��Ж��lu}E��MB���0Ql e�$����~���9V�F�z�g�7jnA?A�/m ��e�{�}�C��{�$�V(x-�Ha��H��sS�QH4G�Z����j����v(Gƽ��A*�(Z M[�Z����.�^n����5[h-Cw��*3�!�5�y�B�l�E䯧C:K�=U�z����KTQ�T/G��տ���d4����b;,��vx�t��Nc �D{H��aw�v5:Z�A���zԠ���t��WH~k��c�0n�n�u�k|+������%�4�M��P$v�8��ҀF���m����|�o>dt��J�_U�i��H;%�u� �!כ�������O{�BTǟܢ�*��~҄cn�W�^4T4�d%_��c�$y��{�rj�*�q�����F�@�-i�,�����6��{�eUnU�}�KB?u}3�Dz�M���4 DX�v�7�0�BAc����^L�-7�tL)8��ߌ: �;��^�p�.zgyg�J3�2�Km/7@᥍��0Ds���YL�,����� ���x{�A�W4^ҹO?���EoS�Ep��SO����u�ۚ�y+���0u�3"��b�D�49k��mܞ�Nذ�š�6mT��W<n4��?����h��f&s]�>VR��)���rb1�o��a���C��v�A�7�ێ�S~��䈪��}����i/�:G!���`%g�P�+��-�\��������N4�}��r��3�A�S;:^�Γ4Z������Zp�ظ�+�pK����ư<Go�llJ?y���A�y�:vkvz۔����������m-훈�g >كǁo��].!!�^�;�v���o_���<A�$��Ss��ⵎ�^T&ꏜ�`�Tpj�7 o��sNJ��A����������s'���j���V��y�{�ݡ�8�����+V=L6u� ���d��?]���C�rq����؟�6�`U|&������jD�J4Im҉V�B��J����9�����g�`��O��U�N�<���i6��?�)c����M��G17F���鳣k�b�/:��5w��;�r�]��(��*�>����Pv2 <Ag��瑍�\��M�c�����͆z�MAS�HZLHB�c|�;� �'����}���E�{�J�����löl�V2<����hI��\����U��Y�W���>�}�/�r�%ނV2h��۠�%�q�n��AP�.�^�����[h{�0�|�<H��Wf�g�:C!L��d �Nƫ���S����^�\�#���T(���J�rG�\���U�v�I0B���q�B�fH�� >t���.w(,�e��n���=��~�WTIME(): from datetime import date import time now = date.today() # return now.strftime("%Y%b%d")+"_"+time.strftime('%H%M%S') return now.strftime("%Y%b%d") #Return filename of Check Resule def FILE(): import os if os.path.exists('/tmp/OS_CHECK'): FN = '/tmp/OS_CHECK/OS_CHECK-'+NOWTIME() return FN else: os.system('mkdir -p /tmp/OS_CHECK')
def Ban(self): self.banned = True self.bannedOn.append(str(date.today()))
def birth_year(year): today = date.today().year age = today - year print(f"you are {age} years old")
import date a = {'f': [], 'b': []} print(a) if not a['f']: del a['f'] print(a) print(date.today())