idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
15,100
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
15,101
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 .
15,102
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
15,103
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
15,104
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 .
15,105
def main ( ) : e = mod_env . Internet ( 'VAIS - Load testing' , 'Simulation of several websites' ) e . create ( 800 ) print ( e ) print ( npc . web_users . params )
generates a virtual internet sets pages and runs web_users on it
15,106
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
15,107
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
15,108
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 .
15,109
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 .
15,110
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 .
15,111
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 .
15,112
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 .
15,113
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 .
15,114
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 .
15,115
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 .
15,116
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' ] ) : 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 .
15,117
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 .
15,118
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 .
15,119
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 .
15,120
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 .
15,121
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 .
15,122
def output_traceback ( ex ) : 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 .
15,123
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
15,124
def _set_types ( self ) : 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 : self . x = float ( self . x ) self . y = float ( self . y ) self . _dtype = "float"
Make sure that x y have consistent types and set dtype .
15,125
def magnitude ( self ) : return math . sqrt ( self . x * self . x + self . y * self . y )
Return the magnitude when treating the point as a vector .
15,126
def unit_vector ( self ) : return Point2D ( self . x / self . magnitude , self . y / self . magnitude )
Return the unit vector .
15,127
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 .
15,128
def free ( self , local_path ) : config = self . get_config ( ) folder = st_util . find_folder_with_path ( local_path , config ) self . delete_folder ( local_path , config ) pruned = st_util . prune_devices ( folder , config ) self . set_config ( config ) if pruned : self . restart ( ) 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 self . adapter . set_config ( kodrive_config ) if dir_config [ 'is_shared' ] and dir_config [ 'server' ] : 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 : 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 ) 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 ) 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
15,129
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 ) return old_name
Change name associated with path
15,130
def cmd ( send , _ , args ) : with args [ 'handler' ] . data_lock : channels = ", " . join ( sorted ( args [ 'handler' ] . channels ) ) send ( channels )
Returns a listing of the current channels .
15,131
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 .
15,132
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 .
15,133
def get_content ( self , obj ) : election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] ) division = obj 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 .
15,134
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 : 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 .
15,135
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 .
15,136
def get ( number , locale ) : if locale == 'pt_BR' : 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 .
15,137
def set ( rule , locale ) : if locale == 'pt_BR' : 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 .
15,138
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 .
15,139
def get_boundargs ( cls , * args , ** kargs ) : boundargs = cls . _signature . bind ( * args , ** kargs ) 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 .
15,140
def _asdict ( self ) : return OrderedDict ( ( f . name , getattr ( self , f . name ) ) for f in self . _struct )
Return an OrderedDict of the fields .
15,141
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 .
15,142
def get_one ( self , qry , tpl ) : self . cur . execute ( qry + ' LIMIT 1' , tpl ) result = self . cur . fetchone ( ) 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
15,143
def get_all ( self , qry , tpl ) : self . cur . execute ( qry , tpl ) result = self . cur . fetchall ( ) return result
get all rows for a query
15,144
def set_level ( level ) : Logger . level = level for logger in Logger . loggers . values ( ) : logger . setLevel ( level )
Set level of logging for all loggers .
15,145
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 .
15,146
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 .
15,147
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 .
15,148
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 .
15,149
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 .
15,150
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 .
15,151
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 .
15,152
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
15,153
def setup_db ( session , botconfig , confdir ) : Base . metadata . create_all ( session . connection ( ) ) 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' ) 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 .
15,154
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
15,155
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 .
15,156
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 .
15,157
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
15,158
def parse_requirements_list ( requirements_list ) : req_list = [ ] for requirement in requirements_list : requirement_no_comments = requirement . split ( '#' ) [ 0 ] . strip ( ) 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
15,159
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!' ) if not response . ok : return None return response . json ( )
Get package data from pypi by the package name
15,160
def get_package_update_list ( package_name , version ) : package_version = semantic_version . Version . coerce ( version ) package_data = get_pypi_package_data ( package_name ) version_data = get_pypi_package_data ( package_name , version ) current_release = '' current_release_license = '' latest_release = '' latest_release_license = '' major_updates = [ ] minor_updates = [ ] patch_updates = [ ] pre_releases = [ ] non_semantic_versions = [ ] if package_data : latest_release = package_data [ 'info' ] [ 'version' ] latest_release_license = package_data [ 'info' ] [ 'license' ] if package_data [ 'info' ] [ 'license' ] else '' for release , info in package_data [ 'releases' ] . items ( ) : parsed_release = parse ( release ) upload_time = None if info : upload_time = datetime . strptime ( info [ 0 ] [ 'upload_time' ] , "%Y-%m-%dT%H:%M:%S" ) try : release_version = semantic_version . Version . coerce ( release ) if not parsed_release . is_prerelease : if release_version in semantic_version . Spec ( ">=%s" % package_version . next_major ( ) ) : major_updates . append ( { 'version' : release , 'upload_time' : upload_time , } ) elif release_version in semantic_version . Spec ( ">=%s,<%s" % ( package_version . next_minor ( ) , package_version . next_major ( ) ) ) : minor_updates . append ( { 'version' : release , 'upload_time' : upload_time , } ) elif release_version in semantic_version . Spec ( ">=%s,<%s" % ( package_version . next_patch ( ) , package_version . next_minor ( ) ) ) : patch_updates . append ( { 'version' : release , 'upload_time' : upload_time , } ) else : pre_releases . append ( { 'version' : release , 'upload_time' : upload_time } ) except ValueError : non_semantic_versions . append ( { 'version' : release , 'upload_time' : upload_time } ) if version_data : current_release = version_data [ 'info' ] [ 'version' ] current_release_license = version_data [ 'info' ] [ 'license' ] if version_data [ 'info' ] [ 'license' ] else '' newer_releases = len ( major_updates + minor_updates + patch_updates ) return { 'current_release' : current_release , 'current_release_license' : current_release_license , 'latest_release' : latest_release , 'latest_release_license' : latest_release_license , 'newer_releases' : newer_releases , 'pre_releases' : len ( pre_releases ) , 'major_updates' : sorted ( major_updates , key = lambda x : semantic_version . Version . coerce ( x [ 'version' ] ) , reverse = True ) , 'minor_updates' : sorted ( minor_updates , key = lambda x : semantic_version . Version . coerce ( x [ 'version' ] ) , reverse = True ) , 'patch_updates' : sorted ( patch_updates , key = lambda x : semantic_version . Version . coerce ( x [ 'version' ] ) , reverse = True ) , 'pre_release_updates' : sorted ( pre_releases , key = lambda x : semantic_version . Version . coerce ( x [ 'version' ] ) , reverse = True ) , 'non_semantic_versions' : non_semantic_versions , }
Return update information of a package from a given version
15,161
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
15,162
def __list_updates ( update_type , update_list ) : if len ( update_list ) : print ( " %s:" % update_type ) for update_item in update_list : print ( " -- %(version)s on %(upload_time)s" % update_item )
Function used to list package updates by update type in console
15,163
def __updatable ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( 'file' , nargs = '?' , type = argparse . FileType ( ) , default = None , help = 'Requirements file' ) args = parser . parse_args ( ) if args . file : packages = parse_requirements_list ( args . file ) else : packages = get_parsed_environment_package_list ( ) for package in packages : __list_package_updates ( package [ 'package' ] , package [ 'version' ] )
Function used to output packages update information in the console
15,164
def handle ( send , msg , args ) : worker = args [ "handler" ] . workers result = worker . run_pool ( get_urls , [ msg ] ) try : urls = result . get ( 5 ) except multiprocessing . TimeoutError : worker . restart_pool ( ) send ( "Url regex timed out." , target = args [ "config" ] [ "core" ] [ "ctrlchan" ] ) return for url in urls : if ( args [ "db" ] . query ( Urls ) . filter ( Urls . url == url , Urls . time > datetime . now ( ) - timedelta ( seconds = 10 ) ) . count ( ) > 1 ) : return if url . startswith ( "https://twitter.com" ) : tid = url . split ( "/" ) [ - 1 ] twitter_api = get_api ( args [ "config" ] ) status = twitter_api . GetStatus ( tid ) text = status . text . replace ( "\n" , " / " ) send ( "** {} (@{}) on Twitter: {}" . format ( status . user . name , status . user . screen_name , text ) ) return imgkey = args [ "config" ] [ "api" ] [ "googleapikey" ] title = urlutils . get_title ( url , imgkey ) shortkey = args [ "config" ] [ "api" ] [ "bitlykey" ] short = urlutils . get_short ( url , shortkey ) last = args [ "db" ] . query ( Urls ) . filter ( Urls . url == url ) . order_by ( Urls . time . desc ( ) ) . first ( ) if args [ "config" ] [ "feature" ] . getboolean ( "linkread" ) : if last is not None : lasttime = last . time . strftime ( "%H:%M:%S on %Y-%m-%d" ) send ( "Url %s previously posted at %s by %s -- %s" % ( short , lasttime , last . nick , title ) ) else : send ( "** %s - %s" % ( title , short ) ) args [ "db" ] . add ( Urls ( url = url , title = title , nick = args [ "nick" ] , time = datetime . now ( ) ) )
Get titles for urls .
15,165
def page_location_template ( self ) : cycle = self . election_day . cycle . name model_class = self . model_type . model_class ( ) if model_class == ElectionDay : return "/{}/" . format ( cycle ) if model_class == Office : if self . jurisdiction : if self . division_level . name == DivisionLevel . STATE : return "/{}/president/{{state}}" . format ( cycle ) else : return "/{}/president/" . format ( cycle ) else : return "/{}/{{state}}/governor/" . format ( cycle ) elif model_class == Body : if self . body . slug == "senate" : if self . jurisdiction : if self . division_level . name == DivisionLevel . STATE : return "/{}/senate/{{state}}/" . format ( cycle ) else : return "/{}/senate/" . format ( cycle ) else : return "/{}/{{state}}/senate/" . format ( cycle ) else : if self . jurisdiction : if self . division_level . name == DivisionLevel . STATE : return "/{}/house/{{state}}/" . format ( cycle ) else : return "/{}/house/" . format ( cycle ) else : return "/{}/{{state}}/house/" . format ( cycle ) elif model_class == Division : return "/{}/{{state}}/" . format ( cycle ) else : return "ORPHAN TYPE"
Returns the published URL template for a page type .
15,166
def cmd ( send , msg , _ ) : if not msg : url = 'http://tjbash.org/random1.html' params = { } else : targs = msg . split ( ) if len ( targs ) == 1 and targs [ 0 ] . isnumeric ( ) : url = 'http://tjbash.org/%s' % targs [ 0 ] params = { } else : url = 'http://tjbash.org/search.html' params = { 'query' : 'tag:%s' % '+' . join ( targs ) } req = get ( url , params = params ) doc = fromstring ( req . text ) quotes = doc . find_class ( 'quote-body' ) if not quotes : send ( "There were no results." ) return quote = choice ( quotes ) lines = [ x . strip ( ) for x in map ( operator . methodcaller ( 'strip' ) , quote . itertext ( ) ) ] for line in lines [ : 4 ] : send ( line ) tags = quote . getparent ( ) . find_class ( 'quote-tags' ) postid = quote . getparent ( ) . getparent ( ) . get ( 'id' ) . replace ( 'quote-' , '' ) if tags : tags = [ x . text for x in tags [ 0 ] . findall ( './/a' ) ] send ( " -- {} -- {}http://tjbash.org/{}" . format ( ', ' . join ( tags ) , "continued: " if ( len ( lines ) > 3 ) else "" , postid ) ) else : send ( " -- http://tjbash.org/{}" . format ( postid ) )
Finds a random quote from tjbash . org given search criteria .
15,167
def get_queryset ( self ) : try : date = ElectionDay . objects . get ( date = self . kwargs [ 'date' ] ) except Exception : raise APIException ( 'No elections on {}.' . format ( self . kwargs [ 'date' ] ) ) body_ids = [ ] for election in date . elections . all ( ) : body = election . race . office . body if body : body_ids . append ( body . uid ) return Body . objects . filter ( uid__in = body_ids )
Returns a queryset of all bodies holding an election on a date .
15,168
def configure_engine ( cls , url : Union [ str , URL , Dict [ str , Any ] ] = None , bind : Union [ Connection , Engine ] = None , session : Dict [ str , Any ] = None , ready_callback : Union [ Callable [ [ Engine , sessionmaker ] , Any ] , str ] = None , poolclass : Union [ str , Pool ] = None , ** engine_args ) : assert check_argument_types ( ) if bind is None : if isinstance ( url , dict ) : url = URL ( ** url ) elif isinstance ( url , str ) : url = make_url ( url ) elif url is None : raise TypeError ( 'both "url" and "bind" cannot be None' ) if isinstance ( poolclass , str ) : poolclass = resolve_reference ( poolclass ) if url . get_dialect ( ) . name == 'sqlite' : connect_args = engine_args . setdefault ( 'connect_args' , { } ) connect_args . setdefault ( 'check_same_thread' , False ) bind = create_engine ( url , poolclass = poolclass , ** engine_args ) session = session or { } session . setdefault ( 'expire_on_commit' , False ) ready_callback = resolve_reference ( ready_callback ) return bind , sessionmaker ( bind , ** session ) , ready_callback
Create an engine and selectively apply certain hacks to make it Asphalt friendly .
15,169
def valid_file ( value ) : if not value : raise argparse . ArgumentTypeError ( "'' is not a valid file path" ) elif not os . path . exists ( value ) : raise argparse . ArgumentTypeError ( "%s is not a valid file path" % value ) elif os . path . isdir ( value ) : raise argparse . ArgumentTypeError ( "%s is a directory, not a regular file" % value ) return value
Check if given file exists and is a regular file .
15,170
def valid_level ( value ) : value = value . upper ( ) if getattr ( logging , value , None ) is None : raise argparse . ArgumentTypeError ( "%s is not a valid level" % value ) return value
Validation function for parser logging level argument .
15,171
def get_logger ( cls , custom_name = None ) : name = custom_name or cls . get_name ( ) return logging . getLogger ( name )
Returns a logger for the plugin .
15,172
def all ( self , domain = None ) : if domain is None : return { k : dict ( v ) for k , v in list ( self . messages . items ( ) ) } return dict ( self . messages . get ( domain , { } ) )
Gets the messages within a given domain .
15,173
def set ( self , id , translation , domain = 'messages' ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( translation , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) self . add ( { id : translation } , domain )
Sets a message translation .
15,174
def has ( self , id , domain ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) if self . defines ( id , domain ) : return True if self . fallback_catalogue is not None : return self . fallback_catalogue . has ( id , domain ) return False
Checks if a message has a translation .
15,175
def get ( self , id , domain = 'messages' ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) if self . defines ( id , domain ) : return self . messages [ domain ] [ id ] if self . fallback_catalogue is not None : return self . fallback_catalogue . get ( id , domain ) return id
Gets a message translation .
15,176
def replace ( self , messages , domain = 'messages' ) : assert isinstance ( messages , ( dict , CaseInsensitiveDict ) ) assert isinstance ( domain , ( str , unicode ) ) self . messages [ domain ] = CaseInsensitiveDict ( { } ) self . add ( messages , domain )
Sets translations for a given domain .
15,177
def add_catalogue ( self , catalogue ) : assert isinstance ( catalogue , MessageCatalogue ) if catalogue . locale != self . locale : raise ValueError ( 'Cannot add a catalogue for locale "%s" as the ' 'current locale for this catalogue is "%s"' % ( catalogue . locale , self . locale ) ) for domain , messages in list ( catalogue . all ( ) . items ( ) ) : self . add ( messages , domain ) for resource in catalogue . resources : self . add_resource ( resource )
Merges translations from the given Catalogue into the current one . The two catalogues must have the same locale .
15,178
def add_fallback_catalogue ( self , catalogue ) : assert isinstance ( catalogue , MessageCatalogue ) c = self while True : if c . locale == catalogue . locale : raise ValueError ( 'Circular reference detected when adding a ' 'fallback catalogue for locale "%s".' % catalogue . locale ) c = c . parent if c is None : break catalogue . parent = self self . fallback_catalogue = catalogue for resource in catalogue . resources : self . add_resource ( resource )
Merges translations from the given Catalogue into the current one only when the translation does not exist .
15,179
def trans ( self , id , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } assert isinstance ( parameters , dict ) if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' msg = self . get_catalogue ( locale ) . get ( id , domain ) return self . format ( msg , parameters )
Translates the given message .
15,180
def set_fallback_locales ( self , locales ) : self . catalogues = { } for locale in locales : self . _assert_valid_locale ( locale ) self . fallback_locales = locales
Sets the fallback locales .
15,181
def get_messages ( self , locale = None ) : if locale is None : locale = self . locale if locale not in self . catalogues : self . _load_catalogue ( locale ) catalogues = [ self . catalogues [ locale ] ] catalogue = catalogues [ 0 ] while True : catalogue = catalogue . fallback_catalogue if catalogue is None : break catalogues . append ( catalogue ) messages = { } for catalogue in catalogues [ : : - 1 ] : recursive_update ( messages , catalogue . all ( ) ) return messages
Collects all messages for the given locale .
15,182
def trans ( self , id , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' catalogue = self . get_catalogue ( locale ) if not catalogue . has ( id , domain ) : raise RuntimeError ( "There is no translation for {0} in domain {1}" . format ( id , domain ) ) msg = self . get_catalogue ( locale ) . get ( id , domain ) return self . format ( msg , parameters )
Throws RuntimeError whenever a message is missing
15,183
def transchoice ( self , id , number , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' catalogue = self . get_catalogue ( locale ) while not catalogue . defines ( id , domain ) : cat = catalogue . fallback_catalogue if cat : catalogue = cat locale = catalogue . locale else : break if not catalogue . has ( id , domain ) : raise RuntimeError ( "There is no translation for {0} in domain {1}" . format ( id , domain ) ) parameters [ 'count' ] = number msg = selector . select_message ( catalogue . get ( id , domain ) , number , locale ) return self . format ( msg , parameters )
Raises a RuntimeError whenever a message is missing
15,184
def get_catalogue ( self , locale ) : if locale is None : locale = self . locale if locale not in self . catalogues or datetime . now ( ) - self . last_reload > timedelta ( seconds = 1 ) : self . _load_catalogue ( locale ) self . last_reload = datetime . now ( ) return self . catalogues [ locale ]
Reloads messages catalogue if requested after more than one second since last reload
15,185
def do_reload ( bot , target , cmdargs , server_send = None ) : def send ( msg ) : if server_send is not None : server_send ( "%s\n" % msg ) else : do_log ( bot . connection , bot . get_target ( target ) , msg ) confdir = bot . handler . confdir if cmdargs == 'pull' : if isinstance ( target , irc . client . Event ) and target . source . nick != bot . config [ 'auth' ] [ 'owner' ] : bot . connection . privmsg ( bot . get_target ( target ) , "Nope, not gonna do it." ) return if exists ( join ( confdir , '.git' ) ) : send ( misc . do_pull ( srcdir = confdir ) ) else : send ( misc . do_pull ( repo = bot . config [ 'api' ] [ 'githubrepo' ] ) ) importlib . reload ( config ) bot . config = config . load_config ( join ( confdir , 'config.cfg' ) , send ) errored_helpers = modutils . scan_and_reimport ( 'helpers' ) if errored_helpers : send ( "Failed to load some helpers." ) for error in errored_helpers : send ( "%s: %s" % error ) return False if not load_modules ( bot . config , confdir , send ) : return False data = bot . handler . get_data ( ) bot . shutdown_mp ( ) bot . handler = handler . BotHandler ( bot . config , bot . connection , bot . channels , confdir ) bot . handler . set_data ( data ) bot . handler . connection = bot . connection bot . handler . channels = bot . channels return True
The reloading magic .
15,186
def is_method ( arg ) : if inspect . ismethod ( arg ) : return True if isinstance ( arg , NonInstanceMethod ) : return True if inspect . isfunction ( arg ) : return _get_first_arg_name ( arg ) == 'self' return False
Checks whether given object is a method .
15,187
def _ask ( self , answers ) : if isinstance ( self . validator , list ) : for v in self . validator : v . answers = answers else : self . validator . answers = answers while ( True ) : q = self . question % answers if not self . choices ( ) : logger . warn ( 'No choices were supplied for "%s"' % q ) return None if self . value in answers : default = Validator . stringify ( answers [ self . value ] ) answer = self . _get_input ( "%s [%s]: " % ( q , default ) ) if answer == '' : answer = answers [ self . value ] else : answer = self . _get_input ( "%s: " % q ) if answer == '.' and self . multiple : return None if self . validate ( answer ) : return self . answer ( ) else : if isinstance ( self . validator , list ) : for v in self . validator : if v . error ( ) != '' : print ( v . error ( ) ) else : print ( self . validator . error ( ) )
Really ask the question .
15,188
def ask ( self , answers = None ) : if answers is None : answers = { } _answers = { } if self . multiple : print ( ( bold ( 'Multiple answers are supported for this question. ' + 'Please enter a "." character to finish.' ) ) ) _answers [ self . value ] = [ ] answer = self . _ask ( answers ) while answer is not None : _answers [ self . value ] . append ( answer ) answer = self . _ask ( answers ) else : _answers [ self . value ] = self . _ask ( answers ) if isinstance ( self . validator , list ) : for v in self . validator : _answers = dict ( _answers , ** v . hints ( ) ) else : _answers = dict ( _answers , ** self . validator . hints ( ) ) for q in self . _questions : answers = dict ( answers , ** _answers ) _answers = dict ( _answers , ** q . ask ( answers ) ) return _answers
Ask the question then ask any sub - questions .
15,189
def answer ( self ) : if isinstance ( self . validator , list ) : return self . validator [ 0 ] . choice ( ) return self . validator . choice ( )
Return the answer for the question from the validator .
15,190
def choices ( self ) : if isinstance ( self . validator , list ) : return self . validator [ 0 ] . print_choices ( ) return self . validator . print_choices ( )
Print the choices for this question .
15,191
def _timing ( f , logs_every = 100 ) : @ functools . wraps ( f ) def wrap ( * args , ** kw ) : ts = _time . time ( ) result = f ( * args , ** kw ) te = _time . time ( ) qj . _call_counts [ f ] += 1 qj . _timings [ f ] += ( te - ts ) count = qj . _call_counts [ f ] if count % logs_every == 0 : qj ( x = '%2.4f seconds' % ( qj . _timings [ f ] / count ) , s = 'Average timing for %s across %d call%s' % ( f , count , '' if count == 1 else 's' ) , _depth = 2 ) return result return wrap
Decorator to time function calls and log the stats .
15,192
def _catch ( f , exception_type ) : if not ( inspect . isclass ( exception_type ) and issubclass ( exception_type , Exception ) ) : exception_type = Exception @ functools . wraps ( f ) def wrap ( * args , ** kw ) : try : return f ( * args , ** kw ) except exception_type as e : qj ( e , 'Caught an exception in %s' % f , d = 1 , _depth = 2 ) return wrap
Decorator to drop into the debugger if a function throws an exception .
15,193
def _annotate_fn_args ( stack , fn_opname , nargs , nkw = - 1 , consume_fn_name = True ) : kwarg_names = [ ] if nkw == - 1 : if sys . version_info [ 0 ] < 3 : nargs , nkw = ( nargs % 256 , 2 * nargs // 256 ) else : if fn_opname == 'CALL_FUNCTION_KW' : if qj . _DEBUG_QJ : assert len ( stack ) and stack [ - 1 ] . opname == 'LOAD_CONST' if not len ( stack ) or stack [ - 1 ] . opname != 'LOAD_CONST' : return se = stack . pop ( ) kwarg_names = se . oparg_repr [ : : - 1 ] se . oparg_repr = [ '' ] nkw = len ( kwarg_names ) nargs -= nkw if qj . _DEBUG_QJ : assert nargs >= 0 and nkw > 0 else : nkw = 0 for i in range ( nkw ) : se = stack . pop ( ) if se . stack_depth == 0 and ( len ( se . oparg_repr ) == 0 or se . oparg_repr [ 0 ] == '' ) : continue if i % 2 == 1 and sys . version_info [ 0 ] < 3 : if qj . _DEBUG_QJ : assert se . opname == 'LOAD_CONST' if se . opname == 'LOAD_CONST' : se . oparg_repr += [ '=' ] else : pops = [ ] if se . opname . startswith ( 'CALL_FUNCTION' ) : _annotate_fn_args ( stack [ : ] , se . opname , se . oparg , - 1 , True ) pops = _collect_pops ( stack , se . stack_depth - 1 if se . opname . startswith ( 'CALL_FUNCTION' ) else 0 , [ ] , False ) if i > 1 and len ( pops ) : pops [ - 1 ] . oparg_repr += [ ',' ] if sys . version_info [ 0 ] >= 3 : target_se = pops [ - 1 ] if len ( pops ) else se target_se . oparg_repr = [ kwarg_names [ i ] , '=' ] + target_se . oparg_repr for i in range ( nargs ) : se = stack . pop ( ) if se . opname . startswith ( 'CALL_FUNCTION' ) : _annotate_fn_args ( stack , se . opname , se . oparg , - 1 , True ) elif len ( se . oparg_repr ) and se . oparg_repr [ 0 ] in { ']' , '}' , ')' } : if ( i > 0 or nkw > 0 ) : se . oparg_repr += [ ',' ] else : pops = _collect_pops ( stack , se . stack_depth , [ ] , False ) if ( i > 0 or nkw > 0 ) and len ( pops ) : pops [ - 1 ] . oparg_repr += [ ',' ] if consume_fn_name : _collect_pops ( stack , - 1 , [ ] , False )
Add commas and equals as appropriate to function argument lists in the stack .
15,194
def generate_mediation_matrix ( dsm ) : cat = dsm . categories ent = dsm . entities size = dsm . size [ 0 ] if not cat : cat = [ 'appmodule' ] * size packages = [ e . split ( '.' ) [ 0 ] for e in ent ] mediation_matrix = [ [ 0 for _ in range ( size ) ] for _ in range ( size ) ] for i in range ( 0 , size ) : for j in range ( 0 , size ) : if cat [ i ] == 'framework' : if cat [ j ] == 'framework' : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'corelib' : if ( cat [ j ] in ( 'framework' , 'corelib' ) or ent [ i ] . startswith ( packages [ j ] + '.' ) or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'applib' : if ( cat [ j ] in ( 'framework' , 'corelib' , 'applib' ) or ent [ i ] . startswith ( packages [ j ] + '.' ) or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'appmodule' : if ( cat [ j ] in ( 'framework' , 'corelib' , 'applib' , 'broker' , 'data' ) or ent [ i ] . startswith ( packages [ j ] + '.' ) or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'broker' : if ( cat [ j ] in ( 'appmodule' , 'corelib' , 'framework' ) or ent [ i ] . startswith ( packages [ j ] + '.' ) or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'data' : if ( cat [ j ] == 'framework' or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 else : raise DesignStructureMatrixError ( 'Mediation matrix value NOT generated for %s:%s' % ( i , j ) ) return mediation_matrix
Generate the mediation matrix of the given matrix .
15,195
def check ( self , dsm , simplicity_factor = 2 , ** kwargs ) : economy_of_mechanism = False message = '' data = dsm . data categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size dependency_number = 0 for i in range ( 0 , dsm_size ) : for j in range ( 0 , dsm_size ) : if ( categories [ i ] not in ( 'framework' , 'corelib' ) and categories [ j ] not in ( 'framework' , 'corelib' ) and data [ i ] [ j ] > 0 ) : dependency_number += 1 if dependency_number < dsm_size * simplicity_factor : economy_of_mechanism = True else : message = ' ' . join ( [ 'Number of dependencies (%s)' % dependency_number , '> number of rows (%s)' % dsm_size , '* simplicity factor (%s) = %s' % ( simplicity_factor , dsm_size * simplicity_factor ) ] ) return economy_of_mechanism , message
Check economy of mechanism .
15,196
def check ( self , dsm , independence_factor = 5 , ** kwargs ) : least_common_mechanism = False message = '' data = dsm . data categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size dependent_module_number = [ ] for j in range ( 0 , dsm_size ) : dependent_module_number . append ( 0 ) for i in range ( 0 , dsm_size ) : if ( categories [ i ] != 'framework' and categories [ j ] != 'framework' and data [ i ] [ j ] > 0 ) : dependent_module_number [ j ] += 1 for index , item in enumerate ( dsm . categories ) : if item == 'broker' or item == 'applib' : dependent_module_number [ index ] = 0 if max ( dependent_module_number ) <= dsm_size / independence_factor : least_common_mechanism = True else : maximum = max ( dependent_module_number ) message = ( 'Dependencies to %s (%s) > matrix size (%s) / ' 'independence factor (%s) = %s' % ( dsm . entities [ dependent_module_number . index ( maximum ) ] , maximum , dsm_size , independence_factor , dsm_size / independence_factor ) ) return least_common_mechanism , message
Check least common mechanism .
15,197
def check ( self , dsm , ** kwargs ) : layered_architecture = True messages = [ ] categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size for i in range ( 0 , dsm_size - 1 ) : for j in range ( i + 1 , dsm_size ) : if ( categories [ i ] != 'broker' and categories [ j ] != 'broker' and dsm . entities [ i ] . split ( '.' ) [ 0 ] != dsm . entities [ j ] . split ( '.' ) [ 0 ] ) : if dsm . data [ i ] [ j ] > 0 : layered_architecture = False messages . append ( 'Dependency from %s to %s breaks the ' 'layered architecture.' % ( dsm . entities [ i ] , dsm . entities [ j ] ) ) return layered_architecture , '\n' . join ( messages )
Check layered architecture .
15,198
def check ( self , dsm , ** kwargs ) : logger . debug ( 'Entities = %s' % dsm . entities ) messages = [ ] code_clean = True threshold = kwargs . pop ( 'threshold' , 1 ) rows , _ = dsm . size for i in range ( 0 , rows ) : if dsm . data [ i ] [ 0 ] > threshold : messages . append ( 'Number of issues (%d) in module %s ' '> threshold (%d)' % ( dsm . data [ i ] [ 0 ] , dsm . entities [ i ] , threshold ) ) code_clean = False return code_clean , '\n' . join ( messages )
Check code clean .
15,199
def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'date' , nargs = '*' , action = arguments . DateParser ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if not cmdargs . date : send ( "Time until when?" ) return delta = dateutil . relativedelta . relativedelta ( cmdargs . date , datetime . datetime . now ( ) ) diff = "%s is " % cmdargs . date . strftime ( "%x" ) if delta . years : diff += "%d years " % ( delta . years ) if delta . months : diff += "%d months " % ( delta . months ) if delta . days : diff += "%d days " % ( delta . days ) if delta . hours : diff += "%d hours " % ( delta . hours ) if delta . minutes : diff += "%d minutes " % ( delta . minutes ) if delta . seconds : diff += "%d seconds " % ( delta . seconds ) diff += "away" send ( diff )
Reports the difference between now and some specified time .