idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
47,400 | def group_statistics ( self , group , selected_meta , stat_code = 'mean' ) : values = self . get_values ( group , selected_meta ) if stat_code == 'mean' : res = statistics . mean ( values ) elif stat_code == 'variance' : res = statistics . variance ( values ) elif stat_code == 'std' : res = statistics . stdev ( values ) return res | Provides statistics of a group based on the meta data selected . |
47,401 | def tf ( cluster ) : counts = dict ( ) words = cluster . split ( ' ' ) for word in words : counts [ word ] = counts . get ( word , 0 ) + 1 return counts | Computes the term frequency and stores it as a dictionary |
47,402 | def visualize_cloud_of_words ( dictionary , image_path = None ) : from PIL import Image if image_path is not None : mask = np . array ( Image . open ( image_path ) ) wc = WordCloud ( mask = mask , background_color = 'white' , width = 1600 , height = 1200 , prefer_horizontal = 0.8 ) wc = wc . generate_from_frequencies ( dictionary ) else : wc = WordCloud ( background_color = 'white' , width = 1600 , height = 1200 , prefer_horizontal = 0.8 ) wc = wc . generate_from_frequencies ( dictionary ) import matplotlib . pyplot as plt plt . rcParams [ 'figure.figsize' ] = ( 15 , 15 ) plt . imshow ( wc , interpolation = 'bilinear' ) plt . axis ( "off" ) plt . show ( ) | Renders the cloud of words representation for a given dictionary of frequencies |
47,403 | def cloud_of_words ( path_to_bog , cluster_no , image_path = None ) : dictionary = GenometricSpace . best_descriptive_meta_dict ( path_to_bog , cluster_no ) GenometricSpace . visualize_cloud_of_words ( dictionary , image_path ) | Draws the cloud of words representation |
47,404 | def from_pandas ( regs , meta = None , chr_name = None , start_name = None , stop_name = None , strand_name = None , sample_name = None ) : regs = check_regs ( regs , chr_name , start_name , stop_name , strand_name , sample_name ) regs = to_gmql_regions ( regs ) if meta is not None : if not check_meta ( meta , regs ) : raise ValueError ( "Error. Meta dataframe is not GMQL standard" ) else : meta = empty_meta ( regs ) return GDataframe ( regs , meta ) | Creates a GDataframe from a pandas dataframe of region and a pandas dataframe of metadata |
47,405 | def check_regs ( region_df , chr_name = None , start_name = None , stop_name = None , strand_name = None , sample_name = None ) : if sample_name is None : region_df . index = np . repeat ( default_id_sample , len ( region_df ) ) else : region_df = search_column ( region_df , id_sample_aliases , id_sample_types , 'id_sample' , sample_name ) region_df = region_df . set_index ( "id_sample" , drop = True ) region_df = region_df . sort_index ( ) region_df = search_column ( region_df , chr_aliases , chr_types , 'chr' , chr_name ) region_df = search_column ( region_df , start_aliases , start_types , 'start' , start_name ) region_df = search_column ( region_df , stop_aliases , stop_types , 'stop' , stop_name ) region_df = search_column ( region_df , strand_aliases , strand_types , 'strand' , strand_name ) return region_df | Modifies a region dataframe to be coherent with the GMQL data model |
47,406 | def to_dataset_files ( self , local_path = None , remote_path = None ) : return FrameToGMQL . to_dataset_files ( self , path_local = local_path , path_remote = remote_path ) | Save the GDataframe to a local or remote location |
47,407 | def to_GMQLDataset ( self , local_path = None , remote_path = None ) : local = None remote = None if ( local_path is None ) and ( remote_path is None ) : local = TempFileManager . get_new_dataset_tmp_folder ( ) if local_path is not None : local = local_path if remote_path is not None : remote = remote_path self . to_dataset_files ( local , remote ) if local is not None : return Loader . load_from_path ( local_path = local ) elif remote is not None : raise NotImplementedError ( "The remote loading is not implemented yet!" ) | Converts the GDataframe in a GMQLDataset for later local or remote computation |
47,408 | def project_meta ( self , attributes ) : if not isinstance ( attributes , list ) : raise TypeError ( 'attributes must be a list' ) meta_to_project = self . meta [ attributes ] . applymap ( lambda l : ", " . join ( l ) ) new_regs = self . regs . merge ( meta_to_project , left_index = True , right_index = True ) return GDataframe ( regs = new_regs , meta = self . meta ) | Projects the specified metadata attributes to new region fields |
47,409 | def to_matrix ( self , index_regs = None , index_meta = None , columns_regs = None , columns_meta = None , values_regs = None , values_meta = None , ** kwargs ) : index_regs = index_regs if index_regs is not None else [ ] index_meta = index_meta if index_meta is not None else [ ] columns_regs = columns_regs if columns_regs is not None else [ ] columns_meta = columns_meta if columns_meta is not None else [ ] values_regs = values_regs if values_regs is not None else [ ] values_meta = values_meta if values_meta is not None else [ ] index_meta_s = set ( index_meta ) columns_meta_s = set ( columns_meta ) values_meta_s = set ( values_meta ) meta_to_project = list ( index_meta_s . union ( columns_meta_s ) . union ( values_meta_s ) . difference ( set ( self . regs . columns ) ) ) res = self . project_meta ( meta_to_project ) pivot_columns = columns_meta + columns_regs pivot_index = index_meta + index_regs pivot_values = values_regs + values_meta return res . regs . pivot_table ( index = pivot_index , columns = pivot_columns , values = pivot_values , ** kwargs ) | Transforms the GDataframe to a pivot matrix having as index and columns the ones specified . This function is a wrapper around the pivot_table function of Pandas . |
47,410 | def charts_slug_get ( self , slug , ** kwargs ) : kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . charts_slug_get_with_http_info ( slug , ** kwargs ) else : ( data ) = self . charts_slug_get_with_http_info ( slug , ** kwargs ) return data | Chart A Chart is chosen by Pollster editors . One example is \ Obama job approval - Democrats \ . It is always based upon a single Question . Users should strongly consider basing their analysis on Questions instead . Charts are derived data ; Pollster editors publish them and change them as editorial priorities change . |
47,411 | def polls_get ( self , ** kwargs ) : kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . polls_get_with_http_info ( ** kwargs ) else : ( data ) = self . polls_get_with_http_info ( ** kwargs ) return data | Polls A Poll on Pollster is a collection of questions and responses published by a reputable survey house . This endpoint provides raw data from the survey house plus Pollster - provided metadata about each question . Pollster editors don t include every question when they enter Polls and they don t necessarily enter every subpopulation for the responses they _do_ enter . They make editorial decisions about which questions belong in the database . The response will contain a maximum of 25 Poll objects even if the database contains more than 25 polls . Use the next_cursor parameter to fetch the rest 25 Polls at a time . |
47,412 | def polls_slug_get ( self , slug , ** kwargs ) : kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . polls_slug_get_with_http_info ( slug , ** kwargs ) else : ( data ) = self . polls_slug_get_with_http_info ( slug , ** kwargs ) return data | Poll A Poll on Pollster is a collection of questions and responses published by a reputable survey house . This endpoint provides raw data from the survey house plus Pollster - provided metadata about each question . Pollster editors don t include every question when they enter Polls and they don t necessarily enter every subpopulation for the responses they _do_ enter . They make editorial decisions about which questions belong in the database . |
47,413 | def flatpage ( request , url ) : if not url . startswith ( '/' ) : url = '/' + url language = request . LANGUAGE_CODE language_prefix = '/%s' % language language_db_field = language . replace ( '-' , '_' ) if url . startswith ( language_prefix ) : url = url [ len ( language_prefix ) : ] kwargs = { '{0}__{1}' . format ( 'url_%s' % language_db_field , 'exact' ) : url , '{0}__{1}' . format ( 'sites__id' , 'exact' ) : settings . SITE_ID } try : f = get_object_or_404 ( FlatPage_i18n , ** kwargs ) except Http404 : if not url . endswith ( '/' ) and settings . APPEND_SLASH : url += '/' f = get_object_or_404 ( FlatPage_i18n , ** kwargs ) return HttpResponsePermanentRedirect ( '%s/' % request . path ) else : raise return render_flatpage ( request , f ) | Public interface to the flat page view . |
47,414 | def render_flatpage ( request , f ) : if f . registration_required and not request . user . is_authenticated ( ) : from django . contrib . auth . views import redirect_to_login return redirect_to_login ( request . path ) if f . template_name : t = loader . select_template ( ( f . template_name , DEFAULT_TEMPLATE ) ) else : t = loader . get_template ( DEFAULT_TEMPLATE ) f . title = mark_safe ( f . title ) f . content = mark_safe ( f . content ) response = HttpResponse ( t . render ( { 'flatpage' : f } , request ) ) try : from django . core . xheaders import populate_xheaders populate_xheaders ( request , response , FlatPage_i18n , f . id ) except ImportError : pass return response | Internal interface to the flat page view . |
47,415 | def pidfile ( self ) : return os . path . abspath ( os . path . expandvars ( os . path . expanduser ( self . _pidfile , ) , ) , ) | Get the absolute path of the pidfile . |
47,416 | def SQRT ( argument ) : if isinstance ( argument , MetaField ) : return argument . _unary_expression ( "SQRT" ) elif isinstance ( argument , RegField ) : return argument . _unary_expression ( "SQRT" ) else : raise TypeError ( "You have to give as input a RegField (dataset.field)" "or a MetaField (dataset['field']" ) | Computes the square matrix of the argument |
47,417 | def login ( ) : from . RemoteConnection . RemoteManager import RemoteManager global __remote_manager , __session_manager logger = logging . getLogger ( ) remote_address = get_remote_address ( ) res = __session_manager . get_session ( remote_address ) if res is None : warnings . warn ( "There is no active session for address {}. Logging as Guest user" . format ( remote_address ) ) rm = RemoteManager ( address = remote_address ) rm . login ( ) session_type = "guest" else : logger . info ( "Logging using stored authentication token" ) rm = RemoteManager ( address = remote_address , auth_token = res [ 1 ] ) session_type = rm . auto_login ( how = res [ 2 ] ) __remote_manager = rm access_time = int ( time . time ( ) ) auth_token = rm . auth_token __session_manager . add_session ( remote_address , auth_token , access_time , session_type ) | Enables the user to login to the remote GMQL service . If both username and password are None the user will be connected as guest . |
47,418 | def main ( idle ) : while True : LOG . debug ( "Sleeping for {0} seconds." . format ( idle ) ) time . sleep ( idle ) | Any normal python logic which runs a loop . Can take arguments . |
47,419 | def step ( self ) : message = self . get_message ( ) if message is None : self . sleep ( self . idle_time ) return None self . dispatch ( message ) self . sleep ( 0 ) | Grab a new message and dispatch it to the handler . |
47,420 | def init_app ( self , app = None ) : config = getattr ( app , 'config' , app ) self . team_id = config . get ( 'TEAM_ID' ) | Initialize application configuration |
47,421 | def validate ( self , command , token , team_id , method ) : if ( team_id , command ) not in self . _commands : raise SlackError ( 'Command {0} is not found in team {1}' . format ( command , team_id ) ) func , _token , methods , kwargs = self . _commands [ ( team_id , command ) ] if method not in methods : raise SlackError ( '{} request is not allowed' . format ( method ) ) if token != _token : raise SlackError ( 'Your token {} is invalid' . format ( token ) ) | Validate request queries with registerd commands |
47,422 | def response ( self , text , response_type = 'ephemeral' , attachments = None ) : from flask import jsonify if attachments is None : attachments = [ ] data = { 'response_type' : response_type , 'text' : text , 'attachments' : attachments , } return jsonify ( ** data ) | Return a response with json format |
47,423 | def pid ( self ) : try : with open ( self . pidfile , 'r' ) as pidfile : try : pid = int ( pidfile . read ( ) . strip ( ) ) except ValueError : return None try : os . kill ( pid , 0 ) except OSError as e : if e . errno == errno . EPERM : return pid elif e . errno == errno . ESRCH : return None LOG . exception ( "os.kill returned unhandled error " "{0}" . format ( e . strerror ) ) sys . exit ( exit . PIDFILE_ERROR ) return pid except IOError : if not os . path . isfile ( self . pidfile ) : return None LOG . exception ( "Failed to read pidfile {0}." . format ( self . pidfile ) ) sys . exit ( exit . PIDFILE_INACCESSIBLE ) | Get the pid which represents a daemonized process . |
47,424 | def pid ( self , pidnum ) : try : with open ( self . pidfile , "w+" ) as pidfile : pidfile . write ( "{0}\n" . format ( pidnum ) ) except IOError : LOG . exception ( "Failed to write pidfile {0})." . format ( self . pidfile ) ) sys . exit ( exit . PIDFILE_INACCESSIBLE ) | Set the pid for a running process . |
47,425 | def pid ( self ) : try : os . remove ( self . pidfile ) except IOError : if not os . path . isfile ( self . pidfile ) : return None LOG . exception ( "Failed to clear pidfile {0})." . format ( self . pidfile ) ) sys . exit ( exit . PIDFILE_INACCESSIBLE ) | Stop managing the current pid . |
47,426 | def pool ( self ) : self . _pool = self . _pool or gevent . pool . Pool ( size = self . pool_size ) return self . _pool | Get an gevent pool used to dispatch requests . |
47,427 | def set_essid ( interface , essid ) : interface = _get_bytes ( interface ) essid = _get_bytes ( essid ) wrq = ffi . new ( 'struct iwreq*' ) with iwlib_socket ( ) as sock : if essid . lower ( ) in ( b'off' , b'any' ) : wrq . u . essid . flags = 0 essid = b'' elif essid . lower ( ) == b'on' : buf = ffi . new ( 'char []' , iwlib . IW_ESSID_MAX_SIZE + 1 ) wrq . u . essid . pointer = buf wrq . u . essid . length = iwlib . IW_ESSID_MAX_SIZE + 1 wrq . u . essid . flags = 0 if iwlib . iw_get_ext ( sock , interface , iwlib . SIOCGIWESSID , wrq ) < 0 : raise ValueError ( "Error retrieving previous ESSID: %s" % ( os . strerror ( ffi . errno ) ) ) wrq . u . essid . flags = 1 elif len ( essid ) > iwlib . IW_ESSID_MAX_SIZE : raise ValueError ( "ESSID '%s' is longer than the maximum %d" % ( essid , iwlib . IW_ESSID_MAX_SIZE ) ) else : wrq . u . essid . pointer = ffi . new_handle ( essid ) wrq . u . essid . length = len ( essid ) wrq . u . essid . flags = 1 if iwlib . iw_get_kernel_we_version ( ) < 21 : wrq . u . essid . length += 1 if iwlib . iw_set_ext ( sock , interface , iwlib . SIOCSIWESSID , wrq ) < 0 : errno = ffi . errno strerror = "Couldn't set essid on device '%s': %s" % ( interface . decode ( 'utf8' ) , os . strerror ( errno ) ) raise OSError ( errno , strerror ) | Set the ESSID of a given interface |
47,428 | def ensure_data ( ) : if not os . path . exists ( GARUDA_DIR ) : os . makedirs ( GARUDA_DIR ) Path ( f'{GARUDA_DIR}/__init__.py' ) . touch ( ) | Ensure that the Garuda directory and files |
47,429 | def protoc_arguments ( ) : proto_include = resource_filename ( 'grpc_tools' , '_proto' ) return [ protoc . __file__ , '-I' , GARUDA_DIR , f'--python_out={GARUDA_DIR}' , f'--grpc_python_out={GARUDA_DIR}' , GARUDA_PROTO_PATH , f'-I{proto_include}' ] | Construct protobuf compiler arguments |
47,430 | def fix_grpc_import ( ) : with open ( GARUDA_GRPC_PATH , 'r' ) as f : filedata = f . read ( ) filedata = filedata . replace ( 'import garuda_pb2 as garuda__pb2' , f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2' ) with open ( GARUDA_GRPC_PATH , 'w' ) as f : f . write ( filedata ) | Snippet to fix the gRPC import path |
47,431 | def write_average_score_row ( fp , score_name , scores ) : row = "--" + score_name + "--" fp . write ( row ) for vector in scores : row = list ( vector ) row = [ str ( score ) for score in row ] row = "\n" + "\t" . join ( row ) fp . write ( row ) | Simple utility function that writes an average score row in a file designated by a file pointer . |
47,432 | def catch_errors ( f ) : @ functools . wraps ( f ) def wrapper ( self , request , * args , ** kwargs ) : try : return f ( self , request , * args , ** kwargs ) except exceptions . CertificateExpired : self . message_user ( request , _ ( 'The AFIP Taxpayer certificate has expired.' ) , messages . ERROR , ) except exceptions . UntrustedCertificate : self . message_user ( request , _ ( 'The AFIP Taxpayer certificate is untrusted.' ) , messages . ERROR , ) except exceptions . CorruptCertificate : self . message_user ( request , _ ( 'The AFIP Taxpayer certificate is corrupt.' ) , messages . ERROR , ) except exceptions . AuthenticationError as e : logger . exception ( 'AFIP auth failed' ) self . message_user ( request , _ ( 'An unknown authentication error has ocurred: %s' ) % e , messages . ERROR , ) return wrapper | Catches specific errors in admin actions and shows a friendly error . |
47,433 | def augmented_tf_idf ( attribute_matrix ) : number_of_documents = attribute_matrix . shape [ 0 ] max_term_frequencies = np . ones ( number_of_documents , dtype = np . float64 ) idf_array = np . ones ( attribute_matrix . shape [ 1 ] , dtype = np . float64 ) attribute_matrix = attribute_matrix . tocsc ( ) for j in range ( attribute_matrix . shape [ 1 ] ) : document_frequency = attribute_matrix . getcol ( j ) . data . size if document_frequency > 1 : idf_array [ j ] = np . log ( number_of_documents / document_frequency ) attribute_matrix = attribute_matrix . tocsr ( ) for i in range ( attribute_matrix . shape [ 0 ] ) : max_term_frequency = attribute_matrix . getrow ( i ) . data if max_term_frequency . size > 0 : max_term_frequency = max_term_frequency . max ( ) if max_term_frequency > 0.0 : max_term_frequencies [ i ] = max_term_frequency attribute_matrix = attribute_matrix . tocoo ( ) attribute_matrix . data = 0.5 + np . divide ( 0.5 * attribute_matrix . data , np . multiply ( ( max_term_frequencies [ attribute_matrix . row ] ) , ( idf_array [ attribute_matrix . col ] ) ) ) attribute_matrix = attribute_matrix . tocsr ( ) return attribute_matrix | Performs augmented TF - IDF normalization on a bag - of - words vector representation of data . |
47,434 | def get_file_row_generator ( file_path , separator , encoding = None ) : with open ( file_path , encoding = encoding ) as file_object : for line in file_object : words = line . strip ( ) . split ( separator ) yield words | Reads an separated value file row by row . |
47,435 | def store_pickle ( file_path , data ) : pkl_file = open ( file_path , 'wb' ) pickle . dump ( data , pkl_file ) pkl_file . close ( ) | Pickle some data to a given path . |
47,436 | def load_pickle ( file_path ) : pkl_file = open ( file_path , 'rb' ) data = pickle . load ( pkl_file ) pkl_file . close ( ) return data | Unpickle some data from a given path . |
47,437 | def makeServoIDPacket ( curr_id , new_id ) : pkt = Packet . makeWritePacket ( curr_id , xl320 . XL320_ID , [ new_id ] ) return pkt | Given the current ID returns a packet to set the servo to a new ID |
47,438 | def normalize_rows ( features ) : features = features . tocsr ( ) features = normalize ( features , norm = "l2" ) return features | This performs row normalization to 1 of community embedding features . |
47,439 | def normalize_columns ( features ) : features = features . tocsc ( ) for j in range ( features . shape [ 1 ] ) : document_frequency = features . getcol ( j ) . data . size if document_frequency > 1 : features . data [ features . indptr [ j ] : features . indptr [ j + 1 ] ] = features . data [ features . indptr [ j ] : features . indptr [ j + 1 ] ] / np . sqrt ( np . log ( document_frequency ) ) features = features . tocsr ( ) return features | This performs column normalization of community embedding features . |
47,440 | def pagerank_lazy_push ( s , r , w_i , a_i , push_node , rho , lazy ) : A = rho * r [ push_node ] B = ( 1 - rho ) * ( 1 - lazy ) * r [ push_node ] C = ( 1 - rho ) * lazy * ( r [ push_node ] ) s [ push_node ] += A r [ push_node ] = C r [ a_i ] += B * w_i | Performs a random step with a self - loop . |
47,441 | def includeme ( config ) : settings = config . get_settings ( ) authz_class = settings . get ( "multiauth.authorization_policy" , "pyramid.authorization.ACLAuthorizationPolicy" ) authz_policy = config . maybe_dotted ( authz_class ) ( ) config . set_authorization_policy ( authz_policy ) groupfinder = settings . get ( "multiauth.groupfinder" , None ) groupfinder = config . maybe_dotted ( groupfinder ) policy_definitions = get_policy_definitions ( settings ) policy_factories = [ ] policy_names = settings . get ( "multiauth.policies" , "" ) . split ( ) for policy_name in reversed ( policy_names ) : if policy_name in policy_definitions : definition = policy_definitions [ policy_name ] factory = config . maybe_dotted ( definition . pop ( "use" ) ) policy_factories . append ( ( factory , policy_name , definition ) ) else : try : factory = policy_factory_from_module ( config , policy_name ) except ImportError : err = "pyramid_multiauth: policy %r has no settings " "and is not importable" % ( policy_name , ) raise ValueError ( err ) policy_factories . append ( ( factory , policy_name , { } ) ) policies = [ ] def grab_policies ( ) : for factory , name , kwds in policy_factories : policy = factory ( ** kwds ) if policy : policy . _pyramid_multiauth_name = name if not policies or policy is not policies [ 0 ] : policies . insert ( 0 , policy ) config . action ( None , grab_policies , order = PHASE2_CONFIG ) authn_policy = MultiAuthenticationPolicy ( policies , groupfinder ) config . set_authentication_policy ( authn_policy ) | Include pyramid_multiauth into a pyramid configurator . |
47,442 | def get_policy_definitions ( settings ) : policy_definitions = { } for name in settings : if not name . startswith ( "multiauth.policy." ) : continue value = settings [ name ] name = name [ len ( "multiauth.policy." ) : ] policy_name , setting_name = name . split ( "." , 1 ) if policy_name not in policy_definitions : policy_definitions [ policy_name ] = { } policy_definitions [ policy_name ] [ setting_name ] = value return policy_definitions | Find all multiauth policy definitions from the settings dict . |
47,443 | def load_file ( filename ) : if filename in ( 'stdin' , '-' , None ) : instances = [ i for i in gc . get_objects ( ) if isinstance ( i , pycodestyle . Checker ) or isinstance ( i , pep8 . Checker ) ] if len ( instances ) != 1 : raise ValueError ( 'Expected only 1 instance of pycodestyle.Checker, got {0} instead.' . format ( len ( instances ) ) ) return 'stdin' , '' . join ( instances [ 0 ] . lines ) with codecs . open ( filename , encoding = 'utf-8' ) as handle : return filename , handle . read ( ) | Read file to memory . |
47,444 | def ignore ( code ) : if code in Main . options [ 'ignore' ] : return True if any ( c in code for c in Main . options [ 'ignore' ] ) : return True return False | Should this code be ignored . |
47,445 | def add_options ( cls , parser ) : parser . add_option ( '--show-pydocstyle' , action = 'store_true' , help = 'show explanation of each PEP 257 error' ) parser . config_options . append ( 'show-pydocstyle' ) | Add options to flake8 . |
47,446 | def parse_options ( cls , options ) : cls . options [ 'explain' ] = bool ( options . show_pydocstyle ) cls . options [ 'ignore' ] = options . ignore config = pydocstyle . RawConfigParser ( ) for file_name in pydocstyle . ConfigurationParser . PROJECT_CONFIG_FILES : if config . read ( os . path . join ( os . path . abspath ( '.' ) , file_name ) ) : break if not config . has_section ( 'pydocstyle' ) : return native_options = dict ( ) for option in config . options ( 'pydocstyle' ) : if option == 'ignore' : native_options [ 'ignore' ] = config . get ( 'pydocstyle' , option ) if option in ( 'explain' , 'source' ) : native_options [ option ] = config . getboolean ( 'pydocstyle' , option ) native_options [ 'show-source' ] = native_options . pop ( 'source' , None ) if native_options . get ( 'ignore' ) : native_options [ 'ignore' ] = native_options [ 'ignore' ] . split ( ',' ) cls . options . update ( dict ( ( k , v ) for k , v in native_options . items ( ) if v ) ) | Read parsed options from flake8 . |
47,447 | def run ( self ) : pydocstyle . Error . explain = self . options [ 'explain' ] filename , source = load_file ( self . filename ) for error in pydocstyle . PEP257Checker ( ) . check_source ( source , filename ) : if not hasattr ( error , 'code' ) or ignore ( error . code ) : continue lineno = error . line offset = 0 explanation = error . explanation if pydocstyle . Error . explain else '' text = '{0} {1}{2}' . format ( error . code , error . message . split ( ': ' , 1 ) [ 1 ] , explanation ) yield lineno , offset , text , Main | Run analysis on a single file . |
47,448 | def numbers ( self ) : numstring = '{:011d}{:02d}{:04d}{}{}' . format ( self . _receipt . point_of_sales . owner . cuit , int ( self . _receipt . receipt_type . code ) , self . _receipt . point_of_sales . number , self . _receipt . validation . cae , self . _receipt . validation . cae_expiration . strftime ( '%Y%m%d' ) , ) return [ int ( num ) for num in numstring ] | Returns the barcode s number without the verification digit . |
47,449 | def verification_digit ( numbers ) : a = sum ( numbers [ : : 2 ] ) b = a * 3 c = sum ( numbers [ 1 : : 2 ] ) d = b + c e = d % 10 if e == 0 : return e return 10 - e | Returns the verification digit for a given numbre . |
47,450 | def full_number ( self ) : return '{}{}' . format ( '' . join ( str ( n ) for n in self . numbers ) , ReceiptBarcodeGenerator . verification_digit ( self . numbers ) , ) | Returns the full number including the verification digit . |
47,451 | def write_screen_name_to_topics ( filepath , user_label_matrix , node_to_id , id_to_name , label_to_lemma , lemma_to_keyword , separator = "," ) : user_label_matrix = spsp . coo_matrix ( user_label_matrix ) shape = user_label_matrix . shape nnz = user_label_matrix . getnnz ( ) row = user_label_matrix . row col = user_label_matrix . col data = user_label_matrix . data name_to_topic_set = defaultdict ( set ) for edge in range ( row . size ) : node = row [ edge ] user_twitter_id = node_to_id [ node ] name = id_to_name [ user_twitter_id ] label = col [ edge ] lemma = label_to_lemma [ label ] name_to_topic_set [ name ] . add ( lemma ) with open ( filepath , "w" ) as f : file_row = "n_rows:" + separator + str ( shape [ 0 ] ) + separator + "nnz:" + separator + str ( nnz ) + separator + "\n" f . write ( file_row ) for name , topic_set in name_to_topic_set . items ( ) : file_row = list ( ) file_row . append ( name ) file_row . extend ( topic_set ) file_row = separator . join ( file_row ) + "\n" f . write ( file_row ) | Writes a user name and associated topic names per row . |
47,452 | def sweep ( port , rate , ID , retry = 3 ) : if port == 'dummy' : s = ServoSerial ( port , rate , fake = True ) else : s = ServoSerial ( port , rate ) if ID < 0 : ID = xl320 . XL320_BROADCAST_ADDR try : s . open ( ) except SerialException as e : print ( '-' * 40 ) print ( sys . argv [ 0 ] , ':' ) print ( e ) exit ( 1 ) pkt = makePingPacket ( ID ) s . write ( pkt ) for cnt in range ( retry ) : ans = s . read ( ) if ans : for pkt in ans : servo = packetToDict ( pkt ) utils . prettyPrintPacket ( servo ) print ( 'raw pkt: {}' . format ( pkt ) ) else : print ( 'Try {}: no servos found' . format ( cnt ) ) time . sleep ( 0.1 ) s . close ( ) | Sends a ping packet to ID s from 0 to maximum and prints out any returned messages . |
47,453 | def calculate_epsilon_effective ( rho , epsilon , seed_degree , neighbor_degrees , mean_degree ) : neighborhood_degree = neighbor_degrees . mean ( ) epsilon_effective = ( epsilon * np . log ( 1 + seed_degree ) ) / np . log ( 1 + neighborhood_degree ) epsilon_effective_maximum = np . max ( 1 / ( seed_degree * neighbor_degrees ) ) epsilon_effective_minimum = np . min ( 1 / ( seed_degree * neighbor_degrees ) ) if epsilon_effective > epsilon_effective_maximum : epsilon_effective = epsilon_effective_maximum elif epsilon_effective < epsilon_effective_minimum : epsilon_effective = ( epsilon_effective_minimum + epsilon_effective ) / 2 return epsilon_effective | Semi - automatic effective epsilon threshold calculation . |
47,454 | def arcte_with_lazy_pagerank ( adjacency_matrix , rho , epsilon , number_of_threads = None ) : adjacency_matrix = sparse . csr_matrix ( adjacency_matrix ) number_of_nodes = adjacency_matrix . shape [ 0 ] if number_of_threads is None : number_of_threads = get_threads_number ( ) if number_of_threads == 1 : rw_transition , out_degree , in_degree = get_natural_random_walk_matrix ( adjacency_matrix , make_shared = False ) a = adjacency_matrix . copy ( ) a . data = np . ones_like ( a . data ) edge_count_vector = np . squeeze ( np . asarray ( a . sum ( axis = 0 ) , dtype = np . int64 ) ) iterate_nodes = np . where ( edge_count_vector != 0 ) [ 0 ] argsort_indices = np . argsort ( edge_count_vector [ iterate_nodes ] ) iterate_nodes = iterate_nodes [ argsort_indices ] [ : : - 1 ] iterate_nodes = iterate_nodes [ np . where ( edge_count_vector [ iterate_nodes ] > 1.0 ) [ 0 ] ] local_features = arcte_with_lazy_pagerank_worker ( iterate_nodes , rw_transition . indices , rw_transition . indptr , rw_transition . data , out_degree , in_degree , rho , epsilon ) else : rw_transition , out_degree , in_degree = get_natural_random_walk_matrix ( adjacency_matrix , make_shared = True ) a = adjacency_matrix . copy ( ) a . data = np . ones_like ( a . data ) edge_count_vector = np . squeeze ( np . asarray ( a . sum ( axis = 0 ) , dtype = np . int64 ) ) iterate_nodes = np . where ( edge_count_vector != 0 ) [ 0 ] argsort_indices = np . argsort ( edge_count_vector [ iterate_nodes ] ) iterate_nodes = iterate_nodes [ argsort_indices ] [ : : - 1 ] iterate_nodes = iterate_nodes [ np . where ( edge_count_vector [ iterate_nodes ] > 1.0 ) [ 0 ] ] pool = mp . Pool ( number_of_threads ) node_chunks = list ( parallel_chunks ( iterate_nodes , number_of_threads ) ) node_count = 0 for chunk in node_chunks : node_count += len ( list ( chunk ) ) results = list ( ) for chunk_no in range ( len ( pool . _pool ) ) : pool . apply_async ( arcte_with_lazy_pagerank_worker , args = ( node_chunks [ chunk_no ] , rw_transition . indices , rw_transition . indptr , rw_transition . data , out_degree , in_degree , rho , epsilon ) , callback = results . append ) pool . close ( ) pool . join ( ) local_features = results [ 0 ] for additive_features in results [ 1 : ] : local_features += additive_features local_features = sparse . csr_matrix ( local_features ) identity_matrix = sparse . csr_matrix ( sparse . eye ( number_of_nodes , number_of_nodes , dtype = np . float64 ) ) adjacency_matrix_ones = adjacency_matrix adjacency_matrix_ones . data = np . ones_like ( adjacency_matrix . data ) base_community_features = identity_matrix + adjacency_matrix_ones try : features = sparse . hstack ( [ base_community_features , local_features ] ) . tocsr ( ) except ValueError as e : print ( "Failure with horizontal feature stacking." ) features = base_community_features return features | Extracts local community features for all graph nodes based on the partitioning of node - centric similarity vectors . |
47,455 | def get_folds_generator ( node_label_matrix , labelled_node_indices , number_of_categories , dataset_memory_folder , percentage , number_of_folds = 10 ) : number_of_labeled_nodes = labelled_node_indices . size training_set_size = int ( np . ceil ( percentage * number_of_labeled_nodes / 100 ) ) fold_file_path = dataset_memory_folder + "/folds/" + str ( percentage ) + "_folds.txt" train_list = list ( ) test_list = list ( ) if not os . path . exists ( fold_file_path ) : with open ( fold_file_path , "w" ) as fp : for trial in np . arange ( number_of_folds ) : train , test = valid_train_test ( node_label_matrix [ labelled_node_indices , : ] , training_set_size , number_of_categories , trial ) train = labelled_node_indices [ train ] test = labelled_node_indices [ test ] row = [ str ( node ) for node in test ] row = "\t" . join ( row ) + "\n" fp . write ( row ) row = [ str ( node ) for node in train ] row = "\t" . join ( row ) + "\n" fp . write ( row ) train_list . append ( train ) test_list . append ( test ) else : file_row_gen = get_file_row_generator ( fold_file_path , "\t" ) for trial in np . arange ( number_of_folds ) : test = next ( file_row_gen ) test = [ int ( node ) for node in test ] test = np . array ( test ) train = next ( file_row_gen ) train = [ int ( node ) for node in train ] train = np . array ( train ) train_list . append ( train ) test_list . append ( test ) folds = ( ( train , test ) for train , test in zip ( train_list , test_list ) ) return folds | Read or form and store the seed nodes for training and testing . |
47,456 | def generate_folds ( node_label_matrix , labelled_node_indices , number_of_categories , percentage , number_of_folds = 10 ) : number_of_labeled_nodes = labelled_node_indices . size training_set_size = int ( np . ceil ( percentage * number_of_labeled_nodes / 100 ) ) train_list = list ( ) test_list = list ( ) for trial in np . arange ( number_of_folds ) : train , test = valid_train_test ( node_label_matrix [ labelled_node_indices , : ] , training_set_size , number_of_categories , trial ) train = labelled_node_indices [ train ] test = labelled_node_indices [ test ] train_list . append ( train ) test_list . append ( test ) folds = ( ( train , test ) for train , test in zip ( train_list , test_list ) ) return folds | Form the seed nodes for training and testing . |
47,457 | def form_node_label_prediction_matrix ( y_pred , y_test ) : number_of_test_nodes = y_pred . shape [ 0 ] true_number_of_labels = np . squeeze ( y_test . sum ( axis = 1 ) ) index = np . argsort ( y_pred , axis = 1 ) row = np . empty ( y_test . getnnz ( ) , dtype = np . int64 ) col = np . empty ( y_test . getnnz ( ) , dtype = np . int64 ) start = 0 for n in np . arange ( number_of_test_nodes ) : end = start + true_number_of_labels [ 0 , n ] row [ start : end ] = n col [ start : end ] = index [ n , - 1 : - true_number_of_labels [ 0 , n ] - 1 : - 1 ] start = end data = np . ones_like ( row , dtype = np . int8 ) y_pred = sparse . coo_matrix ( ( data , ( row , col ) ) , shape = y_test . shape ) return y_pred | Given the discriminator distances this function forms the node - label prediction matrix . |
47,458 | def calculate_measures ( y_pred , y_test ) : y_pred = y_pred . toarray ( ) y_test = y_test . toarray ( ) macro_precision , macro_recall , macro_F1 , macro_support = precision_recall_fscore_support ( y_test , y_pred , beta = 1.0 , average = "macro" ) micro_precision , micro_recall , micro_F1 , micro_support = precision_recall_fscore_support ( y_test , y_pred , beta = 1.0 , average = "micro" ) F1 = f1_score ( y_test , y_pred , average = None ) measures = [ macro_recall , micro_recall , macro_precision , micro_precision , macro_F1 , micro_F1 , F1 ] return measures | Calculates the F - scores and F - score averages given a classification result and a ground truth . |
47,459 | def decode ( buff ) : pp = list ( map ( ord , buff ) ) if 0 == len ( pp ) == 1 : pp = [ ] return pp | Transforms the raw buffer data read in into a list of bytes |
47,460 | def write ( self , pkt ) : self . setRTS ( self . DD_WRITE ) self . flushInput ( ) pkt = bytearray ( pkt ) pkt = bytes ( pkt ) num = self . serial . write ( pkt ) return num | This is a simple serial write command . It toggles the RTS pin and formats all of the data into bytes before it writes . |
47,461 | def sendPkt ( self , pkt , retry = 5 , sleep_time = 0.01 ) : for cnt in range ( retry ) : self . serial . flushInput ( ) self . write ( pkt ) ans = self . read ( ) if ans : return ans else : time . sleep ( sleep_time ) return None | Sends a packet and waits for a return . If no return is given then it resends the packet . If an error occurs it also resends the packet . |
47,462 | def scipy_sparse_to_csv ( filepath , matrix , separator = "," , directed = False , numbering = "matlab" ) : matrix = spsp . coo_matrix ( matrix ) shape = matrix . shape nnz = matrix . getnnz ( ) if numbering == "matlab" : row = matrix . row + 1 col = matrix . col + 1 data = matrix . data elif numbering == "c" : row = matrix . row col = matrix . col data = matrix . data else : print ( "Invalid numbering style." ) raise RuntimeError with open ( filepath , "w" ) as f : file_row = "n_rows:" + separator + str ( shape [ 0 ] ) + separator + "n_cols:" + separator + str ( shape [ 1 ] ) + separator + "nnz:" + separator + str ( nnz ) + separator + "directed:" + separator + str ( directed ) + "\n" f . write ( file_row ) for edge in range ( row . size ) : if directed is False : if col [ edge ] < row [ edge ] : continue file_row = str ( row [ edge ] ) + separator + str ( col [ edge ] ) + separator + str ( data [ edge ] ) + "\n" f . write ( file_row ) | Writes sparse matrix in separated value format . |
47,463 | def publish ( build ) : build . packages . install ( "wheel" ) build . packages . install ( "twine" ) build . executables . run ( [ "python" , "setup.py" , "sdist" , "bdist_wheel" , "--universal" , "--release" ] ) build . executables . run ( [ "twine" , "upload" , "dist/*" ] ) | publish the package itself |
47,464 | def fast_approximate_personalized_pagerank ( s , r , w_i , a_i , out_degree , in_degree , seed_node , rho = 0.2 , epsilon = 0.00001 ) : r [ seed_node ] = 1.0 pushable = deque ( ) pushable . append ( seed_node ) push_node = pushable . popleft ( ) pagerank_limit_push ( s , r , w_i [ push_node ] , a_i [ push_node ] , push_node , rho ) number_of_push_operations = 1 i = np . where ( np . divide ( r [ a_i [ push_node ] ] , in_degree [ a_i [ push_node ] ] ) >= epsilon ) [ 0 ] if i . size > 0 : pushable . extend ( a_i [ push_node ] [ i ] ) while len ( pushable ) > 0 : push_node = pushable . popleft ( ) if r [ push_node ] / in_degree [ push_node ] >= epsilon : pagerank_limit_push ( s , r , w_i [ push_node ] , a_i [ push_node ] , push_node , rho ) number_of_push_operations += 1 i = np . where ( np . divide ( r [ a_i [ push_node ] ] , in_degree [ a_i [ push_node ] ] ) >= epsilon ) [ 0 ] if i . size > 0 : pushable . extend ( a_i [ push_node ] [ i ] ) return number_of_push_operations | Calculates the approximate personalized PageRank starting from a seed node without self - loops . |
47,465 | def lazy_approximate_personalized_pagerank ( s , r , w_i , a_i , out_degree , in_degree , seed_node , rho = 0.2 , epsilon = 0.00001 , laziness_factor = 0.5 ) : r [ seed_node ] = 1.0 pushable = deque ( ) pushable . append ( seed_node ) push_node = pushable . popleft ( ) pagerank_lazy_push ( s , r , w_i [ push_node ] , a_i [ push_node ] , push_node , rho , laziness_factor ) number_of_push_operations = 1 i = np . where ( np . divide ( r [ a_i [ push_node ] ] , in_degree [ a_i [ push_node ] ] ) >= epsilon ) [ 0 ] if i . size > 0 : pushable . extend ( a_i [ push_node ] [ i ] ) while r [ push_node ] / in_degree [ push_node ] >= epsilon : pagerank_lazy_push ( s , r , w_i [ push_node ] , a_i [ push_node ] , push_node , rho , laziness_factor ) number_of_push_operations += 1 while len ( pushable ) > 0 : push_node = pushable . popleft ( ) if r [ push_node ] / in_degree [ push_node ] >= epsilon : pagerank_lazy_push ( s , r , w_i [ push_node ] , a_i [ push_node ] , push_node , rho , laziness_factor ) number_of_push_operations += 1 i = np . where ( np . divide ( r [ a_i [ push_node ] ] , in_degree [ a_i [ push_node ] ] ) >= epsilon ) [ 0 ] if i . size > 0 : pushable . extend ( a_i [ push_node ] [ i ] ) while r [ push_node ] / in_degree [ push_node ] >= epsilon : pagerank_lazy_push ( s , r , w_i [ push_node ] , a_i [ push_node ] , push_node , rho , laziness_factor ) number_of_push_operations += 1 return number_of_push_operations | Calculates the approximate personalized PageRank starting from a seed node with self - loops . |
47,466 | def read_matlab_features ( array_paths , number_of_nodes , dimensionality ) : file_row_gen = get_file_row_generator ( array_paths [ 0 ] , "\t" ) data = list ( ) append_data = data . append for file_row in file_row_gen : append_data ( float ( file_row [ 0 ] ) ) file_row_gen = get_file_row_generator ( array_paths [ 1 ] , "\t" ) row = list ( ) append_row = row . append for file_row in file_row_gen : append_row ( int ( float ( file_row [ 0 ] ) ) ) file_row_gen = get_file_row_generator ( array_paths [ 2 ] , "\t" ) col = list ( ) append_col = col . append for file_row in file_row_gen : append_col ( int ( float ( file_row [ 0 ] ) ) ) data = np . array ( data ) . astype ( np . float64 ) row = np . array ( row ) . astype ( np . int64 ) - 1 col = np . array ( col ) . astype ( np . int64 ) - 1 print ( np . max ( row ) , np . min ( row ) ) print ( np . max ( col ) , np . min ( col ) ) features = spsp . coo_matrix ( ( data , ( row , col ) ) , shape = ( number_of_nodes , dimensionality ) ) return features | Returns a sparse feature matrix as calculated by a Matlab routine . |
47,467 | def community_neighbors ( c_j , reverse_index_rows , unavailable_communities , unavailable_communities_counter ) : indices = list ( ) extend = indices . extend for node in c_j : extend ( reverse_index_rows [ node ] ) indices = np . array ( indices ) indices = np . setdiff1d ( indices , unavailable_communities [ : unavailable_communities_counter + 1 ] ) return indices | Finds communities with shared nodes to a seed community . Called by mroc . |
47,468 | def jaccard ( c_1 , c_2 ) : nom = np . intersect1d ( c_1 , c_2 ) . size denom = np . union1d ( c_1 , c_2 ) . size return nom / denom | Calculates the Jaccard similarity between two sets of nodes . Called by mroc . |
47,469 | def louvain ( adjacency_matrix ) : adjacency_matrix = nx . from_scipy_sparse_matrix ( adjacency_matrix , create_using = nx . Graph ( ) ) tree = community . generate_dendogram ( adjacency_matrix , part_init = None ) row = list ( ) col = list ( ) append_row = row . append append_col = col . append community_counter = 0 for i in range ( len ( tree ) ) : partition = community . partition_at_level ( tree , i ) for n , c in partition . items ( ) : append_row ( n ) append_col ( community_counter + c ) community_counter += max ( partition . values ( ) ) + 1 row = np . array ( row ) col = np . array ( col ) data = np . ones ( row . size , dtype = np . float64 ) louvain_features = sparse . coo_matrix ( ( data , ( row , col ) ) , shape = ( len ( partition . keys ( ) ) , community_counter ) , dtype = np . float64 ) return louvain_features | Performs community embedding using the LOUVAIN method . |
47,470 | def laplacian_eigenmaps ( adjacency_matrix , k ) : laplacian = get_normalized_laplacian ( adjacency_matrix ) try : eigenvalues , eigenvectors = spla . eigsh ( laplacian , k = k , which = 'SM' , return_eigenvectors = True ) except spla . ArpackNoConvergence as e : print ( "ARPACK has not converged." ) eigenvalue = e . eigenvalues eigenvectors = e . eigenvectors eigenvectors = eigenvectors [ : , 1 : ] return eigenvectors | Performs spectral graph embedding using the graph symmetric normalized Laplacian matrix . |
47,471 | def replicator_eigenmaps ( adjacency_matrix , k ) : number_of_nodes = adjacency_matrix . shape [ 0 ] max_eigenvalue = spla . eigsh ( adjacency_matrix , k = 1 , which = 'LM' , return_eigenvectors = False ) eye_matrix = sparse . eye ( number_of_nodes , number_of_nodes , dtype = np . float64 ) eye_matrix = eye_matrix . tocsr ( ) eye_matrix . data = eye_matrix . data * max_eigenvalue replicator = eye_matrix - adjacency_matrix try : eigenvalues , eigenvectors = spla . eigsh ( replicator , k = k + 1 , which = 'SM' , return_eigenvectors = True ) except spla . ArpackNoConvergence as e : print ( "ARPACK has not converged." ) eigenvalue = e . eigenvalues eigenvectors = e . eigenvectors eigenvectors = eigenvectors [ : , 1 : ] return eigenvectors | Performs spectral graph embedding on the centrality reweighted adjacency matrix |
47,472 | def base_communities ( adjacency_matrix ) : number_of_nodes = adjacency_matrix . shape [ 0 ] adjacency_matrix = adjacency_matrix . tocsr ( ) adjacency_matrix = adjacency_matrix . transpose ( ) features = sparse . csr_matrix ( sparse . eye ( number_of_nodes , number_of_nodes ) ) + adjacency_matrix . tocsr ( ) features = features . tocsr ( ) features . data = np . ones_like ( features . data ) return features | Forms the community indicator normalized feature matrix for any graph . |
47,473 | def create_key ( file_ ) : pkey = crypto . PKey ( ) pkey . generate_key ( crypto . TYPE_RSA , 2048 ) file_ . write ( crypto . dump_privatekey ( crypto . FILETYPE_PEM , pkey ) ) file_ . flush ( ) | Create a key and save it into file_ . |
47,474 | def create_csr ( key_file , organization_name , common_name , serial_number , file_ ) : key = crypto . load_privatekey ( crypto . FILETYPE_PEM , key_file . read ( ) ) req = crypto . X509Req ( ) subj = req . get_subject ( ) subj . O = organization_name subj . CN = common_name subj . serialNumber = serial_number req . set_pubkey ( key ) req . sign ( key , 'md5' ) file_ . write ( crypto . dump_certificate_request ( crypto . FILETYPE_PEM , req ) ) | Create a CSR for a key and save it into file . |
47,475 | def model_fit ( X_train , y_train , svm_hardness , fit_intercept , number_of_threads , classifier_type = "LinearSVC" ) : if classifier_type == "LinearSVC" : if X_train . shape [ 0 ] > X_train . shape [ 1 ] : dual = False else : dual = True model = OneVsRestClassifier ( LinearSVC ( C = svm_hardness , random_state = 0 , dual = dual , fit_intercept = fit_intercept ) , n_jobs = number_of_threads ) model . fit ( X_train , y_train ) elif classifier_type == "LogisticRegression" : if X_train . shape [ 0 ] > X_train . shape [ 1 ] : dual = False else : dual = True model = OneVsRestClassifier ( LogisticRegression ( C = svm_hardness , random_state = 0 , dual = dual , fit_intercept = fit_intercept ) , n_jobs = number_of_threads ) model . fit ( X_train , y_train ) elif classifier_type == "RandomForest" : model = OneVsRestClassifier ( RandomForestClassifier ( n_estimators = 1000 , criterion = "gini" , n_jobs = number_of_threads , random_state = 0 ) ) if issparse ( X_train ) : model . fit ( X_train . tocsc ( ) , y_train . toarray ( ) ) else : model . fit ( X_train , y_train . toarray ( ) ) else : print ( "Invalid classifier type." ) raise RuntimeError return model | Fits a Linear Support Vector Classifier to the labelled graph - based features using the LIBLINEAR library . |
47,476 | def meta_model_fit ( X_train , y_train , svm_hardness , fit_intercept , number_of_threads , regressor_type = "LinearSVR" ) : if regressor_type == "LinearSVR" : if X_train . shape [ 0 ] > X_train . shape [ 1 ] : dual = False else : dual = True model = LinearSVR ( C = svm_hardness , random_state = 0 , dual = dual , fit_intercept = fit_intercept ) y_train_meta = y_train . sum ( axis = 1 ) model . fit ( X_train , y_train_meta ) else : print ( "Invalid regressor type." ) raise RuntimeError return model | Trains meta - labeler for predicting number of labels for each user . |
47,477 | def weigh_users ( X_test , model , classifier_type = "LinearSVC" ) : if classifier_type == "LinearSVC" : decision_weights = model . decision_function ( X_test ) elif classifier_type == "LogisticRegression" : decision_weights = model . predict_proba ( X_test ) elif classifier_type == "RandomForest" : if issparse ( X_test ) : decision_weights = model . predict_proba ( X_test . tocsr ( ) ) else : decision_weights = model . predict_proba ( X_test ) else : print ( "Invalid classifier type." ) raise RuntimeError return decision_weights | Uses a trained model and the unlabelled features to produce a user - to - label distance matrix . |
47,478 | def get_client ( service_name , sandbox = False ) : key = ( service_name . lower ( ) , sandbox , ) try : if key not in cached_clients : cached_clients [ key ] = Client ( wsdls [ key ] , transport = transport ) return cached_clients [ key ] except KeyError : raise ValueError ( 'Unknown service name, {}' . format ( service_name ) ) | Returns a client for a given service . |
47,479 | def extract ( cls , extractor , typ ) : schema = { "title" : typ . __name__ , "type" : "object" , "properties" : { } , "required" : [ ] } for attribute in attr . fields ( typ ) : details = cls . _extract_attribute ( extractor , attribute ) if details . is_required : schema [ "required" ] . append ( details . name ) schema [ "properties" ] [ details . name ] = details . schema return schema | take an attrs based class and convert it to jsonschema . |
47,480 | def prettyPrintPacket ( ctrl_table ) : print ( '---------------------------------------' ) print ( "{:.<29} {}" . format ( 'id' , ctrl_table [ 'id' ] ) ) ctrl_table . pop ( 'id' ) for key , value in ctrl_table . items ( ) : print ( "{:.<29} {}" . format ( key , value ) ) | This will pretty print out a packet s fields . |
47,481 | def write ( fname , data ) : try : with open ( fname , 'w' ) as f : json . dump ( data , f ) except IOError : raise Exception ( 'Could not open {0!s} for writing' . format ( ( fname ) ) ) | Writes a Json file |
47,482 | def makePacket ( ID , instr , reg = None , params = None ) : pkt = [ ] pkt += [ 0xFF , 0xFF , 0xFD ] pkt += [ 0x00 ] pkt += [ ID ] pkt += [ 0x00 , 0x00 ] pkt += [ instr ] if reg : pkt += le ( reg ) if params : pkt += params length = le ( len ( pkt ) - 5 ) pkt [ 5 ] = length [ 0 ] pkt [ 6 ] = length [ 1 ] crc = crc16 ( pkt ) pkt += le ( crc ) return pkt | This makes a generic packet . |
47,483 | def makeControlModePacket ( ID , mode ) : pkt = makeWritePacket ( ID , xl320 . XL320_CONTROL_MODE , le ( mode ) ) return pkt | Sets the xl - 320 to either servo or wheel mode |
47,484 | def makeBaudRatePacket ( ID , rate ) : if rate not in [ 0 , 1 , 2 , 3 ] : raise Exception ( 'Packet.makeBaudRatePacket: wrong rate {}' . format ( rate ) ) pkt = makeWritePacket ( ID , xl320 . XL320_BAUD_RATE , [ rate ] ) return pkt | Set baud rate of servo . |
47,485 | def makeSyncAnglePacket ( info ) : addr = le ( xl320 . XL320_GOAL_POSITION ) data = [ ] data . append ( addr [ 0 ] ) data . append ( addr [ 1 ] ) data . append ( 2 ) data . append ( 0 ) for pkt in info : data . append ( pkt [ 0 ] ) angle = le ( int ( pkt [ 1 ] / 300 * 1023 ) ) data . append ( angle [ 0 ] ) data . append ( angle [ 1 ] ) ID = xl320 . XL320_BROADCAST_ADDR instr = xl320 . XL320_SYNC_WRITE pkt = makePacket ( ID , instr , None , data ) return pkt | Write sync angle information to servos . |
47,486 | def makeBulkAnglePacket ( info ) : addr = le ( xl320 . XL320_GOAL_POSITION ) data = [ ] for pkt in info : data . append ( pkt [ 0 ] ) data . append ( addr [ 0 ] ) data . append ( addr [ 1 ] ) data . append ( 2 ) data . append ( 0 ) angle = le ( int ( pkt [ 1 ] / 300 * 1023 ) ) data . append ( angle [ 0 ] ) data . append ( angle [ 1 ] ) ID = xl320 . XL320_BROADCAST_ADDR instr = xl320 . XL320_BULK_WRITE pkt = makePacket ( ID , instr , None , data ) return pkt | Write bulk angle information to servos . |
47,487 | def findPkt ( pkt ) : ret = [ ] while len ( pkt ) - 10 >= 0 : if pkt [ 0 : 4 ] != [ 0xFF , 0xFF , 0xFD , 0x00 ] : pkt . pop ( 0 ) continue length = ( pkt [ 6 ] << 8 ) + pkt [ 5 ] crc_pos = 5 + length pkt_crc = pkt [ crc_pos : crc_pos + 2 ] crc = le ( crc16 ( pkt [ : crc_pos ] ) ) if pkt_crc == crc : pkt_end = crc_pos + 2 ret . append ( pkt [ : pkt_end ] ) del pkt [ : pkt_end ] else : pkt_end = crc_pos + 2 del pkt [ : pkt_end ] return ret | Search through a string of binary for a valid xl320 package . |
47,488 | def populate_all ( ) : ReceiptType . objects . populate ( ) ConceptType . objects . populate ( ) DocumentType . objects . populate ( ) VatType . objects . populate ( ) TaxType . objects . populate ( ) CurrencyType . objects . populate ( ) | Fetch and store all metadata from the AFIP . |
47,489 | def first_currency ( ) : ct = CurrencyType . objects . filter ( code = 'PES' ) . first ( ) if ct : return ct . pk | Returns the id for the first currency |
47,490 | def populate ( self , ticket = None ) : ticket = ticket or AuthTicket . objects . get_any_active ( 'wsfe' ) client = clients . get_client ( 'wsfe' , ticket . owner . is_sandboxed ) service = getattr ( client . service , self . __service_name ) response_xml = service ( serializers . serialize_ticket ( ticket ) ) check_response ( response_xml ) for result in getattr ( response_xml . ResultGet , self . __type_name ) : self . get_or_create ( code = result . Id , description = result . Desc , valid_from = parsers . parse_date ( result . FchDesde ) , valid_to = parsers . parse_date ( result . FchHasta ) , ) | Populate the database with types retrieved from the AFIP . |
47,491 | def certificate_object ( self ) : if not self . certificate : return None self . certificate . seek ( 0 ) return crypto . parse_certificate ( self . certificate . read ( ) ) | Returns the certificate as an OpenSSL object |
47,492 | def get_certificate_expiration ( self ) : datestring = self . certificate_object . get_notAfter ( ) . decode ( ) dt = datetime . strptime ( datestring , '%Y%m%d%H%M%SZ' ) return dt . replace ( tzinfo = timezone . utc ) | Gets the certificate expiration from the certificate |
47,493 | def generate_key ( self , force = False ) : if self . key and not force : logger . warning ( 'Tried to generate key for a taxpayer that already had one' ) return False with NamedTemporaryFile ( suffix = '.key' ) as file_ : crypto . create_key ( file_ ) self . key = File ( file_ , name = '{}.key' . format ( uuid . uuid4 ( ) . hex ) ) self . save ( ) return True | Creates a key file for this TaxPayer |
47,494 | def generate_csr ( self , basename = 'djangoafip' ) : csr = BytesIO ( ) crypto . create_csr ( self . key . file , self . name , '{}{}' . format ( basename , int ( datetime . now ( ) . timestamp ( ) ) ) , 'CUIT {}' . format ( self . cuit ) , csr , ) csr . seek ( 0 ) return csr | Creates a CSR for this TaxPayer s key |
47,495 | def create_ticket ( self , service ) : ticket = AuthTicket ( owner = self , service = service ) ticket . authorize ( ) return ticket | Create an AuthTicket for a given service . |
47,496 | def get_ticket ( self , service ) : return self . auth_tickets . filter ( expires__gt = datetime . now ( timezone . utc ) , service = service ) . last ( ) | Return an existing AuthTicket for a given service . |
47,497 | def fetch_points_of_sales ( self , ticket = None ) : ticket = ticket or self . get_or_create_ticket ( 'wsfe' ) client = clients . get_client ( 'wsfe' , self . is_sandboxed ) response = client . service . FEParamGetPtosVenta ( serializers . serialize_ticket ( ticket ) , ) check_response ( response ) results = [ ] for pos_data in response . ResultGet . PtoVenta : results . append ( PointOfSales . objects . update_or_create ( number = pos_data . Nro , issuance_type = pos_data . EmisionTipo , owner = self , defaults = { 'blocked' : pos_data . Bloqueado == 'N' , 'drop_date' : parsers . parse_date ( pos_data . FchBaja ) , } ) ) return results | Fetch all point of sales objects . |
47,498 | def logo_as_data_uri ( self ) : _ , ext = os . path . splitext ( self . logo . file . name ) with open ( self . logo . file . name , 'rb' ) as f : data = base64 . b64encode ( f . read ( ) ) return 'data:image/{};base64,{}' . format ( ext [ 1 : ] , data . decode ( ) ) | This TaxPayer s logo as a data uri . |
47,499 | def authorize ( self ) : request = self . __create_request_xml ( ) request = self . __sign_request ( request ) request = b64encode ( request ) . decode ( ) client = clients . get_client ( 'wsaa' , self . owner . is_sandboxed ) try : raw_response = client . service . loginCms ( request ) except Fault as e : if str ( e ) == 'Certificado expirado' : raise exceptions . CertificateExpired ( str ( e ) ) from e if str ( e ) == 'Certificado no emitido por AC de confianza' : raise exceptions . UntrustedCertificate ( str ( e ) ) from e raise exceptions . AuthenticationError ( str ( e ) ) from e response = etree . fromstring ( raw_response . encode ( 'utf-8' ) ) self . token = response . xpath ( self . TOKEN_XPATH ) [ 0 ] . text self . signature = response . xpath ( self . SIGN_XPATH ) [ 0 ] . text self . save ( ) | Send this ticket to AFIP for authorization . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.