idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
8,500 | def name_tree ( tree ) : existing_names = Counter ( ( _ . name for _ in tree . traverse ( ) if _ . name ) ) if sum ( 1 for _ in tree . traverse ( ) ) == len ( existing_names ) : return i = 0 existing_names = Counter ( ) for node in tree . traverse ( 'preorder' ) : name = node . name if node . is_leaf ( ) else ( 'root' ... | Names all the tree nodes that are not named or have non - unique names with unique names . |
8,501 | def enable_result_transforms ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : func_transformator = kwargs . pop ( 'electrode_transformator' , None ) data , electrodes , topography = func ( * args , ** kwargs ) if func_transformator is not None : data_transformed , electrodes_transformed , to... | Decorator that tries to use the object provided using a kwarg called electrode_transformator to transform the return values of an import function . It is intended to be used to transform electrode numbers and locations i . e . for use in roll - along - measurement schemes . |
8,502 | def record_path ( self ) : if self . record_button . get_property ( 'active' ) and ( self . record_path_selector . selected_path ) : return self . record_path_selector . selected_path else : return None | If recording is not enabled return None as record path . |
8,503 | def _write_crmod_file ( filename ) : crmod_lines = [ '***FILES***' , '../grid/elem.dat' , '../grid/elec.dat' , '../rho/rho.dat' , '../config/config.dat' , 'F ! potentials ?' , '../mod/pot/pot.dat' , 'T ! measurements ?' , '../mod/volt.dat' , 'F ! sensitivities ?' , '../mod/se... | Write a valid crmod configuration file to filename . |
8,504 | def utf ( text ) : try : output = unicode ( text , encoding = 'utf-8' ) except UnicodeDecodeError : output = text except TypeError : output = text return output | Shortcut funnction for encoding given text with utf - 8 |
8,505 | def check_bom ( file ) : lead = file . read ( 3 ) if len ( lead ) == 3 and lead == codecs . BOM_UTF8 : return codecs . lookup ( 'utf-8' ) . name elif len ( lead ) >= 2 and lead [ : 2 ] == codecs . BOM_UTF16_BE : if len ( lead ) == 3 : file . seek ( - 1 , os . SEEK_CUR ) return codecs . lookup ( 'utf-16-be' ) . name eli... | Determines file codec from from its BOM record . |
8,506 | def guess_lineno ( file ) : offset = file . tell ( ) file . seek ( 0 ) startpos = 0 lineno = 1 while True : line = file . readline ( ) if not line : break endpos = file . tell ( ) if startpos <= offset < endpos : break lineno += 1 file . seek ( offset ) return lineno | Guess current line number in a file . |
8,507 | def search ( query ) : params = { 's.cmd' : 'setTextQuery(%s)setPageSize(50)setHoldingsOnly(true)' % query } return requests . get ( BASE_URL , params = params , timeout = 10 ) . json ( ) | Search Penn Libraries Franklin for documents The maximum pagesize currently is 50 . |
8,508 | def make_record ( level , xref_id , tag , value , sub_records , offset , dialect , parser = None ) : if value and len ( value ) > 2 and ( ( value [ 0 ] == '@' and value [ - 1 ] == '@' ) or ( value [ 0 ] == 64 and value [ - 1 ] == 64 ) ) : klass = Pointer rec = klass ( parser ) else : klass = _tag_class . get ( tag , Re... | Create Record instance based on parameters . |
8,509 | def sub_tag ( self , path , follow = True ) : tags = path . split ( '/' ) rec = self for tag in tags : recs = [ x for x in ( rec . sub_records or [ ] ) if x . tag == tag ] if not recs : return None rec = recs [ 0 ] if follow and isinstance ( rec , Pointer ) : rec = rec . ref return rec | Returns direct sub - record with given tag name or None . |
8,510 | def sub_tag_value ( self , path , follow = True ) : rec = self . sub_tag ( path , follow ) if rec : return rec . value return None | Returns value of a direct sub - record or None . |
8,511 | def sub_tags ( self , * tags , ** kw ) : records = [ x for x in self . sub_records if x . tag in tags ] if kw . get ( 'follow' , True ) : records = [ rec . ref if isinstance ( rec , Pointer ) else rec for rec in records ] return records | Returns list of direct sub - records matching any tag name . |
8,512 | def freeze ( self ) : if self . value is None : self . value = "" if self . dialect in [ DIALECT_ALTREE ] : name_tuple = parse_name_altree ( self ) elif self . dialect in [ DIALECT_MYHERITAGE ] : name_tuple = parse_name_myher ( self ) elif self . dialect in [ DIALECT_ANCESTRIS ] : name_tuple = parse_name_ancestris ( se... | Method called by parser when updates to this record finish . |
8,513 | def given ( self ) : if self . _primary . value [ 0 ] and self . _primary . value [ 2 ] : return self . _primary . value [ 0 ] + ' ' + self . _primary . value [ 2 ] return self . _primary . value [ 0 ] or self . _primary . value [ 2 ] | Given name could include both first and middle name |
8,514 | def maiden ( self ) : if self . _dialect == DIALECT_DEFAULT : for name in self . _names : if name . type == "maiden" : return name . value [ 1 ] if self . _primary and len ( self . _primary . value ) > 3 : return self . _primary . value [ 3 ] return None | Maiden last name can be None |
8,515 | def order ( self , order ) : given = self . given surname = self . surname if order in ( ORDER_MAIDEN_GIVEN , ORDER_GIVEN_MAIDEN ) : surname = self . maiden or self . surname given = ( "1" + given ) if given else "2" surname = ( "1" + surname ) if surname else "2" if order in ( ORDER_SURNAME_GIVEN , ORDER_MAIDEN_GIVEN ... | Returns name order key . |
8,516 | def format ( self ) : name = self . _primary . value [ 0 ] if self . surname : if name : name += ' ' name += self . surname if self . _primary . value [ 2 ] : if name : name += ' ' name += self . _primary . value [ 2 ] return name | Format name for output . |
8,517 | def match ( self , xn ) : if all ( map ( lambda x : x . match ( xn ) , self . conditions ) ) : return self . outcomes return None | Processes a transaction against this rule |
8,518 | def import_sip04_data_all ( data_filename ) : filename , fformat = os . path . splitext ( data_filename ) if fformat == '.csv' : print ( 'Import SIP04 data from .csv file' ) df_all = _import_csv_file ( data_filename ) elif fformat == '.mat' : print ( 'Import SIP04 data from .mat file' ) df_all = _import_mat_file ( data... | Import ALL data from the result files |
8,519 | def init_session ( db_url = None , echo = False , engine = None , settings = None ) : if engine is None : engine = init_engine ( db_url = db_url , echo = echo , settings = settings ) return sessionmaker ( bind = engine ) | A SQLAlchemy Session requires that an engine be initialized if one isn t provided . |
8,520 | def import_sip256c ( self , filename , settings = None , reciprocal = None , ** kwargs ) : if settings is None : settings = { } df , dummy1 , dummy2 = reda_sip256c . parse_radic_file ( filename , settings , reciprocal = reciprocal , ** kwargs ) self . _add_to_container ( df ) print ( 'Summary:' ) self . _describe_data ... | Radic SIP256c data import |
8,521 | def import_eit_fzj ( self , filename , configfile , correction_file = None , timestep = None , ** kwargs ) : df_emd , dummy1 , dummy2 = eit_fzj . read_3p_data ( filename , configfile , ** kwargs ) if correction_file is not None : eit_fzj_utils . apply_correction_factors ( df_emd , correction_file ) if timestep is not N... | EIT data import for FZJ Medusa systems |
8,522 | def check_dataframe ( self , dataframe ) : required_columns = ( 'a' , 'b' , 'm' , 'n' , 'r' , ) for column in required_columns : if column not in dataframe : raise Exception ( 'Required column not in dataframe: {0}' . format ( column ) ) | Check the given dataframe for the required columns |
8,523 | def query ( self , query , inplace = True ) : result = self . data . query ( query , inplace = inplace ) return result | State what you want to keep |
8,524 | def remove_frequencies ( self , fmin , fmax ) : self . data . query ( 'frequency > {0} and frequency < {1}' . format ( fmin , fmax ) , inplace = True ) g = self . data . groupby ( 'frequency' ) print ( 'Remaining frequencies:' ) print ( sorted ( g . groups . keys ( ) ) ) | Remove frequencies from the dataset |
8,525 | def compute_K_analytical ( self , spacing ) : assert isinstance ( spacing , Number ) K = geometric_factors . compute_K_analytical ( self . data , spacing ) self . data = geometric_factors . apply_K ( self . data , K ) fix_sign_with_K ( self . data ) | Assuming an equal electrode spacing compute the K - factor over a homogeneous half - space . |
8,526 | def scatter_norrec ( self , filename = None , individual = False ) : std_diff_labels = { 'r' : 'rdiff' , 'rpha' : 'rphadiff' , } diff_labels = std_diff_labels labels_to_use = { } for key , item in diff_labels . items ( ) : if key in self . data . columns and item in self . data . columns : labels_to_use [ key ] = item ... | Create a scatter plot for all diff pairs |
8,527 | def get_spectrum ( self , nr_id = None , abmn = None , plot_filename = None ) : assert nr_id is None or abmn is None if abmn is not None : subdata = self . data . query ( 'a == {} and b == {} and m == {} and n == {}' . format ( * abmn ) ) . sort_values ( 'frequency' ) if subdata . shape [ 0 ] == 0 : return None , None ... | Return a spectrum and its reciprocal counter part if present in the dataset . Optimally refer to the spectrum by its normal - reciprocal id . |
8,528 | def plot_all_spectra ( self , outdir ) : os . makedirs ( outdir , exist_ok = True ) g = self . data . groupby ( 'id' ) for nr , ( name , item ) in enumerate ( g ) : print ( 'Plotting spectrum with id {} ({} / {})' . format ( name , nr , len ( g . groups . keys ( ) ) ) ) plot_filename = '' . join ( ( outdir + os . sep ,... | This is a convenience function to plot ALL spectra currently stored in the container . It is useful to asses whether data filters do perform correctly . |
8,529 | def plot_pseudosections ( self , column , filename = None , return_fig = False ) : assert column in self . data . columns g = self . data . groupby ( 'frequency' ) fig , axes = plt . subplots ( 4 , 2 , figsize = ( 15 / 2.54 , 20 / 2.54 ) , sharex = True , sharey = True ) for ax , ( key , item ) in zip ( axes . flat , g... | Create a multi - plot with one pseudosection for each frequency . |
8,530 | def export_to_directory_crtomo ( self , directory , norrec = 'norrec' ) : exporter_crtomo . write_files_to_directory ( self . data , directory , norrec = norrec ) | Export the sEIT data into data files that can be read by CRTomo . |
8,531 | def export_to_crtomo_seit_manager ( self , grid ) : import crtomo g = self . data . groupby ( 'frequency' ) seit_data = { } for name , item in g : print ( name , item . shape , item . size ) if item . shape [ 0 ] > 0 : seit_data [ name ] = item [ [ 'a' , 'b' , 'm' , 'n' , 'r' , 'rpha' ] ] . values seit = crtomo . eitMa... | Return a ready - initialized seit - manager object from the CRTomo tools . This function only works if the crtomo_tools are installed . |
8,532 | def get_tape ( self , start = 0 , end = 10 ) : self . tape_start = start self . tape_end = end self . tape_length = end - start tmp = '\n' + "|" + str ( start ) + "| " for i in xrange ( len ( self . tape [ start : end ] ) ) : if i == self . cur_cell : tmp += "[" + str ( self . tape [ i ] ) + "] " else : tmp += ":" + s... | Pretty prints the tape values |
8,533 | def import_sip04 ( self , filename , timestep = None ) : df = reda_sip04 . import_sip04_data ( filename ) if timestep is not None : print ( 'adding timestep' ) df [ 'timestep' ] = timestep self . _add_to_container ( df ) print ( 'Summary:' ) self . _describe_data ( df ) | SIP04 data import |
8,534 | def check_dataframe ( self , dataframe ) : if dataframe is None : return None if not isinstance ( dataframe , pd . DataFrame ) : raise Exception ( 'The provided dataframe object is not a pandas.DataFrame' ) for column in self . required_columns : if column not in dataframe : raise Exception ( 'Required column not in da... | Check the given dataframe for the required type and columns |
8,535 | def reduce_duplicate_frequencies ( self ) : group_keys = [ 'frequency' , ] if 'timestep' in self . data . columns : group_keys = group_keys + [ 'timestep' , ] g = self . data . groupby ( group_keys ) def group_apply ( item ) : y = item [ [ 'zt_1' , 'zt_2' , 'zt_3' ] ] . values . flatten ( ) zt_imag_std = np . std ( y .... | In case multiple frequencies were measured average them and compute std min max values for zt . |
8,536 | def _load_class ( class_path ) : parts = class_path . rsplit ( '.' , 1 ) module = __import__ ( parts [ 0 ] , fromlist = parts [ 1 ] ) return getattr ( module , parts [ 1 ] ) | Load the module and return the required class . |
8,537 | def rev_comp ( seq , molecule = 'dna' ) : if molecule == 'dna' : nuc_dict = { "A" : "T" , "B" : "V" , "C" : "G" , "D" : "H" , "G" : "C" , "H" : "D" , "K" : "M" , "M" : "K" , "N" : "N" , "R" : "Y" , "S" : "S" , "T" : "A" , "V" : "B" , "W" : "W" , "Y" : "R" } elif molecule == 'rna' : nuc_dict = { "A" : "U" , "B" : "V" , ... | DNA|RNA seq - > reverse complement |
8,538 | def from_json ( cls , key , scopes , subject = None ) : credentials_type = key [ 'type' ] if credentials_type != 'service_account' : raise ValueError ( 'key: expected type service_account ' '(got %s)' % credentials_type ) email = key [ 'client_email' ] key = OpenSSL . crypto . load_privatekey ( OpenSSL . crypto . FILET... | Alternate constructor intended for using JSON format of private key . |
8,539 | def from_pkcs12 ( cls , key , email , scopes , subject = None , passphrase = PKCS12_PASSPHRASE ) : key = OpenSSL . crypto . load_pkcs12 ( key , passphrase ) . get_privatekey ( ) return cls ( key = key , email = email , scopes = scopes , subject = subject ) | Alternate constructor intended for using . p12 files . |
8,540 | def issued_at ( self ) : issued_at = self . _issued_at if issued_at is None : self . _issued_at = int ( time . time ( ) ) return self . _issued_at | Time when access token was requested as seconds since epoch . |
8,541 | def access_token ( self ) : if ( self . _access_token is None or self . expiration_time <= int ( time . time ( ) ) ) : resp = self . make_access_request ( ) self . _access_token = resp . json ( ) [ 'access_token' ] return self . _access_token | Stores always valid OAuth2 access token . |
8,542 | def make_access_request ( self ) : del self . issued_at assertion = b'.' . join ( ( self . header ( ) , self . claims ( ) , self . signature ( ) ) ) post_data = { 'grant_type' : GRANT_TYPE , 'assertion' : assertion , } resp = requests . post ( AUDIENCE , post_data ) if resp . status_code != 200 : raise AuthenticationEr... | Makes an OAuth2 access token request with crafted JWT and signature . |
8,543 | def authorized_request ( self , method , url , ** kwargs ) : headers = kwargs . pop ( 'headers' , { } ) if headers . get ( 'Authorization' ) or kwargs . get ( 'auth' ) : raise ValueError ( "Found custom Authorization header, " "method call would override it." ) headers [ 'Authorization' ] = 'Bearer ' + self . access_to... | Shortcut for requests . request with proper Authorization header . |
8,544 | def import_txt ( filename , ** kwargs ) : with open ( filename , 'r' ) as fid : text = fid . read ( ) strings_to_replace = { 'Mixed / non conventional' : 'Mixed/non-conventional' , 'Date' : 'Date Time AM-PM' , } for key in strings_to_replace . keys ( ) : text = text . replace ( key , strings_to_replace [ key ] ) buffer... | Import Syscal measurements from a text file exported as Spreadsheet . |
8,545 | def import_bin ( filename , ** kwargs ) : metadata , data_raw = _import_bin ( filename ) skip_rows = kwargs . get ( 'skip_rows' , 0 ) if skip_rows > 0 : data_raw . drop ( data_raw . index [ range ( 0 , skip_rows ) ] , inplace = True ) data_raw = data_raw . reset_index ( ) if kwargs . get ( 'check_meas_nums' , True ) : ... | Read a . bin file generated by the IRIS Instruments Syscal Pro System and return a curated dataframe for further processing . This dataframe contains only information currently deemed important . Use the function reda . importers . iris_syscal_pro_binary . _import_bin to extract ALL information from a given . bin file ... |
8,546 | def call_and_notificate ( args , opts ) : stctime = time . clock ( ) stttime = time . time ( ) stdtime = datetime . datetime . now ( ) exit_code , output = call ( args ) cdelta = time . clock ( ) - stctime tdelta = time . time ( ) - stttime endtime = datetime . datetime . now ( ) if exit_code == 0 : status = u"Success"... | Execute specified arguments and send notification email |
8,547 | def get_thumbnail_format ( self ) : if self . field . thumbnail_format : return self . field . thumbnail_format . lower ( ) else : filename_split = self . name . rsplit ( '.' , 1 ) return filename_split [ - 1 ] | Determines the target thumbnail type either by looking for a format override specified at the model level or by using the format the user uploaded . |
8,548 | def save ( self , name , content , save = True ) : super ( ImageWithThumbsFieldFile , self ) . save ( name , content , save ) try : self . generate_thumbs ( name , content ) except IOError , exc : if 'cannot identify' in exc . message or 'bad EPS header' in exc . message : raise UploadedImageIsUnreadableError ( "We wer... | Handles some extra logic to generate the thumbnails when the original file is uploaded . |
8,549 | def delete ( self , save = True ) : for thumb in self . field . thumbs : thumb_name , thumb_options = thumb thumb_filename = self . _calc_thumb_filename ( thumb_name ) self . storage . delete ( thumb_filename ) super ( ImageWithThumbsFieldFile , self ) . delete ( save ) | Deletes the original plus any thumbnails . Fails silently if there are errors deleting the thumbnails . |
8,550 | def dump_edn_val ( v ) : " edn simple value dump" if isinstance ( v , ( str , unicode ) ) : return json . dumps ( v ) elif isinstance ( v , E ) : return unicode ( v ) else : return dumps ( v ) | edn simple value dump |
8,551 | def tx_schema ( self , ** kwargs ) : for s in self . schema . schema : tx = self . tx ( s , ** kwargs ) | Builds the data structure edn and puts it in the db |
8,552 | def tx ( self , * args , ** kwargs ) : if 0 == len ( args ) : return TX ( self ) ops = [ ] for op in args : if isinstance ( op , list ) : ops += op elif isinstance ( op , ( str , unicode ) ) : ops . append ( op ) if 'debug' in kwargs : pp ( ops ) tx_proc = "[ %s ]" % "" . join ( ops ) x = self . rest ( 'POST' , self . ... | Executes a raw tx string or get a new TX object to work with . |
8,553 | def e ( self , eid ) : ta = datetime . datetime . now ( ) rs = self . rest ( 'GET' , self . uri_db + '-/entity' , data = { 'e' : int ( eid ) } , parse = True ) tb = datetime . datetime . now ( ) - ta print cl ( '<<< fetched entity %s in %sms' % ( eid , tb . microseconds / 1000.0 ) , 'cyan' ) return rs | Get an Entity |
8,554 | def retract ( self , e , a , v ) : ta = datetime . datetime . now ( ) ret = u"[:db/retract %i :%s %s]" % ( e , a , dump_edn_val ( v ) ) rs = self . tx ( ret ) tb = datetime . datetime . now ( ) - ta print cl ( '<<< retracted %s,%s,%s in %sms' % ( e , a , v , tb . microseconds / 1000.0 ) , 'cyan' ) return rs | redact the value of an attribute |
8,555 | def datoms ( self , index = 'aevt' , e = '' , a = '' , v = '' , limit = 0 , offset = 0 , chunk = 100 , start = '' , end = '' , since = '' , as_of = '' , history = '' , ** kwargs ) : assert index in [ 'aevt' , 'eavt' , 'avet' , 'vaet' ] , "non-existant index" data = { 'index' : index , 'a' : ':{0}' . format ( a ) if a e... | Returns a lazy generator that will only fetch groups of datoms at the chunk size specified . |
8,556 | def debug ( self , defn , args , kwargs , fmt = None , color = 'green' ) : ta = datetime . datetime . now ( ) rs = defn ( * args , ** kwargs ) tb = datetime . datetime . now ( ) - ta fmt = fmt or "processed {defn} in {ms}ms" logmsg = fmt . format ( ms = tb . microseconds / 1000.0 , defn = defn ) "terminal output" print... | debug timing colored terminal output |
8,557 | def find ( self , * args , ** kwargs ) : " new query builder on current db" return Query ( * args , db = self , schema = self . schema ) | new query builder on current db |
8,558 | def hashone ( self ) : "execute query, get back" rs = self . one ( ) if not rs : return { } else : finds = " " . join ( self . _find ) . split ( ' ' ) return dict ( zip ( ( x . replace ( '?' , '' ) for x in finds ) , rs ) ) | execute query get back |
8,559 | def all ( self ) : " execute query, get all list of lists" query , inputs = self . _toedn ( ) return self . db . q ( query , inputs = inputs , limit = self . _limit , offset = self . _offset , history = self . _history ) | execute query get all list of lists |
8,560 | def _toedn ( self ) : finds = u"" inputs = u"" wheres = u"" args = [ ] ": in and args" for a , b in self . _input : inputs += " {0}" . format ( a ) args . append ( dump_edn_val ( b ) ) if inputs : inputs = u":in ${0}" . format ( inputs ) " :where " for where in self . _where : if isinstance ( where , ( str , unicode ) ... | prepare the query for the rest api |
8,561 | def add ( self , * args , ** kwargs ) : assert self . resp is None , "Transaction already committed" entity , av_pairs , args = None , [ ] , list ( args ) if len ( args ) : if isinstance ( args [ 0 ] , ( int , long ) ) : " first arg is an entity or tempid" entity = E ( args [ 0 ] , tx = self ) elif isinstance ( args [ ... | Accumulate datums for the transaction |
8,562 | def resolve ( self ) : assert isinstance ( self . resp , dict ) , "Transaction in uncommitted or failed state" rids = [ ( v ) for k , v in self . resp [ 'tempids' ] . items ( ) ] self . txid = self . resp [ 'tx-data' ] [ 0 ] [ 'tx' ] rids . reverse ( ) for t in self . tmpents : pos = self . tmpents . index ( t ) t . _e... | Resolve one or more tempids . Automatically takes place after transaction is executed . |
8,563 | def get_usage ( self ) : resp = requests . get ( FITNESS_URL , timeout = 30 ) resp . raise_for_status ( ) soup = BeautifulSoup ( resp . text , "html5lib" ) eastern = pytz . timezone ( 'US/Eastern' ) output = [ ] for item in soup . findAll ( "div" , { "class" : "barChart" } ) : data = [ x . strip ( ) for x in item . get... | Get fitness locations and their current usage . |
8,564 | def search ( self , keyword ) : params = { "source" : "map" , "description" : keyword } data = self . _request ( ENDPOINTS [ 'SEARCH' ] , params ) data [ 'result_data' ] = [ res for res in data [ 'result_data' ] if isinstance ( res , dict ) ] return data | Return all buildings related to the provided query . |
8,565 | def compute_K_numerical ( dataframe , settings = None , keep_dir = None ) : inversion_code = reda . rcParams . get ( 'geom_factor.inversion_code' , 'crtomo' ) if inversion_code == 'crtomo' : import reda . utils . geom_fac_crtomo as geom_fac_crtomo if keep_dir is not None : keep_dir = os . path . abspath ( keep_dir ) K ... | Use a finite - element modeling code to infer geometric factors for meshes with topography or irregular electrode spacings . |
8,566 | def _get_object_key ( self , p_object ) : matched_key = None matched_index = None if hasattr ( p_object , self . _searchNames [ 0 ] ) : return getattr ( p_object , self . _searchNames [ 0 ] ) for x in xrange ( len ( self . _searchNames ) ) : key = self . _searchNames [ x ] if hasattr ( p_object , key ) : matched_key = ... | Get key from object |
8,567 | def correct ( self , temp , we_t ) : if not PIDTempComp . in_range ( temp ) : return None n_t = self . cf_t ( temp ) if n_t is None : return None we_c = we_t * n_t return we_c | Compute weC from weT |
8,568 | def compute_norrec_differences ( df , keys_diff ) : raise Exception ( 'This function is depreciated!' ) print ( 'computing normal-reciprocal differences' ) def norrec_diff ( x ) : if x . shape [ 0 ] != 2 : return np . nan else : return np . abs ( x . iloc [ 1 ] - x . iloc [ 0 ] ) keys_keep = list ( set ( df . columns .... | DO NOT USE ANY MORE - DEPRECIATED! |
8,569 | def _normalize_abmn ( abmn ) : abmn_2d = np . atleast_2d ( abmn ) abmn_normalized = np . hstack ( ( np . sort ( abmn_2d [ : , 0 : 2 ] , axis = 1 ) , np . sort ( abmn_2d [ : , 2 : 4 ] , axis = 1 ) , ) ) return abmn_normalized | return a normalized version of abmn |
8,570 | def assign_norrec_diffs ( df , diff_list ) : extra_dims = [ x for x in ( 'timestep' , 'frequency' , 'id' ) if x in df . columns ] g = df . groupby ( extra_dims ) def subrow ( row ) : if row . size == 2 : return row . iloc [ 1 ] - row . iloc [ 0 ] else : return np . nan for diffcol in diff_list : diff = g [ diffcol ] . ... | Compute and write the difference between normal and reciprocal values for all columns specified in the diff_list parameter . |
8,571 | def handle_authenticated_user ( self , response ) : current_user = get_user ( self . request ) ulogin , registered = ULoginUser . objects . get_or_create ( uid = response [ 'uid' ] , network = response [ 'network' ] , defaults = { 'identity' : response [ 'identity' ] , 'user' : current_user } ) if not registered : ulog... | Handles the ULogin response if user is already authenticated |
8,572 | def form_valid ( self , form ) : response = self . ulogin_response ( form . cleaned_data [ 'token' ] , self . request . get_host ( ) ) if 'error' in response : return render ( self . request , self . error_template_name , { 'json' : response } ) if user_is_authenticated ( get_user ( self . request ) ) : user , identity... | The request from ulogin service is correct |
8,573 | def ulogin_response ( self , token , host ) : response = requests . get ( settings . TOKEN_URL , params = { 'token' : token , 'host' : host } ) content = response . content if sys . version_info >= ( 3 , 0 ) : content = content . decode ( 'utf8' ) return json . loads ( content ) | Makes a request to ULOGIN |
8,574 | def initialise_parsimonious_states ( tree , feature , states ) : ps_feature_down = get_personalized_feature_name ( feature , BU_PARS_STATES ) ps_feature = get_personalized_feature_name ( feature , PARS_STATES ) all_states = set ( states ) for node in tree . traverse ( ) : state = getattr ( node , feature , set ( ) ) if... | Initializes the bottom - up state arrays for tips based on their states given by the feature . |
8,575 | def uppass ( tree , feature ) : ps_feature = get_personalized_feature_name ( feature , BU_PARS_STATES ) for node in tree . traverse ( 'postorder' ) : if not node . is_leaf ( ) : children_states = get_most_common_states ( getattr ( child , ps_feature ) for child in node . children ) node_states = getattr ( node , ps_fea... | UPPASS traverses the tree starting from the tips and going up till the root and assigns to each parent node a state based on the states of its child nodes . |
8,576 | def parsimonious_acr ( tree , character , prediction_method , states , num_nodes , num_tips ) : initialise_parsimonious_states ( tree , character , states ) uppass ( tree , character ) results = [ ] result = { STATES : states , NUM_NODES : num_nodes , NUM_TIPS : num_tips } logger = logging . getLogger ( 'pastml' ) def ... | Calculates parsimonious states on the tree and stores them in the corresponding feature . |
8,577 | def balance_to_ringchart_items ( balance , account = '' , show = SHOW_CREDIT ) : show = show if show else SHOW_CREDIT rcis = [ ] for item in balance : subaccount = item [ 'account_fragment' ] if not account else ':' . join ( ( account , item [ 'account_fragment' ] ) ) ch = balance_to_ringchart_items ( item [ 'children'... | Convert a balance data structure into RingChartItem objects . |
8,578 | def log_to_file ( log_path , log_urllib = False , limit = None ) : log_path = log_path file_handler = logging . FileHandler ( log_path ) if limit : file_handler = RotatingFileHandler ( log_path , mode = 'a' , maxBytes = limit * 1024 * 1024 , backupCount = 2 , encoding = None , delay = 0 ) fmt = '[%(asctime)s %(filename... | Add file_handler to logger |
8,579 | def session_context ( fn ) : @ functools . wraps ( fn ) def wrap ( * args , ** kwargs ) : session = args [ 0 ] . Session ( ) result = fn ( * args , session = session , ** kwargs ) session . close ( ) return result return wrap | Handles session setup and teardown |
8,580 | def _syscal_write_electrode_coords ( fid , spacing , N ) : fid . write ( '# X Y Z\n' ) for i in range ( 0 , N ) : fid . write ( '{0} {1} {2} {3}\n' . format ( i + 1 , i * spacing , 0 , 0 ) ) | helper function that writes out electrode positions to a file descriptor |
8,581 | def _syscal_write_quadpoles ( fid , quadpoles ) : fid . write ( '# A B M N\n' ) for nr , quadpole in enumerate ( quadpoles ) : fid . write ( '{0} {1} {2} {3} {4}\n' . format ( nr , quadpole [ 0 ] , quadpole [ 1 ] , quadpole [ 2 ] , quadpole [ 3 ] ) ) | helper function that writes the actual measurement configurations to a file descriptor . |
8,582 | def syscal_save_to_config_txt ( filename , configs , spacing = 1 ) : print ( 'Number of measurements: ' , configs . shape [ 0 ] ) number_of_electrodes = configs . max ( ) . astype ( int ) with open ( filename , 'w' ) as fid : _syscal_write_electrode_coords ( fid , spacing , number_of_electrodes ) _syscal_write_quadpole... | Write configurations to a Syscal ascii file that can be read by the Electre Pro program . |
8,583 | def setup ( use_latex = False , overwrite = False ) : import matplotlib as mpl if overwrite : mpl . rcParams [ "lines.linewidth" ] = 2.0 mpl . rcParams [ "lines.markeredgewidth" ] = 3.0 mpl . rcParams [ "lines.markersize" ] = 3.0 mpl . rcParams [ "font.size" ] = 12 mpl . rcParams [ 'mathtext.default' ] = 'regular' if l... | Set up matplotlib imports and settings . |
8,584 | def load_seit_data ( directory , frequency_file = 'frequencies.dat' , data_prefix = 'volt_' , ** kwargs ) : frequencies = np . loadtxt ( directory + os . sep + frequency_file ) data_files = sorted ( glob ( directory + os . sep + data_prefix + '*' ) ) if frequencies . size != len ( data_files ) : raise Exception ( 'numb... | Load sEIT data from data directory . This function loads data previously exported from reda using reda . exporters . crtomo . write_files_to_directory |
8,585 | def get_diagonalisation ( frequencies , rate_matrix = None ) : Q = get_normalised_generator ( frequencies , rate_matrix ) d , A = np . linalg . eig ( Q ) return d , A , np . linalg . inv ( A ) | Normalises and diagonalises the rate matrix . |
8,586 | def get_normalised_generator ( frequencies , rate_matrix = None ) : if rate_matrix is None : n = len ( frequencies ) rate_matrix = np . ones ( shape = ( n , n ) , dtype = np . float64 ) - np . eye ( n ) generator = rate_matrix * frequencies generator -= np . diag ( generator . sum ( axis = 1 ) ) mu = - generator . diag... | Calculates the normalised generator from the rate matrix and character state frequencies . |
8,587 | def get_pij_matrix ( t , diag , A , A_inv ) : return A . dot ( np . diag ( np . exp ( diag * t ) ) ) . dot ( A_inv ) | Calculates the probability matrix of substitutions i - > j over time t given the normalised generator diagonalisation . |
8,588 | def split_arguments ( args ) : prev = False for i , value in enumerate ( args [ 1 : ] ) : if value . startswith ( '-' ) : prev = True elif prev : prev = False else : return args [ : i + 1 ] , args [ i + 1 : ] return args , [ ] | Split specified arguments to two list . |
8,589 | def parse_arguments ( args , config ) : import notify from conf import config_to_options opts = config_to_options ( config ) usage = ( "%(prog)s " "[-h] [-t TO_ADDR] [-f FROM_ADDR] [-e ENCODING] [-s SUBJECT]\n" " " "[-o HOST] [-p PORT] [--username USERNAME] [--password PASSWORD]\n" " " "[--set... | Parse specified arguments via config |
8,590 | def should_require_authentication ( self , url ) : return ( not self . routes or any ( route . match ( url ) for route in self . routes ) ) | Returns True if we should require authentication for the URL given |
8,591 | def authenticate ( self , environ ) : try : hd = parse_dict_header ( environ [ 'HTTP_AUTHORIZATION' ] ) except ( KeyError , ValueError ) : return False return self . credentials_valid ( hd [ 'response' ] , environ [ 'REQUEST_METHOD' ] , environ [ 'httpauth.uri' ] , hd [ 'nonce' ] , hd [ 'Digest username' ] , ) | Returns True if the credentials passed in the Authorization header are valid False otherwise . |
8,592 | def next ( self ) : try : return self . dict_to_xn ( self . csvreader . next ( ) ) except MetadataException : return next ( self ) | Return the next transaction object . |
8,593 | def parse_date ( self , date ) : if self . date_format is not None : return datetime . datetime . strptime ( date , self . date_format ) . date ( ) if re . match ( '\d{8}$' , date ) : return datetime . date ( * map ( int , ( date [ : 4 ] , date [ 4 : 6 ] , date [ 6 : ] ) ) ) try : parts = date_delim . split ( date , 2 ... | Parse the date and return a datetime object |
8,594 | def create ( self , uri , buffer = "queue" , interval = 10 ) : return self . _http_client . put_json ( "subscriptions/{}" . format ( self . short_name ) , { "subscription" : { "uri" : uri , "buffer" : buffer , "interval" : interval , } } ) | Create a subscription with this short name and the provided parameters |
8,595 | def read_pal_version ( ) : verfile = os . path . join ( "cextern" , "pal" , "configure.ac" ) verstring = "-1.-1.-1" for line in open ( verfile ) : if line . startswith ( "AC_INIT" ) : match = re . search ( r"\[(\d+\.\d+\.\d+)\]" , line ) if match : verstring = match . group ( 1 ) break ( major , minor , patch ) = verst... | Scans the PAL configure . ac looking for the version number . |
8,596 | def _reset_model ( self , response ) : self . _provision_done = False self . _changes . clear ( ) fields = self . process_raw_data ( response ) self . _set_fields ( fields ) self . _provision_done = True | Update the fields value with the received information . |
8,597 | def is_ready ( self ) : if not self . provisioning_state : raise exception . ServiceException ( "The object doesn't contain " "`provisioningState`." ) elif self . provisioning_state == constant . FAILED : raise exception . ServiceException ( "Failed to complete the required operation." ) elif self . provisioning_state ... | Check if the current model is ready to be used . |
8,598 | def _get_all ( cls , parent_id = None , grandparent_id = None ) : client = cls . _get_client ( ) endpoint = cls . _endpoint . format ( resource_id = "" , parent_id = parent_id or "" , grandparent_id = grandparent_id or "" ) resources = [ ] while True : response = client . get_resource ( endpoint ) for raw_data in respo... | Retrives all the required resources . |
8,599 | def get ( cls , resource_id = None , parent_id = None , grandparent_id = None ) : if not resource_id : return cls . _get_all ( parent_id , grandparent_id ) else : return cls . _get ( resource_id , parent_id , grandparent_id ) | Retrieves the required resources . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.