Best Python code snippet using avocado_python
tiip_employee.py
Source:tiip_employee.py
1# -*- coding: utf-8 -*-2# Copyright (c) 2021, TeamPRO and contributors3# For license information, please see license.txt4from __future__ import unicode_literals5import frappe6from frappe.utils import flt7from frappe.model.document import Document8from datetime import date9class TIIPEmployee(Document):10 def get_all_employees(self):11 # self.sales_invoice =[]12 # self.analytical_section =[]13 # email = frappe.db.get_value("Employee",self.employee_id,["prefered_email"])14 # get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer from`tabSales Invoice` WHERE account_manager = '%s' or delivery_manager = '%s' """ % (email,email),as_dict=True)15 # for get in get_si:16 # self.append("sales_invoice",{17 # "si_no": get.name,18 # "grand_total":get.total,19 # "total_sc":get.total_dec,20 # "date":get.posting_date,21 # "client_name":get.customer,22 # "outstanding_amount":get.outstanding_amount23 # }).save(ignore_permissions=True)24 # frappe.db.commit()25 get_tiip = frappe.get_value("Tiips", {'parent': self.employee_id}, ['year','ft_value','bt_value','at_value'])26 # frappe.errprint(get_tiip[0])27 self.append("analytical_section",{28 "year":get_tiip[0],29 "ft":get_tiip[1],30 "bt":get_tiip[2],31 "at":get_tiip[3]32 }).save(ignore_permissions=True)33 frappe.db.commit()34 def get_data(self):35 self.sales_invoice =[]36 service = frappe.db.get_value("Employee",self.employee_id,["based_on_value"])37 if service == "Role Based":38 email = frappe.db.get_value("Employee",self.employee_id,["prefered_email"])39 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 40 from`tabSales Invoice` 41 WHERE (account_manager = '%s' 42 AND posting_date BETWEEN '%s' and '%s'43 AND status in ("Paid","Overdue","Unpaid") )44 OR (delivery_manager = '%s' 45 AND posting_date BETWEEN '%s' and '%s'46 AND status in ("Paid","Overdue","Unpaid") )"""47 % (email,self.from_date,self.to_date,email,self.from_date,self.to_date),as_dict=True)48 # get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 49 # from`tabSales Invoice` 50 # WHERE (account_manager = '%s' 51 # AND posting_date BETWEEN '%s' and '%s'52 # AND status in ("Paid","Overdue","Unpaid") )53 # AND (delivery_manager = '%s' 54 # AND posting_date BETWEEN '%s' and '%s'55 # AND status in ("Paid","Overdue","Unpaid") )"""56 # % (email,self.from_date,self.to_date,email,self.from_date,self.to_date),as_dict=True)57 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si 58 from `tabClosure` 59 WHERE (candidate_owner = '%s'60 AND so_confirmed_date BETWEEN '%s' and '%s' 61 AND collection_status in ("PAID"))62 OR (account_manager = '%s' 63 AND so_confirmed_date BETWEEN '%s' and '%s' 64 AND collection_status in ("PAID"))""" 65 % (email,self.from_date,self.to_date,email,self.from_date,self.to_date),as_dict=True)66 elif service == "Service Based":67 frappe.errprint("service")68 services = frappe.get_all("Employee services", {'parent': self.employee_id},['services'])69 frappe.errprint(services)70 # s = services[0].services71 service_list = []72 for s in services:73 service_list.append(s.services)74 str_list = str(service_list).strip('[')75 str_list = str(str_list).strip(']')76 # frappe.errprint(str_list)77 if service_list:78 get_closure = 079 get_si = 080 # for s in services:81 # frappe.errprint(s.services)82 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 83 from`tabSales Invoice` 84 WHERE services IN (%s) 85 AND posting_date BETWEEN '%s' and '%s' 86 AND status in ("Paid","Overdue","Unpaid") """ % (87 str_list,self.from_date,self.to_date),as_dict=True)88 frappe.errprint(get_si)89 # total_value += flt(service_si[0].total)90 # frappe.errprint(total_value)91 if set(["REC-I","REC-D"]).intersection(set(service_list)):92 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si93 from `tabClosure` 94 WHERE so_confirmed_date BETWEEN '%s' and '%s' 95 AND collection_status in ("PAID")""" 96 % (self.from_date,self.to_date),as_dict=True)97 # frappe.errprint(get_si[0])98 for get in get_si:99 self.append("sales_invoice",{100 "si_no": get.name,101 "grand_total":get.total,102 "total_sc":get.total_dec,103 "date":get.posting_date,104 "client_name":get.customer,105 "outstanding_amount":get.outstanding_amount106 }).save(ignore_permissions=True)107 frappe.db.commit()108 if get_closure:109 for get in get_closure:110 self.append("sales_invoice",{111 "si_no": get.given_name,112 "grand_total":get.candidate_si,113 "total_sc":get.candidate_service_charge,114 "date":get.so_confirmed_date,115 "client_name":get.customer,116 "outstanding_amount":get.outstanding_amount117 }).save(ignore_permissions=True)118 frappe.db.commit()119 def get_data_monthly(self):120 # value = 0121 self.sales_invoice =[]122 today = date.today()123 year = today.year124 if self.monthly == "Jan":125 value = 1126 elif self.monthly == "Feb":127 value = 2128 elif self.monthly == "March":129 value = 3130 131 elif self.monthly == "April":132 value = 4133 134 elif self.monthly == "May":135 value = 5136 137 elif self.monthly == "June":138 value = 6139 140 elif self.monthly == "July":141 value = 7142 143 elif self.monthly == "Aug":144 value = 8145 146 elif self.monthly == "Sep":147 value = 9148 149 elif self.monthly == "Oct":150 value = 10151 152 elif self.monthly == "Nov":153 value = 11154 155 elif self.monthly == "Dec":156 value = 12157 158 service = frappe.db.get_value("Employee",self.employee_id,["based_on_value"])159 if service == "Role Based":160 email = frappe.db.get_value("Employee",self.employee_id,["prefered_email"])161 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 162 from`tabSales Invoice` 163 WHERE (account_manager = '%s' 164 AND month(posting_date) = '%s'165 And year(posting_date) = '%s'166 AND status in ("Paid","Overdue","Unpaid") )167 OR (delivery_manager = '%s' 168 AND month(posting_date) = '%s'169 And year(posting_date) = '%s'170 AND status in ("Paid","Overdue","Unpaid") )"""171 % (email,value,year,email,value,year),as_dict=True)172 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si 173 from `tabClosure` 174 WHERE (candidate_owner = '%s'175 AND month(so_confirmed_date) = '%s'176 AND year(so_confirmed_date) = '%s'177 AND collection_status in ("PAID"))178 OR (account_manager = '%s' 179 AND month(so_confirmed_date) = '%s'180 AND year(so_confirmed_date) = '%s'181 AND collection_status in ("PAID"))""" 182 % (email,value,year,email,value,year),as_dict=True)183 elif service == "Service Based":184 frappe.errprint("service")185 services = frappe.get_all("Employee services", {'parent': self.employee_id},['services'])186 frappe.errprint(services)187 # s = services[0].services188 service_list = []189 for s in services:190 service_list.append(s.services)191 str_list = str(service_list).strip('[')192 str_list = str(str_list).strip(']')193 # frappe.errprint(str_list)194 if service_list:195 get_closure = 0196 get_si = 0197 # for s in services:198 # frappe.errprint(s.services)199 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 200 from`tabSales Invoice` 201 WHERE services IN (%s) 202 AND month(posting_date) = '%s'203 AND year(posting_date) = '%s'204 AND status in ("Paid","Overdue","Unpaid") """ % (205 str_list,value,year),as_dict=True)206 frappe.errprint(get_si)207 # total_value += flt(service_si[0].total)208 # frappe.errprint(total_value)209 if set(["REC-I","REC-D"]).intersection(set(service_list)):210 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si211 from `tabClosure` WHERE212 month(so_confirmed_date) = '%s'213 AND year(so_confirmed_date) = '%s'214 AND collection_status in ("PAID")""" 215 % (value,year),as_dict=True)216 # frappe.errprint(get_si)217 for get in get_si:218 self.append("sales_invoice",{219 "si_no": get.name,220 "grand_total":get.total,221 "total_sc":get.total_dec,222 "date":get.posting_date,223 "client_name":get.customer,224 "outstanding_amount":get.outstanding_amount225 }).save(ignore_permissions=True)226 frappe.db.commit()227 if get_closure:228 for get in get_closure:229 self.append("sales_invoice",{230 "si_no": get.given_name,231 "grand_total":get.candidate_si,232 "total_sc":get.candidate_service_charge,233 "date":get.so_confirmed_date,234 "client_name":get.customer,235 "outstanding_amount":get.outstanding_amount236 }).save(ignore_permissions=True)237 frappe.db.commit()238 def get_data_quarterly(self):239 # value = 0240 self.sales_invoice =[]241 today = date.today()242 year = today.year243 if self.quarterly == "Q1":244 start = 1 ;end =3245 elif self.quarterly == "Q2":246 start = 4 ;end =6247 elif self.quarterly == "Q3":248 start = 7 ;end =9249 elif self.quarterly == "Q4":250 start = 10 ;end =12251 service = frappe.db.get_value("Employee",self.employee_id,["based_on_value"])252 if service == "Role Based":253 email = frappe.db.get_value("Employee",self.employee_id,["prefered_email"])254 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 255 from`tabSales Invoice` 256 WHERE (account_manager = '%s' 257 AND month(posting_date) BETWEEN '%s' and '%s'258 And year(posting_date) = '%s'259 AND status in ("Paid","Overdue","Unpaid") )260 OR (delivery_manager = '%s' 261 AND month(posting_date) BETWEEN '%s' and '%s'262 And year(posting_date) = '%s'263 AND status in ("Paid","Overdue","Unpaid") )"""264 % (email,start,end,year,email,start,end,year),as_dict=True)265 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si 266 from `tabClosure` 267 WHERE (candidate_owner = '%s'268 AND month(so_confirmed_date) BETWEEN '%s' and '%s'269 AND year(so_confirmed_date) = '%s'270 AND collection_status in ("PAID"))271 OR (account_manager = '%s' 272 AND month(so_confirmed_date) BETWEEN '%s' and '%s'273 AND year(so_confirmed_date) = '%s'274 AND collection_status in ("PAID"))""" 275 % (email,start,end,year,email,start,end,year),as_dict=True)276 elif service == "Service Based":277 frappe.errprint("service")278 services = frappe.get_all("Employee services", {'parent': self.employee_id},['services'])279 frappe.errprint(services)280 # s = services[0].services281 service_list = []282 for s in services:283 service_list.append(s.services)284 frappe.errprint(service_list)285 str_list = str(service_list).strip('[')286 str_list = str(str_list).strip(']')287 # frappe.errprint(str_list)288 if service_list:289 get_closure = 0290 get_si = 0291 # for s in services:292 # frappe.errprint(s.services)293 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 294 from`tabSales Invoice` 295 WHERE services IN (%s) 296 AND month(posting_date) BETWEEN '%s' and '%s'297 And year(posting_date) = '%s'298 AND status in ("Paid","Overdue","Unpaid") """ % (299 str_list,start,end,year),as_dict=True)300 frappe.errprint(get_si)301 # total_value += flt(service_si[0].total)302 # frappe.errprint(total_value)303 frappe.errprint(service_list)304 if set(["REC-I","REC-D"]).intersection(set(service_list)):305 frappe.errprint("hiii")306 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si307 from `tabClosure` WHERE308 month(so_confirmed_date) BETWEEN '%s' and '%s'309 AND year(so_confirmed_date) = '%s'310 AND collection_status in ("PAID")""" 311 % (start,end,year),as_dict=True)312 frappe.errprint(get_closure)313 for get in get_si:314 self.append("sales_invoice",{315 "si_no": get.name,316 "grand_total":get.total,317 "total_sc":get.total_dec,318 "date":get.posting_date,319 "client_name":get.customer,320 "outstanding_amount":get.outstanding_amount321 }).save(ignore_permissions=True)322 frappe.db.commit()323 if get_closure:324 for get in get_closure:325 self.append("sales_invoice",{326 "si_no": get.given_name,327 "grand_total":get.candidate_si,328 "total_sc":get.candidate_service_charge,329 "date":get.so_confirmed_date,330 "client_name":get.customer,331 "outstanding_amount":get.outstanding_amount332 }).save(ignore_permissions=True)333 frappe.db.commit()334 def get_data_half_yearly(self):335 # value = 0336 self.sales_invoice =[]337 today = date.today()338 year = today.year339 if self.half_yearly == "H1":340 start = 1 ;end =6341 elif self.half_yearly == "H2":342 start = 7 ;end =12343 service = frappe.db.get_value("Employee",self.employee_id,["based_on_value"])344 if service == "Role Based":345 email = frappe.db.get_value("Employee",self.employee_id,["prefered_email"])346 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 347 from`tabSales Invoice` 348 WHERE (account_manager = '%s' 349 AND month(posting_date) BETWEEN '%s' and '%s'350 And year(posting_date) = '%s'351 AND status in ("Paid","Overdue","Unpaid") )352 OR (delivery_manager = '%s' 353 AND month(posting_date) BETWEEN '%s' and '%s'354 And year(posting_date) = '%s'355 AND status in ("Paid","Overdue","Unpaid") )"""356 % (email,start,end,year,email,start,end,year),as_dict=True)357 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si 358 from `tabClosure` 359 WHERE (candidate_owner = '%s'360 AND month(so_confirmed_date) BETWEEN '%s' and '%s'361 AND year(so_confirmed_date) = '%s'362 AND collection_status in ("PAID"))363 OR (account_manager = '%s' 364 AND month(so_confirmed_date) BETWEEN '%s' and '%s'365 AND year(so_confirmed_date) = '%s'366 AND collection_status in ("PAID"))""" 367 % (email,start,end,year,email,start,end,year),as_dict=True)368 elif service == "Service Based":369 frappe.errprint("service")370 services = frappe.get_all("Employee services", {'parent': self.employee_id},['services'])371 frappe.errprint(services)372 # s = services[0].services373 service_list = []374 for s in services:375 service_list.append(s.services)376 str_list = str(service_list).strip('[')377 str_list = str(str_list).strip(']')378 frappe.errprint(str_list)379 if service_list:380 get_closure = 0381 get_si = 0382 # for s in services:383 # frappe.errprint(s.services)384 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 385 from`tabSales Invoice` 386 WHERE services IN (%s) 387 AND month(posting_date) BETWEEN '%s' and '%s'388 And year(posting_date) = '%s'389 AND status in ("Paid","Overdue","Unpaid") """ % (390 str_list,start,end,year),as_dict=True)391 frappe.errprint(get_si)392 # total_value += flt(service_si[0].total)393 # frappe.errprint(total_value)394 if set(["REC-I","REC-D"]).intersection(set(service_list)):395 frappe.errprint("hi rec")396 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si397 from `tabClosure` WHERE398 month(so_confirmed_date) BETWEEN '%s' and '%s'399 AND year(so_confirmed_date) = '%s'400 AND collection_status in ("PAID")""" 401 % (start,end,year),as_dict=True)402 # frappe.errprint(get_si)403 for get in get_si:404 self.append("sales_invoice",{405 "si_no": get.name,406 "grand_total":get.total,407 "total_sc":get.total_dec,408 "date":get.posting_date,409 "client_name":get.customer,410 "outstanding_amount":get.outstanding_amount411 }).save(ignore_permissions=True)412 frappe.db.commit()413 if get_closure:414 for get in get_closure:415 self.append("sales_invoice",{416 "si_no": get.given_name,417 "grand_total":get.candidate_si,418 "total_sc":get.candidate_service_charge,419 "date":get.so_confirmed_date,420 "client_name":get.customer,421 "outstanding_amount":get.outstanding_amount422 }).save(ignore_permissions=True)423 frappe.db.commit()424 def get_data_yearly(self):425 426 self.sales_invoice =[]427 428 service = frappe.db.get_value("Employee",self.employee_id,["based_on_value"])429 if service == "Role Based":430 email = frappe.db.get_value("Employee",self.employee_id,["prefered_email"])431 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 432 from`tabSales Invoice` 433 WHERE (account_manager = '%s' 434 And year(posting_date) = '%s'435 AND status in ("Paid","Overdue","Unpaid") )436 OR (delivery_manager = '%s' 437 And year(posting_date) = '%s'438 AND status in ("Paid","Overdue","Unpaid") )"""439 % (email,self.yearly,email,self.yearly),as_dict=True)440 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si 441 from `tabClosure` 442 WHERE (candidate_owner = '%s'443 AND year(so_confirmed_date) = '%s'444 AND collection_status in ("PAID"))445 OR (account_manager = '%s' 446 AND year(so_confirmed_date) = '%s'447 AND collection_status in ("PAID"))""" 448 % (email,self.yearly,email,self.yearly),as_dict=True)449 elif service == "Service Based":450 frappe.errprint("service")451 services = frappe.get_all("Employee services", {'parent': self.employee_id},['services'])452 frappe.errprint(services)453 # s = services[0].services454 service_list = []455 for s in services:456 service_list.append(s.services)457 str_list = str(service_list).strip('[')458 str_list = str(str_list).strip(']')459 # frappe.errprint(str_list)460 if service_list:461 get_closure = 0462 get_si = 0463 # for s in services:464 # frappe.errprint(s.services)465 get_si = frappe.db.sql("""select total_dec,name,total,posting_date,outstanding_amount,customer 466 from`tabSales Invoice` 467 WHERE services IN (%s) 468 And year(posting_date) = '%s'469 AND status in ("Paid","Overdue","Unpaid") """ % (470 str_list,self.yearly),as_dict=True)471 frappe.errprint(get_si)472 # total_value += flt(service_si[0].total)473 # frappe.errprint(total_value)474 if set(["REC-I","REC-D"]).intersection(set(service_list)):475 get_closure = frappe.db.sql("""select candidate_service_charge,given_name,customer,so_confirmed_date,outstanding_amount,candidate_si476 from `tabClosure` WHERE477 year(so_confirmed_date) = '%s'478 AND collection_status in ("PAID")""" 479 % (self.yearly),as_dict=True)480 # frappe.errprint(get_si)481 for get in get_si:482 self.append("sales_invoice",{483 "si_no": get.name,484 "grand_total":get.total,485 "total_sc":get.total_dec,486 "date":get.posting_date,487 "client_name":get.customer,488 "outstanding_amount":get.outstanding_amount489 }).save(ignore_permissions=True)490 frappe.db.commit()491 if get_closure:492 for get in get_closure:493 self.append("sales_invoice",{494 "si_no": get.given_name,495 "grand_total":get.candidate_si,496 "total_sc":get.candidate_service_charge,497 "date":get.so_confirmed_date,498 "client_name":get.customer,499 "outstanding_amount":get.outstanding_amount500 }).save(ignore_permissions=True)...
mochaunits.py
Source:mochaunits.py
...13 'reaumur': ('Ré', 4/5, -218.52),14 'romer': ('Rø', 21/40, -135.90375),15 'urist': ('U', 9/5, 9508.33),16}17def get_si(value: float) -> (float, str):18 if value == 0:19 return 0, prefixes[0]20 index = floor(log10(value)/3)21 index = max(min(prefixes), min(max(prefixes), index))22 new_value = value / 10**(3*index)23 return new_value, prefixes[index]24# https://stackoverflow.com/a/10854034/257979825def round_time(dt = None, round_to: int = 1):26 """Round a datetime object to any time lapse in seconds27 dt : datetime.datetime object, default now.28 round_to : Closest number of seconds to round to, default 1 second.29 Author: Thierry Husson 2012 - Use it as you want but don't blame me.30 """31 import datetime32 if dt == None:33 dt = datetime.datetime.now()34 seconds = (dt.replace(tzinfo=None) - dt.min).seconds35 rounding = (seconds+round_to/2) // round_to * round_to36 return dt + datetime.timedelta(0, rounding-seconds, -dt.microsecond)37def pretty_dim(multidim, rounding: int=3) -> str:38 """Prettify dim"""39 val, unit = str(multidim).split(' ')40 val = round(float(val), rounding)41 if val % 1 == 0:42 val = int(val)43 return '{} {}'.format(val, unit)44class Dimension:45 def __init__(self, value, *tags):46 self.value = value47 self.tags = set(tags)48 # properties49 @property50 def copy(self):51 return deepcopy(self)52 @property53 def multi(self):54 return Multidimension(self.value, {type(self): 1}, *self.tags)55 # double underscore methods56 def __abs__(self):57 return type(self)(abs(self.value), *self.tags)58 def __add__(self, other):59 assert isinstance(self, type(other))60 return type(self)(self.value+other.value, *self.tags)61 def __bool__(self) -> bool:62 return bool(self.value)63 def __complex__(self) -> complex:64 return complex(self.value)65 def __eq__(self, other) -> bool:66 assert isinstance(self, type(other))67 return self.value == other.value68 def __float__(self) -> float:69 return float(self.value)70 def __hash__(self) -> int:71 return hash(self.value)72 def __int__(self) -> int:73 return int(self.value)74 def __le__(self, other) -> bool:75 assert isinstance(self, type(other))76 return self.value <= other.value77 def __lt__(self, other) -> bool:78 assert isinstance(self, type(other))79 return self.value < other.value80 def __mul__(self, other): # returns either type(self) or Multidimension81 if isinstance(other, Dimension):82 return self.multi * other.multi83 if isinstance(other, Multidimension):84 return self.multi * other85 return type(self)(self.value*other, *self.tags)86 def __neg__(self):87 return type(self)(-self.value, *self.tags)88 def __pos__(self):89 return self90 def __pow__(self, other):91 return self.multi ** other92 def __repr__(self) -> str:93 return '{}({}, *{})'.format(type(self).__name__, self.value, self.tags)94 def __rmul__(self, other):95 return self * other96 def __rtruediv__(self, other):97 return other / self.multi98 def __sub__(self, other):99 assert isinstance(self, type(other))100 return type(self)(self.value-other.value, *self.tags)101 def __truediv__(self, other): # returns either type(self) or Multidimension102 if isinstance(other, Dimension):103 if isinstance(self, type(other)):104 return self.value / other.value105 return self.multi / other.multi106 if isinstance(other, Multidimension): # call rtruediv of Multidimension107 return self.multi / other108 return type(self)(self.value/other, *self.tags)109class Length(Dimension):110 # properties111 @property112 def astro(self) -> str:113 x = self.value114 LD = 3.84402e8115 au = 1.495978707e11116 ly = 9.4607304725808e15117 if self.value < au:118 return str(x/LD) + ' LD'119 if self.value < ly:120 return str(x/au) + ' au'121 return '{} {}ly'.format(*get_si(x/ly))122 @property123 def imperial(self) -> str:124 x = self.value125 inch = 2.54e-2126 ft = 0.3048127 yd = 0.9144128 mi = 1609.344129 if self.value < ft:130 return str(x/inch) + ' in'131 if self.value < yd:132 return str(x/ft) + ' ft'133 if self.value < mi:134 return str(x/yd) + ' yd'135 return str(x/mi) + ' mi'136 # double underscore methods137 def __str__(self) -> str:138 x = self.value139 if x < 0:140 return '-' + str(-self)141 if 'imperial' in self.tags:142 return self.imperial143 if 'astro' in self.tags and 3.84402e8 < x:144 return self.astro145 return '{} {}m'.format(*get_si(x))146class Mass(Dimension):147 # properties148 @property149 def astro(self) -> str:150 x = self.value151 m_m = 7.342e22152 m_e = 5.97237e24153 m_j = 1.8982e27154 m_s = 1.98847e30155 if self.value < m_e:156 return str(x/m_m) + ' Lunar Masses'157 if self.value < m_j:158 return str(x/m_e) + ' Earth Masses'159 if self.value < m_s:160 return str(x/m_j) + ' Jupiter Masses'161 return str(x/m_s) + ' Solar Masses'162 @property163 def imperial(self) -> str:164 x = self.value165 lb = .45359237166 oz = lb / 12167 if self.value < lb:168 return str(x/oz) + ' oz'169 return str(x/lb) + ' lb'170 # double underscore methods171 def __str__(self) -> str:172 x = self.value173 if x < 0:174 return '-' + str(-self)175 if 'imperial' in self.tags:176 return self.imperial177 if 1e23 < x and 'astro' in self.tags:178 return self.astro179 return '{} {}g'.format(*get_si(x*1000))180class Time(Dimension):181 # properties182 @property183 def imperial(self) -> str:184 x = self.value185 minute = 60186 h = 60*minute187 d = 24*h188 wk = 7*d189 yr = 365.2425*d190 mo = yr / 12191 if self.value < h:192 return str(x/minute) + ' min'193 if self.value < d:194 return str(x/h) + ' h'195 if self.value < wk:196 return str(x/d) + ' d'197 if self.value < mo:198 return str(x/wk) + ' wk'199 if self.value < yr:200 return str(x/mo) + ' mo'201 return '{} {}yr'.format(*get_si(x/yr))202 # double underscore methods203 def __str__(self) -> str:204 x = self.value205 if x < 0:206 return '-' + str(-self)207 if 'imperial' in self.tags and 60 <= x:208 return self.imperial209 return '{} {}s'.format(*get_si(x))210class Temperature(Dimension):211 # double underscore methods212 def __str__(self) -> str:213 for name, (sym, scalar, offset) in temperatures.items():214 if name in self.tags:215 return '{} {}{}'.format(scalar * self.value + offset, '°' if offset else '', sym)216 return '{} K'.format(self.value)217class Current(Dimension):218 # double underscore methods219 def __str__(self) -> str:220 x = self.value221 if x < 0:222 return '-' + str(-self)223 return '{} {}A'.format(*get_si(x))224class Angle(Dimension):225 # properties226 @property227 def degrees(self) -> str:228 x = self.value229 deg = pi/180230 arcmin = deg / 60231 arcsec = arcmin / 60232 if deg < self.value:233 return str(x/deg) + '°'234 if arcmin < self.value:235 return str(x/arcmin) + 'â²'236 if arcsec < self.value:237 return str(x/arcsec) + 'â³'238 return '{} {}as'.format(*get_si(x/arcsec))239 # double underscore methods240 def __str__(self) -> str:241 x = self.value242 if x < 0:243 return '-' + str(-self)244 if 'deg' in self.tags:245 return self.degrees246 return '{} {}rad'.format(*get_si(x))247quantities = [248 ({Length: 1, Time: -2}, 'Acceleration', 'm/s^2'),249 ({Length: 2, Mass: 1, Time: -1}, 'Angular Momentum', 'N*m*s'),250 ({Length: 2}, 'Area', 'm^2'),251 ({Length: -3, Mass: 1}, 'Density', 'kg/m^3'),252 ({Length: 2, Mass: 1, Time: -2}, 'Energy', 'J'),253 ({Length: 1, Mass: 1, Time: -2}, 'Force', 'N'),254 ({Length: 1, Mass: 1, Time: -1}, 'Momentum', 'N*s'),255 ({Time: -1}, 'Frequency', 'Hz'),256 ({Length: 2, Mass: 1, Time: -3}, 'Power', 'W'),257 ({Length: -1, Mass: 1, Time: -2}, 'Pressure', 'Pa'),258 ({Length: 1, Time: -1}, 'Speed', 'm/s'),259 ({Length: 3}, 'Volume', 'm^3'),260 # w/ temperature261 ({Length: 2, Mass: 1, Temperature: -1, Time: -2}, 'Entropy', 'J/K'),262 # w/ current263 ({Current: 1, Time: 1}, 'Electric Charge', 'C'),264 ({Current: 2, Length: -2, Mass: -1, Time: 4}, 'Electrical Capacitance', 'F'),265 ({Current: 2, Length: -2, Mass: -1, Time: 3}, 'Electrical Conductance', 'S'),266 ({Current: -2, Length: 2, Mass: 1, Time: -2}, 'Electrical Inductance', 'H'),267 ({Current: -2, Length: 2, Mass: 1, Time: -3}, 'Electrical Resistance', 'Ω'),268 ({Current: -1, Length: 2, Mass: 1, Time: -2}, 'Magnetic Flux', 'Wb'),269 ({Current: -1, Mass: 1, Time: -2}, 'Magnetic Induction', 'T'),270 ({Current: -1, Length: 2, Mass: 1, Time: -3}, 'Voltage', 'V'),271]272class Multidimension:273 def __init__(self, value: float, dimensions: dict, *tags):274 self.value = value275 self.dimensions = dimensions # type dict Class -> int276 self.tags = set(tags)277 # properties278 @property279 def clean(self):280 """Delete units with 0"""281 new = self.copy282 new.dimensions = {key: value for key, value in self.dimensions.items() if value}283 return new284 @property285 def copy(self):286 return deepcopy(self)287 @property288 def inverse(self):289 new = self.copy290 new.value = 1/self.value291 new.dimensions = {key: -value for key, value in self.dimensions.items()}292 return new293 # properties294 @property295 def quantity(self) -> str:296 """Attempt to fetch the name"""297 for dim, name, _ in quantities:298 if dim == self.clean.dimensions:299 return name300 raise KeyError301 @property302 def unit(self) -> str:303 """Attempt to fetch the unit"""304 for dim, _, unit in quantities:305 if dim == self.clean.dimensions:306 return unit307 raise KeyError(self.dimensions)308 # double underscore methods309 def __add__(self, other):310 assert self.dimensions == other.dimensions311 return Multidimension(self.value + other.value, self.dimensions, *self.tags)312 def __mul__(self, other):313 if isinstance(other, Dimension):314 return self * other.multi315 if isinstance(other, Multidimension):316 dimensions = self.dimensions.copy()317 for dimension, i in other.dimensions.items():318 if dimension in dimensions:319 dimensions[dimension] += i320 else:321 dimensions[dimension] = i322 return Multidimension(self.value * other.value, dimensions, *self.tags)323 return Multidimension(self.value*other, self.dimensions, *self.tags)324 def __neg__(self):325 return Multidimension(-self.value, self.dimensions, *self.tags)326 def __pos__(self):327 return self328 def __pow__(self, other):329 assert isinstance(other, int)330 return Multidimension(self.value**other, {t: other*i for t, i in self.dimensions.items()}, *self.tags)331 def __repr__(self) -> str:332 return 'Multivalue({0}, {1}, *{2})'.format(self.value, self.dimensions, self.tags)333 def __rtruediv__(self, other):334 return Multidimension(other, {}, *self.tags) / self335 def __str__(self) -> str:336 x = self.value337 if x < 0:338 return '-' + str(-self)339 val, prefix = get_si(x)340 return '{} {}{}'.format(val, prefix, self.unit)341 def __sub__(self, other):342 return self + -other343 def __truediv__(self, other): # possibilities: other is number or dimension344 dimensions = self.dimensions.copy()345 if isinstance(other, Dimension):346 return self / other.multi347 if isinstance(other, Multidimension):348 return self * other.inverse...
spin.py
Source:spin.py
1import numpy as np2from ..spin import sx,sy,sz,bmat3from ..superconductivity import build_eh4def get_si(h,i=1):5 """Return a certain Pauli matrix for the full Hamiltonian"""6 if not h.has_spin: return None # no spin7 if i==1: si = sx # sx matrix8 elif i==2: si = sy # sy matrix9 elif i==3: si = sz # sz matrix10 else: raise # unknown pauli matrix11 if h.has_eh: ndim = h.intra.shape[0]//4 # half the dimension12 else: ndim = h.intra.shape[0]//2 # dimension13 if h.has_spin: # spinful system14 op = [[None for i in range(ndim)] for j in range(ndim)] # initialize15 for i in range(ndim): op[i][i] = si # store matrix16 op = bmat(op) # create matrix17 if h.has_eh: op = build_eh(op,is_sparse=True) # add electron and hole parts18 return op19# define the functions for the three spin components20get_sx = lambda h: get_si(h,i=1) # sx matrix21get_sy = lambda h: get_si(h,i=2) # sy matrix...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!