idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
13,800
def sparql_query ( self , collection_name , query ) : request_url = '/sparql/' + collection_name + '?' request_url += urlencode ( ( ( 'query' , query ) , ) ) return self . api_request ( request_url )
Submit a sparql query to the server to search metadata and annotations .
62
14
13,801
def get_contribution ( self , url ) : result = self . api_request ( url ) # add the contrib id into the metadata result [ 'id' ] = os . path . split ( result [ 'url' ] ) [ 1 ] return result
Get the details of a particular contribution given it s url
55
11
13,802
def create_contribution ( self , metadata ) : result = self . api_request ( '/contrib/' , method = 'POST' , data = json . dumps ( metadata ) ) # add the contrib id into the metadata result [ 'id' ] = os . path . split ( result [ 'url' ] ) [ 1 ] return result
Create a new contribution given a dictionary of metadata
74
9
13,803
def delete_contribution ( self , url ) : # first validate that this is a real contrib try : result = self . api_request ( url ) if 'url' in result and 'documents' in result : self . api_request ( result [ 'url' ] , method = 'DELETE' ) return True except : pass return False
Delete the contribution with this identifier
75
6
13,804
def lint ( ) : path = os . path . realpath ( os . getcwd ( ) ) cmd = 'flake8 %s' % path opt = '' print ( ">>> Linting codebase with the following command: %s %s" % ( cmd , opt ) ) try : return_code = call ( [ cmd , opt ] , shell = True ) if return_code < 0 : print ( ">>> Terminated by signal" , - return_code , file = sys . stderr ) elif return_code != 0 : sys . exit ( '>>> Lint checks failed' ) else : print ( ">>> Lint checks passed" , return_code , file = sys . stderr ) except OSError as e : print ( ">>> Execution failed:" , e , file = sys . stderr )
run linter on our code base .
180
8
13,805
def prompt_yn ( stmt ) : print ( stmt ) answer = '' while answer not in [ 'Y' , 'N' ] : sys . stdout . write ( "$ " ) answer = sys . stdin . readline ( ) . upper ( ) . strip ( ) return answer == 'Y'
Prints the statement stmt to the terminal and wait for a Y or N answer . Returns True for Y False for N .
66
26
13,806
def get_agents ( self , addr = True , agent_cls = None , include_manager = False ) : agents = list ( self . agents . dict . values ( ) ) if hasattr ( self , 'manager' ) and self . manager is not None : if not include_manager : agents = [ a for a in agents if a . addr . rsplit ( '/' , 1 ) [ 1 ] != '0' ] if agent_cls is not None : agents = [ a for a in agents if type ( a ) is agent_cls ] if addr : agents = [ agent . addr for agent in agents ] return agents
Get agents in the environment .
136
6
13,807
async def trigger_act ( self , * args , addr = None , agent = None , * * kwargs ) : if agent is None and addr is None : raise TypeError ( "Either addr or agent has to be defined." ) if agent is None : for a in self . get_agents ( addr = False ) : if addr == a . addr : agent = a self . _log ( logging . DEBUG , "Triggering agent in {}" . format ( agent . addr ) ) ret = await agent . act ( * args , * * kwargs ) return ret
Trigger agent to act .
122
5
13,808
async def trigger_all ( self , * args , * * kwargs ) : tasks = [ ] for a in self . get_agents ( addr = False , include_manager = False ) : task = asyncio . ensure_future ( self . trigger_act ( * args , agent = a , * * kwargs ) ) tasks . append ( task ) rets = await asyncio . gather ( * tasks ) return rets
Trigger all agents in the environment to act asynchronously .
93
12
13,809
def create_random_connections ( self , n = 5 ) : if type ( n ) != int : raise TypeError ( "Argument 'n' must be of type int." ) if n <= 0 : raise ValueError ( "Argument 'n' must be greater than zero." ) for a in self . get_agents ( addr = False ) : others = self . get_agents ( addr = False ) [ : ] others . remove ( a ) shuffle ( others ) for r_agent in others [ : n ] : a . add_connection ( r_agent )
Create random connections for all agents in the environment .
122
10
13,810
def create_connections ( self , connection_map ) : agents = self . get_agents ( addr = False ) rets = [ ] for a in agents : if a . addr in connection_map : r = a . add_connections ( connection_map [ a . addr ] ) rets . append ( r ) return rets
Create agent connections from a given connection map .
72
9
13,811
def get_connections ( self , data = True ) : connections = [ ] for a in self . get_agents ( addr = False ) : c = ( a . addr , a . get_connections ( data = data ) ) connections . append ( c ) return connections
Return connections from all the agents in the environment .
58
10
13,812
def get_random_agent ( self , agent ) : r_agent = choice ( self . get_agents ( addr = False ) ) while r_agent . addr == agent . addr : r_agent = choice ( self . get_agents ( addr = False ) ) return r_agent
Return random agent that is not the same as agent given as parameter .
61
14
13,813
def add_artifact ( self , artifact ) : artifact . env_time = self . age self . artifacts . append ( artifact ) self . _log ( logging . DEBUG , "ARTIFACTS appended: '{}', length={}" . format ( artifact , len ( self . artifacts ) ) )
Add artifact with given framing to the environment .
65
9
13,814
async def get_artifacts ( self , agent = None ) : # TODO: Figure better way for this if hasattr ( self , 'manager' ) and self . manager is not None : artifacts = await self . manager . get_artifacts ( ) else : artifacts = self . artifacts if agent is not None : artifacts = [ a for a in artifacts if agent . name == a . creator ] return artifacts
Return artifacts published to the environment .
85
7
13,815
def destroy ( self , folder = None , as_coro = False ) : async def _destroy ( folder ) : ret = self . save_info ( folder ) for a in self . get_agents ( addr = False ) : a . close ( folder = folder ) await self . shutdown ( as_coro = True ) return ret return run_or_coro ( _destroy ( folder ) , as_coro )
Destroy the environment .
90
4
13,816
def tee ( * popenargs , * * kwargs ) : import subprocess , select , sys process = subprocess . Popen ( stdout = subprocess . PIPE , stderr = subprocess . PIPE , * popenargs , * * kwargs ) stdout , stderr = '' , '' def read_stream ( input_callback , output_stream ) : # (no fold) read = input_callback ( ) output_stream . write ( read ) output_stream . flush ( ) return read while process . poll ( ) is None : watch = process . stdout . fileno ( ) , process . stderr . fileno ( ) ready = select . select ( watch , [ ] , [ ] ) [ 0 ] for fd in ready : if fd == process . stdout . fileno ( ) : stdout += read_stream ( process . stdout . readline , sys . stdout ) if fd == process . stderr . fileno ( ) : stderr += read_stream ( process . stderr . readline , sys . stderr ) stdout += read_stream ( process . stdout . read , sys . stdout ) stderr += read_stream ( process . stderr . read , sys . stderr ) return stdout , stderr
Run a command as if it were piped though tee .
289
12
13,817
def save ( self , user , commit = True ) : self . is_instance ( user ) schema = UpdateSchema ( ) valid = schema . process ( user ) if not valid : return valid db . session . add ( user ) if commit : db . session . commit ( ) events . user_save_event . send ( user ) return user
Persist user and emit event
73
6
13,818
def login ( self , email = None , password = None , remember = False ) : from flask_login import login_user user = self . first ( email = email ) if user is None : events . login_failed_nonexistent_event . send ( ) return False # check for account being locked if user . is_locked ( ) : raise x . AccountLocked ( locked_until = user . locked_until ) # check for email being confirmed is_new = user . email and not user . email_new if is_new and not user . email_confirmed and self . require_confirmation : raise x . EmailNotConfirmed ( email = user . email_secure ) verified = user . verify_password ( password ) if not verified : user . increment_failed_logins ( ) self . save ( user ) events . login_failed_event . send ( user ) return False # login otherwise login_user ( user = user , remember = remember ) user . reset_login_counter ( ) self . save ( user ) events . login_event . send ( user ) # notify principal app = current_app . _get_current_object ( ) identity_changed . send ( app , identity = Identity ( user . id ) ) # and return return True
Authenticate user and emit event .
268
7
13,819
def force_login ( self , user ) : from flask_login import login_user # check for account being locked if user . is_locked ( ) : raise x . AccountLocked ( locked_until = user . locked_until ) # check for email being confirmed is_new = user . email and not user . email_new if is_new and not user . email_confirmed and self . require_confirmation : raise x . EmailNotConfirmed ( email = user . email_secure ) # login login_user ( user = user , remember = True ) user . reset_login_counter ( ) self . save ( user ) # notify principal app = current_app . _get_current_object ( ) identity_changed . send ( app , identity = Identity ( user . id ) ) # and return return True
Force login a user without credentials
173
6
13,820
def logout ( self ) : from flask_login import logout_user , current_user if not current_user . is_authenticated : return True # logout otherwise user = current_user events . logout_event . send ( user ) logout_user ( ) # notify principal app = current_app . _get_current_object ( ) identity_changed . send ( app , identity = AnonymousIdentity ( ) ) return True
Logout user and emit event .
94
7
13,821
def attempt_social_login ( self , provider , id ) : if not provider or not id : return False params = dict ( ) params [ provider . lower ( ) + '_id' ] = id user = self . first ( * * params ) if not user : return False self . force_login ( user ) return True
Attempt social login and return boolean result
69
7
13,822
def get_token ( self , user_id ) : if not self . jwt_implementation : return self . default_token_implementation ( user_id ) try : implementation = import_string ( self . jwt_implementation ) except ImportError : msg = 'Failed to import custom JWT implementation. ' msg += 'Check that configured module exists [{}]' raise x . ConfigurationException ( msg . format ( self . jwt_implementation ) ) # return custom token return implementation ( user_id )
Get user token Checks if a custom token implementation is registered and uses that . Otherwise falls back to default token implementation . Returns a string token on success .
111
30
13,823
def get_user_by_token ( self , token ) : if not self . jwt_loader_implementation : return self . default_token_user_loader ( token ) try : implementation = import_string ( self . jwt_loader_implementation ) except ImportError : msg = 'Failed to import custom JWT user loader implementation. ' msg += 'Check that configured module exists [{}]' raise x . ConfigurationException ( msg . format ( self . jwt_loader_implementation ) ) # return user from custom loader return implementation ( token )
Get user by token Using for logging in . Check to see if a custom token user loader was registered and uses that . Otherwise falls back to default loader implementation . You should be fine with default implementation as long as your token has user_id claim in it .
120
52
13,824
def default_token_implementation ( self , user_id ) : user = self . get ( user_id ) if not user : msg = 'No user with such id [{}]' raise x . JwtNoUser ( msg . format ( user_id ) ) # return token if exists and valid if user . _token : try : self . decode_token ( user . _token ) return user . _token except jwt . exceptions . ExpiredSignatureError : pass from_now = datetime . timedelta ( seconds = self . jwt_lifetime ) expires = datetime . datetime . utcnow ( ) + from_now issued = datetime . datetime . utcnow ( ) not_before = datetime . datetime . utcnow ( ) data = dict ( exp = expires , nbf = not_before , iat = issued , user_id = user_id ) token = jwt . encode ( data , self . jwt_secret , algorithm = self . jwt_algo ) string_token = token . decode ( 'utf-8' ) user . _token = string_token self . save ( user ) return string_token
Default JWT token implementation This is used by default for generating user tokens if custom implementation was not configured . The token will contain user_id and expiration date . If you need more information added to the token register your custom implementation .
253
46
13,825
def default_token_user_loader ( self , token ) : try : data = self . decode_token ( token ) except jwt . exceptions . DecodeError as e : raise x . JwtDecodeError ( str ( e ) ) except jwt . ExpiredSignatureError as e : raise x . JwtExpired ( str ( e ) ) user = self . get ( data [ 'user_id' ] ) if not user : msg = 'No user with such id [{}]' raise x . JwtNoUser ( msg . format ( data [ 'user_id' ] ) ) if user . is_locked ( ) : msg = 'This account is locked' raise x . AccountLocked ( msg , locked_until = user . locked_until ) if self . require_confirmation and not user . email_confirmed : msg = 'Please confirm your email address [{}]' raise x . EmailNotConfirmed ( msg . format ( user . email_secure ) , email = user . email ) # test token matches the one on file if not token == user . _token : raise x . JwtTokenMismatch ( 'The token does not match our records' ) # return on success return user
Default token user loader Accepts a token and decodes it checking signature and expiration . Then loads user by id from the token to see if account is not locked . If all is good returns user record otherwise throws an exception .
261
45
13,826
def register ( self , user_data , base_confirm_url = '' , send_welcome = True ) : user = self . __model__ ( * * user_data ) schema = RegisterSchema ( ) valid = schema . process ( user ) if not valid : return valid db . session . add ( user ) db . session . commit ( ) if not user . id : return False # send welcome message if send_welcome : self . send_welcome_message ( user , base_confirm_url ) events . register_event . send ( user ) return user
Register user Accepts user data validates it and performs registration . Will send a welcome message with a confirmation link on success .
124
25
13,827
def send_welcome_message ( self , user , base_url ) : if not self . require_confirmation and not self . welcome_message : return # get subject subject = '' subjects = self . email_subjects if self . require_confirmation : subject = 'Welcome, please activate your account!' if 'welcome_confirm' in subjects . keys ( ) : subject = subjects [ 'welcome_confirm' ] if not self . require_confirmation : subject = 'Welcome to our site!' if 'welcome' in subjects . keys ( ) : subject = subjects [ 'welcome' ] # prepare data sender = current_app . config [ 'MAIL_DEFAULT_SENDER' ] recipient = user . email link = '{url}/{link}/' . format ( url = base_url . rstrip ( '/' ) , link = user . email_link ) data = dict ( link = link ) # render message if self . require_confirmation : html = render_template ( 'user/mail/account-confirm.html' , * * data ) txt = render_template ( 'user/mail/account-confirm.txt' , * * data ) else : html = render_template ( 'user/mail/welcome.html' , * * data ) txt = render_template ( 'user/mail/welcome.txt' , * * data ) # and send mail . send ( Message ( subject = subject , recipients = [ recipient ] , body = txt , html = html , sender = sender ) )
Send welcome mail with email confirmation link
339
7
13,828
def resend_welcome_message ( self , user , base_url ) : user . require_email_confirmation ( ) self . save ( user ) self . send_welcome_message ( user , base_url )
Regenerate email link and resend welcome
49
9
13,829
def confirm_email_with_link ( self , link ) : user = self . first ( email_link = link ) if not user : return False elif user and user . email_confirmed : return True elif user and user . email_link_expired ( ) : raise x . EmailLinkExpired ( 'Link expired, generate a new one' ) # confirm otherwise user . confirm_email ( ) db . session . add ( user ) db . session . commit ( ) events . email_confirmed_event . send ( user ) return user
Confirm email with link A universal method to confirm email . used for both initial confirmation and when email is changed .
116
23
13,830
def change_email ( self , user , new_email , base_confirm_url = '' , send_message = True ) : from boiler . user . models import UpdateSchema schema = UpdateSchema ( ) user . email = new_email valid = schema . validate ( user ) if not valid : return valid db . session . add ( user ) db . session . commit ( ) # send confirmation link if send_message : self . send_email_changed_message ( user , base_confirm_url ) events . email_update_requested_event . send ( user ) return user
Change email Saves new email and sends confirmation before doing the switch . Can optionally skip sending out message for testing purposes .
127
24
13,831
def resend_email_changed_message ( self , user , base_url ) : user . require_email_confirmation ( ) self . save ( user ) self . send_email_changed_message ( user , base_url )
Regenerate email confirmation link and resend message
51
10
13,832
def request_password_reset ( self , user , base_url ) : user . generate_password_link ( ) db . session . add ( user ) db . session . commit ( ) events . password_change_requested_event . send ( user ) self . send_password_change_message ( user , base_url )
Regenerate password link and send message
71
8
13,833
def change_password ( self , user , new_password ) : from boiler . user . models import UpdateSchema from flask_login import logout_user schema = UpdateSchema ( ) user . password = new_password user . password_link = None user . password_link_expires = None valid = schema . validate ( user ) if not valid : return valid db . session . add ( user ) db . session . commit ( ) # logout if a web request if has_request_context ( ) : logout_user ( ) events . password_changed_event . send ( user ) return user
Change user password and logout
129
6
13,834
def send_password_change_message ( self , user , base_url ) : subject = 'Change your password here' if 'password_change' in self . email_subjects . keys ( ) : subject = self . email_subjects [ 'password_change' ] sender = current_app . config [ 'MAIL_DEFAULT_SENDER' ] recipient = user . email link = '{url}/{link}/' . format ( url = base_url . rstrip ( '/' ) , link = user . password_link ) data = dict ( link = link ) html = render_template ( 'user/mail/password-change.html' , * * data ) txt = render_template ( 'user/mail/password-change.txt' , * * data ) mail . send ( Message ( subject = subject , recipients = [ recipient ] , body = txt , html = html , sender = sender ) )
Send password change message
203
4
13,835
def add_role_to_user ( self , user , role ) : user . add_role ( role ) self . save ( user ) events . user_got_role_event . send ( user , role = role )
Adds a role to user
48
5
13,836
def remove_role_from_user ( self , user , role ) : user . remove_role ( role ) self . save ( user ) events . user_lost_role_event . send ( user , role = role )
Removes role from user
48
5
13,837
def random_walk ( network ) : latest = network . latest_transmission_recipient ( ) if ( not network . transmissions ( ) or latest is None ) : sender = random . choice ( network . nodes ( type = Source ) ) else : sender = latest receiver = random . choice ( sender . neighbors ( direction = "to" , type = Agent ) ) sender . transmit ( to_whom = receiver )
Take a random walk from a source .
87
8
13,838
def moran_cultural ( network ) : if not network . transmissions ( ) : # first step, replacer is a source replacer = random . choice ( network . nodes ( type = Source ) ) replacer . transmit ( ) else : replacer = random . choice ( network . nodes ( type = Agent ) ) replaced = random . choice ( replacer . neighbors ( direction = "to" , type = Agent ) ) from operator import attrgetter replacer . transmit ( what = max ( replacer . infos ( ) , key = attrgetter ( 'creation_time' ) ) , to_whom = replaced )
Generalized cultural Moran process .
134
6
13,839
def moran_sexual ( network ) : if not network . transmissions ( ) : replacer = random . choice ( network . nodes ( type = Source ) ) replacer . transmit ( ) else : from operator import attrgetter agents = network . nodes ( type = Agent ) baby = max ( agents , key = attrgetter ( 'creation_time' ) ) agents = [ a for a in agents if a . id != baby . id ] replacer = random . choice ( agents ) replaced = random . choice ( replacer . neighbors ( direction = "to" , type = Agent ) ) # Give the baby the same outgoing connections as the replaced. for node in replaced . neighbors ( direction = "to" ) : baby . connect ( direction = "to" , whom = node ) # Give the baby the same incoming connections as the replaced. for node in replaced . neighbors ( direction = "from" ) : node . connect ( direction = "to" , whom = baby ) # Kill the replaced agent. replaced . fail ( ) # Endow the baby with the ome of the replacer. replacer . transmit ( to_whom = baby )
The generalized sexual Moran process .
243
6
13,840
def dump_object ( self , obj ) : if isinstance ( obj , uuid . UUID ) : return str ( obj ) if hasattr ( obj , 'isoformat' ) : return obj . isoformat ( ) if isinstance ( obj , ( bytes , bytearray , memoryview ) ) : return base64 . b64encode ( obj ) . decode ( 'ASCII' ) raise TypeError ( '{!r} is not JSON serializable' . format ( obj ) )
Called to encode unrecognized object .
106
8
13,841
def normalize_datum ( self , datum ) : if datum is None : return datum if isinstance ( datum , self . PACKABLE_TYPES ) : return datum if isinstance ( datum , uuid . UUID ) : datum = str ( datum ) if isinstance ( datum , bytearray ) : datum = bytes ( datum ) if isinstance ( datum , memoryview ) : datum = datum . tobytes ( ) if hasattr ( datum , 'isoformat' ) : datum = datum . isoformat ( ) if isinstance ( datum , ( bytes , str ) ) : return datum if isinstance ( datum , ( collections . Sequence , collections . Set ) ) : return [ self . normalize_datum ( item ) for item in datum ] if isinstance ( datum , collections . Mapping ) : out = { } for k , v in datum . items ( ) : out [ k ] = self . normalize_datum ( v ) return out raise TypeError ( '{} is not msgpackable' . format ( datum . __class__ . __name__ ) )
Convert datum into something that umsgpack likes .
256
12
13,842
def map_value ( self , value , gid ) : base_gid = self . base_gid_pattern . search ( gid ) . group ( 1 ) if self . anonymyze : try : if value in self . _maps [ base_gid ] : return self . _maps [ base_gid ] [ value ] else : k = ( len ( self . _maps [ base_gid ] ) + 1 ) % self . mapmax new_item = u'{0}_{1:0{2}d}' . format ( base_gid . upper ( ) , k , self . mapexp ) self . _maps [ base_gid ] [ value ] = new_item return new_item except KeyError : return value elif base_gid in [ 'client' , 'mail' , 'from' , 'rcpt' , 'user' ] and self . ip_lookup : ip_match = self . ip_pattern . search ( value ) if ip_match is None : return value host = self . gethost ( ip_match . group ( 1 ) ) if host == ip_match . group ( 1 ) or value . startswith ( host ) : return value return u'' . join ( [ value [ : ip_match . start ( 1 ) ] , self . gethost ( ip_match . group ( 1 ) ) , value [ ip_match . end ( 1 ) : ] ] ) elif ( base_gid == 'user' or base_gid == 'uid' ) and self . uid_lookup : return self . getuname ( value ) else : return value
Return the value for a group id applying requested mapping . Map only groups related to a filter ie when the basename of the group is identical to the name of a filter .
358
35
13,843
def match_to_dict ( self , match , gids ) : values = { } for gid in gids : try : values [ gid ] = self . map_value ( match . group ( gid ) , gid ) except IndexError : pass return values
Map values from match into a dictionary .
58
8
13,844
def match_to_string ( self , match , gids , values = None ) : s = match . string parts = [ ] k = 0 for gid in sorted ( gids , key = lambda x : gids [ x ] ) : if values is None : try : value = self . map_value ( match . group ( gid ) , gid ) parts . append ( s [ k : match . start ( gid ) ] ) parts . append ( value ) k = match . end ( gid ) except IndexError : continue elif gid in values : parts . append ( s [ k : match . start ( gid ) ] ) parts . append ( values [ gid ] ) k = match . end ( gid ) parts . append ( s [ k : ] ) return u"" . join ( parts )
Return the mapped string from match object . If a dictionary of values is provided then use it to build the string .
176
23
13,845
def gethost ( self , ip_addr ) : # Handle silly fake ipv6 addresses try : if ip_addr [ : 7 ] == '::ffff:' : ip_addr = ip_addr [ 7 : ] except TypeError : pass if ip_addr [ 0 ] in string . letters : return ip_addr try : return self . hostsmap [ ip_addr ] except KeyError : pass try : name = socket . gethostbyaddr ( ip_addr ) [ 0 ] except socket . error : name = ip_addr self . hostsmap [ ip_addr ] = name return name
Do reverse lookup on an ip address
127
7
13,846
def getuname ( self , uid ) : uid = int ( uid ) try : return self . uidsmap [ uid ] except KeyError : pass try : name = pwd . getpwuid ( uid ) [ 0 ] except ( KeyError , AttributeError ) : name = "uid=%d" % uid self . uidsmap [ uid ] = name return name
Get the username of a given uid .
88
9
13,847
def redirect ( endpoint , * * kw ) : _endpoint = None if isinstance ( endpoint , six . string_types ) : _endpoint = endpoint # valid for https:// or /path/ # Endpoint should not have slashes. Use : (colon) to build endpoint if "/" in endpoint : return f_redirect ( endpoint ) else : for r in Mocha . _app . url_map . iter_rules ( ) : _endpoint = endpoint if 'GET' in r . methods and endpoint in r . endpoint : _endpoint = r . endpoint break else : # self, will refer the caller method, by getting the method name if isinstance ( endpoint , Mocha ) : fn = sys . _getframe ( ) . f_back . f_code . co_name endpoint = getattr ( endpoint , fn ) if is_method ( endpoint ) : _endpoint = _get_action_endpoint ( endpoint ) if not _endpoint : _endpoint = _build_endpoint_route_name ( endpoint ) if _endpoint : return f_redirect ( url_for ( _endpoint , * * kw ) ) else : raise exceptions . MochaError ( "Invalid endpoint" )
Redirect allow to redirect dynamically using the classes methods without knowing the right endpoint . Expecting all endpoint have GET as method it will try to pick the first match based on the endpoint provided or the based on the Rule map_url
263
46
13,848
def get_true_argspec ( method ) : argspec = inspect . getargspec ( method ) args = argspec [ 0 ] if args and args [ 0 ] == 'self' : return argspec if hasattr ( method , '__func__' ) : method = method . __func__ if not hasattr ( method , '__closure__' ) or method . __closure__ is None : raise DecoratorCompatibilityError closure = method . __closure__ for cell in closure : inner_method = cell . cell_contents if inner_method is method : continue if not inspect . isfunction ( inner_method ) and not inspect . ismethod ( inner_method ) : continue true_argspec = get_true_argspec ( inner_method ) if true_argspec : return true_argspec
Drills through layers of decorators attempting to locate the actual argspec for the method .
174
18
13,849
def setup_installed_apps ( cls ) : cls . _installed_apps = cls . _app . config . get ( "INSTALLED_APPS" , [ ] ) if cls . _installed_apps : def import_app ( module , props = { } ) : _ = werkzeug . import_string ( module ) setattr ( _ , "__options__" , utils . dict_dot ( props ) ) for k in cls . _installed_apps : if isinstance ( k , six . string_types ) : # One string import_app ( k , { } ) elif isinstance ( k , tuple ) : import_app ( k [ 0 ] , k [ 1 ] ) elif isinstance ( k , list ) : # list of tuple[(module props), ...] for t in k : import_app ( t [ 0 ] , t [ 1 ] )
To import 3rd party applications along with associated properties
197
10
13,850
def _add_asset_bundle ( cls , path ) : f = "%s/assets.yml" % path if os . path . isfile ( f ) : cls . _asset_bundles . add ( f )
Add a webassets bundle yml file
54
8
13,851
def _setup_db ( cls ) : uri = cls . _app . config . get ( "DB_URL" ) if uri : db . connect__ ( uri , cls . _app )
Setup the DB connection if DB_URL is set
47
10
13,852
def parse_options ( cls , options ) : options = options . copy ( ) subdomain = options . pop ( 'subdomain' , None ) endpoint = options . pop ( 'endpoint' , None ) return subdomain , endpoint , options ,
Extracts subdomain and endpoint values from the options dict and returns them along with a new dict without those values .
53
24
13,853
def get_base_route ( cls ) : base_route = cls . __name__ . lower ( ) if cls . base_route is not None : base_route = cls . base_route base_rule = parse_rule ( base_route ) cls . base_args = [ r [ 2 ] for r in base_rule ] return base_route . strip ( "/" )
Returns the route base to use for the current class .
87
11
13,854
def find_gene_by_name ( self , gene_name : str ) -> Gene : for gene in self . genes : if gene . name == gene_name : return gene raise AttributeError ( f'gene "{gene_name}" does not exist' )
Find and return a gene in the influence graph with the given name . Raise an AttributeError if there is no gene in the graph with the given name .
59
32
13,855
def find_multiplex_by_name ( self , multiplex_name : str ) -> Multiplex : for multiplex in self . multiplexes : if multiplex . name == multiplex_name : return multiplex raise AttributeError ( f'multiplex "{multiplex_name}" does not exist' )
Find and return a multiplex in the influence graph with the given name . Raise an AttributeError if there is no multiplex in the graph with the given name .
67
34
13,856
def all_states ( self ) -> Tuple [ State , ... ] : return tuple ( self . _transform_list_of_states_to_state ( states ) for states in self . _cartesian_product_of_every_states_of_each_genes ( ) )
Return all the possible states of this influence graph .
62
10
13,857
def _cartesian_product_of_every_states_of_each_genes ( self ) -> Tuple [ Tuple [ int , ... ] ] : if not self . genes : return ( ) return tuple ( product ( * [ gene . states for gene in self . genes ] ) )
Private method which return the cartesian product of the states of the genes in the model . It represents all the possible state for a given model .
63
29
13,858
def _transform_list_of_states_to_state ( self , state : List [ int ] ) -> State : return State ( { gene : state [ i ] for i , gene in enumerate ( self . genes ) } )
Private method which transform a list which contains the state of the gene in the models to a State object .
50
21
13,859
def read_sha1 ( file_path , buf_size = None , start_byte = 0 , read_size = None , extra_hashers = [ ] , # update(data) will be called on all of these ) : read_size = read_size or os . stat ( file_path ) . st_size buf_size = buf_size or DEFAULT_BUFFER_SIZE data_read = 0 total_sha1 = hashlib . sha1 ( ) while data_read < read_size : with open ( file_path , 'rb' , buffering = 0 ) as f : f . seek ( start_byte ) data = f . read ( min ( buf_size , read_size - data_read ) ) assert ( len ( data ) > 0 ) total_sha1 . update ( data ) for hasher in extra_hashers : hasher . update ( data ) data_read += len ( data ) start_byte += len ( data ) assert ( data_read == read_size ) return total_sha1
Determines the sha1 hash of a file in chunks to prevent loading the entire file at once into memory
225
23
13,860
def verify_uploaded_file ( self , destination_folder_id , source_path , verbose = True , ) : source_file_size = os . stat ( source_path ) . st_size total_part_size = 0 file_position = 0 uploaded_box_file_ids = self . find_file ( destination_folder_id , os . path . basename ( source_path ) ) total_sha1 = hashlib . sha1 ( ) for i , file_id in enumerate ( uploaded_box_file_ids ) : file_info = self . client . file ( file_id = file_id ) . get ( ) uploaded_sha1 = file_info . response_object [ 'sha1' ] uploaded_size = file_info . response_object [ 'size' ] part_sha1 = read_sha1 ( source_path , start_byte = file_position , read_size = uploaded_size , extra_hashers = [ total_sha1 ] ) if part_sha1 . hexdigest ( ) != uploaded_sha1 : print ( '\n' ) print ( 'Part sha1: ' + part_sha1 . hexdigest ( ) ) print ( 'Uploaded sha1: ' + uploaded_sha1 ) print ( 'Sha1 hash of uploaded file {0} ({1}) does not match' . format ( file_info . response_object [ 'name' ] , file_id ) ) return False file_position += uploaded_size total_part_size += uploaded_size if len ( uploaded_box_file_ids ) > 1 : print ( 'Finished verifying part {0} of {1} of {2}' . format ( i + 1 , len ( uploaded_box_file_ids ) , file_id ) ) assert ( source_file_size == total_part_size ) if verbose : print ( 'Verified uploaded file {0} ({1}) with sha1: {2}' . format ( source_path , file_id , total_sha1 . hexdigest ( ) ) ) return True
Verifies the integrity of a file uploaded to Box
460
10
13,861
def handle_resourcelist ( ltext , * * kwargs ) : base = kwargs . get ( 'base' , VERSA_BASEIRI ) model = kwargs . get ( 'model' ) iris = ltext . strip ( ) . split ( ) newlist = model . generate_resource ( ) for i in iris : model . add ( newlist , VERSA_BASEIRI + 'item' , I ( iri . absolutize ( i , base ) ) ) return newlist
A helper that converts lists of resources from a textual format such as Markdown including absolutizing relative IRIs
115
23
13,862
def handle_resourceset ( ltext , * * kwargs ) : fullprop = kwargs . get ( 'fullprop' ) rid = kwargs . get ( 'rid' ) base = kwargs . get ( 'base' , VERSA_BASEIRI ) model = kwargs . get ( 'model' ) iris = ltext . strip ( ) . split ( ) for i in iris : model . add ( rid , fullprop , I ( iri . absolutize ( i , base ) ) ) return None
A helper that converts sets of resources from a textual format such as Markdown including absolutizing relative IRIs
120
23
13,863
def create_cache_database ( self ) : conn = sqlite3 . connect ( self . database ) conn . text_factory = str c = conn . cursor ( ) c . execute ( """CREATE TABLE items (url text, metadata text, datetime text)""" ) c . execute ( """CREATE TABLE documents (url text, path text, datetime text)""" ) c . execute ( """CREATE TABLE primary_texts (item_url text, primary_text text, datetime text)""" ) conn . commit ( ) conn . close ( )
Create a new SQLite3 database for use with Cache objects
120
12
13,864
def __exists_row_not_too_old ( self , row ) : if row is None : return False record_time = dateutil . parser . parse ( row [ 2 ] ) now = datetime . datetime . now ( dateutil . tz . gettz ( ) ) age = ( record_time - now ) . total_seconds ( ) if age > self . max_age : return False return True
Check if the given row exists and is not too old
90
11
13,865
def has_item ( self , item_url ) : c = self . conn . cursor ( ) c . execute ( "SELECT * FROM items WHERE url=?" , ( str ( item_url ) , ) ) row = c . fetchone ( ) c . close ( ) return self . __exists_row_not_too_old ( row )
Check if the metadata for the given item is present in the cache
75
13
13,866
def has_document ( self , doc_url ) : c = self . conn . cursor ( ) c . execute ( "SELECT * FROM documents WHERE url=?" , ( str ( doc_url ) , ) ) row = c . fetchone ( ) c . close ( ) return self . __exists_row_not_too_old ( row )
Check if the content of the given document is present in the cache
75
13
13,867
def get_document ( self , doc_url ) : c = self . conn . cursor ( ) c . execute ( "SELECT * FROM documents WHERE url=?" , ( str ( doc_url ) , ) ) row = c . fetchone ( ) c . close ( ) if row is None : raise ValueError ( "Item not present in cache" ) file_path = row [ 1 ] try : with open ( file_path , 'rb' ) as f : return f . read ( ) except IOError as e : raise IOError ( "Error reading file " + file_path + " to retrieve document " + doc_url + ": " + e . message )
Retrieve the content for the given document from the cache .
143
12
13,868
def get_primary_text ( self , item_url ) : c = self . conn . cursor ( ) c . execute ( "SELECT * FROM primary_texts WHERE item_url=?" , ( str ( item_url ) , ) ) row = c . fetchone ( ) c . close ( ) if row is None : raise ValueError ( "Item not present in cache" ) return row [ 1 ]
Retrieve the primary text for the given item from the cache .
87
13
13,869
def add_item ( self , item_url , item_metadata ) : c = self . conn . cursor ( ) c . execute ( "DELETE FROM items WHERE url=?" , ( str ( item_url ) , ) ) self . conn . commit ( ) c . execute ( "INSERT INTO items VALUES (?, ?, ?)" , ( str ( item_url ) , item_metadata , self . __now_iso_8601 ( ) ) ) self . conn . commit ( ) c . close ( )
Add the given item to the cache database updating the existing metadata if the item is already present
111
18
13,870
def add_document ( self , doc_url , data ) : file_path = self . __generate_filepath ( ) with open ( file_path , 'wb' ) as f : f . write ( data ) c = self . conn . cursor ( ) c . execute ( "SELECT * FROM documents WHERE url=?" , ( str ( doc_url ) , ) ) for row in c . fetchall ( ) : old_file_path = row [ 1 ] if os . path . isfile ( old_file_path ) : os . unlink ( old_file_path ) c . execute ( "DELETE FROM documents WHERE url=?" , ( str ( doc_url ) , ) ) self . conn . commit ( ) c . execute ( "INSERT INTO documents VALUES (?, ?, ?)" , ( str ( doc_url ) , file_path , self . __now_iso_8601 ( ) ) ) self . conn . commit ( ) c . close ( )
Add the given document to the cache updating the existing content data if the document is already present
213
18
13,871
def add_primary_text ( self , item_url , primary_text ) : c = self . conn . cursor ( ) c . execute ( "DELETE FROM primary_texts WHERE item_url=?" , ( str ( item_url ) , ) ) self . conn . commit ( ) c . execute ( "INSERT INTO primary_texts VALUES (?, ?, ?)" , ( str ( item_url ) , primary_text , self . __now_iso_8601 ( ) ) ) self . conn . commit ( ) c . close ( )
Add the given primary text to the cache database updating the existing record if the primary text is already present
121
20
13,872
async def profile ( self , ctx , tag ) : if not self . check_valid_tag ( tag ) : return await ctx . send ( 'Invalid tag!' ) profile = await self . cr . get_profile ( tag ) em = discord . Embed ( color = 0x00FFFFF ) em . set_author ( name = str ( profile ) , icon_url = profile . clan_badge_url ) em . set_thumbnail ( url = profile . arena . badge_url ) # Example of adding data. (Bad) for attr in self . cdir ( profile ) : value = getattr ( profile , attr ) if not callable ( value ) : em . add_field ( name = attr . replace ( '_' ) . title ( ) , value = str ( value ) ) await ctx . send ( embed = em )
Example command for use inside a discord bot cog .
187
10
13,873
def write_remaining ( self ) : if not self . results : return with db . execution_context ( ) : with db . atomic ( ) : Result . insert_many ( self . results ) . execute ( ) del self . results [ : ]
Write the remaning stack content
53
7
13,874
def configure ( project_path , config_file = None ) : if config_file is None : config_file = os . path . join ( project_path , 'config.json' ) try : with open ( config_file , 'r' ) as f : config = json . load ( f ) except ValueError as e : raise OctConfigurationError ( "Configuration setting failed with error: %s" % e ) for key in REQUIRED_CONFIG_KEYS : if key not in config : raise OctConfigurationError ( "Error: the required configuration key %s is not define" % key ) return config
Get the configuration of the test and return it as a config object
131
13
13,875
def configure_for_turret ( project_name , config_file ) : config = configure ( project_name , config_file ) for key in WARNING_CONFIG_KEYS : if key not in config : print ( "WARNING: %s configuration key not present, the value will be set to default value" % key ) common_config = { 'hq_address' : config . get ( 'hq_address' , '127.0.0.1' ) , 'hq_publisher' : config . get ( 'publish_port' , 5000 ) , 'hq_rc' : config . get ( 'rc_port' , 5001 ) , 'turrets_requirements' : config . get ( 'turrets_requirements' , [ ] ) } configs = [ ] for turret in config [ 'turrets' ] : if isinstance ( turret , six . string_types ) : turret = load_turret_config ( project_name , turret ) turret . update ( common_config ) turret . update ( config . get ( 'extra_turret_config' , { } ) ) configs . append ( turret ) return configs
Load the configuration file in python dict and check for keys that will be set to default value if not present
254
21
13,876
def get_db_uri ( config , output_dir ) : db_config = config . get ( "results_database" , { "db_uri" : "default" } ) if db_config [ 'db_uri' ] == 'default' : return os . path . join ( output_dir , "results.sqlite" ) return db_config [ 'db_uri' ]
Process results_database parameters in config to format them for set database function
85
14
13,877
def update ( self ) : self . json = c . get_document ( self . uri . did ) . json ( ) self . e_list = c . element_list ( self . uri . as_dict ( ) ) . json ( )
All client calls to update this instance with Onshape .
54
11
13,878
def find_element ( self , name , type = ElementType . ANY ) : for e in self . e_list : # if a type is specified and this isn't it, move to the next loop. if type . value and not e [ 'elementType' ] == type : continue if e [ "name" ] == name : uri = self . uri uri . eid = e [ "id" ] return uri
Find an elemnent in the document with the given name - could be a PartStudio Assembly or blob .
93
22
13,879
def beta_array ( C , HIGHSCALE , * args , * * kwargs ) : beta_odict = beta ( C , HIGHSCALE , * args , * * kwargs ) return np . hstack ( [ np . asarray ( b ) . ravel ( ) for b in beta_odict . values ( ) ] )
Return the beta functions of all SM parameters and SMEFT Wilson coefficients as a 1D numpy array .
75
22
13,880
def _search ( self , query , search_term ) : criterias = mongoengine . Q ( ) rel_criterias = mongoengine . Q ( ) terms = shlex . split ( search_term ) # If an ObjectId pattern, see if we can get an instant lookup. if len ( terms ) == 1 and re . match ( RE_OBJECTID , terms [ 0 ] ) : q = query . filter ( id = bson . ObjectId ( terms [ 0 ] ) ) if q . count ( ) == 1 : # Note: .get doesn't work, they need a QuerySet return q for term in terms : op , term = parse_like_term ( term ) # Case insensitive by default if op == 'contains' : op = 'icontains' criteria = mongoengine . Q ( ) for field in self . _search_fields : if isinstance ( field , mongoengine . fields . ReferenceField ) : rel_model = field . document_type rel_fields = ( getattr ( self , 'column_searchable_refs' , { } ) . get ( field . name , { } ) . get ( 'fields' , [ 'id' ] ) ) # If term isn't an ID, don't do an ID lookup if rel_fields == [ 'id' ] and not re . match ( RE_OBJECTID , term ) : continue ids = [ o . id for o in search_relative_field ( rel_model , rel_fields , term ) ] rel_criterias |= mongoengine . Q ( * * { '%s__in' % field . name : ids } ) elif isinstance ( field , mongoengine . fields . ListField ) : if not isinstance ( field . field , mongoengine . fields . ReferenceField ) : continue # todo: support lists of other types rel_model = field . field . document_type_obj rel_fields = ( getattr ( self , 'column_searchable_refs' , { } ) . get ( field . name , { } ) . get ( 'fields' , 'id' ) ) ids = [ o . id for o in search_relative_field ( rel_model , rel_fields , term ) ] rel_criterias |= mongoengine . Q ( * * { '%s__in' % field . name : ids } ) else : flt = { '%s__%s' % ( field . name , op ) : term } q = mongoengine . Q ( * * flt ) criteria |= q criterias &= criteria # import pprint # pp = pprint.PrettyPrinter(indent=4).pprint # print(pp(query.filter(criterias)._query)) return query . filter ( criterias | rel_criterias )
Improved search between words .
620
5
13,881
def set_data_from_iterable ( self , frames , values , labels = None ) : if not isinstance ( frames , collections . Iterable ) : raise TypeError , "frames must be an iterable" if not isinstance ( values , collections . Iterable ) : raise TypeError , "values must be an iterable" assert ( len ( frames ) == len ( values ) ) self . frames = frames self . values = values if labels is None : self . label2int [ 'New Point' ] = 0 self . int2label [ 0 ] = 'New Point' self . labels = [ 0 for i in xrange ( len ( frames ) ) ] else : if not isinstance ( labels , collections . Iterable ) : raise TypeError , "labels must be an iterable" for l in labels : if l not in self . label2int : self . label2int [ l ] = len ( self . label2int ) self . int2label [ len ( self . int2label ) ] = l self . labels . append ( self . label2int [ l ] )
Initialize a dataset structure from iterable parameters
234
9
13,882
def writexml ( self , writer , indent = "" , addindent = "" , newl = "" ) : # dataset = self.data.appendChild(self.doc.createElement('dataset')) # dataset.setAttribute('id', str(imodel)) # dataset.setAttribute('dimensions', '2') writer . write ( '%s<dataset id="%s" dimensions="%s">%s' % ( indent , self . datasetid , self . dimensions , newl ) ) indent2 = indent + addindent for l , x , y in zip ( self . labels , self . frames , self . values ) : writer . write ( '%s<point label="%s" frame="%d" value="%f"/>%s' % ( indent2 , self . int2label [ l ] , x , y , newl ) ) writer . write ( '%s</dataset>%s' % ( indent , newl ) )
Write the continuous dataset using sonic visualiser xml conventions
215
10
13,883
def gaus_pdf ( x , mean , std ) : return exp ( - ( ( x - mean ) / std ) ** 2 / 2 ) / sqrt ( 2 * pi ) / std
Gaussian distribution s probability density function .
41
8
13,884
def logistic ( x , x0 , k , L ) : return L / ( 1 + exp ( - k * ( x - x0 ) ) )
Logistic function .
33
4
13,885
def populate_menv ( menv , agent_cls_name , log_folder ) : gs = menv . gs n_agents = gs [ 0 ] * gs [ 1 ] n_slaves = len ( menv . addrs ) logger . info ( "Populating {} with {} agents" . format ( HOST , n_agents * n_slaves ) ) run ( menv . populate ( agent_cls_name , n_agents , log_folder = log_folder ) ) logger . info ( "Populating complete." )
Populate given multiprocessing grid environment with agents .
122
12
13,886
def get_slave_addrs ( mgr_addr , N ) : return [ ( HOST , p ) for p in range ( mgr_addr + 1 , mgr_addr + 1 + N ) ]
Get ports for the slave environments .
46
7
13,887
def weighted_average ( rule , artifact ) : e = 0 w = 0 for i in range ( len ( rule . R ) ) : r = rule . R [ i ] ( artifact ) if r is not None : e += r * rule . W [ i ] w += abs ( rule . W [ i ] ) if w == 0.0 : return 0.0 return e / w
Evaluate artifact s value to be weighted average of values returned by rule s subrules .
82
19
13,888
def minimum ( rule , artifact ) : m = 1.0 for i in range ( len ( rule . R ) ) : e = rule . R [ i ] ( artifact ) if e is not None : if e < m : m = e return m
Evaluate artifact s value to be minimum of values returned by rule s subrules .
53
18
13,889
def add_subrule ( self , subrule , weight ) : if not issubclass ( subrule . __class__ , ( Rule , RuleLeaf ) ) : raise TypeError ( "Rule's class must be (subclass of) {} or {}, got " "{}." . format ( Rule , RuleLeaf , subrule . __class__ ) ) self . __domains = set . union ( self . __domains , subrule . domains ) self . R . append ( subrule ) self . W . append ( weight )
Add subrule to the rule .
115
7
13,890
def parse_seqres ( self , pdb ) : seqresre = re . compile ( "SEQRES" ) seqreslines = [ line for line in pdb . lines if seqresre . match ( line ) ] for line in seqreslines : chain = line [ 11 ] resnames = line [ 19 : 70 ] . strip ( ) self . setdefault ( chain , [ ] ) self [ chain ] += resnames . split ( )
Parse the SEQRES entries into the object
96
10
13,891
def parse_atoms ( self , pdb ) : atomre = re . compile ( "ATOM" ) atomlines = [ line for line in pdb . lines if atomre . match ( line ) ] chainresnums = { } for line in atomlines : chain = line [ 21 ] resname = line [ 17 : 20 ] resnum = line [ 22 : 27 ] #print resnum chainresnums . setdefault ( chain , [ ] ) if resnum in chainresnums [ chain ] : assert self [ chain ] [ chainresnums [ chain ] . index ( resnum ) ] == resname else : if resnum [ - 1 ] == ' ' : self . setdefault ( chain , [ ] ) self [ chain ] += [ resname ] chainresnums [ chain ] += [ resnum ] return chainresnums
Parse the ATOM entries into the object
183
9
13,892
def seqres_lines ( self ) : lines = [ ] for chain in self . keys ( ) : seq = self [ chain ] serNum = 1 startidx = 0 while startidx < len ( seq ) : endidx = min ( startidx + 13 , len ( seq ) ) lines += [ "SEQRES %2i %s %4i %s\n" % ( serNum , chain , len ( seq ) , " " . join ( seq [ startidx : endidx ] ) ) ] serNum += 1 startidx += 13 return lines
Generate SEQRES lines representing the contents
125
9
13,893
def replace_seqres ( self , pdb , update_atoms = True ) : newpdb = PDB ( ) inserted_seqres = False entries_before_seqres = set ( [ "HEADER" , "OBSLTE" , "TITLE" , "CAVEAT" , "COMPND" , "SOURCE" , "KEYWDS" , "EXPDTA" , "AUTHOR" , "REVDAT" , "SPRSDE" , "JRNL" , "REMARK" , "DBREF" , "SEQADV" ] ) mutated_resids = { } if update_atoms : old_seqs = ChainSequences ( ) chainresnums = old_seqs . parse_atoms ( pdb ) assert self . keys ( ) == old_seqs . keys ( ) for chain in self . keys ( ) : assert len ( self [ chain ] ) == len ( old_seqs [ chain ] ) for i in xrange ( len ( self [ chain ] ) ) : if self [ chain ] [ i ] != old_seqs [ chain ] [ i ] : resid = chain + chainresnums [ chain ] [ i ] mutated_resids [ resid ] = self [ chain ] [ i ] for line in pdb . lines : entry = line [ 0 : 6 ] if ( not inserted_seqres ) and entry not in entries_before_seqres : inserted_seqres = True newpdb . lines += self . seqres_lines ( ) if update_atoms and entry == "ATOM " : resid = line [ 21 : 27 ] atom = line [ 12 : 16 ] . strip ( ) if not mutated_resids . has_key ( resid ) : newpdb . lines += [ line ] else : newpdb . lines += [ line [ : 17 ] + mutated_resids [ resid ] + line [ 20 : ] ] elif entry != "SEQRES" : newpdb . lines += [ line ] if update_atoms : newpdb . remove_nonbackbone_atoms ( mutated_resids . keys ( ) ) return newpdb
Replace SEQRES lines with a new sequence optionally removing mutated sidechains
468
15
13,894
def has_host_match ( log_data , hosts ) : hostname = getattr ( log_data , 'host' , None ) if hostname and hostname not in host_cache : for host_pattern in hosts : if host_pattern . search ( hostname ) is not None : host_cache . add ( hostname ) return True else : return False return True
Match the data with a list of hostname patterns . If the log line data doesn t include host information considers the line as matched .
80
27
13,895
def run ( self , app ) : GlimLog . info ( 'Glim server started on %s environment' % self . args . env ) try : kwargs = Config . get ( 'app.server.options' ) run ( app . wsgi , host = Config . get ( 'app.server.host' ) , port = Config . get ( 'app.server.port' ) , debug = Config . get ( 'app.server.debugger' ) , reloader = Config . get ( 'app.server.reloader' ) , server = Config . get ( 'app.server.wsgi' ) , * * kwargs ) except Exception as e : print ( traceback . format_exc ( ) ) exit ( )
Function starts the web server given configuration .
161
8
13,896
def get_symmetrical_std_devs ( values , ignore_zeros = True ) : pos_stdeviation = get_symmetrical_std_dev ( values , True , ignore_zeros = ignore_zeros ) neg_stdeviation = get_symmetrical_std_dev ( values , False , ignore_zeros = ignore_zeros ) return pos_stdeviation , neg_stdeviation
Takes a list of values and splits it into positive and negative values . For both of these subsets a symmetrical distribution is created by mirroring each value along the origin and the standard deviation for both subsets is returned .
94
46
13,897
def get_std_xy_dataset_statistics ( x_values , y_values , expect_negative_correlation = False , STDev_cutoff = 1.0 ) : assert ( len ( x_values ) == len ( y_values ) ) csv_lines = [ 'ID,X,Y' ] + [ ',' . join ( map ( str , [ c + 1 , x_values [ c ] , y_values [ c ] ] ) ) for c in xrange ( len ( x_values ) ) ] data = parse_csv ( csv_lines , expect_negative_correlation = expect_negative_correlation , STDev_cutoff = STDev_cutoff ) assert ( len ( data [ 'predictions' ] ) == 1 ) assert ( 1 in data [ 'predictions' ] ) assert ( data [ 'predictions' ] [ 1 ] [ 'name' ] == 'Y' ) summary_data = data [ 'predictions' ] [ 1 ] stats = { } for spair in field_name_mapper : stats [ spair [ 1 ] ] = summary_data [ spair [ 0 ] ] if stats [ 'std_warnings' ] : stats [ 'std_warnings' ] = '\n' . join ( stats [ 'std_warnings' ] ) else : stats [ 'std_warnings' ] = None return stats
Calls parse_csv and returns the analysis in a format similar to get_xy_dataset_statistics in klab . stats . misc .
305
32
13,898
def active_multiplex ( self , state : 'State' ) -> Tuple [ 'Multiplex' ] : return tuple ( multiplex for multiplex in self . multiplexes if multiplex . is_active ( state ) )
Return a tuple of all the active multiplex in the given state .
48
14
13,899
def sanitized_name ( self ) : a = re . split ( "[:/]" , self . name ) return "_" . join ( [ i for i in a if len ( i ) > 0 ] )
Sanitized name of the agent used for file and directory creation .
44
13