idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
15,000
def cmdloop ( self , intro = None ) : self . preloop ( ) # Set up completion with readline. if self . use_rawinput and self . completekey : try : import readline self . old_completer = readline . get_completer ( ) readline . set_completer ( self . complete ) readline . parse_and_bind ( self . completekey + ': complete' ) except ImportError : pass try : if intro is not None : self . intro = intro if self . intro : self . stdout . write ( str ( self . intro ) + "\n" ) stop = None while not stop : if self . cmdqueue : line = self . cmdqueue . pop ( 0 ) else : if self . use_rawinput : try : if sys . version_info [ 0 ] == 2 : line = raw_input ( self . prompt ) else : line = input ( self . prompt ) except EOFError : line = 'EOF' except KeyboardInterrupt : line = 'ctrlc' else : self . stdout . write ( self . prompt ) self . stdout . flush ( ) line = self . stdin . readline ( ) if not len ( line ) : line = 'EOF' else : line = line . rstrip ( '\r\n' ) line = self . precmd ( line ) stop = self . onecmd ( line ) stop = self . postcmd ( stop , line ) self . postloop ( ) finally : if self . use_rawinput and self . completekey : try : import readline readline . set_completer ( self . old_completer ) except ImportError : pass
Override the command loop to handle Ctrl - C .
362
10
15,001
def do_exit ( self , arg ) : if self . arm . is_connected ( ) : self . arm . disconnect ( ) print ( 'Bye!' ) return True
Exit the shell .
37
4
15,002
def do_ctrlc ( self , arg ) : print ( 'STOP' ) if self . arm . is_connected ( ) : self . arm . write ( 'STOP' )
Ctrl - C sends a STOP command to the arm .
40
11
15,003
def do_status ( self , arg ) : info = self . arm . get_info ( ) max_len = len ( max ( info . keys ( ) , key = len ) ) print ( self . style . theme ( '\nArm Status' ) ) for key , value in info . items ( ) : print ( self . style . help ( key . ljust ( max_len + 2 ) , str ( value ) ) ) print ( )
Print information about the arm .
96
6
15,004
def do_connect ( self , arg ) : if self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is already connected.' ) ) else : try : port = self . arm . connect ( ) print ( self . style . success ( 'Success: ' , 'Connected to \'{}\'.' . format ( port ) ) ) except r12 . ArmException as e : print ( self . style . error ( 'Error: ' , str ( e ) ) )
Connect to the arm .
112
5
15,005
def do_disconnect ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is already disconnected.' ) ) else : self . arm . disconnect ( ) print ( self . style . success ( 'Success: ' , 'Disconnected.' ) )
Disconnect from the arm .
72
6
15,006
def do_run ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is not connected.' ) ) return # Load the script. try : with open ( arg ) as f : lines = [ line . strip ( ) for line in f . readlines ( ) ] except IOError : print ( self . style . error ( 'Error: ' , 'Could not load file \'{}\'.' . format ( arg ) ) ) return for line in lines : if self . wrapper : line = self . wrapper . wrap_input ( line ) self . arm . write ( line ) res = self . arm . read ( ) if self . wrapper : res = self . wrapper . wrap_output ( res ) print ( res )
Load and run an external FORTH script .
172
9
15,007
def do_dump ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is not connected.' ) ) return print ( self . arm . dump ( ) )
Output all bytes waiting in output queue .
54
8
15,008
def complete_run ( self , text , line , b , e ) : # Don't break on path separators. text = line . split ( ) [ - 1 ] # Try to find files with a forth file ending, .fs. forth_files = glob . glob ( text + '*.fs' ) # Failing that, just try and complete something. if len ( forth_files ) == 0 : return [ f . split ( os . path . sep ) [ - 1 ] for f in glob . glob ( text + '*' ) ] forth_files = [ f . split ( os . path . sep ) [ - 1 ] for f in forth_files ] return forth_files
Autocomplete file names with . forth ending .
146
10
15,009
def get_names ( self ) : # Overridden to support autocompletion for the ROBOFORTH commands. return ( [ 'do_' + x for x in self . commands [ 'shell' ] ] + [ 'do_' + x for x in self . commands [ 'forth' ] ] )
Get names for autocompletion .
66
7
15,010
def parse_help_text ( self , file_path ) : with open ( file_path ) as f : lines = f . readlines ( ) # Parse commands and descriptions, which are separated by a multi-space # (any sequence of two or more space characters in a row. cmds = [ ] descs = [ ] for line in lines : line = line . strip ( ) if len ( line ) == 0 : cmds . append ( '' ) descs . append ( '' ) else : tokens = line . split ( ' ' ) cmds . append ( tokens [ 0 ] ) descs . append ( '' . join ( tokens [ 1 : ] ) . strip ( ) ) max_len = len ( max ( cmds , key = len ) ) # Convert commands and descriptions into help text. text = '' for cmd , desc in zip ( cmds , descs ) : if len ( cmd ) == 0 : text += '\n' else : text += self . style . help ( cmd . ljust ( max_len + 2 ) , desc + '\n' ) return cmds , text
Load of list of commands and descriptions from a file .
236
11
15,011
def load_forth_commands ( self , help_dir ) : try : help_file_path = os . path . join ( help_dir , 'roboforth.txt' ) commands , help_text = self . parse_help_text ( help_file_path ) except IOError : print ( self . style . warn ( 'Warning: ' , 'Failed to load ROBOFORTH help.' ) ) return self . commands [ 'forth' ] = commands self . help [ 'forth' ] = '\n' . join ( [ self . style . theme ( 'Forth Commands' ) , help_text ] )
Load completion list for ROBOFORTH commands .
137
10
15,012
def preloop ( self ) : script_dir = os . path . dirname ( os . path . realpath ( __file__ ) ) help_dir = os . path . join ( script_dir , HELP_DIR_NAME ) self . load_forth_commands ( help_dir ) self . load_shell_commands ( help_dir )
Executed before the command loop starts .
76
8
15,013
def bootstrap_legislative_office ( self , election ) : body = election . race . office . body body_division = election . race . office . body . jurisdiction . division office_division = election . race . office . division self . bootstrap_federal_body_type_page ( election ) self . bootstrap_state_body_type_page ( election ) PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( body ) , object_id = body . pk , election_day = election . election_day , division = body_division , ) # Senate seats if office_division . level . name == DivisionLevel . STATE : PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( office_division ) , object_id = office_division . pk , election_day = election . election_day , special_election = False , ) # House seats elif office_division . level . name == DivisionLevel . DISTRICT : PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( office_division . parent ) , object_id = office_division . parent . pk , election_day = election . election_day , special_election = False , ) # Generic state pages, type and content page_type , created = PageType . objects . get_or_create ( model_type = ContentType . objects . get ( app_label = "geography" , model = "division" ) , election_day = election . election_day , division_level = DivisionLevel . objects . get ( name = DivisionLevel . STATE ) , ) PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( page_type ) , object_id = page_type . pk , election_day = election . election_day , )
For legislative offices create page content for the legislative Body the Office belongs to AND the state - level Division .
428
21
15,014
def cmd ( send , msg , args ) : latest = get_latest ( ) if not msg : msg = randrange ( 1 , latest ) elif msg == 'latest' : msg = latest elif msg . isdigit ( ) : msg = int ( msg ) if msg > latest or msg < 1 : send ( "Number out of range" ) return else : send ( do_search ( msg , args [ 'config' ] [ 'api' ] [ 'googleapikey' ] , args [ 'config' ] [ 'api' ] [ 'xkcdsearchid' ] ) ) return url = 'http://xkcd.com/%d/info.0.json' % msg if msg != 'latest' else 'http://xkcd.com/info.0.json' data = get ( url ) . json ( ) output = "%s -- http://xkcd.com/%d" % ( data [ 'safe_title' ] , data [ 'num' ] ) send ( output )
Gets a xkcd comic .
220
8
15,015
def generate_config_parser ( config , include_all = False ) : # The allow_no_value allows us to output commented lines. config_parser = SafeConfigParser ( allow_no_value = True ) for section_name , option_name in _get_included_schema_sections_options ( config , include_all ) : if not config_parser . has_section ( section_name ) : config_parser . add_section ( section_name ) option = config [ section_name ] [ option_name ] if option . get ( 'required' ) : config_parser . set ( section_name , '# REQUIRED' ) config_parser . set ( section_name , '# ' + option . get ( 'description' , 'No description provided.' ) ) if option . get ( 'deprecated' ) : config_parser . set ( section_name , '# DEPRECATED' ) option_value = _get_value ( option ) config_parser . set ( section_name , option_name , option_value ) config_parser . set ( section_name , '' ) return config_parser
Generates a config parser from a configuration dictionary .
245
10
15,016
def generate_documentation ( schema ) : documentation_title = "Configuration documentation" documentation = documentation_title + "\n" documentation += "=" * len ( documentation_title ) + '\n' for section_name in schema : section_created = False for option_name in schema [ section_name ] : option = schema [ section_name ] [ option_name ] if not section_created : documentation += '\n' documentation += section_name + '\n' documentation += '-' * len ( section_name ) + '\n' section_created = True documentation += '\n' documentation += option_name + '\n' documentation += '~' * len ( option_name ) + '\n' if option . get ( 'required' ) : documentation += "** This option is required! **\n" if option . get ( 'type' ) : documentation += '*Type : %s.*\n' % option . get ( 'type' ) if option . get ( 'description' ) : documentation += option . get ( 'description' ) + '\n' if option . get ( 'default' ) : documentation += 'The default value is %s.\n' % option . get ( 'default' ) if option . get ( 'deprecated' ) : documentation += "** This option is deprecated! **\n" return documentation
Generates reStructuredText documentation from a Confirm file .
292
13
15,017
def append_existing_values ( schema , config ) : for section_name in config : for option_name in config [ section_name ] : option_value = config [ section_name ] [ option_name ] # Note that we must preserve existing values, wether or not they # exist in the schema file! schema . setdefault ( section_name , { } ) . setdefault ( option_name , { } ) [ 'value' ] = option_value return schema
Adds the values of the existing config to the config dictionary .
101
12
15,018
def generate_schema_file ( config_file ) : config = utils . load_config_from_ini_file ( config_file ) schema = { } for section_name in config : for option_name in config [ section_name ] : schema . setdefault ( section_name , { } ) . setdefault ( option_name , { } ) schema [ section_name ] [ option_name ] [ 'description' ] = 'No description provided.' return utils . dump_schema_file ( schema )
Generates a basic confirm schema file from a configuration file .
113
12
15,019
def rankwithlist ( l , lwith , test = False ) : if not ( isinstance ( l , list ) and isinstance ( lwith , list ) ) : l , lwith = list ( l ) , list ( lwith ) from scipy . stats import rankdata if test : print ( l , lwith ) print ( rankdata ( l ) , rankdata ( lwith ) ) print ( rankdata ( l + lwith ) ) return rankdata ( l + lwith ) [ : len ( l ) ]
rank l wrt lwith
112
6
15,020
def dfbool2intervals ( df , colbool ) : df . index = range ( len ( df ) ) intervals = bools2intervals ( df [ colbool ] ) for intervali , interval in enumerate ( intervals ) : df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval id' ] = intervali df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval start' ] = interval [ 0 ] df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval stop' ] = interval [ 1 ] df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval length' ] = interval [ 1 ] - interval [ 0 ] + 1 df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval within index' ] = range ( interval [ 1 ] - interval [ 0 ] + 1 ) df [ f'{colbool} interval index' ] = df . index return df
ds contains bool values
230
4
15,021
def normalize_kind ( self , kindlike ) : if kindlike is None : return ( object , ) elif isinstance ( kindlike , type ) : return ( kindlike , ) else : return tuple ( kindlike )
Make a kind out of a possible shorthand . If the given argument is a sequence of types or a singular type it becomes a kind that accepts exactly those types . If the given argument is None it becomes a type that accepts anything .
48
46
15,022
def str_kind ( self , kind ) : if len ( kind ) == 0 : return 'Nothing' elif len ( kind ) == 1 : return kind [ 0 ] . __name__ elif len ( kind ) == 2 : return kind [ 0 ] . __name__ + ' or ' + kind [ 1 ] . __name__ else : return 'one of {' + ', ' . join ( t . __name__ for t in kind ) + '}'
Get a string describing a kind .
99
7
15,023
def checktype ( self , val , kind , * * kargs ) : if not isinstance ( val , kind ) : raise TypeError ( 'Expected {}; got {}' . format ( self . str_kind ( kind ) , self . str_valtype ( val ) ) )
Raise TypeError if val does not satisfy kind .
61
11
15,024
def raises ( cls , sender , attrname , error , args = ANYTHING , kwargs = ANYTHING ) : def raise_error ( ) : raise error return cls ( sender , attrname , returns = Invoke ( raise_error ) , args = ANYTHING , kwargs = ANYTHING )
An alternative constructor which raises the given error
68
8
15,025
def and_raises ( self , * errors ) : for error in errors : self . __expect ( Expectation . raises , error )
Expects an error or more to be raised from the given expectation .
30
14
15,026
def and_calls ( self , * funcs ) : for fn in funcs : self . __expect ( Expectation , Invoke ( fn ) )
Expects the return value from one or more functions to be raised from the given expectation .
34
18
15,027
def and_yields ( self , * values ) : def generator ( ) : for value in values : yield value self . __expect ( Expectation , Invoke ( generator ) )
Expects the return value of the expectation to be a generator of the given values
40
16
15,028
def attribute_invoked ( self , sender , name , args , kwargs ) : return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , '__call__' ) ( * args , * * kwargs )
Handles the creation of ExpectationBuilder when an attribute is invoked .
63
14
15,029
def attribute_read ( self , sender , name ) : return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , name )
Handles the creation of ExpectationBuilder when an attribute is read .
42
14
15,030
def key_read ( self , sender , name ) : return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , '__getitem__' ) ( name )
Handles the creation of ExpectationBuilder when a dictionary item access .
50
14
15,031
def friendly_load ( parser , token ) : bits = token . contents . split ( ) if len ( bits ) >= 4 and bits [ - 2 ] == "from" : # from syntax is used; load individual tags from the library name = bits [ - 1 ] try : lib = find_library ( parser , name ) subset = load_from_library ( lib , name , bits [ 1 : - 2 ] ) parser . add_library ( subset ) except TemplateSyntaxError : pass else : # one or more libraries are specified; load and add them to the parser for name in bits [ 1 : ] : try : lib = find_library ( parser , name ) parser . add_library ( lib ) except TemplateSyntaxError : pass return LoadNode ( )
Tries to load a custom template tag set . Non existing tag libraries are ignored .
161
17
15,032
def off ( self ) : self . win . keypad ( 0 ) curses . nocbreak ( ) curses . echo ( ) try : curses . curs_set ( 1 ) except : pass curses . endwin ( )
Turn off curses
46
3
15,033
def _move_agent ( self , agent , direction , wrap_allowed = True ) : x , y = agent . coords [ 'x' ] , agent . coords [ 'y' ] print ( 'moving agent ' , agent . name , 'to x,y=' , direction , 'wrap_allowed = ' , wrap_allowed ) agent . coords [ 'x' ] = x + direction [ 0 ] agent . coords [ 'y' ] = y + direction [ 1 ]
moves agent agent in direction
105
6
15,034
def key_func ( * keys , * * kwargs ) : ensure_argcount ( keys , min_ = 1 ) ensure_keyword_args ( kwargs , optional = ( 'default' , ) ) keys = list ( map ( ensure_string , keys ) ) if 'default' in kwargs : default = kwargs [ 'default' ] def getitems ( obj ) : for key in keys : try : obj = obj [ key ] except KeyError : return default return obj else : if len ( keys ) == 1 : getitems = operator . itemgetter ( keys [ 0 ] ) else : def getitems ( obj ) : for key in keys : obj = obj [ key ] return obj return getitems
Creates a key function based on given keys .
156
10
15,035
def find_files ( path , patterns ) : if not isinstance ( patterns , ( list , tuple ) ) : patterns = [ patterns ] matches = [ ] for root , dirnames , filenames in os . walk ( path ) : for pattern in patterns : for filename in fnmatch . filter ( filenames , pattern ) : matches . append ( os . path . join ( root , filename ) ) return matches
Returns all files from a given path that matches the pattern or list of patterns
87
15
15,036
def recursive_update ( _dict , _update ) : for k , v in _update . items ( ) : if isinstance ( v , collections . Mapping ) : r = recursive_update ( _dict . get ( k , { } ) , v ) _dict [ k ] = r else : _dict [ k ] = _update [ k ] return _dict
Same as dict . update but updates also nested dicts instead of overriding then
78
15
15,037
def validate ( self , value ) : if not self . blank and value == '' : self . error_message = 'Can not be empty. Please provide a value.' return False self . _choice = value return True
The most basic validation
45
4
15,038
def validate ( self , value ) : if '.' not in value : self . error_message = '%s is not a fully qualified domain name.' % value return False try : ipaddress = socket . gethostbyname ( value ) except socket . gaierror : self . error_message = '%s does not resolve.' % value return False try : socket . gethostbyaddr ( ipaddress ) except socket . herror : self . error_message = '%s reverse address (%s) does not resolve.' % ( value , ipaddress ) return False self . _choice = value return True
Attempts a forward lookup via the socket library and if successful will try to do a reverse lookup to verify DNS is returning both lookups .
127
27
15,039
def validate ( self , value ) : try : self . _choice = IPAddress ( value ) return True except ( ValueError , AddrFormatError ) : self . error_message = '%s is not a valid IP address.' % value return False
Return a boolean if the value is valid
54
8
15,040
def validate ( self , value ) : try : self . _choice = IPAddress ( value ) except ( ValueError , AddrFormatError ) : self . error_message = '%s is not a valid IP address.' % value return False if self . _choice . is_netmask ( ) : return True else : self . error_message = '%s is not a valid IP netmask.' % value return False
Return a boolean if the value is a valid netmask .
90
12
15,041
def validate ( self , value ) : if self . blank and value == '' : return True if URIValidator . uri_regex . match ( value ) : self . _choice = value return True else : self . error_message = '%s is not a valid URI' % value return False
Return a boolean indicating if the value is a valid URI
65
11
15,042
def validate ( self , value ) : if value in list ( self . choices . keys ( ) ) : self . _choice = value return True try : self . _choice = list ( self . choices . keys ( ) ) [ int ( value ) ] return True except ( ValueError , IndexError ) : self . error_message = '%s is not a valid choice.' % value return False
Return a boolean if the choice is a number in the enumeration
83
13
15,043
def validate ( self , value ) : try : int_value = int ( value ) self . _choice = int_value return True except ValueError : self . error_message = '%s is not a valid integer.' % value return False
Return True if the choice is an integer ; False otherwise .
51
12
15,044
def main ( ) : e = mod_env . Internet ( 'VAIS - Load testing' , 'Simulation of several websites' ) e . create ( 800 ) print ( e ) #Create some users to browse the web and load test website print ( npc . web_users . params )
generates a virtual internet sets pages and runs web_users on it
62
14
15,045
def create ( project , skel ) : app = project_name ( project ) header ( "Create New Project ..." ) print ( "- Project: %s " % app ) create_project ( app , skel ) print ( "" ) print ( "----- That's Juicy! ----" ) print ( "" ) print ( "- Your new project [ %s ] has been created" % app ) print ( "- Location: [ application/%s ]" % app ) print ( "" ) print ( "> What's next?" ) print ( "- Edit the config [ application/config.py ] " ) print ( "- If necessary edit and run the command [ juicy setup ]" ) print ( "- Launch app on devlopment mode, run [ juicy serve %s ]" % app ) print ( "" ) print ( "*" * 80 )
Create a new Project in the current directory
176
8
15,046
def deploy ( remote , assets_to_s3 ) : header ( "Deploying..." ) if assets_to_s3 : for mod in get_deploy_assets2s3_list ( CWD ) : _assets2s3 ( mod ) remote_name = remote or "ALL" print ( "Pushing application's content to remote: %s " % remote_name ) hosts = get_deploy_hosts_list ( CWD , remote or None ) git_push_to_master ( cwd = CWD , hosts = hosts , name = remote_name ) print ( "Done!" )
To DEPLOY your application
132
6
15,047
def write_relationships ( self , file_name , flat = True ) : with open ( file_name , 'w' ) as writer : if flat : self . _write_relationships_flat ( writer ) else : self . _write_relationships_non_flat ( writer )
This module will output the eDNA tags which are used inside each calculation .
62
15
15,048
def cmd ( send , msg , args ) : nickregex = args [ 'config' ] [ 'core' ] [ 'nickregex' ] setmode = args [ 'handler' ] . connection . mode channel = args [ 'target' ] with args [ 'handler' ] . data_lock : ops = args [ 'handler' ] . opers [ channel ] . copy ( ) if args [ 'botnick' ] not in ops : send ( "Bot must be an op." ) return time , user = msg . split ( maxsplit = 1 ) if user == args [ 'botnick' ] : send ( "I won't put myself in timeout!" ) return if not re . match ( nickregex , user ) : send ( "%s is an invalid nick." % user ) return time = parse_time ( time ) if time is None : send ( "Invalid unit." ) else : if args [ 'config' ] [ 'feature' ] [ 'networktype' ] == 'unrealircd' : setmode ( channel , " +b ~q:%s!*@*" % user ) defer_args = [ channel , " -b ~q:%s!*@*" % user ] elif args [ 'config' ] [ 'feature' ] [ 'networktype' ] == 'atheme' : setmode ( channel , " +q-v %s!*@* %s" % ( user , user ) ) defer_args = [ channel , " -q %s!*@*" % user ] else : raise Exception ( "networktype undefined or unknown in config.cfg" ) ident = args [ 'handler' ] . workers . defer ( time , True , setmode , * defer_args ) send ( "%s has been put in timeout, ident: %d" % ( user , ident ) )
Quiets a user then unquiets them after the specified period of time .
396
16
15,049
async def _update_config ( self ) : if self . config [ 'data' ] is None or self . config_expired : data = await self . get_data ( self . url_builder ( 'configuration' ) ) self . config = dict ( data = data , last_update = datetime . now ( ) )
Update configuration data if required .
72
6
15,050
async def find_movie ( self , query ) : params = OrderedDict ( [ ( 'query' , query ) , ( 'include_adult' , False ) , ] ) url = self . url_builder ( 'search/movie' , { } , params ) data = await self . get_data ( url ) if data is None : return return [ Movie . from_json ( item , self . config [ 'data' ] . get ( 'images' ) ) for item in data . get ( 'results' , [ ] ) ]
Retrieve movie data by search query .
117
8
15,051
async def find_person ( self , query ) : url = self . url_builder ( 'search/person' , dict ( ) , url_params = OrderedDict ( [ ( 'query' , query ) , ( 'include_adult' , False ) ] ) , ) data = await self . get_data ( url ) if data is None : return return [ Person . from_json ( item , self . config [ 'data' ] . get ( 'images' ) ) for item in data . get ( 'results' , [ ] ) ]
Retrieve person data by search query .
119
8
15,052
async def get_movie ( self , id_ ) : url = self . url_builder ( 'movie/{movie_id}' , dict ( movie_id = id_ ) , url_params = OrderedDict ( append_to_response = 'credits' ) , ) data = await self . get_data ( url ) if data is None : return return Movie . from_json ( data , self . config [ 'data' ] . get ( 'images' ) )
Retrieve movie data by ID .
105
7
15,053
async def get_person ( self , id_ ) : data = await self . _get_person_json ( id_ , OrderedDict ( append_to_response = 'movie_credits' ) ) return Person . from_json ( data , self . config [ 'data' ] . get ( 'images' ) )
Retrieve person data by ID .
72
7
15,054
async def _get_person_json ( self , id_ , url_params = None ) : url = self . url_builder ( 'person/{person_id}' , dict ( person_id = id_ ) , url_params = url_params or OrderedDict ( ) , ) data = await self . get_data ( url ) return data
Retrieve raw person JSON by ID .
79
8
15,055
async def get_random_popular_person ( self , limit = 500 ) : index = random . randrange ( limit ) data = await self . _get_popular_people_page ( ) if data is None : return if index >= len ( data [ 'results' ] ) : # result is not on first page page , index = self . _calculate_page_index ( index , data ) data = await self . _get_popular_people_page ( page ) if data is None : return json_data = data [ 'results' ] [ index ] details = await self . _get_person_json ( json_data [ 'id' ] ) details . update ( * * json_data ) return Person . from_json ( details , self . config [ 'data' ] . get ( 'images' ) )
Randomly select a popular person .
178
7
15,056
async def _get_popular_people_page ( self , page = 1 ) : return await self . get_data ( self . url_builder ( 'person/popular' , url_params = OrderedDict ( page = page ) , ) )
Get a specific page of popular person data .
55
9
15,057
def _calculate_page_index ( index , data ) : if index > data [ 'total_results' ] : raise ValueError ( 'index not in paged data' ) page_length = len ( data [ 'results' ] ) return ( index // page_length ) + 1 , ( index % page_length ) - 1
Determine the location of a given index in paged data .
73
14
15,058
def cmd ( send , msg , args ) : if not msg : send ( "NATO what?" ) return nato = gen_nato ( msg ) if len ( nato ) > 100 : send ( "Your NATO is too long. Have you considered letters?" ) else : send ( nato )
Converts text into NATO form .
64
7
15,059
def cmd ( send , msg , _ ) : bold = '\x02' if not msg : msg = bold + "Date: " + bold + "%A, %m/%d/%Y" + bold + " Time: " + bold + "%H:%M:%S" send ( time . strftime ( msg ) )
Tells the time .
73
5
15,060
def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--channel' , nargs = '?' , action = arguments . ChanParser ) parser . add_argument ( 'nick' , nargs = '?' , action = arguments . NickParser , default = args [ 'nick' ] ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if args [ 'target' ] == 'private' : send ( "You're always the highlight of your monologues!" ) return target = cmdargs . channels [ 0 ] if hasattr ( cmdargs , 'channels' ) else args [ 'target' ] row = args [ 'db' ] . query ( Log ) . filter ( Log . msg . ilike ( "%%%s%%" % cmdargs . nick ) , ~ Log . msg . contains ( '%shighlight' % args [ 'config' ] [ 'core' ] [ 'cmdchar' ] ) , Log . target == target , Log . source != args [ 'botnick' ] , Log . source != cmdargs . nick , ( Log . type == 'pubmsg' ) | ( Log . type == 'privmsg' ) | ( Log . type == 'action' ) ) . order_by ( Log . time . desc ( ) ) . first ( ) if row is None : send ( "%s has never been pinged." % cmdargs . nick ) else : time = row . time . strftime ( '%Y-%m-%d %H:%M:%S' ) send ( "%s <%s> %s" % ( time , row . source , row . msg ) )
When a nick was last pinged .
385
8
15,061
def output_traceback ( ex ) : # Dump full traceback to console. output = "" . join ( traceback . format_exc ( ) ) . strip ( ) for line in output . split ( '\n' ) : logging . error ( line ) trace_obj = traceback . extract_tb ( ex . __traceback__ ) [ - 1 ] trace = [ basename ( trace_obj [ 0 ] ) , trace_obj [ 1 ] ] name = type ( ex ) . __name__ output = str ( ex ) . replace ( '\n' , ' ' ) msg = "%s in %s on line %s: %s" % ( name , trace [ 0 ] , trace [ 1 ] , output ) return ( msg , output )
Returns a tuple of a prettyprinted error message and string representation of the error .
164
16
15,062
def release ( no_master , release_type ) : try : locale . setlocale ( locale . LC_ALL , '' ) except : print ( "Warning: Unable to set locale. Expect encoding problems." ) git . is_repo_clean ( master = ( not no_master ) ) config = utils . get_config ( ) config . update ( utils . get_dist_metadata ( ) ) config [ 'project_dir' ] = Path ( os . getcwd ( ) ) config [ 'release_type' ] = release_type with tempfile . TemporaryDirectory ( prefix = 'ap_tmp' ) as tmp_dir : config [ 'tmp_dir' ] = tmp_dir values = release_ui ( config ) if type ( values ) is not str : utils . release ( project_name = config [ 'project_name' ] , tmp_dir = tmp_dir , project_dir = config [ 'project_dir' ] , pypi_servers = config [ 'pypi_servers' ] , * * values ) print ( 'New release options:' ) pprint . pprint ( values ) else : print ( values )
Releases a new version
252
5
15,063
def _set_types ( self ) : # If we given something that is not an int or a float we raise # a RuntimeError as we do not want to have to guess if the given # input should be interpreted as an int or a float, for example the # interpretation of the string "1" vs the interpretation of the string # "1.0". for c in ( self . x , self . y ) : if not ( isinstance ( c , int ) or isinstance ( c , float ) ) : raise ( RuntimeError ( 'x, y coords should be int or float' ) ) if isinstance ( self . x , int ) and isinstance ( self . y , int ) : self . _dtype = "int" else : # At least one value is a float so promote both to float. self . x = float ( self . x ) self . y = float ( self . y ) self . _dtype = "float"
Make sure that x y have consistent types and set dtype .
202
13
15,064
def magnitude ( self ) : return math . sqrt ( self . x * self . x + self . y * self . y )
Return the magnitude when treating the point as a vector .
28
11
15,065
def unit_vector ( self ) : return Point2D ( self . x / self . magnitude , self . y / self . magnitude )
Return the unit vector .
29
5
15,066
def astype ( self , dtype ) : if dtype == "int" : return Point2D ( int ( round ( self . x , 0 ) ) , int ( round ( self . y , 0 ) ) ) elif dtype == "float" : return Point2D ( float ( self . x ) , float ( self . y ) ) else : raise ( RuntimeError ( "Invalid dtype: {}" . format ( dtype ) ) )
Return a point of the specified dtype .
97
9
15,067
def free ( self , local_path ) : # Process local ~~~ # 1. Syncthing config config = self . get_config ( ) # Check whether folders are still connected to this device folder = st_util . find_folder_with_path ( local_path , config ) self . delete_folder ( local_path , config ) pruned = st_util . prune_devices ( folder , config ) # Done processing st config, commit :) self . set_config ( config ) if pruned : self . restart ( ) # 2. App config dir_config = self . adapter . get_dir_config ( local_path ) if not dir_config : raise custom_errors . FileNotInConfig ( local_path ) kodrive_config = self . adapter . get_config ( ) for key in kodrive_config [ 'directories' ] : d = kodrive_config [ 'directories' ] [ key ] if d [ 'local_path' ] . rstrip ( '/' ) == local_path . rstrip ( '/' ) : del kodrive_config [ 'directories' ] [ key ] break # Done process app config, commit :) self . adapter . set_config ( kodrive_config ) # If the folder was shared, try remove data from remote if dir_config [ 'is_shared' ] and dir_config [ 'server' ] : # Process remote ~~~ r_api_key = dir_config [ 'api_key' ] r_device_id = dir_config [ 'device_id' ] if dir_config [ 'host' ] : host = dir_config [ 'host' ] else : host = self . devid_to_ip ( r_device_id , False ) try : # Create remote proxy to interact with remote remote = SyncthingProxy ( r_device_id , host , r_api_key , port = dir_config [ 'port' ] if 'port' in dir_config else None ) except Exception as e : return True r_config = remote . get_config ( ) r_folder = st_util . find_folder_with_path ( dir_config [ 'remote_path' ] , r_config ) # Delete device id from folder r_config = remote . get_config ( ) self_devid = self . get_device_id ( ) del_device = remote . delete_device_from_folder ( dir_config [ 'remote_path' ] , self_devid , r_config ) # Check to see if no other folder depends has this device pruned = st_util . prune_devices ( r_folder , r_config ) remote . set_config ( r_config ) if pruned : remote . restart ( ) return True
Stop synchronization of local_path
601
6
15,068
def tag ( self , path , name ) : if not path [ len ( path ) - 1 ] == '/' : path += '/' config = self . get_config ( ) folder = self . find_folder ( { 'path' : path } , config ) if not folder : raise custom_errors . FileNotInConfig ( path ) old_name = folder [ 'label' ] folder [ 'label' ] = name dir_config = self . adapter . get_dir_config ( path ) dir_config [ 'label' ] = name self . adapter . set_dir_config ( dir_config ) self . set_config ( config ) # self.restart return old_name
Change name associated with path
147
5
15,069
def cmd ( send , _ , args ) : with args [ 'handler' ] . data_lock : channels = ", " . join ( sorted ( args [ 'handler' ] . channels ) ) send ( channels )
Returns a listing of the current channels .
45
8
15,070
def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'stock' , nargs = '?' , default = random_stock ( ) ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return send ( gen_stock ( cmdargs . stock ) )
Gets a stock quote .
89
6
15,071
def get_elections ( self , obj ) : election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] ) elections = list ( obj . elections . filter ( election_day = election_day ) ) district = DivisionLevel . objects . get ( name = DivisionLevel . DISTRICT ) for district in obj . children . filter ( level = district ) : elections . extend ( list ( district . elections . filter ( election_day = election_day , meta__isnull = False ) ) ) return ElectionSerializer ( elections , many = True ) . data
All elections in division .
126
5
15,072
def get_content ( self , obj ) : election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] ) division = obj # In case of house special election, # use parent division. if obj . level . name == DivisionLevel . DISTRICT : division = obj . parent special = True if self . context . get ( 'special' ) else False return PageContent . objects . division_content ( election_day , division , special )
All content for a state s page on an election day .
101
12
15,073
def bootstrap_executive_office ( self , election ) : division = election . race . office . jurisdiction . division content_type = ContentType . objects . get_for_model ( election . race . office ) PageContent . objects . get_or_create ( content_type = content_type , object_id = election . race . office . pk , election_day = election . election_day , division = division , ) if division . level == self . NATIONAL_LEVEL : self . bootstrap_executive_office_states ( election ) else : # Create state governor page type page_type , created = PageType . objects . get_or_create ( model_type = ContentType . objects . get ( app_label = "government" , model = "office" ) , election_day = election . election_day , division_level = self . STATE_LEVEL , ) PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( page_type ) , object_id = page_type . pk , election_day = election . election_day , ) generic_state_page_type , created = PageType . objects . get_or_create ( model_type = ContentType . objects . get ( app_label = "geography" , model = "division" ) , election_day = election . election_day , division_level = DivisionLevel . objects . get ( name = DivisionLevel . STATE ) , ) PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( generic_state_page_type ) , object_id = generic_state_page_type . pk , election_day = election . election_day , ) PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( division ) , object_id = division . pk , election_day = election . election_day , special_election = False , )
For executive offices create page content for the office .
440
10
15,074
def cmd ( send , msg , args ) : req = get ( 'http://www.imdb.com/random/title' ) html = fromstring ( req . text ) name = html . find ( 'head/title' ) . text . split ( '-' ) [ 0 ] . strip ( ) key = args [ 'config' ] [ 'api' ] [ 'bitlykey' ] send ( "%s -- %s" % ( name , get_short ( req . url , key ) ) )
Gets a random movie .
109
6
15,075
def get ( number , locale ) : if locale == 'pt_BR' : # temporary set a locale for brazilian locale = 'xbr' if len ( locale ) > 3 : locale = locale . split ( "_" ) [ 0 ] rule = PluralizationRules . _rules . get ( locale , lambda _ : 0 ) _return = rule ( number ) if not isinstance ( _return , int ) or _return < 0 : return 0 return _return
Returns the plural position to use for the given locale and number .
99
13
15,076
def set ( rule , locale ) : if locale == 'pt_BR' : # temporary set a locale for brazilian locale = 'xbr' if len ( locale ) > 3 : locale = locale . split ( "_" ) [ 0 ] if not hasattr ( rule , '__call__' ) : raise ValueError ( 'The given rule can not be called' ) PluralizationRules . _rules [ locale ] = rule
Overrides the default plural rule for a given locale .
92
12
15,077
def cmd ( send , msg , _ ) : if not msg : send ( "What acronym?" ) return words = get_list ( ) letters = [ c for c in msg . lower ( ) if c in string . ascii_lowercase ] output = " " . join ( [ choice ( words [ c ] ) for c in letters ] ) if output : send ( '%s: %s' % ( msg , output . title ( ) ) ) else : send ( "No acronym found for %s" % msg )
Generates a meaning for the specified acronym .
112
9
15,078
def get_boundargs ( cls , * args , * * kargs ) : boundargs = cls . _signature . bind ( * args , * * kargs ) # Include default arguments. for param in cls . _signature . parameters . values ( ) : if ( param . name not in boundargs . arguments and param . default is not param . empty ) : boundargs . arguments [ param . name ] = param . default return boundargs
Return an inspect . BoundArguments object for the application of this Struct s signature to its arguments . Add missing values for default fields as keyword arguments .
97
30
15,079
def _asdict ( self ) : return OrderedDict ( ( f . name , getattr ( self , f . name ) ) for f in self . _struct )
Return an OrderedDict of the fields .
37
10
15,080
def _replace ( self , * * kargs ) : fields = { f . name : getattr ( self , f . name ) for f in self . _struct } fields . update ( kargs ) return type ( self ) ( * * fields )
Return a copy of this Struct with the same fields except with the changes specified by kargs .
53
19
15,081
def get_one ( self , qry , tpl ) : self . cur . execute ( qry + ' LIMIT 1' , tpl ) result = self . cur . fetchone ( ) # unpack tuple if it has only # one element # TODO unpack results if type ( result ) is tuple and len ( result ) == 1 : result = result [ 0 ] return result
get a single from from a query limit 1 is automatically added
82
12
15,082
def get_all ( self , qry , tpl ) : self . cur . execute ( qry , tpl ) result = self . cur . fetchall ( ) return result
get all rows for a query
38
6
15,083
def set_level ( level ) : Logger . level = level for logger in Logger . loggers . values ( ) : logger . setLevel ( level )
Set level of logging for all loggers .
34
9
15,084
def get_logger ( name , level = None , fmt = ':%(lineno)d: %(message)s' ) : if name not in Logger . loggers : if Logger . level is None and level is None : Logger . level = level = logging . ERROR elif Logger . level is None : Logger . level = level elif level is None : level = Logger . level logger = logging . getLogger ( name ) logger_handler = logging . StreamHandler ( ) logger_handler . setFormatter ( LoggingFormatter ( fmt = name + fmt ) ) logger . addHandler ( logger_handler ) logger . setLevel ( level ) Logger . loggers [ name ] = logger return Logger . loggers [ name ]
Return a logger .
165
4
15,085
def format ( self , record ) : if record . levelno == logging . DEBUG : string = Back . WHITE + Fore . BLACK + ' debug ' elif record . levelno == logging . INFO : string = Back . BLUE + Fore . WHITE + ' info ' elif record . levelno == logging . WARNING : string = Back . YELLOW + Fore . BLACK + ' warning ' elif record . levelno == logging . ERROR : string = Back . RED + Fore . WHITE + ' error ' elif record . levelno == logging . CRITICAL : string = Back . BLACK + Fore . WHITE + ' critical ' else : string = '' return '{none}{string}{none} {super}' . format ( none = Style . RESET_ALL , string = string , super = super ( ) . format ( record ) )
Override default format method .
177
5
15,086
def log ( self , source : str , target : str , flags : int , msg : str , mtype : str ) -> None : entry = Log ( source = str ( source ) , target = target , flags = flags , msg = msg , type = mtype , time = datetime . now ( ) ) with self . session_scope ( ) as session : session . add ( entry ) session . flush ( )
Logs a message to the database .
88
8
15,087
def get_domains ( self ) : if self . domains is None : self . domains = list ( set ( self . source . get_domains ( ) + self . target . get_domains ( ) ) ) return self . domains
Returns domains affected by operation .
51
6
15,088
def get_messages ( self , domain ) : if domain not in self . domains : raise ValueError ( 'Invalid domain: {0}' . format ( domain ) ) if domain not in self . messages or 'all' not in self . messages [ domain ] : self . _process_domain ( domain ) return self . messages [ domain ] [ 'all' ]
Returns all valid messages after operation .
78
7
15,089
def get_new_messages ( self , domain ) : if domain not in self . domains : raise ValueError ( 'Invalid domain: {0}' . format ( domain ) ) if domain not in self . messages or 'new' not in self . messages [ domain ] : self . _process_domain ( domain ) return self . messages [ domain ] [ 'new' ]
Returns new valid messages after operation .
80
7
15,090
def get_obsolete_messages ( self , domain ) : if domain not in self . domains : raise ValueError ( 'Invalid domain: {0}' . format ( domain ) ) if domain not in self . messages or 'obsolete' not in self . messages [ domain ] : self . _process_domain ( domain ) return self . messages [ domain ] [ 'obsolete' ]
Returns obsolete valid messages after operation .
83
7
15,091
def get_result ( self ) : for domain in self . domains : if domain not in self . messages : self . _process_domain ( domain ) return self . result
Returns resulting catalogue
36
3
15,092
def setup_db ( session , botconfig , confdir ) : Base . metadata . create_all ( session . connection ( ) ) # If we're creating a fresh db, we don't need to worry about migrations. if not session . get_bind ( ) . has_table ( 'alembic_version' ) : conf_obj = config . Config ( ) conf_obj . set_main_option ( 'bot_config_path' , confdir ) with resources . path ( 'cslbot' , botconfig [ 'alembic' ] [ 'script_location' ] ) as script_location : conf_obj . set_main_option ( 'script_location' , str ( script_location ) ) command . stamp ( conf_obj , 'head' ) # Populate permissions table with owner. owner_nick = botconfig [ 'auth' ] [ 'owner' ] if not session . query ( Permissions ) . filter ( Permissions . nick == owner_nick ) . count ( ) : session . add ( Permissions ( nick = owner_nick , role = 'owner' ) )
Sets up the database .
238
6
15,093
def sumvalues ( self , q = 0 ) : if q == 0 : return self . _totalf else : return - np . partition ( - self . _freq_list , q ) [ : q ] . sum ( )
Sum of top q passowrd frequencies
50
8
15,094
def iterpws ( self , n ) : for _id in np . argsort ( self . _freq_list ) [ : : - 1 ] [ : n ] : pw = self . _T . restore_key ( _id ) if self . _min_pass_len <= len ( pw ) <= self . _max_pass_len : yield _id , pw , self . _freq_list [ _id ]
Returns passwords in order of their frequencies .
96
8
15,095
def cmd ( send , msg , args ) : if not msg : send ( "Need a CIDR range." ) return try : ipn = ip_network ( msg ) except ValueError : send ( "Not a valid CIDR range." ) return send ( "%s - %s" % ( ipn [ 0 ] , ipn [ - 1 ] ) )
Gets a CIDR range .
78
8
15,096
def get_environment_requirements_list ( ) : requirement_list = [ ] requirements = check_output ( [ sys . executable , '-m' , 'pip' , 'freeze' ] ) for requirement in requirements . split ( ) : requirement_list . append ( requirement . decode ( "utf-8" ) ) return requirement_list
Take the requirements list from the current running environment
75
9
15,097
def parse_requirements_list ( requirements_list ) : req_list = [ ] for requirement in requirements_list : requirement_no_comments = requirement . split ( '#' ) [ 0 ] . strip ( ) # if matching requirement line (Thing==1.2.3), update dict, continue req_match = re . match ( r'\s*(?P<package>[^\s\[\]]+)(?P<extras>\[\S+\])?==(?P<version>\S+)' , requirement_no_comments ) if req_match : req_list . append ( { 'package' : req_match . group ( 'package' ) , 'version' : req_match . group ( 'version' ) , } ) return req_list
Take a list and return a list of dicts with { package versions ) based on the requirements specs
174
20
15,098
def get_pypi_package_data ( package_name , version = None ) : pypi_url = 'https://pypi.org/pypi' if version : package_url = '%s/%s/%s/json' % ( pypi_url , package_name , version , ) else : package_url = '%s/%s/json' % ( pypi_url , package_name , ) try : response = requests . get ( package_url ) except requests . ConnectionError : raise RuntimeError ( 'Connection error!' ) # Package not available on pypi if not response . ok : return None return response . json ( )
Get package data from pypi by the package name
150
11
15,099
def __list_package_updates ( package_name , version ) : updates = get_package_update_list ( package_name , version ) if updates [ 'newer_releases' ] or updates [ 'pre_releases' ] : print ( '%s (%s)' % ( package_name , version ) ) __list_updates ( 'Major releases' , updates [ 'major_updates' ] ) __list_updates ( 'Minor releases' , updates [ 'minor_updates' ] ) __list_updates ( 'Patch releases' , updates [ 'patch_updates' ] ) __list_updates ( 'Pre releases' , updates [ 'pre_release_updates' ] ) __list_updates ( 'Unknown releases' , updates [ 'non_semantic_versions' ] ) print ( "___" )
Function used to list all package updates in console
187
9