idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
13,400
def get_reference_fields ( self , exclude_models = None ) : if exclude_models is None : exclude_models = [ ] result = [ ] for django_model in django . apps . apps . get_models ( ) : if any ( [ issubclass ( django_model , m ) for m in exclude_models ] ) : continue for django_field in django_model . _meta . fields : if i...
Get all Django model fields which reference the Item model .
13,401
def override_parent_subgraph ( self , parent_subgraph , invisible_edges = None ) : with transaction . atomic ( ) : if invisible_edges is None : invisible_edges = set ( ) children = list ( parent_subgraph . keys ( ) ) all_old_relations = dict ( proso . list . group_by ( list ( ItemRelation . objects . filter ( child_id_...
Get all items with outcoming edges from the given subgraph drop all their parent relations and then add parents according to the given subgraph .
13,402
def query_api ( self , data = None , endpoint = 'SMS' ) : url = self . api_url % endpoint if data : response = requests . post ( url , data = data , auth = self . auth ) else : response = requests . get ( url , auth = self . auth ) try : response . raise_for_status ( ) except HTTPError as e : raise HTTPError ( 'HTTP %s...
Send a request to the 46elks API . Fetches SMS history as JSON by default sends a HTTP POST request with the incoming data dictionary as a urlencoded query if data is provided otherwise HTTP GET
13,403
def validate_number ( self , number ) : if not isinstance ( number , str ) : raise ElksException ( 'Recipient phone number may not be empty' ) if number [ 0 ] == '+' and len ( number ) > 2 and len ( number ) < 16 : return True else : raise ElksException ( "Phone number must be of format +CCCXXX..." )
Checks if a number looks somewhat like a E . 164 number . Not an exhaustive check as the API takes care of that
13,404
def format_sms_payload ( self , message , to , sender = 'elkme' , options = [ ] ) : self . validate_number ( to ) if not isinstance ( message , str ) : message = " " . join ( message ) message = message . rstrip ( ) sms = { 'from' : sender , 'to' : to , 'message' : message } for option in options : if option not in [ '...
Helper function to create a SMS payload with little effort
13,405
def send_sms ( self , message , to , sender = 'elkme' , options = [ ] ) : sms = self . format_sms_payload ( message = message , to = to , sender = sender , options = options ) return self . query_api ( sms )
Sends a text message to a configuration conf containing the message in the message paramter
13,406
async def get_types ( self ) : async with aiohttp . ClientSession ( ) as session : async with session . get ( 'https://api.weeb.sh/images/types' , headers = self . __headers ) as resp : if resp . status == 200 : return ( await resp . json ( ) ) [ 'types' ] else : raise Exception ( ( await resp . json ( ) ) [ 'message' ...
Gets all available types .
13,407
async def get_image ( self , imgtype = None , tags = None , nsfw = None , hidden = None , filetype = None ) : if not imgtype and not tags : raise MissingTypeOrTags ( "'get_image' requires at least one of either type or tags." ) if imgtype and not isinstance ( imgtype , str ) : raise TypeError ( "type of 'imgtype' must ...
Request an image from weeb . sh .
13,408
async def generate_image ( self , imgtype , face = None , hair = None ) : if not isinstance ( imgtype , str ) : raise TypeError ( "type of 'imgtype' must be str." ) if face and not isinstance ( face , str ) : raise TypeError ( "type of 'face' must be str." ) if hair and not isinstance ( hair , str ) : raise TypeError (...
Generate a basic image using the auto - image endpoint of weeb . sh .
13,409
async def generate_status ( self , status , avatar = None ) : if not isinstance ( status , str ) : raise TypeError ( "type of 'status' must be str." ) if avatar and not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) url = f'https://api.weeb.sh/auto-image/discord-status?status={status}...
Generate a discord status icon below the image provided .
13,410
async def generate_waifu_insult ( self , avatar ) : if not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) async with aiohttp . ClientSession ( ) as session : async with session . post ( "https://api.weeb.sh/auto-image/waifu-insult" , headers = self . __headers , data = { "avatar" : av...
Generate a waifu insult image .
13,411
async def generate_license ( self , title , avatar , badges = None , widgets = None ) : if not isinstance ( title , str ) : raise TypeError ( "type of 'title' must be str." ) if not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) if badges and not isinstance ( badges , list ) : raise T...
Generate a license .
13,412
async def generate_love_ship ( self , target_one , target_two ) : if not isinstance ( target_one , str ) : raise TypeError ( "type of 'target_one' must be str." ) if not isinstance ( target_two , str ) : raise TypeError ( "type of 'target_two' must be str." ) data = { "targetOne" : target_one , "targetTwo" : target_two...
Generate a love ship .
13,413
def launch_command ( command , parameter = '' ) : result = '' if not isinstance ( parameter , list ) : parameter = [ parameter ] for name in parameter : result += subprocess . Popen ( 'cozy-monitor {} {}' . format ( command , name ) , shell = True , stdout = subprocess . PIPE ) . stdout . read ( ) return result
Can launch a cozy - monitor command
13,414
def status ( app_name = None , only_cozy = False , as_boolean = False ) : apps = { } apps_status = subprocess . Popen ( 'cozy-monitor status' , shell = True , stdout = subprocess . PIPE ) . stdout . read ( ) apps_status = apps_status . split ( '\n' ) for app_status in apps_status : if app_status : app_status = ANSI_ESC...
Get apps status
13,415
def transitive_closure ( m , orig , rel ) : links = list ( m . match ( orig , rel ) ) for link in links : yield link [ 0 ] [ TARGET ] yield from transitive_closure ( m , target , rel )
Generate the closure over a transitive relationship in depth - first fashion
13,416
def all_origins ( m ) : seen = set ( ) for link in m . match ( ) : origin = link [ ORIGIN ] if origin not in seen : seen . add ( origin ) yield origin
Generate all unique statement origins in the given model
13,417
def column ( m , linkpart ) : assert linkpart in ( 0 , 1 , 2 , 3 ) seen = set ( ) for link in m . match ( ) : val = link [ linkpart ] if val not in seen : seen . add ( val ) yield val
Generate all parts of links according to the parameter
13,418
def resourcetypes ( rid , model ) : types = [ ] for o , r , t , a in model . match ( rid , VTYPE_REL ) : types . append ( t ) return types
Return a list of Versa types for a resource
13,419
def replace_values ( in_m , out_m , map_from = ( ) , map_to = ( ) ) : for link in in_m . match ( ) : new_link = list ( link ) if map_from : if link [ ORIGIN ] in map_from : new_link [ ORIGIN ] = map_to [ map_from . index ( link [ ORIGIN ] ) ] new_link [ ATTRIBUTES ] = link [ ATTRIBUTES ] . copy ( ) out_m . add ( * new_...
Make a copy of a model with one value replaced with another
13,420
def replace_entity_resource ( model , oldres , newres ) : oldrids = set ( ) for rid , link in model : if link [ ORIGIN ] == oldres or link [ TARGET ] == oldres or oldres in link [ ATTRIBUTES ] . values ( ) : oldrids . add ( rid ) new_link = ( newres if o == oldres else o , r , newres if t == oldres else t , dict ( ( k ...
Replace one entity in the model with another with the same links
13,421
def duplicate_statements ( model , oldorigin , neworigin , rfilter = None ) : for o , r , t , a in model . match ( oldorigin ) : if rfilter is None or rfilter ( o , r , t , a ) : model . add ( I ( neworigin ) , r , t , a ) return
Take links with a given origin and create duplicate links with the same information but a new origin
13,422
def uniquify ( model ) : seen = set ( ) to_remove = set ( ) for ix , ( o , r , t , a ) in model : hashable_link = ( o , r , t ) + tuple ( sorted ( a . items ( ) ) ) if hashable_link in seen : to_remove . add ( ix ) seen . add ( hashable_link ) model . remove ( to_remove ) return
Remove all duplicate relationships
13,423
def jsonload ( model , fp ) : dumped_list = json . load ( fp ) for link in dumped_list : if len ( link ) == 2 : sid , ( s , p , o , a ) = link elif len ( link ) == 4 : ( s , p , o , a ) = link tt = a . get ( '@target-type' ) if tt == '@iri-ref' : o = I ( o ) a . pop ( '@target-type' , None ) else : continue model . add...
Load Versa model dumped into JSON form either raw or canonical
13,424
def jsondump ( model , fp ) : fp . write ( '[' ) links_ser = [ ] for link in model : links_ser . append ( json . dumps ( link ) ) fp . write ( ',\n' . join ( links_ser ) ) fp . write ( ']' )
Dump Versa model into JSON form
13,425
def set_statics ( self ) : if not os . path . exists ( self . results_dir ) : return None try : shutil . copytree ( os . path . join ( self . templates_dir , 'css' ) , os . path . join ( self . results_dir , 'css' ) ) shutil . copytree ( os . path . join ( self . templates_dir , 'scripts' ) , os . path . join ( self . ...
Create statics directory and copy files in it
13,426
def write_report ( self , template ) : with open ( self . fn , 'w' ) as f : f . write ( template )
Write the compiled jinja template to the results file
13,427
def set_raw_holding_register ( self , name , value ) : self . _conn . write_register ( unit = self . _slave , address = ( self . _holding_regs [ name ] [ 'addr' ] ) , value = value )
Write to register by name .
13,428
def unzip ( filepath , output_path ) : filename = os . path . split ( filepath ) [ 1 ] ( name , extension ) = os . path . splitext ( filename ) extension = extension [ 1 : ] . lower ( ) extension2 = os . path . splitext ( name ) [ 1 ] [ 1 : ] . lower ( ) if extension not in ZIP_EXTENSIONS : raise Exception ( "Impossibl...
Unzip an archive file
13,429
def _configure_sockets ( self , config , with_streamer = False , with_forwarder = False ) : rc_port = config . get ( 'rc_port' , 5001 ) self . result_collector . set_hwm ( 0 ) self . result_collector . bind ( "tcp://*:{}" . format ( rc_port ) ) self . poller . register ( self . result_collector , zmq . POLLIN )
Configure sockets for HQ
13,430
def wait_turrets ( self , wait_for ) : print ( "Waiting for %d turrets" % ( wait_for - len ( self . turrets_manager . turrets ) ) ) while len ( self . turrets_manager . turrets ) < wait_for : self . turrets_manager . status_request ( ) socks = dict ( self . poller . poll ( 2000 ) ) if self . result_collector in socks :...
Wait until wait_for turrets are connected and ready
13,431
def run ( self ) : elapsed = 0 run_time = self . config [ 'run_time' ] start_time = time . time ( ) t = time . time self . turrets_manager . start ( self . transaction_context ) self . started = True while elapsed <= run_time : try : self . _run_loop_action ( ) self . _print_status ( elapsed ) elapsed = t ( ) - start_t...
Run the hight quarter lunch the turrets and wait for results
13,432
def query ( logfile , jobID = None ) : joblist = logfile . readFromLogfile ( ) if jobID and type ( jobID ) == type ( 1 ) : command = [ 'qstat' , '-j' , str ( jobID ) ] else : command = [ 'qstat' ] processoutput = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( ) ...
If jobID is an integer then return False if the job has finished and True if it is still running . Otherwise returns a table of jobs run by the user .
13,433
def set_tmp_folder ( ) : output = "%s" % datetime . datetime . now ( ) for char in [ ' ' , ':' , '.' , '-' ] : output = output . replace ( char , '' ) output . strip ( ) tmp_folder = os . path . join ( tempfile . gettempdir ( ) , output ) return tmp_folder
Create a temporary folder using the current time in which the zip can be extracted and which should be destroyed afterward .
13,434
def file_logger ( app , level = None ) : path = os . path . join ( os . getcwd ( ) , 'var' , 'logs' , 'app.log' ) max_bytes = 1024 * 1024 * 2 file_handler = RotatingFileHandler ( filename = path , mode = 'a' , maxBytes = max_bytes , backupCount = 10 ) if level is None : level = logging . INFO file_handler . setLevel ( ...
Get file logger Returns configured fire logger ready to be attached to app
13,435
def tag ( self , repository_tag , tags = [ ] ) : if not isinstance ( repository_tag , six . string_types ) : raise TypeError ( 'repository_tag must be a string' ) if not isinstance ( tags , list ) : raise TypeError ( 'tags must be a list.' ) if ':' in repository_tag : repository , tag = repository_tag . split ( ':' ) t...
Tags image with one or more tags .
13,436
def build ( client , repository_tag , docker_file , tag = None , use_cache = False ) : if not isinstance ( client , docker . Client ) : raise TypeError ( "client needs to be of type docker.Client." ) if not isinstance ( docker_file , six . string_types ) or not os . path . exists ( docker_file ) : raise Exception ( "do...
Build a docker image
13,437
def get_grades_by_regid_and_term ( regid , term ) : url = "{}/{},{},{}.json" . format ( enrollment_res_url_prefix , term . year , term . quarter , regid ) return _json_to_grades ( get_resource ( url ) , regid , term )
Returns a StudentGrades model for the regid and term .
13,438
def _requires_refresh_token ( self ) : expires_on = datetime . datetime . strptime ( self . login_data [ 'token' ] [ 'expiresOn' ] , '%Y-%m-%dT%H:%M:%SZ' ) refresh = datetime . datetime . utcnow ( ) + datetime . timedelta ( seconds = 30 ) return expires_on < refresh
Check if a refresh of the token is needed
13,439
def _request_token ( self , force = False ) : if self . login_data is None : raise RuntimeError ( "Don't have a token to refresh" ) if not force : if not self . _requires_refresh_token ( ) : return True headers = { "Accept" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToke...
Request a new auth token
13,440
def get_home ( self , home_id = None ) : now = datetime . datetime . utcnow ( ) if self . home and now < self . home_refresh_at : return self . home if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) if home_id is None : home_id = self . home_id url = self . api_base_url + "Home/GetHomeById" params =...
Get the data about a home
13,441
def get_zones ( self ) : home_data = self . get_home ( ) if not home_data [ 'isSuccess' ] : return [ ] zones = [ ] for receiver in home_data [ 'data' ] [ 'receivers' ] : for zone in receiver [ 'zones' ] : zones . append ( zone ) return zones
Get all zones
13,442
def get_zone_names ( self ) : zone_names = [ ] for zone in self . get_zones ( ) : zone_names . append ( zone [ 'name' ] ) return zone_names
Get the name of all zones
13,443
def get_zone ( self , zone_name ) : for zone in self . get_zones ( ) : if zone_name == zone [ 'name' ] : return zone raise RuntimeError ( "Unknown zone" )
Get the information about a particular zone
13,444
def get_zone_temperature ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return zone [ 'currentTemperature' ]
Get the temperature for a zone
13,445
def set_target_temperature_by_id ( self , zone_id , target_temperature ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) data = { "ZoneId" : zone_id , "TargetTemperature" : target_temperature } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'B...
Set the target temperature for a zone by id
13,446
def set_target_temperture_by_name ( self , zone_name , target_temperature ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . set_target_temperature_by_id ( zone [ "zoneId" ] , target_temperature )
Set the target temperature for a zone by name
13,447
def activate_boost_by_id ( self , zone_id , target_temperature , num_hours = 1 ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) zones = [ zone_id ] data = { "ZoneIds" : zones , "NumberOfHours" : num_hours , "TargetTemperature" : target_temperature } headers = { "Accept" : "application/json" , "...
Activate boost for a zone based on the numeric id
13,448
def activate_boost_by_name ( self , zone_name , target_temperature , num_hours = 1 ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . activate_boost_by_id ( zone [ "zoneId" ] , target_temperature , num_hours )
Activate boost by the name of the zone
13,449
def deactivate_boost_by_name ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . deactivate_boost_by_id ( zone [ "zoneId" ] )
Deactivate boost by the name of the zone
13,450
def set_mode_by_id ( self , zone_id , mode ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) data = { "ZoneId" : zone_id , "mode" : mode . value } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'acce...
Set the mode by using the zone id Supported zones are available in the enum Mode
13,451
def set_mode_by_name ( self , zone_name , mode ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . set_mode_by_id ( zone [ "zoneId" ] , mode )
Set the mode by using the name of the zone
13,452
def get_zone_mode ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return ZoneMode ( zone [ 'mode' ] )
Get the mode for a zone
13,453
def _convertToElementList ( elements_list ) : elements = [ ] current_element = [ ] for node_index in elements_list : if node_index == - 1 : elements . append ( current_element ) current_element = [ ] else : current_element . append ( node_index ) return elements
Take a list of element node indexes deliminated by - 1 and convert it into a list element node indexes list .
13,454
def get_locale ( self ) : if not self . locale : try : import flask_babel as babel self . locale = str ( babel . get_locale ( ) ) . lower ( ) except ImportError : from flask import current_app self . locale = current_app . config [ 'DEFAULT_LOCALE' ] . lower return self . locale
Get locale Will extract locale from application trying to get one from babel first then if not available will get one from app config
13,455
def get_language ( self ) : locale = self . get_locale ( ) language = locale if '_' in locale : language = locale [ 0 : locale . index ( '_' ) ] return language
Get language If locale contains region will cut that off . Returns just the language code
13,456
def localize_humanize ( self ) : import humanize language = self . get_language ( ) if language != 'en' : humanize . i18n . activate ( language )
Setts current language to humanize
13,457
def get_filters ( self ) : filters = dict ( ) for filter in self . get_filter_names ( ) : filters [ filter ] = getattr ( self , filter ) return filters
Returns a dictionary of filters
13,458
def _render ( self , value , format ) : template = '<script>\ndocument.write(moment(\"{t}\").{f});\n</script>' return Markup ( template . format ( t = value , f = format ) )
Writes javascript to call momentjs function
13,459
def get_filters ( self ) : return dict ( moment_format = self . format , moment_calendar = self . calendar , moment_fromnow = self . from_now , )
Returns a collection of momentjs filters
13,460
def user_stats ( request ) : user = get_user_id ( request ) language = get_language ( request ) concepts = None if "concepts" in request . GET : concepts = Concept . objects . filter ( lang = language , active = True , identifier__in = load_query_json ( request . GET , "concepts" ) ) data = UserStat . objects . get_use...
JSON of user stats of the user
13,461
def user_stats_bulk ( request ) : language = get_language ( request ) users = load_query_json ( request . GET , "users" ) if request . user . is_staff : if not hasattr ( request . user , 'userprofile' ) or User . objects . filter ( pk__in = users , userprofile__classes__owner = request . user . userprofile ) . count ( ...
Get statistics for selected users and concepts
13,462
def user_stats_api ( request , provider ) : if 'key' not in request . GET or provider not in settings . USER_STATS_API_KEY or request . GET [ 'key' ] != settings . USER_STATS_API_KEY [ provider ] : return HttpResponse ( 'Unauthorized' , status = 401 ) since = None if 'since' in request . GET : since = datetime . dateti...
Get statistics for selected Edookit users
13,463
def tag_values ( request ) : data = defaultdict ( lambda : { "values" : { } } ) for tag in Tag . objects . filter ( lang = get_language ( request ) ) : data [ tag . type ] [ "name" ] = tag . type_name data [ tag . type ] [ "values" ] [ tag . value ] = tag . value_name return render_json ( request , data , template = 'c...
Get tags types and values with localized names
13,464
def add_to_grid ( self , agent ) : for i in range ( len ( self . grid ) ) : for j in range ( len ( self . grid [ 0 ] ) ) : if self . grid [ i ] [ j ] is None : x = self . origin [ 0 ] + i y = self . origin [ 1 ] + j self . grid [ i ] [ j ] = agent return ( x , y ) raise ValueError ( "Trying to add an agent to a full gr...
Add agent to the next available spot in the grid .
13,465
async def set_agent_neighbors ( self ) : for i in range ( len ( self . grid ) ) : for j in range ( len ( self . grid [ 0 ] ) ) : agent = self . grid [ i ] [ j ] xy = ( self . origin [ 0 ] + i , self . origin [ 1 ] + j ) nxy = _get_neighbor_xy ( 'N' , xy ) exy = _get_neighbor_xy ( 'E' , xy ) sxy = _get_neighbor_xy ( 'S'...
Set neighbors for each agent in each cardinal direction .
13,466
async def set_slave_params ( self ) : self . _slave_origins = [ ] cur_x = self . origin [ 0 ] for addr in self . addrs : new_origin = ( cur_x , self . origin [ 1 ] ) await self . set_origin ( addr , new_origin ) await self . set_gs ( addr , self . _gs ) self . _slave_origins . append ( ( new_origin , addr ) ) new_x = c...
Set origin and grid size for each slave environment .
13,467
async def set_agent_neighbors ( self ) : for addr in self . addrs : r_manager = await self . env . connect ( addr ) await r_manager . set_agent_neighbors ( )
Set neighbors for all the agents in all the slave environments . Assumes that all the slave environments have their neighbors set .
13,468
async def populate ( self , agent_cls , * args , ** kwargs ) : n = self . gs [ 0 ] * self . gs [ 1 ] tasks = [ ] for addr in self . addrs : task = asyncio . ensure_future ( self . _populate_slave ( addr , agent_cls , n , * args , ** kwargs ) ) tasks . append ( task ) rets = await asyncio . gather ( * tasks ) return ret...
Populate all the slave grid environments with agents . Assumes that no agents have been spawned yet to the slave environment grids . This excludes the slave environment managers as they are not in the grids . )
13,469
def generate_docs ( app ) : config = app . config config_dir = app . env . srcdir javascript_root = os . path . join ( config_dir , config . jsdoc_source_root ) if javascript_root [ - 1 ] != os . path . sep : javascript_root += os . path . sep if not javascript_root : return output_root = os . path . join ( config_dir ...
Generate the reST documentation files for the JavaScript code
13,470
def setup ( app ) : app . add_config_value ( 'jsdoc_source_root' , '..' , 'env' ) app . add_config_value ( 'jsdoc_output_root' , 'javascript' , 'env' ) app . add_config_value ( 'jsdoc_exclude' , [ ] , 'env' ) app . connect ( 'builder-inited' , generate_docs )
Sphinx extension entry point
13,471
def find_user ( search_params ) : user = None params = { prop : value for prop , value in search_params . items ( ) if value } if 'id' in params or 'email' in params : user = user_service . first ( ** params ) return user
Find user Attempts to find a user by a set of search params . You must be in application context .
13,472
def create ( email , password ) : with get_app ( ) . app_context ( ) : user = User ( email = email , password = password ) result = user_service . save ( user ) if not isinstance ( result , User ) : print_validation_errors ( result ) return click . echo ( green ( '\nUser created:' ) ) click . echo ( green ( '-' * 40 ) ...
Creates a new user record
13,473
def change_password ( * _ , user_id = None , password = None ) : click . echo ( green ( '\nChange password:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : user = find_user ( dict ( id = user_id ) ) if not user : click . echo ( red ( 'User not found\n' ) ) return result = user_service . ch...
Change user password
13,474
def change_email ( * _ , user_id = None , new_email = None ) : click . echo ( green ( '\nChange email:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : user = find_user ( dict ( id = user_id ) ) if not user : click . echo ( red ( 'User not found\n' ) ) return user . email = new_email result...
Change email for a user
13,475
def create_role ( * _ , ** kwargs ) : click . echo ( green ( '\nCreating new role:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : role = Role ( ** kwargs ) result = role_service . save ( role ) if not isinstance ( result , Role ) : print_validation_errors ( result ) click . echo ( green (...
Create user role
13,476
def list_roles ( ) : click . echo ( green ( '\nListing roles:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : roles = Role . query . all ( ) if not roles : click . echo ( red ( 'No roles found' ) ) return for index , role in enumerate ( roles ) : click . echo ( '{}. {}: {}' . format ( inde...
List existing roles
13,477
def list_user_roles ( * _ , user_id ) : click . echo ( green ( '\nListing user roles:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : user = find_user ( dict ( id = user_id ) ) if not user : click . echo ( red ( 'User not found\n' ) ) return for index , role in enumerate ( user . roles ) :...
List user roles
13,478
async def update ( self ) : if self . client . session . closed : async with core . Client ( ) as client : data = await client . request ( self . url ) else : data = await self . client . request ( self . url ) self . raw_data = data self . from_data ( data ) return self
Update an object with current info .
13,479
def clan_badge_url ( self ) : if self . clan_tag is None : return None url = self . raw_data . get ( 'clan' ) . get ( 'badge' ) . get ( 'url' ) if not url : return None return "http://api.cr-api.com" + url
Returns clan badge url
13,480
def get_chest ( self , index = 0 ) : index += self . chest_cycle . position if index == self . chest_cycle . super_magical : return 'Super Magical' if index == self . chest_cycle . epic : return 'Epic' if index == self . chest_cycle . legendary : return 'Legendary' return CHESTS [ index % len ( CHESTS ) ]
Get your current chest + - the index
13,481
def update ( ) : with settings ( warn_only = True ) : print ( cyan ( '\nInstalling/Updating required packages...' ) ) pip = local ( 'venv/bin/pip install -U --allow-all-external --src libs -r requirements.txt' , capture = True ) if pip . failed : print ( red ( pip ) ) abort ( "pip exited with return code %i" % pip . re...
Update virtual env with requirements packages .
13,482
def _detect_devices ( self ) -> None : devices_num = len ( self . devices_list ) if devices_num == 0 : raise DeviceConnectionException ( 'No devices are connected. Please connect the device with USB or via WLAN and turn on the USB debugging option.' ) elif not self . device_sn and devices_num > 1 : raise DeviceConnecti...
Detect whether devices connected .
13,483
def get_device_model ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'getprop' , 'ro.product.model' ) return output . strip ( )
Show device model .
13,484
def get_battery_info ( self ) -> dict : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'battery' ) battery_status = re . split ( '\n |: ' , output [ 33 : ] . strip ( ) ) return dict ( zip ( battery_status [ : : 2 ] , battery_status [ 1 : : 2 ] ) )
Show device battery information .
13,485
def get_resolution ( self ) -> list : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'wm' , 'size' ) return output . split ( ) [ 2 ] . split ( 'x' )
Show device resolution .
13,486
def get_displays_params ( self ) -> str : output , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'window' , 'displays' ) return output
Show displays parameters .
13,487
def get_android_id ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'settings' , 'get' , 'secure' , 'android_id' ) return output . strip ( )
Show Android ID .
13,488
def get_android_version ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'getprop' , 'ro.build.version.release' ) return output . strip ( )
Show Android version .
13,489
def get_device_mac ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/sys/class/net/wlan0/address' ) return output . strip ( )
Show device MAC .
13,490
def get_cpu_info ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/proc/cpuinfo' ) return output
Show device CPU information .
13,491
def get_memory_info ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/proc/meminfo' ) return output
Show device memory information .
13,492
def get_sdk_version ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'getprop' , 'ro.build.version.sdk' ) return output . strip ( )
Show Android SDK version .
13,493
def root ( self ) -> None : output , _ = self . _execute ( '-s' , self . device_sn , 'root' ) if not output : raise PermissionError ( f'{self.device_sn!r} does not have root permission.' )
Restart adbd with root permissions .
13,494
def tcpip ( self , port : int or str = 5555 ) -> None : self . _execute ( '-s' , self . device_sn , 'tcpip' , str ( port ) )
Restart adb server listening on TCP on PORT .
13,495
def get_ip_addr ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'ip' , '-f' , 'inet' , 'addr' , 'show' , 'wlan0' ) ip_addr = re . findall ( r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" , output ) if not ip_addr : raise ConnectionEr...
Show IP Address .
13,496
def sync_l ( self , option : str = 'all' ) -> None : if option in [ 'system' , 'vendor' , 'oem' , 'data' , 'all' ] : self . _execute ( '-s' , self . device_sn , 'sync' , '-l' , option ) else : raise ValueError ( 'There is no option named: {!r}.' . format ( option ) )
List but don t copy .
13,497
def install ( self , package : str , option : str = '-r' ) -> None : if not os . path . isfile ( package ) : raise FileNotFoundError ( f'{package!r} does not exist.' ) for i in option : if i not in '-lrtsdg' : raise ValueError ( f'There is no option named: {option!r}.' ) self . _execute ( '-s' , self . device_sn , 'ins...
Push package to the device and install it .
13,498
def uninstall ( self , package : str ) -> None : if package not in self . view_packgets_list ( ) : raise NoSuchPackageException ( f'There is no such package {package!r}.' ) self . _execute ( '-s' , self . device_sn , 'uninstall' , package )
Remove this app package from the device .
13,499
def view_packgets_list ( self , option : str = '-e' , keyword : str = '' ) -> list : if option not in [ '-f' , '-d' , '-e' , '-s' , '-3' , '-i' , '-u' ] : raise ValueError ( f'There is no option called {option!r}.' ) output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'pm' , 'list' , 'packages' , option ...
Show all packages .