idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
13,500 | def view_package_path ( self , package : str ) -> _PATH : if package not in self . view_packgets_list ( ) : raise NoSuchPackageException ( f'There is no such package {package!r}.' ) output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'pm' , 'path' , package ) return output [ 8 : - 1 ] | Print the path to the APK of the given . |
13,501 | def view_focused_activity ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'activity' , 'activities' ) return re . findall ( r'mFocusedActivity: .+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)' , output ) [ 0 ] | View focused activity . |
13,502 | def view_running_services ( self , package : str = '' ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'activity' , 'services' , package ) return output | View running services . |
13,503 | def view_package_info ( self , package : str = '' ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'package' , package ) return output | View package detail information . |
13,504 | def view_current_app_behavior ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'window' , 'windows' ) return re . findall ( r'mCurrentFocus=.+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)' , output ) [ 0 ] | View application behavior in the current window . |
13,505 | def view_surface_app_activity ( self ) -> str : output , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'window' , 'w' ) return re . findall ( r"name=([a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)" , output ) | Get package with activity of applications that are running in the foreground . |
13,506 | def app_start_service ( self , * args ) -> None : _ , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'startservice' , * args ) if error and error . startswith ( 'Error' ) : raise ApplicationsException ( error . split ( ':' , 1 ) [ - 1 ] . strip ( ) ) | Start a service . |
13,507 | def app_broadcast ( self , * args ) -> None : _ , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'broadcast' , * args ) if error : raise ApplicationsException ( error . split ( ':' , 1 ) [ - 1 ] . strip ( ) ) | Send a broadcast . |
13,508 | def app_trim_memory ( self , pid : int or str , level : str = 'RUNNING_LOW' ) -> None : _ , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'send-trim-memory' , str ( pid ) , level ) if error and error . startswith ( 'Error' ) : raise ApplicationsException ( error . split ( ':' , 1 ) [ - 1 ] . strip ( ) ) | Trim memory . |
13,509 | def app_start_up_time ( self , package : str ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'start' , '-W' , package ) return re . findall ( 'TotalTime: \d+' , output ) [ 0 ] | Get the time it took to launch your application . |
13,510 | def click ( self , x : int , y : int ) -> None : self . _execute ( '-s' , self . device_sn , 'shell' , 'input' , 'tap' , str ( x ) , str ( y ) ) | Simulate finger click . |
13,511 | def send_keyevents ( self , keyevent : int ) -> None : self . _execute ( '-s' , self . device_sn , 'shell' , 'input' , 'keyevent' , str ( keyevent ) ) | Simulates typing keyevents . |
13,512 | def send_keyevents_long_press ( self , keyevent : int ) -> None : self . _execute ( '-s' , self . device_sn , 'shell' , 'input' , 'keyevent' , '--longpress' , str ( keyevent ) ) | Simulates typing keyevents long press . |
13,513 | def uidump ( self , local : _PATH = None ) -> None : local = local if local else self . _temp self . _execute ( '-s' , self . device_sn , 'shell' , 'uiautomator' , 'dump' , '--compressed' , '/data/local/tmp/uidump.xml' ) self . pull ( '/data/local/tmp/uidump.xml' , local ) ui = html . fromstring ( open ( local , 'rb' ) . read ( ) ) self . _nodes = ui . iter ( tag = "node" ) | Get the current interface layout file . |
13,514 | def find_element ( self , value , by = By . ID , update = False ) -> Elements : if update or not self . _nodes : self . uidump ( ) for node in self . _nodes : if node . attrib [ by ] == value : bounds = node . attrib [ 'bounds' ] coord = list ( map ( int , re . findall ( r'\d+' , bounds ) ) ) click_point = ( coord [ 0 ] + coord [ 2 ] ) / 2 , ( coord [ 1 ] + coord [ 3 ] ) / 2 return self . _element_cls ( self , node . attrib , by , value , coord , click_point ) raise NoSuchElementException ( f'No such element: {by}={value!r}.' ) | Find a element or the first element . |
13,515 | def find_elements_by_name ( self , name , update = False ) -> Elements : return self . find_elements ( by = By . NAME , value = name , update = update ) | Finds multiple elements by name . |
13,516 | def find_element_by_class ( self , class_ , update = False ) -> Elements : return self . find_element ( by = By . CLASS , value = class_ , update = update ) | Finds an element by class . |
13,517 | def find_elements_by_class ( self , class_ , update = False ) -> Elements : return self . find_elements ( by = By . CLASS , value = class_ , update = update ) | Finds multiple elements by class . |
13,518 | def unlock ( self , password , width = 1080 , length = 1920 ) -> None : self . wake ( ) self . swipe_up ( width , length ) self . send_keys ( str ( password ) ) | Unlock screen . |
13,519 | def make_a_call ( self , number : int or str = 18268237856 ) -> None : self . app_start_action ( Actions . CALL , '-d' , 'tel:{}' . format ( str ( number ) ) ) | Make a call . |
13,520 | def swipe_left ( self , width : int = 1080 , length : int = 1920 ) -> None : self . swipe ( 0.8 * width , 0.5 * length , 0.2 * width , 0.5 * length ) | Swipe left . |
13,521 | def swipe_right ( self , width : int = 1080 , length : int = 1920 ) -> None : self . swipe ( 0.2 * width , 0.5 * length , 0.8 * width , 0.5 * length ) | Swipe right . |
13,522 | def swipe_up ( self , width : int = 1080 , length : int = 1920 ) -> None : self . swipe ( 0.5 * width , 0.8 * length , 0.5 * width , 0.2 * length ) | Swipe up . |
13,523 | def swipe_down ( self , width : int = 1080 , length : int = 1920 ) -> None : self . swipe ( 0.5 * width , 0.2 * length , 0.5 * width , 0.8 * length ) | Swipe down . |
13,524 | def _register ( cls , app , ** kwargs ) : nav = __options__ . get ( "nav" , { } ) nav . setdefault ( "title" , "Contact" ) nav . setdefault ( "visible" , True ) nav . setdefault ( "order" , 100 ) title = nav . pop ( "title" ) render . nav . add ( title , cls . page , ** nav ) kwargs [ "base_route" ] = __options__ . get ( "route" , "/contact/" ) data = { "recipients" : __options__ . get ( "recipients" ) , "success_message" : __options__ . get ( "success_message" , "Message sent. Thanks!" ) } @ app . before_first_request def setup ( ) : if db . _IS_OK_ : try : app_data . set ( APP_DATA_KEY , data , init = True ) except Exception as ex : logging . fatal ( "mocha.contrib.app_data has not been setup. Need to run `mocha :dbsync`" ) abort ( 500 ) super ( cls , cls ) . _register ( app , ** kwargs ) | Reset some params |
13,525 | def saturateHexColor ( hexcolor , adjustment = 1.0 ) : assert ( adjustment >= 0 and len ( hexcolor ) >= 1 ) prefix = "" if hexcolor [ 0 ] == '#' : hexcolor = hexcolor [ 1 : ] prefix = "#" assert ( len ( hexcolor ) == 6 ) if adjustment == 1.0 : return "%s%s" % ( prefix , hexcolor ) else : hsvColor = list ( colorsys . rgb_to_hsv ( int ( hexcolor [ 0 : 2 ] , 16 ) / 255.0 , int ( hexcolor [ 2 : 4 ] , 16 ) / 255.0 , int ( hexcolor [ 4 : 6 ] , 16 ) / 255.0 ) ) hsvColor [ 1 ] = min ( 1.0 , hsvColor [ 1 ] * adjustment ) rgbColor = [ min ( 255 , 255 * v ) for v in colorsys . hsv_to_rgb ( hsvColor [ 0 ] , hsvColor [ 1 ] , hsvColor [ 2 ] ) ] return "%s%.2x%.2x%.2x" % ( prefix , rgbColor [ 0 ] , rgbColor [ 1 ] , rgbColor [ 2 ] ) | Takes in an RGB color in 6 - character hexadecimal with an optional preceding hash character . Returns the RGB color in the same format adjusted by saturation by the second parameter . |
13,526 | async def get_constants ( self ) : url = self . BASE + '/constants' data = await self . request ( url ) return Constants ( self , data ) | Get clash royale constants . |
13,527 | def pack_turret ( turret , temp_files , base_config_path , path = None ) : file_name = turret [ 'name' ] files = temp_files [ : ] for fname in turret . get ( 'extra_files' , [ ] ) : if os . path . isabs ( fname ) or path is None : files . append ( fname ) else : files . append ( os . path . join ( path , fname ) ) if path is not None : file_name = os . path . join ( path , file_name ) tar_file = tarfile . open ( file_name + ".tar.gz" , 'w:gz' ) for f in files : tar_file . add ( os . path . abspath ( f ) , arcname = os . path . basename ( f ) ) script_path = os . path . join ( os . path . abspath ( base_config_path ) , turret [ 'script' ] ) tar_file . add ( script_path , arcname = turret [ 'script' ] ) for f in tar_file . getnames ( ) : print ( "Added %s" % f ) tar_file . close ( ) print ( "Archive %s created" % ( tar_file . name ) ) print ( "=========================================" ) | pack a turret into a tar file based on the turret configuration |
13,528 | def clear ( self ) -> None : self . click ( ) for i in self . text : self . _parent . send_keyevents ( Keys . DEL ) | Clears the text if it s a text entry element . |
13,529 | def add ( self , domain_accession , domain_type , match_quality ) : self . matches [ domain_type ] = self . matches . get ( domain_type , { } ) self . matches [ domain_type ] [ domain_accession ] = match_quality | match_quality should be a value between 0 and 1 . |
13,530 | def _validate ( self ) : for c , m in self . atom_to_seqres_sequence_maps . iteritems ( ) : if self . seqres_to_uniparc_sequence_maps . keys ( ) : atom_uniparc_keys = set ( self . atom_to_uniparc_sequence_maps . get ( c , { } ) . keys ( ) ) atom_seqres_keys = set ( self . atom_to_seqres_sequence_maps . get ( c , { } ) . keys ( ) ) assert ( atom_uniparc_keys . intersection ( atom_seqres_keys ) == atom_uniparc_keys ) for k , v in m . map . iteritems ( ) : uparc_id_1 , uparc_id_2 = None , None try : uparc_id_1 = self . seqres_to_uniparc_sequence_maps [ c ] . map [ v ] uparc_id_2 = self . atom_to_uniparc_sequence_maps [ c ] . map [ k ] except : continue assert ( uparc_id_1 == uparc_id_2 ) | Tests that the maps agree through composition . |
13,531 | def classes ( request ) : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in' ) , 'error_type' : 'user_unauthorized' } , template = 'user_json.html' , status = 401 ) clss = [ c . to_json ( ) for c in Class . objects . filter ( owner = request . user . userprofile ) ] return render_json ( request , clss , status = 200 , template = 'user_json.html' , help_text = classes . __doc__ ) | Get all classes of current user |
13,532 | def create_class ( request ) : if request . method == 'GET' : return render ( request , 'classes_create.html' , { } , help_text = create_class . __doc__ ) if request . method == 'POST' : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in.' ) , 'error_type' : 'user_unauthorized' } , template = 'classes_create.html' , status = 401 ) data = json_body ( request . body . decode ( "utf-8" ) ) if 'code' in data and Class . objects . filter ( code = data [ 'code' ] ) . exists ( ) : return render_json ( request , { 'error' : _ ( 'A class with this code already exists.' ) , 'error_type' : 'class_with_code_exists' } , template = 'classes_create.html' , status = 400 ) if 'name' not in data or not data [ 'name' ] : return render_json ( request , { 'error' : _ ( 'Class name is missing.' ) , 'error_type' : 'missing_class_name' } , template = 'classes_create.html' , status = 400 ) cls = Class ( name = data [ 'name' ] , owner = request . user . userprofile ) if 'code' in data : cls . code = data [ 'code' ] cls . save ( ) return render_json ( request , cls . to_json ( ) , template = 'classes_create.html' , status = 201 ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Create new class |
13,533 | def join_class ( request ) : if request . method == 'GET' : return render ( request , 'classes_join.html' , { } , help_text = join_class . __doc__ ) if request . method == 'POST' : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in.' ) , 'error_type' : 'user_unauthorized' } , template = 'classes_join.html' , status = 401 ) data = json_body ( request . body . decode ( "utf-8" ) ) if 'code' not in data or not data [ 'code' ] : return render_json ( request , { 'error' : _ ( 'Class code is missing.' ) , 'error_type' : 'missing_class_code' } , template = 'classes_join.html' , status = 400 ) try : cls = Class . objects . get ( code = data [ 'code' ] ) except Class . DoesNotExist : return render_json ( request , { 'error' : _ ( 'Class with given code not found.' ) , 'error_type' : 'class_not_found' , } , template = 'classes_join.html' , status = 404 ) cls . members . add ( request . user . userprofile ) return render_json ( request , cls . to_json ( ) , template = 'classes_join.html' , status = 200 ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Join a class |
13,534 | def create_student ( request ) : if not get_config ( 'proso_user' , 'allow_create_students' , default = False ) : return render_json ( request , { 'error' : _ ( 'Creation of new users is not allowed.' ) , 'error_type' : 'student_creation_not_allowed' } , template = 'class_create_student.html' , help_text = create_student . __doc__ , status = 403 ) if request . method == 'GET' : return render ( request , 'class_create_student.html' , { } , help_text = create_student . __doc__ ) if request . method == 'POST' : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in.' ) , 'error_type' : 'user_unauthorized' } , template = 'class_create_student.html' , status = 401 ) data = json_body ( request . body . decode ( "utf-8" ) ) try : cls = Class . objects . get ( pk = data [ 'class' ] , owner = request . user . userprofile ) except ( Class . DoesNotExist , KeyError ) : return render_json ( request , { 'error' : _ ( 'Class with given id not found.' ) , 'error_type' : 'class_not_found' , } , template = 'class_create_student.html' , status = 404 ) if 'first_name' not in data or not data [ 'first_name' ] : return render_json ( request , { 'error' : _ ( 'First name code is missing.' ) , 'error_type' : 'missing_first_name' } , template = 'class_create_student.html' , status = 400 ) user = User ( first_name = data [ 'first_name' ] ) if data . get ( 'last_name' ) : user . last_name = data [ 'last_name' ] if data . get ( 'email' ) : if User . objects . filter ( email = data [ 'email' ] ) . exists ( ) : return render_json ( request , { 'error' : _ ( 'There is already a user with the given e-mail.' ) , 'error_type' : 'email_exists' } , template = 'class_create_student.html' , status = 400 ) user . email = data [ 'email' ] if data . get ( 'username' ) : if User . objects . filter ( username = data [ 'username' ] ) . exists ( ) : return render_json ( request , { 'error' : _ ( 'There is already a user with the given username.' ) , 'error_type' : 'username_exists' } , template = 'class_create_student.html' , status = 400 ) user . username = data [ 'username' ] else : user . username = get_unused_username ( user ) if data . get ( 'password' ) : user . set_password ( data [ 'password' ] ) user . save ( ) cls . members . add ( user . userprofile ) return render_json ( request , user . userprofile . to_json ( nested = True ) , template = 'class_create_student.html' , status = 201 ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Create new user in class |
13,535 | def login_student ( request ) : if not get_config ( 'proso_user' , 'allow_login_students' , default = False ) : return render_json ( request , { 'error' : _ ( 'Log in as student is not allowed.' ) , 'error_type' : 'login_student_not_allowed' } , template = 'class_create_student.html' , help_text = login_student . __doc__ , status = 403 ) if request . method == 'GET' : return render ( request , 'class_login_student.html' , { } , help_text = login_student . __doc__ ) elif request . method == 'POST' : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in.' ) , 'error_type' : 'user_unauthorized' } , template = 'class_create_student.html' , status = 401 ) data = json_body ( request . body . decode ( "utf-8" ) ) try : student = User . objects . get ( userprofile = data . get ( 'student' ) , userprofile__classes__owner = request . user . userprofile ) except User . DoesNotExist : return render_json ( request , { 'error' : _ ( 'Student not found' ) , 'error_type' : 'student_not_found' } , template = 'class_login_student.html' , status = 401 ) if not student . is_active : return render_json ( request , { 'error' : _ ( 'The account has not been activated.' ) , 'error_type' : 'account_not_activated' } , template = 'class_login_student.html' , status = 401 ) student . backend = 'django.contrib.auth.backends.ModelBackend' login ( request , student ) request . method = "GET" return profile ( request ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Log in student |
13,536 | def create ( tournament , name , ** params ) : params . update ( { "name" : name } ) return api . fetch_and_parse ( "POST" , "tournaments/%s/participants" % tournament , "participant" , ** params ) | Add a participant to a tournament . |
13,537 | def _build_cmd ( self , args : Union [ list , tuple ] ) -> str : cmd = [ self . path ] cmd . extend ( args ) return cmd | Build command . |
13,538 | def get_local_time ( index ) : dt = index . to_pydatetime ( ) dt = dt . replace ( tzinfo = pytz . utc ) return dt . astimezone ( tzlocal ( ) ) . time ( ) | Localize datetime for better output in graphs |
13,539 | def resp_graph_raw ( dataframe , image_name , dir = './' ) : factor = int ( len ( dataframe ) / 10 ) df = dataframe . reset_index ( ) fig = pygal . Dot ( stroke = False , x_label_rotation = 25 , x_title = 'Elapsed Time In Test (secs)' , y_title = 'Average Response Time (secs)' , js = ( 'scripts/pygal-tooltip.min.js' , ) ) try : grp = df . groupby ( pd . cut ( df . index , np . arange ( 0 , len ( df ) , factor ) ) ) fig . x_labels = [ x for x in grp . first ( ) [ 'epoch' ] ] fig . title = image_name . split ( '.' ) [ 0 ] fig . add ( 'Time' , [ x for x in grp . describe ( ) [ 'scriptrun_time' ] . unstack ( ) [ 'mean' ] . round ( 2 ) ] ) except ZeroDivisionError : print ( "Not enough data for raw graph" ) fig . render_to_file ( filename = os . path . join ( dir , image_name ) ) | Response time graph for raw data |
13,540 | def resp_graph ( dataframe , image_name , dir = './' ) : fig = pygal . TimeLine ( x_title = 'Elapsed Time In Test (secs)' , y_title = 'Response Time (secs)' , x_label_rotation = 25 , js = ( 'scripts/pygal-tooltip.min.js' , ) ) fig . add ( 'AVG' , [ ( get_local_time ( index ) , row [ 'mean' ] if pd . notnull ( row [ 'mean' ] ) else None ) for index , row in dataframe . iterrows ( ) ] ) fig . add ( '90%' , [ ( get_local_time ( index ) , row [ '90%' ] if pd . notnull ( row [ '90%' ] ) else None ) for index , row in dataframe . iterrows ( ) ] ) fig . add ( '80%' , [ ( get_local_time ( index ) , row [ '80%' ] if pd . notnull ( row [ '80%' ] ) else None ) for index , row in dataframe . iterrows ( ) ] ) fig . render_to_file ( filename = os . path . join ( dir , image_name ) ) | Response time graph for bucketed data |
13,541 | def add_eval ( self , agent , e , fr = None ) : self . _evals [ agent . name ] = e self . _framings [ agent . name ] = fr | Add or change agent s evaluation of the artifact with given framing information . |
13,542 | def attach ( self , stdout = True , stderr = True , stream = True , logs = False ) : try : data = parse_stream ( self . client . attach ( self . id , stdout , stderr , stream , logs ) ) except KeyboardInterrupt : logger . warning ( "service container: {0} has been interrupted. " "The container will be stopped but will not be deleted." . format ( self . name ) ) data = None self . stop ( ) return data | Keeping this simple until we need to extend later . |
13,543 | def start ( self , attach = False ) : if self . state ( ) [ 'running' ] : logger . info ( 'is already running.' , extra = { 'formatter' : 'container' , 'container' : self . name } ) return True else : try : logger . info ( 'is being started.' , extra = { 'formatter' : 'container' , 'container' : self . name } ) self . client . start ( self . id ) if self . _transcribe : self . start_transcribing ( ) except APIError as e : if e . response . status_code == 500 : self . client . start ( self . id ) else : raise RuntimeError ( "Docker Error: {0}" . format ( e . explanation ) ) if attach : self . attach ( ) exit_code = self . wait ( ) else : exit_code = self . _wait_for_exit_code ( ) return True if exit_code == 0 else False | Start a container . If the container is running it will return itself . |
13,544 | def stop ( self ) : logger . info ( 'is being stopped' , extra = { 'formatter' : 'container' , 'container' : self . name } ) response = self . client . stop ( self . id ) while self . state ( ) [ 'running' ] : time . sleep ( 1 ) return response | stop the container |
13,545 | def dump_logs ( self ) : msg = "log dump: \n" if self . _transcribe : if self . _transcribe_queue : while not self . _transcribe_queue . empty ( ) : logs = self . _transcribe_queue . get ( ) if isinstance ( logs , six . binary_type ) : logs = logs . decode ( encoding = 'UTF-8' , errors = "ignore" ) msg = '{0} {1}' . format ( msg , logs ) else : logs = self . client . logs ( self . id , stdout = True , stderr = True , stream = False , timestamps = False , tail = 'all' ) if isinstance ( logs , six . binary_type ) : logs = logs . decode ( encoding = 'UTF-8' , errors = "ignore" ) msg = '{0}{1}' . format ( msg , logs ) logger . error ( msg ) | dump entirety of the container logs to stdout |
13,546 | def _registrations_for_section_with_active_flag ( section , is_active , transcriptable_course = "" ) : instructor_reg_id = "" if ( section . is_independent_study and section . independent_study_instructor_regid is not None ) : instructor_reg_id = section . independent_study_instructor_regid params = [ ( "curriculum_abbreviation" , section . curriculum_abbr ) , ( "instructor_reg_id" , instructor_reg_id ) , ( "course_number" , section . course_number ) , ( "verbose" , "true" ) , ( "year" , section . term . year ) , ( "quarter" , section . term . quarter ) , ( "is_active" , "true" if is_active else "" ) , ( "section_id" , section . section_id ) , ] if transcriptable_course != "" : params . append ( ( "transcriptable_course" , transcriptable_course , ) ) url = "{}?{}" . format ( registration_res_url_prefix , urlencode ( params ) ) return _json_to_registrations ( get_resource ( url ) , section ) | Returns a list of all uw_sws . models . Registration objects for a section . There can be duplicates for a person . If is_active is True the objects will have is_active set to True . Otherwise is_active is undefined and out of scope for this method . |
13,547 | def _json_to_registrations ( data , section ) : registrations = [ ] person_threads = { } for reg_data in data . get ( "Registrations" , [ ] ) : registration = Registration ( ) registration . section = section registration . is_active = reg_data [ "IsActive" ] registration . is_credit = reg_data [ "IsCredit" ] registration . is_auditor = reg_data [ "Auditor" ] registration . is_independent_start = reg_data [ "IsIndependentStart" ] if len ( reg_data [ "StartDate" ] ) : registration . start_date = parse ( reg_data [ "StartDate" ] ) if len ( reg_data [ "EndDate" ] ) : registration . end_date = parse ( reg_data [ "EndDate" ] ) if len ( reg_data [ "RequestDate" ] ) : registration . request_date = parse ( reg_data [ "RequestDate" ] ) registration . request_status = reg_data [ "RequestStatus" ] registration . duplicate_code = reg_data [ "DuplicateCode" ] registration . credits = reg_data [ "Credits" ] registration . repository_timestamp = datetime . strptime ( reg_data [ "RepositoryTimeStamp" ] , "%m/%d/%Y %H:%M:%S %p" ) registration . repeat_course = reg_data [ "RepeatCourse" ] registration . grade = reg_data [ "Grade" ] registration . _uwregid = reg_data [ "Person" ] [ "RegID" ] if registration . _uwregid not in person_threads : thread = SWSPersonByRegIDThread ( ) thread . regid = registration . _uwregid thread . start ( ) person_threads [ registration . _uwregid ] = thread registrations . append ( registration ) for registration in registrations : thread = person_threads [ registration . _uwregid ] thread . join ( ) registration . person = thread . person del registration . _uwregid return registrations | Returns a list of all uw_sws . models . Registration objects |
13,548 | def get_credits_by_section_and_regid ( section , regid ) : deprecation ( "Use get_credits_by_reg_url" ) url = "{}{},{},{},{},{},{},.json" . format ( reg_credits_url_prefix , section . term . year , section . term . quarter , re . sub ( ' ' , '%20' , section . curriculum_abbr ) , section . course_number , section . section_id , regid ) reg_data = get_resource ( url ) try : return Decimal ( reg_data [ 'Credits' ] . strip ( ) ) except InvalidOperation : pass | Returns a uw_sws . models . Registration object for the section and regid passed in . |
13,549 | def get_schedule_by_regid_and_term ( regid , term , non_time_schedule_instructors = True , per_section_prefetch_callback = None , transcriptable_course = "" , ** kwargs ) : if "include_instructor_not_on_time_schedule" in kwargs : include = kwargs [ "include_instructor_not_on_time_schedule" ] non_time_schedule_instructors = include params = [ ( 'reg_id' , regid ) , ] if transcriptable_course != "" : params . append ( ( "transcriptable_course" , transcriptable_course , ) ) params . extend ( [ ( 'quarter' , term . quarter ) , ( 'is_active' , 'true' ) , ( 'year' , term . year ) , ] ) url = "{}?{}" . format ( registration_res_url_prefix , urlencode ( params ) ) return _json_to_schedule ( get_resource ( url ) , term , regid , non_time_schedule_instructors , per_section_prefetch_callback ) | Returns a uw_sws . models . ClassSchedule object for the regid and term passed in . |
13,550 | def _add_credits_grade_to_section ( url , section ) : section_reg_data = get_resource ( url ) if section_reg_data is not None : section . student_grade = section_reg_data [ 'Grade' ] section . is_auditor = section_reg_data [ 'Auditor' ] if len ( section_reg_data [ 'GradeDate' ] ) > 0 : section . grade_date = parse ( section_reg_data [ "GradeDate" ] ) . date ( ) try : raw_credits = section_reg_data [ 'Credits' ] . strip ( ) section . student_credits = Decimal ( raw_credits ) except InvalidOperation : pass | Given the registration url passed in add credits grade grade date in the section object |
13,551 | def find_transition ( self , gene : Gene , multiplexes : Tuple [ Multiplex , ... ] ) -> Transition : multiplexes = tuple ( multiplex for multiplex in multiplexes if gene in multiplex . genes ) for transition in self . transitions : if transition . gene == gene and set ( transition . multiplexes ) == set ( multiplexes ) : return transition raise AttributeError ( f'transition K_{gene.name}' + '' . join ( f"+{multiplex!r}" for multiplex in multiplexes ) + ' does not exist' ) | Find and return a transition in the model for the given gene and multiplexes . Raise an AttributeError if there is no multiplex in the graph with the given name . |
13,552 | def available_state ( self , state : State ) -> Tuple [ State , ... ] : result = [ ] for gene in self . genes : result . extend ( self . available_state_for_gene ( gene , state ) ) if len ( result ) > 1 and state in result : result . remove ( state ) return tuple ( result ) | Return the state reachable from a given state . |
13,553 | def available_state_for_gene ( self , gene : Gene , state : State ) -> Tuple [ State , ... ] : result : List [ State ] = [ ] active_multiplex : Tuple [ Multiplex ] = gene . active_multiplex ( state ) transition : Transition = self . find_transition ( gene , active_multiplex ) current_state : int = state [ gene ] done = set ( ) for target_state in transition . states : target_state : int = self . _state_after_transition ( current_state , target_state ) if target_state not in done : done . add ( target_state ) new_state : State = state . copy ( ) new_state [ gene ] = target_state result . append ( new_state ) return tuple ( result ) | Return the state reachable from a given state for a particular gene . |
13,554 | def convert_single ( ID , from_type , to_type ) : if from_type not in converter_types : raise PubMedConverterTypeException ( from_type ) if to_type not in converter_types : raise PubMedConverterTypeException ( to_type ) results = convert ( [ ID ] , from_type ) if ID in results : return results [ ID ] . get ( to_type ) else : return results [ ID . upper ( ) ] . get ( to_type ) | Convenience function wrapper for convert . Takes a single ID and converts it from from_type to to_type . The return value is the ID in the scheme of to_type . |
13,555 | def cli_main ( ) : if '--debug' in sys . argv : LOG . setLevel ( logging . DEBUG ) elif '--verbose' in sys . argv : LOG . setLevel ( logging . INFO ) args = _get_arguments ( ) try : plugin , folder = get_plugin_and_folder ( inputzip = args . inputzip , inputdir = args . inputdir , inputfile = args . inputfile ) LOG . debug ( 'Plugin: %s -- Folder: %s' % ( plugin . name , folder ) ) run_mq2 ( plugin , folder , lod_threshold = args . lod , session = args . session ) except MQ2Exception as err : print ( err ) return 1 return 0 | Main function when running from CLI . |
13,556 | def loop ( self ) : logging . info ( "Running %s in loop mode." % self . service_name ) res = None while True : try : res = self . run ( ) time . sleep ( self . loop_duration ) except KeyboardInterrupt : logging . warning ( "Keyboard Interrupt during loop, stopping %s service now..." % self . service_name ) break except Exception as e : logging . exception ( "Error in %s main loop! (%s)" % ( self . service_name , e ) ) raise e return res | Run the demo suite in a loop . |
13,557 | def prep ( s , p , o ) : def bnode_check ( r ) : return isinstance ( r , mock_bnode ) or r . startswith ( 'VERSABLANKNODE_' ) s = BNode ( ) if bnode_check ( s ) else URIRef ( s ) p = URIRef ( p ) o = BNode ( ) if bnode_check ( o ) else ( URIRef ( o ) if isinstance ( o , I ) else Literal ( o ) ) return s , p , o | Prepare a triple for rdflib |
13,558 | def url ( request , json_list , nested , url_name = 'show_{}' , ignore_get = None ) : if not ignore_get : ignore_get = [ ] if isinstance ( url_name , str ) : url_string = str ( url_name ) url_name = lambda x : url_string . format ( x ) urls = cache . get ( 'proso_urls' ) if urls is None : urls = { } else : urls = json_lib . loads ( urls ) cache_updated = False pass_string = pass_get_parameters_string ( request , ignore_get ) for json in json_list : if 'object_type' not in json or 'id' not in json : continue key = 'show_%s_%s' % ( json [ 'object_type' ] , json [ 'id' ] ) if key in urls : json [ 'url' ] = urls [ key ] else : cache_updated = True json [ 'url' ] = reverse ( url_name ( json [ 'object_type' ] ) , kwargs = { 'id' : json [ 'id' ] } ) urls [ key ] = json [ 'url' ] json [ 'url' ] = append_get_parameters ( json [ 'url' ] , pass_string ) if cache_updated : cache . set ( 'proso_urls' , json_lib . dumps ( urls ) , CACHE_EXPIRATION ) | Enrich the given list of objects so they have URL . |
13,559 | def sub_state_by_gene_name ( self , * gene_names : str ) -> 'State' : return State ( { gene : state for gene , state in self . items ( ) if gene . name in gene_names } ) | Create a sub state with only the gene passed in arguments . |
13,560 | def combine_events_to_queries ( _mongo_events ) : queries = { } for event in _mongo_events : if event . request_id not in queries : try : connection = ProfilingQueryConnection ( * event . connection_id ) except NameError : connection = event . connection_id queries [ event . request_id ] = dict ( command_name = event . command_name , connection = connection , operation_id = event . operation_id , ) if isinstance ( event , pymongo . monitoring . CommandStartedEvent ) : queries [ event . request_id ] . update ( command = sanitize_dict ( event . command . to_dict ( ) ) , database_name = event . database_name , ) elif isinstance ( event , pymongo . monitoring . CommandSucceededEvent ) : queries [ event . request_id ] . update ( duration = event . duration_micros / 1000 ) elif isinstance ( event , pymongo . monitoring . CommandFailedEvent ) : queries [ event . request_id ] . update ( failure = sanitize_dict ( event . failure ) , duration = event . duration_micros / 1000 , ) return queries . values ( ) | Combines pymongo . monitoring events to queries . |
13,561 | def lograptor ( files , patterns = None , matcher = 'ruled' , cfgfiles = None , apps = None , hosts = None , filters = None , time_period = None , time_range = None , case = False , invert = False , word = False , files_with_match = None , count = False , quiet = False , max_count = 0 , only_matching = False , line_number = False , with_filename = None , ip_lookup = False , uid_lookup = False , anonymize = False , thread = False , before_context = 0 , after_context = 0 , context = 0 ) : cli_parser = create_argument_parser ( ) args = cli_parser . parse_args ( ) args . files = files args . matcher = matcher args . cfgfiles = cfgfiles args . time_period = time_period args . time_range = time_range args . case = case args . invert = invert args . word = word args . files_with_match = files_with_match args . count = count args . quiet = quiet args . max_count = max_count args . only_matching = only_matching args . line_number = line_number args . with_filename = with_filename args . anonymize = anonymize args . ip_lookup = ip_lookup args . uid_lookup = uid_lookup args . thread = thread args . context = context args . after_context = after_context args . before_context = before_context args . patterns = [ '' ] if patterns is None else patterns if apps is not None : args . apps = apps if hosts is not None : args . hosts = hosts if filters is not None : args . filters = filters _lograptor = LogRaptor ( args ) return _lograptor ( ) | Run lograptor with arguments . Experimental feature to use the log processor into generic Python scripts . This part is still under development do not use . |
13,562 | def generate_config ( conf ) : c = { } def to_key ( key , default ) : if conf . get ( key ) : c [ key ] = '{} = {}' . format ( key , conf . get ( key ) ) else : c [ key ] = default to_key ( 'username' , '# username = u1234...' ) to_key ( 'password' , '# password = secret...' ) to_key ( 'from' , '# from = elkme' ) to_key ( 'to' , '# to = +46700000000' ) return ( True , c ) | Generates a configuration file using the ConfigParser library that can be saved to a file for subsequent reads |
13,563 | def retrieve_xml ( pdb_id , silent = True ) : xml_gz = retrieve_file_from_RCSB ( get_rcsb_files_connection ( ) , "/download/%s.xml.gz" % pdb_id , silent = silent ) cf = StringIO . StringIO ( ) cf . write ( xml_gz ) cf . seek ( 0 ) df = gzip . GzipFile ( fileobj = cf , mode = 'rb' ) contents = df . read ( ) df . close ( ) return contents | The RCSB website now compresses XML files . |
13,564 | def mail_logger ( app , level = None ) : credentials = None if app . config [ 'MAIL_USERNAME' ] and app . config [ 'MAIL_PASSWORD' ] : credentials = ( app . config [ 'MAIL_USERNAME' ] , app . config [ 'MAIL_PASSWORD' ] ) secure = None if app . config [ 'MAIL_USE_TLS' ] : secure = tuple ( ) config = dict ( mailhost = ( app . config [ 'MAIL_SERVER' ] , app . config [ 'MAIL_PORT' ] ) , fromaddr = app . config [ 'MAIL_DEFAULT_SENDER' ] , toaddrs = app . config [ 'ADMINS' ] , credentials = credentials , subject = 'Application exception' , secure = secure , timeout = 1.0 ) mail_handler = SMTPHandler ( ** config ) if level is None : level = logging . ERROR mail_handler . setLevel ( level ) mail_log_format = mail_handler . setFormatter ( logging . Formatter ( mail_log_format ) ) return mail_handler | Get mail logger Returns configured instance of mail logger ready to be attached to app . |
13,565 | def dual_use_decorator ( fn ) : @ functools . wraps ( fn ) def decorator ( * args , ** kw ) : if len ( args ) == 1 and not kw and callable ( args [ 0 ] ) : return fn ( ) ( args [ 0 ] ) else : return fn ( * args , ** kw ) return decorator | Turn a function into a decorator that can be called with or without arguments . |
13,566 | def get_args ( obj ) : if inspect . isfunction ( obj ) : return inspect . getargspec ( obj ) . args elif inspect . ismethod ( obj ) : return inspect . getargspec ( obj ) . args [ 1 : ] elif inspect . isclass ( obj ) : return inspect . getargspec ( obj . __init__ ) . args [ 1 : ] elif hasattr ( obj , '__call__' ) : return inspect . getargspec ( obj . __call__ ) . args [ 1 : ] else : raise TypeError ( "Can't inspect signature of '%s' object." % obj ) | Get a list of argument names for a callable . |
13,567 | def apply_ctx ( fn , ctx ) : if 'ctx' in get_args ( fn ) : return functools . partial ( fn , ctx = ctx ) else : return fn | Return fn with ctx partially applied if requested . |
13,568 | def log_exception ( exc_info = None , stream = None ) : exc_info = exc_info or sys . exc_info ( ) stream = stream or sys . stderr try : from traceback import print_exception print_exception ( exc_info [ 0 ] , exc_info [ 1 ] , exc_info [ 2 ] , None , stream ) stream . flush ( ) finally : exc_info = None | Log the exc_info tuple in the server log . |
13,569 | def _create_get_request ( self , resource , billomat_id = '' , command = None , params = None ) : if not params : params = { } if not command : command = '' else : command = '/' + command assert ( isinstance ( resource , str ) ) if billomat_id : assert ( isinstance ( billomat_id , int ) or isinstance ( billomat_id , str ) ) if isinstance ( billomat_id , int ) : billomat_id = str ( billomat_id ) response = self . session . get ( url = self . api_url + resource + ( '/' + billomat_id if billomat_id else '' ) + command , params = params , ) return self . _handle_response ( response ) | Creates a get request and return the response data |
13,570 | def _create_put_request ( self , resource , billomat_id , command = None , send_data = None ) : assert ( isinstance ( resource , str ) ) if isinstance ( billomat_id , int ) : billomat_id = str ( billomat_id ) if not command : command = '' else : command = '/' + command response = self . session . put ( url = self . api_url + resource + '/' + billomat_id + command , data = json . dumps ( send_data ) , ) return self . _handle_response ( response ) | Creates a put request and return the response data |
13,571 | def _create_delete_request ( self , resource , billomat_id ) : assert ( isinstance ( resource , str ) ) if isinstance ( billomat_id , int ) : billomat_id = str ( billomat_id ) response = self . session . delete ( url = self . api_url + resource + '/' + billomat_id , ) return self . _handle_response ( response ) | Creates a post request and return the response data |
13,572 | def _handle_failed_response ( self , response ) : if response . status_code == requests . codes . too_many_requests : return self . rate_limit_exceeded ( response ) else : response . raise_for_status ( ) | Handle the failed response and check for rate limit exceeded If rate limit exceeded it runs the rate_limit_exceeded function which you should overwrite |
13,573 | def _get_resource_per_page ( self , resource , per_page = 1000 , page = 1 , params = None ) : assert ( isinstance ( resource , str ) ) common_params = { 'per_page' : per_page , 'page' : page } if not params : params = common_params else : params . update ( common_params ) return self . _create_get_request ( resource = resource , params = params ) | Gets specific data per resource page and per page |
13,574 | def resolve_response_data ( head_key , data_key , data ) : new_data = [ ] if isinstance ( data , list ) : for data_row in data : if head_key in data_row and data_key in data_row [ head_key ] : if isinstance ( data_row [ head_key ] [ data_key ] , list ) : new_data += data_row [ head_key ] [ data_key ] else : new_data . append ( data_row [ head_key ] [ data_key ] ) elif data_key in data_row : return data_row [ data_key ] else : if head_key in data and data_key in data [ head_key ] : new_data += data [ head_key ] [ data_key ] elif data_key in data : return data [ data_key ] return new_data | Resolves the responses you get from billomat If you have done a get_one_element request then you will get a dictionary If you have done a get_all_elements request then you will get a list with all elements in it |
13,575 | def get_clients_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = CLIENTS , per_page = per_page , page = page , params = params ) | Get clients per page |
13,576 | def get_all_clients ( self , params = None ) : return self . _iterate_through_pages ( get_function = self . get_clients_per_page , resource = CLIENTS , ** { 'params' : params } ) | Get all clients This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing |
13,577 | def update_client ( self , client_id , client_dict ) : return self . _create_put_request ( resource = CLIENTS , billomat_id = client_id , send_data = client_dict ) | Updates a client |
13,578 | def get_client_properties_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = CLIENT_PROPERTIES , per_page = per_page , page = page , params = params ) | Get client properties per page |
13,579 | def get_client_tags_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = CLIENT_TAGS , per_page = per_page , page = page , params = params ) | Get client tags per page |
13,580 | def get_all_client_tags ( self , params = None ) : return self . _iterate_through_pages ( get_function = self . get_client_tags_per_page , resource = CLIENT_TAGS , ** { 'params' : params } ) | Get all client tags This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing |
13,581 | def get_contacts_of_client_per_page ( self , client_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = CONTACTS , per_page = per_page , page = page , params = { 'client_id' : client_id } , ) | Get contacts of client per page |
13,582 | def update_contact_of_client ( self , contact_id , contact_dict ) : return self . _create_put_request ( resource = CONTACTS , billomat_id = contact_id , send_data = contact_dict ) | Updates a contact |
13,583 | def get_suppliers_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = SUPPLIERS , per_page = per_page , page = page , params = params ) | Get suppliers per page |
13,584 | def get_all_suppliers ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( get_function = self . get_suppliers_per_page , resource = SUPPLIERS , ** { 'params' : params } ) | Get all suppliers This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing |
13,585 | def update_supplier ( self , supplier_id , supplier_dict ) : return self . _create_put_request ( resource = SUPPLIERS , billomat_id = supplier_id , send_data = supplier_dict ) | Updates a supplier |
13,586 | def get_supplier_properties_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = SUPPLIER_PROPERTIES , per_page = per_page , page = page , params = params ) | Get supplier properties per page |
13,587 | def get_tags_of_supplier_per_page ( self , supplier_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = SUPPLIER_TAGS , per_page = per_page , page = page , params = { 'supplier_id' : supplier_id } , ) | Get tags of suppliers per page |
13,588 | def get_articles_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = ARTICLES , per_page = per_page , page = page , params = params ) | Get articles per page |
13,589 | def get_all_articles ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_articles_per_page , resource = ARTICLES , ** { 'params' : params } ) | Get all articles This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing |
13,590 | def update_article ( self , article_id , article_dict ) : return self . _create_put_request ( resource = ARTICLES , billomat_id = article_id , send_data = article_dict ) | Updates an article |
13,591 | def get_article_properties_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = ARTICLE_PROPERTIES , per_page = per_page , page = page , params = params ) | Get article properties per page |
13,592 | def get_all_article_properties ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( get_function = self . get_article_properties_per_page , resource = ARTICLE_PROPERTIES , ** { 'params' : params } ) | Get all article properties This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing |
13,593 | def get_tags_of_article_per_page ( self , article_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = ARTICLE_TAGS , per_page = per_page , page = page , params = { 'article_id' : article_id } , ) | Get articles tags per page |
13,594 | def get_all_tags_of_article ( self , article_id ) : return self . _iterate_through_pages ( get_function = self . get_tags_of_article_per_page , resource = ARTICLE_TAGS , ** { 'article_id' : article_id } ) | Get all tags of article This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing |
13,595 | def get_units_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = UNITS , per_page = per_page , page = page , params = params ) | Get units per page |
13,596 | def get_all_units ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_units_per_page , resource = UNITS , ** { 'params' : params } ) | Get all units This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing |
13,597 | def update_unit ( self , unit_id , unit_dict ) : return self . _create_put_request ( resource = UNITS , billomat_id = unit_id , send_data = unit_dict ) | Updates an unit |
13,598 | def get_invoices_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = INVOICES , per_page = per_page , page = page , params = params ) | Get invoices per page |
13,599 | def get_all_invoices ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_invoices_per_page , resource = INVOICES , ** { 'params' : params } ) | Get all invoices This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.