idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
14,200 | def get_max_id ( self , object_type , role ) : if object_type == 'user' : objectclass = 'posixAccount' ldap_attr = 'uidNumber' elif object_type == 'group' : # pragma: no cover objectclass = 'posixGroup' ldap_attr = 'gidNumber' else : raise ldap_tools . exceptions . InvalidResult ( 'Unknown object type' ) minID , maxID = Client . __set_id_boundary ( role ) filter = [ "(objectclass={})" . format ( objectclass ) , "({}>={})" . format ( ldap_attr , minID ) ] if maxID is not None : filter . append ( "({}<={})" . format ( ldap_attr , maxID ) ) id_list = self . search ( filter , [ ldap_attr ] ) if id_list == [ ] : id = minID else : if object_type == 'user' : id = max ( [ i . uidNumber . value for i in id_list ] ) + 1 elif object_type == 'group' : id = max ( [ i . gidNumber . value for i in id_list ] ) + 1 else : raise ldap_tools . exceptions . InvalidResult ( 'Unknown object' ) return id | Get the highest used ID . | 299 | 6 |
14,201 | def get_dem ( bounds , out_file = "dem.tif" , src_crs = "EPSG:3005" , dst_crs = "EPSG:3005" , resolution = 25 ) : bbox = "," . join ( [ str ( b ) for b in bounds ] ) # todo: validate resolution units are equivalent to src_crs units # build request payload = { "service" : "WCS" , "version" : "1.0.0" , "request" : "GetCoverage" , "coverage" : "pub:bc_elevation_25m_bcalb" , "Format" : "GeoTIFF" , "bbox" : bbox , "CRS" : src_crs , "RESPONSE_CRS" : dst_crs , "resx" : str ( resolution ) , "resy" : str ( resolution ) , } # request data from WCS r = requests . get ( bcdata . WCS_URL , params = payload ) # save to tiff if r . status_code == 200 : with open ( out_file , "wb" ) as file : file . write ( r . content ) return out_file else : raise RuntimeError ( "WCS request failed with status code {}" . format ( str ( r . status_code ) ) ) | Get 25m DEM for provided bounds write to GeoTIFF | 298 | 12 |
14,202 | def main ( ) : # pragma: no cover entry_point . add_command ( CLI . version ) entry_point . add_command ( UserCLI . user ) entry_point . add_command ( GroupCLI . group ) entry_point . add_command ( AuditCLI . audit ) entry_point . add_command ( KeyCLI . key ) entry_point ( ) | Enter main function . | 84 | 4 |
14,203 | def print_args ( output = sys . stdout ) : def decorator ( func ) : """The decorator function. """ @ wraps ( func ) def _ ( * args , * * kwargs ) : """The decorated function. """ output . write ( "Args: {0}, KwArgs: {1}\n" . format ( str ( args ) , str ( kwargs ) ) ) return func ( * args , * * kwargs ) return _ return decorator | Decorate a function so that print arguments before calling it . | 102 | 12 |
14,204 | def constant ( func ) : @ wraps ( func ) def _ ( * args , * * kwargs ) : """The decorated function. """ if not _ . res : _ . res = func ( * args , * * kwargs ) return _ . res _ . res = None return _ | Decorate a function so that the result is a constant value . | 62 | 13 |
14,205 | def memoized ( func ) : cache = { } @ wraps ( func ) def memoized_function ( * args ) : """The decorated function. """ try : return cache [ args ] except KeyError : value = func ( * args ) try : cache [ args ] = value except MemoryError : cache . clear ( ) gc . collect ( ) return value return memoized_function | Decorate a function to memoize results . | 80 | 9 |
14,206 | def _open_sqlite ( db_file ) : db_file = os . path . expanduser ( db_file ) try : with open ( db_file ) : # test that the file can be accessed pass return sqlite3 . connect ( db_file , detect_types = sqlite3 . PARSE_DECLTYPES ) except ( IOError , sqlite3 . Error ) as err : raise Dump2PolarionException ( "{}" . format ( err ) ) | Opens database connection . | 105 | 5 |
14,207 | def import_sqlite ( db_file , older_than = None , * * kwargs ) : conn = _open_sqlite ( db_file ) cur = conn . cursor ( ) # get rows that were not exported yet select = "SELECT * FROM testcases WHERE exported != 'yes'" if older_than : cur . execute ( " " . join ( ( select , "AND sqltime < ?" ) ) , ( older_than , ) ) else : cur . execute ( select ) columns = [ description [ 0 ] for description in cur . description ] rows = cur . fetchall ( ) # map data to columns results = [ ] for row in rows : record = OrderedDict ( list ( zip ( columns , row ) ) ) results . append ( record ) testrun = _get_testrun_from_sqlite ( conn ) conn . close ( ) return xunit_exporter . ImportedData ( results = results , testrun = testrun ) | Reads the content of the database file and returns imported data . | 207 | 13 |
14,208 | def mark_exported_sqlite ( db_file , older_than = None ) : logger . debug ( "Marking rows in database as exported" ) conn = _open_sqlite ( db_file ) cur = conn . cursor ( ) update = "UPDATE testcases SET exported = 'yes' WHERE verdict IS NOT null AND verdict != ''" if older_than : cur . execute ( " " . join ( ( update , "AND sqltime < ?" ) ) , ( older_than , ) ) else : cur . execute ( update ) conn . commit ( ) conn . close ( ) | Marks rows with verdict as exported . | 127 | 8 |
14,209 | def createSubtitle ( self , fps , section ) : matched = self . _pattern . search ( section ) if matched is not None : matchedDict = matched . groupdict ( ) return Subtitle ( self . frametime ( fps , matchedDict . get ( "time_from" ) ) , self . frametime ( fps , matchedDict . get ( "time_to" ) ) , self . formatSub ( matchedDict . get ( "text" ) ) ) return None | Returns a correct Subtitle object from a text given in section . If section cannot be parsed None is returned . By default section is checked against subPattern regular expression . | 104 | 33 |
14,210 | def convertTime ( self , frametime , which ) : SubAssert ( frametime . frame >= 0 , _ ( "Negative time present." ) ) return frametime . frame | Convert FrameTime object to properly formatted string that describes subtitle start or end time . | 38 | 17 |
14,211 | def _set_location ( instance , location ) : location = str ( location ) if not location . startswith ( '/' ) : location = urljoin ( instance . request_path . rstrip ( '/' ) + '/' , location ) instance . response . location = location | Sets a Location response header . If the location does not start with a slash the path of the current request is prepended . | 59 | 26 |
14,212 | def no_cache ( asset_url ) : pos = asset_url . rfind ( '?' ) if pos > 0 : asset_url = asset_url [ : pos ] return asset_url | Removes query parameters | 42 | 4 |
14,213 | def __ngrams ( s , n = 3 ) : return list ( zip ( * [ s [ i : ] for i in range ( n ) ] ) ) | Raw n - grams from a sequence | 34 | 7 |
14,214 | def word_ngrams ( s , n = 3 , token_fn = tokens . on_whitespace ) : tokens = token_fn ( s ) return __ngrams ( tokens , n = min ( len ( tokens ) , n ) ) | Word - level n - grams in a string | 52 | 9 |
14,215 | def char_ngrams ( s , n = 3 , token_fn = tokens . on_whitespace ) : tokens = token_fn ( s ) ngram_tuples = [ __ngrams ( t , n = min ( len ( t ) , n ) ) for t in tokens ] def unpack ( l ) : return sum ( l , [ ] ) def untuple ( l ) : return [ '' . join ( t ) for t in l ] return untuple ( unpack ( ngram_tuples ) ) | Character - level n - grams from within the words in a string . | 112 | 14 |
14,216 | def __matches ( s1 , s2 , ngrams_fn , n = 3 ) : ngrams1 , ngrams2 = set ( ngrams_fn ( s1 , n = n ) ) , set ( ngrams_fn ( s2 , n = n ) ) return ngrams1 . intersection ( ngrams2 ) | Returns the n - grams that match between two sequences | 78 | 10 |
14,217 | def char_matches ( s1 , s2 , n = 3 ) : return __matches ( s1 , s2 , char_ngrams , n = n ) | Character - level n - grams that match between two strings | 37 | 11 |
14,218 | def word_matches ( s1 , s2 , n = 3 ) : return __matches ( s1 , s2 , word_ngrams , n = n ) | Word - level n - grams that match between two strings | 37 | 11 |
14,219 | def __similarity ( s1 , s2 , ngrams_fn , n = 3 ) : ngrams1 , ngrams2 = set ( ngrams_fn ( s1 , n = n ) ) , set ( ngrams_fn ( s2 , n = n ) ) matches = ngrams1 . intersection ( ngrams2 ) return 2 * len ( matches ) / ( len ( ngrams1 ) + len ( ngrams2 ) ) | The fraction of n - grams matching between two sequences | 104 | 10 |
14,220 | def _get_json ( self , model , space = None , rel_path = None , extra_params = None , get_all = None ) : # Only API.spaces and API.event should not provide # the `space argument if space is None and model not in ( Space , Event ) : raise Exception ( 'In general, `API._get_json` should always ' 'be called with a `space` argument.' ) if not extra_params : extra_params = { } # Handle pagination for requests carrying large amounts of data extra_params [ 'page' ] = extra_params . get ( 'page' , 1 ) # Generate the url to hit url = '{0}/{1}/{2}.json?{3}' . format ( settings . API_ROOT_PATH , settings . API_VERSION , rel_path or model . rel_path , urllib . urlencode ( extra_params ) , ) # If the cache is being used and the url has been hit already if self . cache_responses and url in self . cache : response = self . cache [ url ] else : # Fetch the data headers = { 'X-Api-Key' : self . key , 'X-Api-Secret' : self . secret , } response = self . session . get ( url = url , headers = headers ) # If the cache is being used, update it if self . cache_responses : self . cache [ url ] = response if response . status_code == 200 : # OK results = [ ] json_response = response . json ( ) for obj in json_response : instance = model ( data = obj ) instance . api = self if space : instance . space = space results . append ( instance ) # If it looks like there are more pages to fetch, # try and fetch the next one per_page = extra_params . get ( 'per_page' , None ) if ( get_all and per_page and len ( json_response ) and per_page == len ( json_response ) ) : extra_params [ 'page' ] += 1 results = results + self . _get_json ( model , space , rel_path , extra_params , get_all = get_all ) return results elif response . status_code == 204 : # No Content return [ ] else : # Most likely a 404 Not Found raise Exception ( 'Code {0} returned from `{1}`. Response text: "{2}".' . format ( response . status_code , url , response . text ) ) | Base level method for fetching data from the API | 552 | 10 |
14,221 | def _post_json ( self , instance , space = None , rel_path = None , extra_params = None ) : model = type ( instance ) # Only API.spaces and API.event should not provide # the `space argument if space is None and model not in ( Space , Event ) : raise Exception ( 'In general, `API._post_json` should always ' 'be called with a `space` argument.' ) if 'number' in instance . data : raise AttributeError ( 'You cannot create a ticket which already has a number' ) if not extra_params : extra_params = { } # Generate the url to hit url = '{0}/{1}/{2}?{3}' . format ( settings . API_ROOT_PATH , settings . API_VERSION , rel_path or model . rel_path , urllib . urlencode ( extra_params ) , ) # Fetch the data response = requests . post ( url = url , data = json . dumps ( instance . data ) , headers = { 'X-Api-Key' : self . key , 'X-Api-Secret' : self . secret , 'Content-type' : "application/json" , } , ) if response . status_code == 201 : # OK instance = model ( data = response . json ( ) ) instance . api = self if space : instance . space = space return instance else : # Most likely a 404 Not Found raise Exception ( 'Code {0} returned from `{1}`. Response text: "{2}".' . format ( response . status_code , url , response . text ) ) | Base level method for updating data via the API | 356 | 9 |
14,222 | def _put_json ( self , instance , space = None , rel_path = None , extra_params = None , id_field = None ) : model = type ( instance ) # Only API.spaces and API.event should not provide # the `space argument if space is None and model not in ( Space , Event ) : raise Exception ( 'In general, `API._put_json` should always ' 'be called with a `space` argument.' ) if not extra_params : extra_params = { } if not id_field : id_field = 'number' # Generate the url to hit url = '{0}/{1}/{2}/{3}.json?{4}' . format ( settings . API_ROOT_PATH , settings . API_VERSION , rel_path or model . rel_path , instance [ id_field ] , urllib . urlencode ( extra_params ) , ) # Fetch the data response = requests . put ( url = url , data = json . dumps ( instance . data ) , headers = { 'X-Api-Key' : self . key , 'X-Api-Secret' : self . secret , 'Content-type' : "application/json" , } , ) if response . status_code == 204 : # OK return instance else : # Most likely a 404 Not Found raise Exception ( 'Code {0} returned from `{1}`. Response text: "{2}".' . format ( response . status_code , url , response . text ) ) | Base level method for adding new data to the API | 335 | 10 |
14,223 | def _delete_json ( self , instance , space = None , rel_path = None , extra_params = None , id_field = None , append_to_path = None ) : model = type ( instance ) # Only API.spaces and API.event should not provide # the `space argument if space is None and model not in ( Space , Event ) : raise Exception ( 'In general, `API._delete_json` should always ' 'be called with a `space` argument.' ) if not extra_params : extra_params = { } if not id_field : id_field = 'number' if not instance . get ( id_field , None ) : raise AttributeError ( '%s does not have a value for the id field \'%s\'' % ( instance . __class__ . __name__ , id_field ) ) # Generate the url to hit url = '{0}/{1}/{2}/{3}{4}.json?{5}' . format ( settings . API_ROOT_PATH , settings . API_VERSION , rel_path or model . rel_path , instance [ id_field ] , append_to_path or '' , urllib . urlencode ( extra_params ) , ) # Fetch the data response = requests . delete ( url = url , headers = { 'X-Api-Key' : self . key , 'X-Api-Secret' : self . secret , 'Content-type' : "application/json" , } , ) if response . status_code == 204 : # OK return True else : # Most likely a 404 Not Found raise Exception ( 'Code {0} returned from `{1}`. Response text: "{2}".' . format ( response . status_code , url , response . text ) ) | Base level method for removing data from the API | 394 | 9 |
14,224 | def _bind_variables ( self , instance , space ) : instance . api = self if space : instance . space = space return instance | Bind related variables to the instance | 29 | 6 |
14,225 | def tickets ( self , extra_params = None ) : # Default params params = { 'per_page' : settings . MAX_PER_PAGE , 'report' : 0 , # Report 0 is all tickets } if extra_params : params . update ( extra_params ) return self . api . _get_json ( Ticket , space = self , rel_path = self . _build_rel_path ( 'tickets' ) , extra_params = params , get_all = True , # Retrieve all tickets in the space ) | All Tickets in this Space | 115 | 5 |
14,226 | def milestones ( self , extra_params = None ) : # Default params params = { 'per_page' : settings . MAX_PER_PAGE , } if extra_params : params . update ( extra_params ) return self . api . _get_json ( Milestone , space = self , rel_path = self . _build_rel_path ( 'milestones/all' ) , extra_params = params , get_all = True , # Retrieve all milestones in the space ) | All Milestones in this Space | 106 | 6 |
14,227 | def tools ( self , extra_params = None ) : return self . api . _get_json ( SpaceTool , space = self , rel_path = self . _build_rel_path ( 'space_tools' ) , extra_params = extra_params , ) | All Tools in this Space | 58 | 5 |
14,228 | def components ( self , extra_params = None ) : return self . api . _get_json ( Component , space = self , rel_path = self . _build_rel_path ( 'ticket_components' ) , extra_params = extra_params , ) | All components in this Space | 58 | 5 |
14,229 | def users ( self , extra_params = None ) : return self . api . _get_json ( User , space = self , rel_path = self . _build_rel_path ( 'users' ) , extra_params = extra_params , ) | All Users with access to this Space | 55 | 7 |
14,230 | def tags ( self , extra_params = None ) : return self . api . _get_json ( Tag , space = self , rel_path = self . _build_rel_path ( 'tags' ) , extra_params = extra_params , ) | All Tags in this Space | 55 | 5 |
14,231 | def wiki_pages ( self , extra_params = None ) : return self . api . _get_json ( WikiPage , space = self , rel_path = self . _build_rel_path ( 'wiki_pages' ) , extra_params = extra_params , ) | All Wiki Pages with access to this Space | 60 | 8 |
14,232 | def tickets ( self , extra_params = None ) : return filter ( lambda ticket : ticket . get ( 'milestone_id' , None ) == self [ 'id' ] , self . space . tickets ( extra_params = extra_params ) ) | All Tickets which are a part of this Milestone | 54 | 10 |
14,233 | def tags ( self , extra_params = None ) : # Default params params = { 'per_page' : settings . MAX_PER_PAGE , } if extra_params : params . update ( extra_params ) return self . api . _get_json ( Tag , space = self , rel_path = self . space . _build_rel_path ( 'tickets/%s/tags' % self [ 'number' ] ) , extra_params = params , get_all = True , # Retrieve all tags in the ticket ) | All Tags in this Ticket | 117 | 5 |
14,234 | def milestone ( self , extra_params = None ) : if self . get ( 'milestone_id' , None ) : milestones = self . space . milestones ( id = self [ 'milestone_id' ] , extra_params = extra_params ) if milestones : return milestones [ 0 ] | The Milestone that the Ticket is a part of | 63 | 10 |
14,235 | def user ( self , extra_params = None ) : if self . get ( 'assigned_to_id' , None ) : users = self . space . users ( id = self [ 'assigned_to_id' ] , extra_params = extra_params ) if users : return users [ 0 ] | The User currently assigned to the Ticket | 67 | 7 |
14,236 | def component ( self , extra_params = None ) : if self . get ( 'component_id' , None ) : components = self . space . components ( id = self [ 'component_id' ] , extra_params = extra_params ) if components : return components [ 0 ] | The Component currently assigned to the Ticket | 61 | 7 |
14,237 | def comments ( self , extra_params = None ) : # Default params params = { 'per_page' : settings . MAX_PER_PAGE , } if extra_params : params . update ( extra_params ) return self . api . _get_json ( TicketComment , space = self , rel_path = self . space . _build_rel_path ( 'tickets/%s/ticket_comments' % self [ 'number' ] ) , extra_params = params , get_all = True , # Retrieve all comments in the ticket ) | All Comments in this Ticket | 120 | 5 |
14,238 | def write ( self ) : if not hasattr ( self , 'space' ) : raise AttributeError ( "A ticket must have a 'space' attribute before you can write it to Assembla." ) if self . get ( 'number' ) : # Modifying an existing ticket method = self . space . api . _put_json else : # Creating a new ticket method = self . space . api . _post_json return method ( self , space = self . space , rel_path = self . space . _build_rel_path ( 'tickets' ) , ) | Create or update the Ticket on Assembla | 124 | 9 |
14,239 | def delete ( self ) : if not hasattr ( self , 'space' ) : raise AttributeError ( "A ticket must have a 'space' attribute before you can remove it from Assembla." ) return self . space . api . _delete_json ( self , space = self . space , rel_path = self . space . _build_rel_path ( 'tickets' ) , ) | Remove the Ticket from Assembla | 86 | 7 |
14,240 | def tickets ( self , extra_params = None ) : tickets = [ ] for space in self . api . spaces ( ) : tickets += filter ( lambda ticket : ticket . get ( 'assigned_to_id' , None ) == self [ 'id' ] , space . tickets ( extra_params = extra_params ) ) return tickets | A User s tickets across all available spaces | 72 | 8 |
14,241 | def write ( self ) : if not hasattr ( self , 'space' ) : raise AttributeError ( "A WikiPage must have a 'space' attribute before you can write it to Assembla." ) self . api = self . space . api if self . get ( 'id' ) : # We are modifying an existing wiki page return self . api . _put_json ( self , space = self . space , rel_path = self . space . _build_rel_path ( 'wiki_pages' ) , id_field = 'id' ) else : # Creating a new wiki page return self . api . _post_json ( self , space = self . space , rel_path = self . space . _build_rel_path ( 'wiki_pages' ) , ) | Create or update a Wiki Page on Assembla | 169 | 10 |
14,242 | def add ( self , spec ) : for limit in spec . limit_to : if limit not in self . limit_to : self . limit_to . append ( limit ) | Add limitations of given spec to self s . | 37 | 9 |
14,243 | def combine ( specs ) : new_specs = { } for spec in specs : if new_specs . get ( spec , None ) is None : new_specs [ spec ] = spec else : new_specs [ spec ] . add ( spec ) return list ( new_specs . values ( ) ) | Combine package specifications limitations . | 68 | 6 |
14,244 | def find ( self , package , * * kwargs ) : for finder in self . finders : package_spec = finder . find ( package , * * kwargs ) if package_spec : return package_spec return None | Find a package using package finders . | 51 | 8 |
14,245 | def _lazy_turbo_mapping ( initial , pre_size ) : size = pre_size or ( 2 * len ( initial ) ) or 8 buckets = size * [ None ] if not isinstance ( initial , colls . Mapping ) : initial = dict ( initial ) for k , v in six . iteritems ( initial ) : h = hash ( k ) index = h % size bucket = buckets [ index ] if bucket : bucket . append ( ( k , v ) ) else : buckets [ index ] = [ ( k , v ) ] return LazyPMap ( len ( initial ) , ps . pvector ( ) . extend ( buckets ) ) | _lazy_turbo_mapping is a blatant copy of the pyrsistent . _pmap . _turbo_mapping function except it works for lazy maps ; this seems like the only way to fully overload PMap . | 141 | 49 |
14,246 | def lazy_map ( initial = { } , pre_size = 0 ) : if is_lazy_map ( initial ) : return initial if not initial : return _EMPTY_LMAP return _lazy_turbo_mapping ( initial , pre_size ) | lazy_map is a blatant copy of the pyrsistent . pmap function and is used to create lazy maps . | 58 | 25 |
14,247 | def _examine_val ( self , k , val ) : if not isinstance ( val , ( types . FunctionType , partial ) ) : return val vid = id ( val ) if vid in self . _memoized : return self . _memoized [ vid ] elif [ ] != getargspec_py27like ( val ) [ 0 ] : return val else : val = val ( ) object . __setattr__ ( self , '_memoized' , self . _memoized . set ( vid , val ) ) return val | should only be called internally | 123 | 5 |
14,248 | def psh_fire_msg_action_if_new ( sender , instance , created , * * kwargs ) : if created : from message_sender . tasks import send_message send_message . apply_async ( kwargs = { "message_id" : str ( instance . id ) } ) | Post save hook to fire message send task | 69 | 8 |
14,249 | def update_default_channels ( sender , instance , created , * * kwargs ) : if instance . default : Channel . objects . filter ( default = True ) . exclude ( channel_id = instance . channel_id ) . update ( default = False ) | Post save hook to ensure that there is only one default | 56 | 11 |
14,250 | def map_fit ( interface , state , label , inp ) : import numpy as np ete , etde = 0 , 0 out = interface . output ( 0 ) for row in inp : row = row . strip ( ) . split ( state [ "delimiter" ] ) # split row if len ( row ) > 1 : # check if row is empty # intercept term is added to every sample x = np . array ( [ ( 0 if v in state [ "missing_vals" ] else float ( v ) ) for i , v in enumerate ( row ) if i in state [ "X_indices" ] ] + [ - 1 ] ) # map label value to 1 or -1. If label does not match set error y = 1 if state [ "y_map" ] [ 0 ] == row [ state [ "y_index" ] ] else - 1 if state [ "y_map" ] [ 1 ] == row [ state [ "y_index" ] ] else "Error" ete += np . outer ( x , x ) etde += x * y out . add ( "etde" , etde ) for i , row in enumerate ( ete ) : out . add ( i , row ) | Function calculates matrices ete and etde for every sample aggregates and output them . | 266 | 18 |
14,251 | def reduce_fit ( interface , state , label , inp ) : import numpy as np out = interface . output ( 0 ) sum_etde = 0 sum_ete = [ 0 for _ in range ( len ( state [ "X_indices" ] ) + 1 ) ] for key , value in inp : if key == "etde" : sum_etde += value else : sum_ete [ key ] += value sum_ete += np . true_divide ( np . eye ( len ( sum_ete ) ) , state [ "nu" ] ) out . add ( "params" , np . linalg . lstsq ( sum_ete , sum_etde ) [ 0 ] ) | Function joins all partially calculated matrices ETE and ETDe aggregates them and it calculates final parameters . | 154 | 21 |
14,252 | def fit ( dataset , nu = 0.1 , save_results = True , show = False ) : from disco . worker . pipeline . worker import Worker , Stage from disco . core import Job if dataset . params [ "y_map" ] == [ ] : raise Exception ( "Linear proximal SVM requires a target label mapping parameter." ) try : nu = float ( nu ) if nu <= 0 : raise Exception ( "Parameter nu should be greater than 0" ) except ValueError : raise Exception ( "Parameter should be numerical." ) job = Job ( worker = Worker ( save_results = save_results ) ) # job parallelizes mappers and joins them with one reducer job . pipeline = [ ( "split" , Stage ( "map" , input_chain = dataset . params [ "input_chain" ] , init = simple_init , process = map_fit ) ) , ( 'group_all' , Stage ( "reduce" , init = simple_init , process = reduce_fit , combine = True ) ) ] job . params = dataset . params job . params [ "nu" ] = nu job . run ( name = "linearsvm_fit" , input = dataset . params [ "data_tag" ] ) fitmodel_url = job . wait ( show = show ) return { "linsvm_fitmodel" : fitmodel_url } | Function starts a job for calculation of model parameters | 292 | 9 |
14,253 | def predict ( dataset , fitmodel_url , save_results = True , show = False ) : from disco . worker . pipeline . worker import Worker , Stage from disco . core import Job , result_iterator if "linsvm_fitmodel" not in fitmodel_url : raise Exception ( "Incorrect fit model." ) job = Job ( worker = Worker ( save_results = save_results ) ) # job parallelizes execution of mappers job . pipeline = [ ( "split" , Stage ( "map" , input_chain = dataset . params [ "input_chain" ] , init = simple_init , process = map_predict ) ) ] job . params = dataset . params job . params [ "fit_params" ] = [ v for _ , v in result_iterator ( fitmodel_url [ "linsvm_fitmodel" ] ) ] [ 0 ] job . run ( name = "linsvm_predict" , input = dataset . params [ "data_tag" ] ) return job . wait ( show = show ) | Function starts a job that makes predictions to input data with a given model . | 222 | 15 |
14,254 | def validate_redirect_url ( next_url ) : if not next_url : return None parts = urlparse ( next_url ) if parts . netloc : domain , _ = split_domain_port ( parts . netloc ) allowed_hosts = ( [ '*' ] if django_settings . DEBUG else django_settings . ALLOWED_HOSTS ) if not ( domain and validate_host ( domain , allowed_hosts ) ) : return None return urlunparse ( ( "" , "" , parts . path , parts . params , parts . query , parts . fragment ) ) | Returns the next_url path if next_url matches allowed hosts . | 130 | 14 |
14,255 | def convert_currency ( amount , from_currency , to_currency ) : try : rate = CurrencyRate . objects . get ( from_currency__iso_code = from_currency , to_currency__iso_code = to_currency ) except CurrencyRate . DoesNotExist : return _ ( 'n/a' ) try : history = rate . history . all ( ) [ 0 ] except IndexError : return _ ( 'n/a' ) return amount * history . value | Converts currencies . | 102 | 4 |
14,256 | def url_prefixed ( regex , view , name = None ) : return url ( r'^%(app_prefix)s%(regex)s' % { 'app_prefix' : APP_PREFIX , 'regex' : regex } , view , name = name ) | Returns a urlpattern prefixed with the APP_NAME in debug mode . | 63 | 15 |
14,257 | def createDataFromFile ( self , filePath , inputEncoding = None , defaultFps = None ) : file_ = File ( filePath ) if inputEncoding is None : inputEncoding = file_ . detectEncoding ( ) inputEncoding = inputEncoding . lower ( ) videoInfo = VideoInfo ( defaultFps ) if defaultFps is not None else file_ . detectFps ( ) subtitles = self . _parseFile ( file_ , inputEncoding , videoInfo . fps ) data = SubtitleData ( ) data . subtitles = subtitles data . fps = videoInfo . fps data . inputEncoding = inputEncoding data . outputEncoding = inputEncoding data . outputFormat = self . _parser . parsedFormat ( ) data . videoPath = videoInfo . videoPath return data | Fetch a given filePath and parse its contents . | 172 | 11 |
14,258 | def _set_property ( xml_root , name , value , properties = None ) : if properties is None : properties = xml_root . find ( "properties" ) for prop in properties : if prop . get ( "name" ) == name : prop . set ( "value" , utils . get_unicode_str ( value ) ) break else : etree . SubElement ( properties , "property" , { "name" : name , "value" : utils . get_unicode_str ( value ) } ) | Sets property to specified value . | 114 | 7 |
14,259 | def generate_response_property ( name = None , value = None ) : name = name or "dump2polarion" value = value or "" . join ( random . sample ( string . ascii_lowercase , 12 ) ) return ( name , value ) | Generates response property . | 57 | 5 |
14,260 | def fill_response_property ( xml_root , name = None , value = None ) : name , value = generate_response_property ( name , value ) response_property = None if xml_root . tag == "testsuites" : response_property = _fill_testsuites_response_property ( xml_root , name , value ) elif xml_root . tag in ( "testcases" , "requirements" ) : response_property = _fill_non_testsuites_response_property ( xml_root , name , value ) else : raise Dump2PolarionException ( _NOT_EXPECTED_FORMAT_MSG ) return response_property | Returns response property and fills it if missing . | 148 | 9 |
14,261 | def remove_response_property ( xml_root ) : if xml_root . tag == "testsuites" : properties = xml_root . find ( "properties" ) resp_properties = [ ] for prop in properties : prop_name = prop . get ( "name" , "" ) if "polarion-response-" in prop_name : resp_properties . append ( prop ) for resp_property in resp_properties : properties . remove ( resp_property ) elif xml_root . tag in ( "testcases" , "requirements" ) : resp_properties = xml_root . find ( "response-properties" ) if resp_properties is not None : xml_root . remove ( resp_properties ) else : raise Dump2PolarionException ( _NOT_EXPECTED_FORMAT_MSG ) | Removes response properties if exist . | 178 | 7 |
14,262 | def remove_property ( xml_root , partial_name ) : if xml_root . tag in ( "testsuites" , "testcases" , "requirements" ) : properties = xml_root . find ( "properties" ) remove_properties = [ ] for prop in properties : prop_name = prop . get ( "name" , "" ) if partial_name in prop_name : remove_properties . append ( prop ) for rem_prop in remove_properties : properties . remove ( rem_prop ) else : raise Dump2PolarionException ( _NOT_EXPECTED_FORMAT_MSG ) | Removes properties if exist . | 134 | 6 |
14,263 | def set_lookup_method ( xml_root , value ) : if xml_root . tag == "testsuites" : _set_property ( xml_root , "polarion-lookup-method" , value ) elif xml_root . tag in ( "testcases" , "requirements" ) : _set_property ( xml_root , "lookup-method" , value ) else : raise Dump2PolarionException ( _NOT_EXPECTED_FORMAT_MSG ) | Changes lookup method . | 112 | 4 |
14,264 | def set_dry_run ( xml_root , value = True ) : value_str = str ( value ) . lower ( ) assert value_str in ( "true" , "false" ) if xml_root . tag == "testsuites" : _set_property ( xml_root , "polarion-dry-run" , value_str ) elif xml_root . tag in ( "testcases" , "requirements" ) : _set_property ( xml_root , "dry-run" , value_str ) else : raise Dump2PolarionException ( _NOT_EXPECTED_FORMAT_MSG ) | Sets dry - run so records are not updated only log file is produced . | 141 | 16 |
14,265 | def get_environ ( cls , prefix ) : return ( ( key [ len ( prefix ) + 1 : ] , value ) for key , value in os . environ . items ( ) if key . startswith ( '%s_' % prefix ) ) | Retrieves environment variables from a namespace . | 57 | 9 |
14,266 | def get_bool ( self , name , default = None ) : if name not in self : if default is not None : return default raise EnvironmentError . not_found ( self . _prefix , name ) return bool ( self . get_int ( name ) ) | Retrieves an environment variable value as bool . | 55 | 10 |
14,267 | def get_dict ( self , name , default = None ) : if name not in self : if default is not None : return default raise EnvironmentError . not_found ( self . _prefix , name ) return dict ( * * self . get ( name ) ) | Retrieves an environment variable value as a dictionary . | 55 | 11 |
14,268 | def get_int ( self , name , default = None ) : if name not in self : if default is not None : return default raise EnvironmentError . not_found ( self . _prefix , name ) return int ( self [ name ] ) | Retrieves an environment variable as an integer . | 51 | 10 |
14,269 | def get_list ( self , name , default = None ) : if name not in self : if default is not None : return default raise EnvironmentError . not_found ( self . _prefix , name ) return list ( self [ name ] ) | Retrieves an environment variable as a list . | 51 | 10 |
14,270 | def get_path ( self , name , default = None ) : if name not in self : if default is not None : return default raise EnvironmentError . not_found ( self . _prefix , name ) return pathlib . Path ( self [ name ] ) | Retrieves an environment variable as a filesystem path . | 54 | 11 |
14,271 | def refresh ( self ) : super ( Habitat , self ) . update ( self . get_environ ( self . _prefix ) ) | Update all environment variables from os . environ . | 29 | 10 |
14,272 | def _transform_result ( self , result ) : if self . _transform_func : result = self . _transform_func ( result ) return result or None | Calls transform function on result . | 34 | 7 |
14,273 | def _get_verdict ( result ) : verdict = result . get ( "verdict" ) if not verdict : return None verdict = verdict . strip ( ) . lower ( ) if verdict not in Verdicts . PASS + Verdicts . FAIL + Verdicts . SKIP + Verdicts . WAIT : return None return verdict | Gets verdict of the testcase . | 73 | 8 |
14,274 | def _set_lookup_prop ( self , result_data ) : if self . _lookup_prop : return if result_data . get ( "id" ) : self . _lookup_prop = "id" elif result_data . get ( "title" ) : self . _lookup_prop = "name" else : return logger . debug ( "Setting lookup method for xunit to `%s`" , self . _lookup_prop ) | Set lookup property based on processed testcases if not configured . | 102 | 12 |
14,275 | def _fill_out_err ( result , testcase ) : if result . get ( "stdout" ) : system_out = etree . SubElement ( testcase , "system-out" ) system_out . text = utils . get_unicode_str ( result [ "stdout" ] ) if result . get ( "stderr" ) : system_err = etree . SubElement ( testcase , "system-err" ) system_err . text = utils . get_unicode_str ( result [ "stderr" ] ) | Adds stdout and stderr if present . | 124 | 10 |
14,276 | def _fill_properties ( verdict , result , testcase , testcase_id , testcase_title ) : properties = etree . SubElement ( testcase , "properties" ) etree . SubElement ( properties , "property" , { "name" : "polarion-testcase-id" , "value" : testcase_id or testcase_title } , ) if verdict in Verdicts . PASS and result . get ( "comment" ) : etree . SubElement ( properties , "property" , { "name" : "polarion-testcase-comment" , "value" : utils . get_unicode_str ( result [ "comment" ] ) , } , ) for param , value in six . iteritems ( result . get ( "params" ) or { } ) : etree . SubElement ( properties , "property" , { "name" : "polarion-parameter-{}" . format ( param ) , "value" : utils . get_unicode_str ( value ) , } , ) | Adds properties into testcase element . | 230 | 7 |
14,277 | def export ( self ) : top = self . _top_element ( ) properties = self . _properties_element ( top ) testsuite = self . _testsuite_element ( top ) self . _fill_tests_results ( testsuite ) self . _fill_lookup_prop ( properties ) return utils . prettify_xml ( top ) | Returns XUnit XML . | 78 | 5 |
14,278 | def parse ( log_file ) : with io . open ( os . path . expanduser ( log_file ) , encoding = "utf-8" ) as input_file : for line in input_file : if "Starting import of XUnit results" in line : obj = XUnitParser break elif "Starting import of test cases" in line : obj = TestcasesParser break elif "Starting import of requirements" in line : obj = RequirementsParser break else : raise Dump2PolarionException ( "No valid data found in the log file '{}'" . format ( log_file ) ) return obj ( input_file , log_file ) . parse ( ) | Parse log file . | 144 | 5 |
14,279 | def get_result ( self , line ) : res = self . RESULT_SEARCH . search ( line ) try : name , ids = res . group ( 1 ) , res . group ( 2 ) except ( AttributeError , IndexError ) : return None ids = ids . split ( "/" ) tc_id = ids [ 0 ] try : custom_id = ids [ 1 ] except IndexError : custom_id = None return LogItem ( name , tc_id , custom_id ) | Gets work item name and id . | 110 | 8 |
14,280 | def get_result_warn ( self , line ) : res = self . RESULT_WARN_SEARCH . search ( line ) try : return LogItem ( res . group ( 1 ) , None , None ) except ( AttributeError , IndexError ) : pass # try again with custom ID res = self . RESULT_WARN_SEARCH_CUSTOM . search ( line ) try : return LogItem ( res . group ( 1 ) , None , res . group ( 2 ) ) except ( AttributeError , IndexError ) : return None | Gets work item name of item that was not successfully imported . | 116 | 13 |
14,281 | def get_requirement ( self , line ) : res = self . REQ_SEARCH . search ( line ) try : name , tc_id = res . group ( 1 ) , res . group ( 2 ) except ( AttributeError , IndexError ) : return None return LogItem ( name , tc_id , None ) | Gets requirement name and id . | 70 | 7 |
14,282 | def get_requirement_warn ( self , line ) : res = self . REQ_WARN_SEARCH . search ( line ) try : return LogItem ( res . group ( 1 ) , None , None ) except ( AttributeError , IndexError ) : return None | Gets name of test case that was not successfully imported . | 58 | 12 |
14,283 | def load_config ( app_name , * args , * * kwargs ) : configure_logging ( ) # compatible with Python 2 and 3. prefix = kwargs . get ( 'prefix' , 'etc' ) verbose = kwargs . get ( 'verbose' , False ) location = kwargs . get ( 'location' , None ) passphrase = kwargs . get ( 'passphrase' , os . getenv ( "%s_SETTINGS_CRYPT_KEY" % app_name . upper ( ) , os . getenv ( "SETTINGS_CRYPT_KEY" , None ) ) ) confnames = args if not location : location = os . getenv ( "%s_SETTINGS_LOCATION" % app_name . upper ( ) , None ) if not location : location = os . getenv ( "SETTINGS_LOCATION" , None ) if location : location = "%s/%s" % ( location , app_name ) config = { } for confname in confnames : content = None if location and location . startswith ( 's3://' ) : try : import boto _ , bucket_name , prefix = urlparse ( location ) [ : 3 ] try : conn = boto . connect_s3 ( ) bucket = conn . get_bucket ( bucket_name ) key_name = '%s/%s' % ( prefix , confname ) key = bucket . get_key ( key_name ) content = key . get_contents_as_string ( ) if verbose : LOGGER . info ( "config loaded from 's3://%s/%s'" , bucket_name , key_name ) except ( boto . exception . NoAuthHandlerFound , boto . exception . S3ResponseError ) as _ : pass except ImportError : pass # We cannot find a deployutils S3 bucket. Let's look on the filesystem. if not content : confpath = locate_config ( confname , app_name , location = location , prefix = prefix , verbose = verbose ) if confpath : with open ( confpath , 'rb' ) as conffile : content = conffile . read ( ) if content : if passphrase : content = crypt . decrypt ( content , passphrase ) if hasattr ( content , 'decode' ) : content = content . decode ( 'utf-8' ) for line in content . split ( '\n' ) : if not line . startswith ( '#' ) : look = re . match ( r'(\w+)\s*=\s*(.*)' , line ) if look : try : # We used to parse the file line by line. # Once Django 1.5 introduced ALLOWED_HOSTS # (a tuple that definitely belongs to the site.conf # set), we had no choice other than resort # to eval(value, {}, {}). # We are not resorting to import conf module yet # but that might be necessary once we use # dictionary configs for some of the apps... # TODO: consider using something like ConfigObj # for this: # http://www.voidspace.org.uk/python/configobj.html #pylint:disable=eval-used config . update ( { look . group ( 1 ) . upper ( ) : eval ( look . group ( 2 ) , { } , { } ) } ) except Exception : raise return config | Given a path to a file parse its lines in ini - like format and then set them in the current namespace . | 746 | 24 |
14,284 | def close ( account_id : str ) -> None : logger . info ( 'closing-account' , account_id = account_id ) with transaction . atomic ( ) : account = Account . objects . get ( pk = account_id ) account . close ( ) account . save ( ) | Closes the account . | 63 | 5 |
14,285 | def create_invoices ( account_id : str , due_date : date ) -> Sequence [ Invoice ] : invoices = [ ] with transaction . atomic ( ) : due_charges = Charge . objects . uninvoiced ( account_id = account_id ) . charges ( ) total = total_amount ( due_charges ) for amount_due in total . monies ( ) : if amount_due . amount > 0 : invoice = Invoice . objects . create ( account_id = account_id , due_date = due_date ) Charge . objects . uninvoiced ( account_id = account_id ) . charges ( ) . in_currency ( currency = amount_due . currency ) . update ( invoice = invoice ) invoices . append ( invoice ) logger . info ( 'created-invoices' , account_id = str ( account_id ) , invoice_ids = [ i . pk for i in invoices ] ) for invoice in invoices : invoice_ready . send ( sender = create_invoices , invoice = invoice ) return invoices | Creates the invoices for any due positive charges in the account . If there are due positive charges in different currencies one invoice is created for each currency . | 236 | 32 |
14,286 | def add_charge ( account_id : str , amount : Money , reverses_id : Optional [ str ] = None , product_code : Optional [ str ] = None , product_properties : Optional [ Dict [ str , str ] ] = None ) -> Charge : logger . info ( 'adding-charge' , account_id = account_id , amount = amount , product_code = product_code , product_properties = product_properties ) with transaction . atomic ( ) : charge = Charge ( account_id = account_id , amount = amount ) if reverses_id : charge . reverses_id = reverses_id if product_code : charge . product_code = product_code charge . full_clean ( exclude = [ 'id' , 'account' ] ) # Exclude to avoid unnecessary db queries charge . save ( force_insert = True ) if product_properties : objs = [ ProductProperty ( charge = charge , name = k , value = v ) for k , v in product_properties . items ( ) ] for o in objs : o . full_clean ( exclude = [ 'id' , 'charge' ] ) # Exclude to avoid unnecessary db queries ProductProperty . objects . bulk_create ( objs ) return charge | Add a charge to the account . | 269 | 7 |
14,287 | def build_tree ( self ) : for spec in self . specs : if spec . ismodule : self . modules . append ( Module ( spec . name , spec . path , dsm = self ) ) else : self . packages . append ( Package ( spec . name , spec . path , dsm = self , limit_to = spec . limit_to , build_tree = True , build_dependencies = False , enforce_init = self . enforce_init ) ) | Build the Python packages tree . | 100 | 6 |
14,288 | def split_limits_heads ( self ) : heads = [ ] new_limit_to = [ ] for limit in self . limit_to : if '.' in limit : name , limit = limit . split ( '.' , 1 ) heads . append ( name ) new_limit_to . append ( limit ) else : heads . append ( limit ) return heads , new_limit_to | Return first parts of dot - separated strings and rest of strings . | 82 | 13 |
14,289 | def build_tree ( self ) : for m in listdir ( self . path ) : abs_m = join ( self . path , m ) if isfile ( abs_m ) and m . endswith ( '.py' ) : name = splitext ( m ) [ 0 ] if not self . limit_to or name in self . limit_to : self . modules . append ( Module ( name , abs_m , self . dsm , self ) ) elif isdir ( abs_m ) : if isfile ( join ( abs_m , '__init__.py' ) ) or not self . enforce_init : heads , new_limit_to = self . split_limits_heads ( ) if not heads or m in heads : self . packages . append ( Package ( m , abs_m , self . dsm , self , new_limit_to , build_tree = True , build_dependencies = False , enforce_init = self . enforce_init ) ) | Build the tree for this package . | 213 | 7 |
14,290 | def cardinal ( self , to ) : return sum ( m . cardinal ( to ) for m in self . submodules ) | Return the number of dependencies of this package to the given node . | 25 | 13 |
14,291 | def build_dependencies ( self ) : highest = self . dsm or self . root if self is highest : highest = LeafNode ( ) for _import in self . parse_code ( ) : target = highest . get_target ( _import [ 'target' ] ) if target : what = _import [ 'target' ] . split ( '.' ) [ - 1 ] if what != target . name : _import [ 'what' ] = what _import [ 'target' ] = target self . dependencies . append ( Dependency ( source = self , * * _import ) ) | Build the dependencies for this module . | 124 | 7 |
14,292 | def parse_code ( self ) : code = open ( self . path , encoding = 'utf-8' ) . read ( ) try : body = ast . parse ( code ) . body except SyntaxError : try : code = code . encode ( 'utf-8' ) body = ast . parse ( code ) . body except SyntaxError : return [ ] return self . get_imports ( body ) | Read the source code and return all the import statements . | 87 | 11 |
14,293 | def cardinal ( self , to ) : return sum ( 1 for _ in filter ( lambda d : not d . external and d . target in to , self . dependencies ) ) | Return the number of dependencies of this module to the given node . | 36 | 13 |
14,294 | def generate_urls ( self , first_url , last_url ) : first_url = first_url . split ( "/" ) last_url = last_url . split ( "/" ) if first_url [ 0 ] . lower ( ) != "http:" or last_url [ 0 ] . lower ( ) != "http:" : raise Exception ( "URLs should be accessible via HTTP." ) url_base = "/" . join ( first_url [ : - 1 ] ) start_index = first_url [ - 1 ] . index ( "a" ) file_name = first_url [ - 1 ] [ 0 : start_index ] url_base += "/" + file_name start = first_url [ - 1 ] [ start_index : ] finish = last_url [ - 1 ] [ start_index : ] if start . count ( "." ) == 1 and finish . count ( "." ) == 1 : start , file_extension = start . split ( "." ) finish , _ = finish . split ( "." ) if len ( start ) != len ( finish ) : raise Exception ( "Filenames in url should have the same length." ) file_extension = "." + file_extension else : raise Exception ( "URLs does not have the same pattern." ) alphabet = "abcdefghijklmnopqrstuvwxyz" product = itertools . product ( alphabet , repeat = len ( start ) ) urls = [ ] for p in product : urls . append ( [ url_base + "" . join ( p ) + file_extension ] ) if "" . join ( p ) == finish : break return urls | Function generates URLs in split command fashion . If first_url is xaaaaa and last_url is xaaaac it will automatically generate xaaaab . | 364 | 32 |
14,295 | def fetch_raw_data ( sql , connection , geometry ) : tmp_dc = { } weather_df = pd . DataFrame ( connection . execute ( sql ) . fetchall ( ) , columns = [ 'gid' , 'geom_point' , 'geom_polygon' , 'data_id' , 'time_series' , 'dat_id' , 'type_id' , 'type' , 'height' , 'year' , 'leap_year' ] ) . drop ( 'dat_id' , 1 ) # Get the timezone of the geometry tz = tools . tz_from_geom ( connection , geometry ) for ix in weather_df . index : # Convert the point of the weather location to a shapely object weather_df . loc [ ix , 'geom_point' ] = wkt_loads ( weather_df [ 'geom_point' ] [ ix ] ) # Roll the dataset forward according to the timezone, because the # dataset is based on utc (Berlin +1, Kiev +2, London +0) utc = timezone ( 'utc' ) offset = int ( utc . localize ( datetime ( 2002 , 1 , 1 ) ) . astimezone ( timezone ( tz ) ) . strftime ( "%z" ) [ : - 2 ] ) # Get the year and the length of the data array db_year = weather_df . loc [ ix , 'year' ] db_len = len ( weather_df [ 'time_series' ] [ ix ] ) # Set absolute time index for the data sets to avoid errors. tmp_dc [ ix ] = pd . Series ( np . roll ( np . array ( weather_df [ 'time_series' ] [ ix ] ) , offset ) , index = pd . date_range ( pd . datetime ( db_year , 1 , 1 , 0 ) , periods = db_len , freq = 'H' , tz = tz ) ) weather_df [ 'time_series' ] = pd . Series ( tmp_dc ) return weather_df | Fetch the coastdat2 from the database adapt it to the local time zone and create a time index . | 469 | 22 |
14,296 | def create_single_weather ( df , rename_dc ) : my_weather = weather . FeedinWeather ( ) data_height = { } name = None # Create a pandas.DataFrame with the time series of the weather data set weather_df = pd . DataFrame ( index = df . time_series . iloc [ 0 ] . index ) for row in df . iterrows ( ) : key = rename_dc [ row [ 1 ] . type ] weather_df [ key ] = row [ 1 ] . time_series data_height [ key ] = row [ 1 ] . height if not np . isnan ( row [ 1 ] . height ) else 0 name = row [ 1 ] . gid my_weather . data = weather_df my_weather . timezone = weather_df . index . tz my_weather . longitude = df . geom_point . iloc [ 0 ] . x my_weather . latitude = df . geom_point . iloc [ 0 ] . y my_weather . geometry = df . geom_point . iloc [ 0 ] my_weather . data_height = data_height my_weather . name = name return my_weather | Create an oemof weather object for the given geometry | 258 | 11 |
14,297 | def create_multi_weather ( df , rename_dc ) : weather_list = [ ] # Create a pandas.DataFrame with the time series of the weather data set # for each data set and append them to a list. for gid in df . gid . unique ( ) : gid_df = df [ df . gid == gid ] obj = create_single_weather ( gid_df , rename_dc ) weather_list . append ( obj ) return weather_list | Create a list of oemof weather objects if the given geometry is a polygon | 106 | 17 |
14,298 | def predict ( tree , x , y = [ ] , dist = False ) : # conditions of continuous and discrete features node_id = 1 # initialize node identifier as first node under the root while 1 : nodes = tree [ node_id ] if nodes [ 0 ] [ 5 ] == "c" : if x [ nodes [ 0 ] [ 1 ] ] <= nodes [ 0 ] [ 2 ] : index , node_id = 0 , nodes [ 0 ] [ 0 ] # set identifier of child node else : index , node_id = 1 , nodes [ 1 ] [ 0 ] # set identifier of child node else : if x [ nodes [ 0 ] [ 1 ] ] in nodes [ 0 ] [ 2 ] : index , node_id = 0 , nodes [ 0 ] [ 0 ] # set identifier of child node elif x [ nodes [ 1 ] [ 1 ] ] in nodes [ 1 ] [ 2 ] : index , node_id = 1 , nodes [ 1 ] [ 0 ] # set identifier of child node else : # value is not in left or right branch. Get label distributions of left and right child # sum labels distribution to get parent label distribution node_id = str ( nodes [ 0 ] [ 0 ] ) + "," + str ( nodes [ 1 ] [ 0 ] ) index , nodes = 0 , [ [ 0 , 0 , 0 , { k : nodes [ 0 ] [ 3 ] . get ( k , 0 ) + nodes [ 1 ] [ 3 ] . get ( k , 0 ) for k in set ( nodes [ 0 ] [ 3 ] ) | set ( nodes [ 1 ] [ 3 ] ) } ] ] if node_id in tree . keys ( ) : # check if tree can be traversed further continue if dist : suma = sum ( nodes [ index ] [ 3 ] . values ( ) ) return Counter ( { k : v / float ( suma ) for k , v in nodes [ index ] [ 3 ] . iteritems ( ) } ) prediction = max ( nodes [ index ] [ 3 ] , key = nodes [ index ] [ 3 ] . get ) if y == [ ] : return prediction probs = sorted ( zip ( nodes [ index ] [ 3 ] . keys ( ) , np . true_divide ( nodes [ index ] [ 3 ] . values ( ) , np . sum ( nodes [ index ] [ 3 ] . values ( ) ) ) ) , key = itemgetter ( 1 ) , reverse = True ) if prediction == y : margin = probs [ 0 ] [ 1 ] - probs [ 1 ] [ 1 ] if len ( probs ) > 1 else 1 else : margin = dict ( probs ) . get ( y , 0 ) - probs [ 0 ] [ 1 ] return node_id , margin | Function makes a prediction of one sample with a tree model . If y label is defined it returns node identifier and margin . | 582 | 24 |
14,299 | def __addTab ( self , filePath ) : for i in range ( self . tabBar . count ( ) ) : widget = self . pages . widget ( i ) if not widget . isStatic and filePath == widget . filePath : return i tab = SubtitleEditor ( filePath , self . _subtitleData , self ) newIndex = self . tabBar . addTab ( self . _createTabName ( tab . name , tab . history . isClean ( ) ) ) tab . history . cleanChanged . connect ( lambda clean : self . _cleanStateForFileChanged ( filePath , clean ) ) self . pages . addWidget ( tab ) return newIndex | Returns existing tab index . Creates a new one if it isn t opened and returns its index otherwise . | 142 | 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.