idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
24,600 | def update_workflow_workitems ( cr , pool , ref_spec_actions ) : workflow_workitems = pool [ 'workflow.workitem' ] ir_model_data_model = pool [ 'ir.model.data' ] for ( target_external_id , fallback_external_id ) in ref_spec_actions : target_activity = ir_model_data_model . get_object ( cr , SUPERUSER_ID , target_extern... | Find all the workflow items from the target state to set them to the wanted state . |
24,601 | def logged_query ( cr , query , args = None , skip_no_result = False ) : if args is None : args = ( ) args = tuple ( args ) if type ( args ) == list else args try : cr . execute ( query , args ) except ( ProgrammingError , IntegrityError ) : logger . error ( 'Error running %s' % cr . mogrify ( query , args ) ) raise if... | Logs query and affected rows at level DEBUG . |
24,602 | def update_module_names ( cr , namespec , merge_modules = False ) : for ( old_name , new_name ) in namespec : if merge_modules : query = "SELECT id FROM ir_module_module WHERE name = %s" cr . execute ( query , [ old_name ] ) row = cr . fetchone ( ) if row : old_id = row [ 0 ] query = "DELETE FROM ir_model_constraint WH... | Deal with changed module names making all the needed changes on the related tables like XML - IDs translations and so on . |
24,603 | def add_ir_model_fields ( cr , columnspec ) : for column in columnspec : query = 'ALTER TABLE ir_model_fields ADD COLUMN %s %s' % ( column ) logged_query ( cr , query , [ ] ) | Typically new columns on ir_model_fields need to be added in a very early stage in the upgrade process of the base module in raw sql as they need to be in place before any model gets initialized . Do not use for fields with additional SQL constraints such as a reference to another table or the cascade constraint but cr... |
24,604 | def m2o_to_m2m ( cr , model , table , field , source_field ) : return m2o_to_x2m ( cr , model , table , field , source_field ) | Recreate relations in many2many fields that were formerly many2one fields . Use rename_columns in your pre - migrate script to retain the column s old value then call m2o_to_m2m in your post - migrate script . |
24,605 | def message ( cr , module , table , column , message , * args , ** kwargs ) : argslist = list ( args or [ ] ) prefix = ': ' if column : argslist . insert ( 0 , column ) prefix = ', column %s' + prefix if table : argslist . insert ( 0 , table ) prefix = ', table %s' + prefix argslist . insert ( 0 , module ) prefix = 'Mo... | Log handler for non - critical notifications about the upgrade . To be extended with logging to a table for reporting purposes . |
24,606 | def reactivate_workflow_transitions ( cr , transition_conditions ) : for transition_id , condition in transition_conditions . iteritems ( ) : cr . execute ( 'update wkf_transition set condition = %s where id = %s' , ( condition , transition_id ) ) | Reactivate workflow transition previously deactivated by deactivate_workflow_transitions . |
24,607 | def convert_field_to_html ( cr , table , field_name , html_field_name ) : if version_info [ 0 ] < 7 : logger . error ( "You cannot use this method in an OpenUpgrade version " "prior to 7.0." ) return cr . execute ( "SELECT id, %(field)s FROM %(table)s WHERE %(field)s IS NOT NULL" % { 'field' : field_name , 'table' : ta... | Convert field value to HTML value . |
24,608 | def lift_constraints ( cr , table , column ) : cr . execute ( 'select relname, array_agg(conname) from ' '(select t1.relname, c.conname ' 'from pg_constraint c ' 'join pg_attribute a ' 'on c.confrelid=a.attrelid and a.attnum=any(c.conkey) ' 'join pg_class t on t.oid=a.attrelid ' 'join pg_class t1 on t1.oid=c.conrelid '... | Lift all constraints on column in table . Typically you use this in a pre - migrate script where you adapt references for many2one fields with changed target objects . If everything went right the constraints will be recreated |
24,609 | def savepoint ( cr ) : if hasattr ( cr , 'savepoint' ) : with cr . savepoint ( ) : yield else : name = uuid . uuid1 ( ) . hex cr . execute ( 'SAVEPOINT "%s"' % name ) try : yield cr . execute ( 'RELEASE SAVEPOINT "%s"' % name ) except : cr . execute ( 'ROLLBACK TO SAVEPOINT "%s"' % name ) | return a context manager wrapping postgres savepoints |
24,610 | def rename_property ( cr , model , old_name , new_name ) : cr . execute ( "update ir_model_fields f set name=%s " "from ir_model m " "where m.id=f.model_id and m.model=%s and f.name=%s " "returning f.id" , ( new_name , model , old_name ) ) field_ids = tuple ( i for i , in cr . fetchall ( ) ) cr . execute ( "update ir_m... | Rename property old_name owned by model to new_name . This should happen in a pre - migration script . |
24,611 | def delete_records_safely_by_xml_id ( env , xml_ids ) : for xml_id in xml_ids : logger . debug ( 'Deleting record for XML-ID %s' , xml_id ) try : with env . cr . savepoint ( ) : env . ref ( xml_id ) . exists ( ) . unlink ( ) except Exception as e : logger . error ( 'Error deleting XML-ID %s: %s' , xml_id , repr ( e ) ) | This removes in the safest possible way the records whose XML - IDs are passed as argument . |
24,612 | def chunked ( records , single = True ) : if version_info [ 0 ] > 10 : invalidate = records . env . cache . invalidate elif version_info [ 0 ] > 7 : invalidate = records . env . invalidate_all else : raise Exception ( 'Not supported Odoo version for this method.' ) size = core . models . PREFETCH_MAX model = records . ... | Memory and performance friendly method to iterate over a potentially large number of records . Yields either a whole chunk or a single record at the time . Don t nest calls to this method . |
24,613 | def get_last_post_for_model ( cr , uid , ids , model_pool ) : if type ( ids ) is not list : ids = [ ids ] res = { } for obj in model_pool . browse ( cr , uid , ids ) : message_ids = obj . message_ids if message_ids : res [ obj . id ] = sorted ( message_ids , key = lambda x : x . date , reverse = True ) [ 0 ] . date els... | Given a set of ids and a model pool return a dict of each object ids with their latest message date as a value . To be called in post - migration scripts |
24,614 | def set_message_last_post ( cr , uid , pool , models ) : if type ( models ) is not list : models = [ models ] for model in models : model_pool = pool [ model ] cr . execute ( "UPDATE {table} " "SET message_last_post=(SELECT max(mm.date) " "FROM mail_message mm " "WHERE mm.model=%s " "AND mm.date IS NOT NULL " "AND mm.r... | Given a list of models set their message_last_post fields to an estimated last post datetime . To be called in post - migration scripts |
24,615 | def column_exists ( cr , table , column ) : cr . execute ( 'SELECT count(attname) FROM pg_attribute ' 'WHERE attrelid = ' '( SELECT oid FROM pg_class WHERE relname = %s ) ' 'AND attname = %s' , ( table , column ) ) return cr . fetchone ( ) [ 0 ] == 1 | Check whether a certain column exists |
24,616 | def start_logging ( out = _stdout , level = 'info' ) : global _log_level , _loggers , _started_logging if level not in log_levels : raise RuntimeError ( "Invalid log level '{0}'; valid are: {1}" . format ( level , ', ' . join ( log_levels ) ) ) if _started_logging : return _started_logging = True _log_level = level han... | Begin logging . |
24,617 | def create_failure ( self , exception = None ) : if exception : return FailedFuture ( type ( exception ) , exception , None ) return FailedFuture ( * sys . exc_info ( ) ) | This returns an object implementing IFailedFuture . |
24,618 | def gather ( self , futures , consume_exceptions = True ) : return asyncio . gather ( * futures , return_exceptions = consume_exceptions ) | This returns a Future that waits for all the Futures in the list futures |
24,619 | def _use_framework ( module ) : import txaio for method_name in __all__ : if method_name in [ 'use_twisted' , 'use_asyncio' ] : continue setattr ( txaio , method_name , getattr ( module , method_name ) ) | Internal helper to set this modules methods to a specified framework helper - methods . |
24,620 | def start_logging ( out = _stdout , level = 'info' ) : global _loggers , _observer , _log_level , _started_logging if level not in log_levels : raise RuntimeError ( "Invalid log level '{0}'; valid are: {1}" . format ( level , ', ' . join ( log_levels ) ) ) if _started_logging : return _started_logging = True _log_level... | Start logging to the file - like object in out . By default this is stdout . |
24,621 | def set_log_level ( self , level , keep = True ) : self . _set_log_level ( level ) self . _log_level_set_explicitly = keep | Set the log level . If keep is True then it will not change along with global log changes . |
24,622 | def sleep ( self , delay ) : d = Deferred ( ) self . _get_loop ( ) . callLater ( delay , d . callback , None ) return d | Inline sleep for use in co - routines . |
24,623 | def _notify_bucket ( self , real_time ) : ( delayed_call , calls ) = self . _buckets [ real_time ] del self . _buckets [ real_time ] errors = [ ] def notify_one_chunk ( calls , chunk_size , chunk_delay_ms ) : for call in calls [ : chunk_size ] : try : call ( ) except Exception as e : errors . append ( e ) calls = calls... | Internal helper . This does the callbacks in a particular bucket . |
24,624 | def check_ab ( ab , verb ) : r try : ab = int ( ab ) except VariableCatch : print ( '* ERROR :: <ab> must be an integer' ) raise pab = [ 11 , 12 , 13 , 14 , 15 , 16 , 21 , 22 , 23 , 24 , 25 , 26 , 31 , 32 , 33 , 34 , 35 , 36 , 41 , 42 , 43 , 44 , 45 , 46 , 51 , 52 , 53 , 54 , 55 , 56 , 61 , 62 , 63 , 64 , 65 , 66 ] i... | r Check source - receiver configuration . |
24,625 | def check_dipole ( inp , name , verb ) : r _check_shape ( np . squeeze ( inp ) , name , ( 3 , ) ) inp [ 0 ] = _check_var ( inp [ 0 ] , float , 1 , name + '-x' ) inp [ 1 ] = _check_var ( inp [ 1 ] , float , 1 , name + '-y' , inp [ 0 ] . shape ) inp [ 2 ] = _check_var ( inp [ 2 ] , float , 1 , name + '-z' , ( 1 , ) ) if ... | r Check dipole parameters . |
24,626 | def check_frequency ( freq , res , aniso , epermH , epermV , mpermH , mpermV , verb ) : r global _min_freq if isinstance ( res , dict ) : res = res [ 'res' ] freq = _check_var ( freq , float , 1 , 'freq' ) freq = _check_min ( freq , _min_freq , 'Frequencies' , 'Hz' , verb ) if verb > 2 : _prnt_min_max_val ( freq , " ... | r Calculate frequency - dependent parameters . |
24,627 | def check_opt ( opt , loop , ht , htarg , verb ) : r use_ne_eval = False if opt == 'parallel' : if numexpr : use_ne_eval = numexpr . evaluate elif verb > 0 : print ( numexpr_msg ) lagged_splined_fht = False if ht == 'fht' : if htarg [ 1 ] != 0 : lagged_splined_fht = True if ht in [ 'hqwe' , 'hquad' ] or lagged_splined_... | r Check optimization parameters . |
24,628 | def check_time_only ( time , signal , verb ) : r global _min_time if int ( signal ) not in [ - 1 , 0 , 1 ] : print ( "* ERROR :: <signal> must be one of: [None, -1, 0, 1]; " + "<signal> provided: " + str ( signal ) ) raise ValueError ( 'signal' ) time = _check_var ( time , float , 1 , 'time' ) time = _check_min ( tim... | r Check time and signal parameters . |
24,629 | def check_solution ( solution , signal , ab , msrc , mrec ) : r if solution not in [ 'fs' , 'dfs' , 'dhs' , 'dsplit' , 'dtetm' ] : print ( "* ERROR :: Solution must be one of ['fs', 'dfs', 'dhs', " + "'dsplit', 'dtetm']; <solution> provided: " + solution ) raise ValueError ( 'solution' ) if solution [ 0 ] == 'd' and ... | r Check required solution with parameters . |
24,630 | def get_abs ( msrc , mrec , srcazm , srcdip , recazm , recdip , verb ) : r ab_calc = np . array ( [ [ 11 , 12 , 13 ] , [ 21 , 22 , 23 ] , [ 31 , 32 , 33 ] ] ) if msrc : ab_calc += 3 if mrec : ab_calc += 30 if msrc : ab_calc -= 33 else : ab_calc = ab_calc % 10 * 10 + ab_calc // 10 bab = np . asarray ( ab_calc * 0 + 1 , ... | r Get required ab s for given angles . |
24,631 | def get_geo_fact ( ab , srcazm , srcdip , recazm , recdip , msrc , mrec ) : r global _min_angle fis = ab % 10 fir = ab // 10 if mrec and not msrc : fis , fir = fir , fis def gfact ( bp , azm , dip ) : r if bp in [ 1 , 4 ] : return np . cos ( azm ) * np . cos ( dip ) elif bp in [ 2 , 5 ] : return np . sin ( azm ) * np .... | r Get required geometrical scaling factor for given angles . |
24,632 | def get_layer_nr ( inp , depth ) : r zinp = inp [ 2 ] pdepth = np . concatenate ( ( depth [ 1 : ] , np . array ( [ np . infty ] ) ) ) b_zinp = np . atleast_1d ( zinp ) [ : , None ] linp = np . where ( ( depth [ None , : ] < b_zinp ) * ( pdepth [ None , : ] >= b_zinp ) ) [ 1 ] return np . squeeze ( linp ) , zinp | r Get number of layer in which inp resides . |
24,633 | def get_off_ang ( src , rec , nsrc , nrec , verb ) : r global _min_off off = np . empty ( ( nrec * nsrc , ) ) angle = np . empty ( ( nrec * nsrc , ) ) for i in range ( nsrc ) : xco = rec [ 0 ] - src [ 0 ] [ i ] yco = rec [ 1 ] - src [ 1 ] [ i ] off [ i * nrec : ( i + 1 ) * nrec ] = np . sqrt ( xco * xco + yco * yco ) a... | r Get depths offsets angles hence spatial input parameters . |
24,634 | def printstartfinish ( verb , inp = None , kcount = None ) : r if inp : if verb > 1 : ttxt = str ( timedelta ( seconds = default_timer ( ) - inp ) ) ktxt = ' ' if kcount : ktxt += str ( kcount ) + ' kernel call(s)' print ( '\n:: empymod END; runtime = ' + ttxt + ' ::' + ktxt + '\n' ) else : t0 = default_timer ( ) if ve... | r Print start and finish with time measure and kernel count . |
24,635 | def set_minimum ( min_freq = None , min_time = None , min_off = None , min_res = None , min_angle = None ) : r global _min_freq , _min_time , _min_off , _min_res , _min_angle if min_freq is not None : _min_freq = min_freq if min_time is not None : _min_time = min_time if min_off is not None : _min_off = min_off if min_... | r Set minimum values of parameters . |
24,636 | def get_minimum ( ) : r d = dict ( min_freq = _min_freq , min_time = _min_time , min_off = _min_off , min_res = _min_res , min_angle = _min_angle ) return d | r Return the current minimum values . |
24,637 | def _check_var ( var , dtype , ndmin , name , shape = None , shape2 = None ) : r if var is None : raise ValueError var = np . array ( var , dtype = dtype , copy = True , ndmin = ndmin ) if shape : _check_shape ( var , name , shape , shape2 ) return var | r Return variable as array of dtype ndmin ; shape - checked . |
24,638 | def _strvar ( a , prec = '{:G}' ) : r return ' ' . join ( [ prec . format ( i ) for i in np . atleast_1d ( a ) ] ) | r Return variable as a string to print with given precision . |
24,639 | def _check_min ( par , minval , name , unit , verb ) : r scalar = False if par . shape == ( ) : scalar = True par = np . atleast_1d ( par ) if minval is not None : ipar = np . where ( par < minval ) par [ ipar ] = minval if verb > 0 and np . size ( ipar ) != 0 : print ( '* WARNING :: ' + name + ' < ' + str ( minval ) +... | r Check minimum value of parameter . |
24,640 | def spline_backwards_hankel ( ht , htarg , opt ) : r ht = ht . lower ( ) if ht in [ 'fht' , 'qwe' , 'hqwe' ] : if ht == 'fht' : htarg = _check_targ ( htarg , [ 'fhtfilt' , 'pts_per_dec' ] ) elif ht in [ 'qwe' , 'hqwe' ] : htarg = _check_targ ( htarg , [ 'rtol' , 'atol' , 'nquad' , 'maxint' , 'pts_per_dec' , 'diff_quad'... | r Check opt if deprecated spline is used . |
24,641 | def gpr ( src , rec , depth , res , freqtime , cf , gain = None , ab = 11 , aniso = None , epermH = None , epermV = None , mpermH = None , mpermV = None , xdirect = False , ht = 'quad' , htarg = None , ft = 'fft' , ftarg = None , opt = None , loop = None , verb = 2 ) : r if verb > 2 : print ( " GPR : EXP... | r Return the Ground - Penetrating Radar signal . |
24,642 | def dipole_k ( src , rec , depth , res , freq , wavenumber , ab = 11 , aniso = None , epermH = None , epermV = None , mpermH = None , mpermV = None , verb = 2 ) : r t0 = printstartfinish ( verb ) modl = check_model ( depth , res , aniso , epermH , epermV , mpermH , mpermV , False , verb ) depth , res , aniso , epermH ,... | r Return the electromagnetic wavenumber - domain field . |
24,643 | def wavenumber ( src , rec , depth , res , freq , wavenumber , ab = 11 , aniso = None , epermH = None , epermV = None , mpermH = None , mpermV = None , verb = 2 ) : r mesg = ( "\n The use of `model.wavenumber` is deprecated and will " + "be removed;\n use `model.dipole_k` instead." ) warnings . warn ( mesg , Depr... | r Depreciated . Use dipole_k instead . |
24,644 | def tem ( fEM , off , freq , time , signal , ft , ftarg , conv = True ) : r if signal in [ - 1 , 1 ] : fact = signal / ( 2j * np . pi * freq ) else : fact = 1 tEM = np . zeros ( ( time . size , off . size ) ) for i in range ( off . size ) : out = getattr ( transform , ft ) ( fEM [ : , i ] * fact , time , freq , ftarg )... | r Return the time - domain response of the frequency - domain response fEM . |
24,645 | def save_filter ( name , filt , full = None , path = 'filters' ) : r filt . tofile ( path ) if full : path = os . path . abspath ( path ) if len ( name . split ( '.' ) ) == 2 : suffix = '.gz' else : suffix = '' fullfile = os . path . join ( path , name . split ( '.' ) [ 0 ] + '_full.txt' + suffix ) nspace , nshift = fu... | r Save DLF - filter and inversion output to plain text files . |
24,646 | def load_filter ( name , full = False , path = 'filters' ) : r filt = DigitalFilter ( name . split ( '.' ) [ 0 ] ) filt . fromfile ( path ) if full : try : path = os . path . abspath ( path ) if len ( name . split ( '.' ) ) == 2 : suffix = '.gz' else : suffix = '' fullfile = os . path . join ( path , name . split ( '.'... | r Load saved DLF - filter and inversion output from text files . |
24,647 | def plot_result ( filt , full , prntres = True ) : r if not plt : print ( plt_msg ) return if prntres : print_result ( filt , full ) spacing = full [ 2 ] [ 0 , : , 0 ] shift = full [ 2 ] [ 1 , 0 , : ] minfield = np . squeeze ( full [ 3 ] ) plt . figure ( "Brute force result" , figsize = ( 9.5 , 4.5 ) ) plt . subplots_a... | r QC the inversion result . |
24,648 | def print_result ( filt , full = None ) : r print ( ' Filter length : %d' % filt . base . size ) print ( ' Best filter' ) if full : if full [ 4 ] == 0 : print ( ' > Min field : %g' % full [ 1 ] ) else : r = 1 / full [ 1 ] print ( ' > Max r : %g' % r ) spacing = full [ 0 ] [ 0 ] shift = full [ 0 ] ... | r Print best filter information . |
24,649 | def _call_qc_transform_pairs ( n , ispacing , ishift , fI , fC , r , r_def , reim ) : r print ( '* QC: Input transform-pairs:' ) print ( ' fC: x-range defined through ``n``, ``spacing``, ``shift``, and ' + '``r``-parameters; b-range defined through ``r``-parameter.' ) print ( ' fI: x- and b-range defined through ``n`... | r QC the input transform pairs . |
24,650 | def _plot_transform_pairs ( fCI , r , k , axes , tit ) : r plt . sca ( axes [ 0 ] ) plt . title ( '|' + tit + ' lhs|' ) for f in fCI : if f . name == 'j2' : lhs = f . lhs ( k ) plt . loglog ( k , np . abs ( lhs [ 0 ] ) , lw = 2 , label = 'j0' ) plt . loglog ( k , np . abs ( lhs [ 1 ] ) , lw = 2 , label = 'j1' ) else : ... | r Plot the input transform pairs . |
24,651 | def _plot_inversion ( f , rhs , r , k , imin , spacing , shift , cvar ) : r if not plt : print ( plt_msg ) return plt . figure ( "Inversion result " + f . name , figsize = ( 9.5 , 4 ) ) plt . subplots_adjust ( wspace = .3 , bottom = 0.2 ) plt . clf ( ) tk = np . logspace ( np . log10 ( k . min ( ) ) , np . log10 ( k . ... | r QC the resulting filter . |
24,652 | def empy_hankel ( ftype , zsrc , zrec , res , freqtime , depth = None , aniso = None , epermH = None , epermV = None , mpermH = None , mpermV = None , htarg = None , verblhs = 0 , verbrhs = 0 ) : r if isinstance ( ftype , list ) : out = [ ] for f in ftype : out . append ( empy_hankel ( f , zsrc , zrec , res , freqtime ... | r Numerical transform pair with empymod . |
24,653 | def _get_min_val ( spaceshift , * params ) : r spacing , shift = spaceshift n , fI , fC , r , r_def , error , reim , cvar , verb , plot , log = params dlf = _calculate_filter ( n , spacing , shift , fI , r_def , reim , 'filt' ) k = dlf . base / r [ : , None ] for i , f in enumerate ( fC ) : lhs = f . lhs ( k ) if f . n... | r Calculate minimum resolved amplitude or maximum r . |
24,654 | def _calculate_filter ( n , spacing , shift , fI , r_def , reim , name ) : r base = np . exp ( spacing * ( np . arange ( n ) - n // 2 ) + shift ) r = np . logspace ( np . log10 ( 1 / np . max ( base ) ) - r_def [ 0 ] , np . log10 ( 1 / np . min ( base ) ) + r_def [ 1 ] , r_def [ 2 ] * n ) k = base / r [ : , None ] dlf ... | r Calculate filter for this spacing shift n . |
24,655 | def _print_count ( log ) : r log [ 'cnt2' ] += 1 cp = log [ 'cnt2' ] / log [ 'totnr' ] * 100 if log [ 'cnt2' ] == 0 : pass elif log [ 'cnt2' ] > log [ 'totnr' ] : print ( " fmin fct calls : %d" % ( log [ 'cnt2' ] - log [ 'totnr' ] ) , end = '\r' ) elif int ( cp ) > log [ 'cnt1' ] or cp < 1 or log [ 'cnt2' ] == log [... | r Print run - count information . |
24,656 | def wavenumber ( zsrc , zrec , lsrc , lrec , depth , etaH , etaV , zetaH , zetaV , lambd , ab , xdirect , msrc , mrec , use_ne_eval ) : r PTM , PTE = greenfct ( zsrc , zrec , lsrc , lrec , depth , etaH , etaV , zetaH , zetaV , lambd , ab , xdirect , msrc , mrec , use_ne_eval ) PJ0 = None PJ1 = None PJ0b = None Ptot = (... | r Calculate wavenumber domain solution . |
24,657 | def reflections ( depth , e_zH , Gam , lrec , lsrc , use_ne_eval ) : r for plus in [ True , False ] : if plus : pm = 1 layer_count = np . arange ( depth . size - 2 , min ( lrec , lsrc ) - 1 , - 1 ) izout = abs ( lsrc - lrec ) minmax = max ( lrec , lsrc ) else : pm = - 1 layer_count = np . arange ( 1 , max ( lrec , lsrc... | r Calculate Rp Rm . |
24,658 | def angle_factor ( angle , ab , msrc , mrec ) : r if ab in [ 33 , ] : return np . ones ( angle . size ) eval_angle = angle . copy ( ) if mrec and not msrc : eval_angle += np . pi if ab in [ 11 , 22 , 15 , 24 , 13 , 31 , 26 , 35 ] : fct = np . cos test_ang_1 = np . pi / 2 test_ang_2 = 3 * np . pi / 2 else : fct = np . s... | r Return the angle - dependent factor . |
24,659 | def versions ( mode = None , add_pckg = None , ncol = 4 ) : r mesg = ( "\n Func `versions` is deprecated and will " + "be removed; use Class `Versions` instead." ) warnings . warn ( mesg , DeprecationWarning ) return Versions ( add_pckg , ncol ) | r Old func - way of class Versions here for backwards compatibility . |
24,660 | def _repr_html_ ( self ) : ncol = int ( self . ncol ) border = "border: 2px solid #fff;'" def colspan ( html , txt , ncol , nrow ) : r html += " <tr>\n" html += " <td style='text-align: center; " if nrow == 0 : html += "font-weight: bold; font-size: 1.2em; " elif nrow % 2 == 0 : html += "background-color: #ddd;" h... | HTML - rendered versions information . |
24,661 | def _get_packages ( add_pckg ) : r pckgs = [ numpy , scipy , empymod ] for module in [ IPython , numexpr , matplotlib ] : if module : pckgs += [ module ] if add_pckg is not None : if isinstance ( add_pckg , tuple ) : add_pckg = list ( add_pckg ) if not isinstance ( add_pckg , list ) : add_pckg = [ add_pckg , ] pckgs +=... | r Create list of packages . |
24,662 | def tofile ( self , path = 'filters' ) : r name = self . savename path = os . path . abspath ( path ) os . makedirs ( path , exist_ok = True ) basefile = os . path . join ( path , name + '_base.txt' ) with open ( basefile , 'w' ) as f : self . base . tofile ( f , sep = "\n" ) for val in [ 'j0' , 'j1' , 'sin' , 'cos' ] ... | r Save filter values to ascii - files . |
24,663 | def fromfile ( self , path = 'filters' ) : r name = self . savename path = os . path . abspath ( path ) basefile = os . path . join ( path , name + '_base.txt' ) with open ( basefile , 'r' ) as f : self . base = np . fromfile ( f , sep = "\n" ) for val in [ 'j0' , 'j1' , 'sin' , 'cos' ] : attrfile = os . path . join ( ... | r Load filter values from ascii - files . |
24,664 | def fht ( zsrc , zrec , lsrc , lrec , off , factAng , depth , ab , etaH , etaV , zetaH , zetaV , xdirect , fhtarg , use_ne_eval , msrc , mrec ) : r fhtfilt = fhtarg [ 0 ] pts_per_dec = fhtarg [ 1 ] lambd = fhtarg [ 2 ] int_pts = fhtarg [ 3 ] PJ = kernel . wavenumber ( zsrc , zrec , lsrc , lrec , depth , etaH , etaV , z... | r Hankel Transform using the Digital Linear Filter method . |
24,665 | def hquad ( zsrc , zrec , lsrc , lrec , off , factAng , depth , ab , etaH , etaV , zetaH , zetaV , xdirect , quadargs , use_ne_eval , msrc , mrec ) : r rtol , atol , limit , a , b , pts_per_dec = quadargs la = np . log10 ( a ) lb = np . log10 ( b ) ilambd = np . logspace ( la , lb , ( lb - la ) * pts_per_dec + 1 ) PJ0 ... | r Hankel Transform using the QUADPACK library . |
24,666 | def ffht ( fEM , time , freq , ftarg ) : r ffhtfilt = ftarg [ 0 ] pts_per_dec = ftarg [ 1 ] kind = ftarg [ 2 ] if pts_per_dec == 0 : fEM = fEM . reshape ( time . size , - 1 ) tEM = dlf ( fEM , 2 * np . pi * freq , time , ffhtfilt , pts_per_dec , kind = kind ) return tEM , True | r Fourier Transform using the Digital Linear Filter method . |
24,667 | def fft ( fEM , time , freq , ftarg ) : r dfreq , nfreq , ntot , pts_per_dec = ftarg if pts_per_dec : sfEMr = iuSpline ( np . log ( freq ) , fEM . real ) sfEMi = iuSpline ( np . log ( freq ) , fEM . imag ) freq = np . arange ( 1 , nfreq + 1 ) * dfreq fEM = sfEMr ( np . log ( freq ) ) + 1j * sfEMi ( np . log ( freq ) ) ... | r Fourier Transform using the Fast Fourier Transform . |
24,668 | def quad ( sPJ0r , sPJ0i , sPJ1r , sPJ1i , sPJ0br , sPJ0bi , ab , off , factAng , iinp ) : r def quad_PJ0 ( klambd , sPJ0 , koff ) : r return sPJ0 ( np . log ( klambd ) ) * special . j0 ( koff * klambd ) def quad_PJ1 ( klambd , sPJ1 , ab , koff , kang ) : r tP1 = kang * sPJ1 ( np . log ( klambd ) ) if ab in [ 11 , 12 ,... | r Quadrature for Hankel transform . |
24,669 | def get_spline_values ( filt , inp , nr_per_dec = None ) : r if nr_per_dec == 0 : return filt . base / inp [ : , None ] , inp outmax = filt . base [ - 1 ] / inp . min ( ) outmin = filt . base [ 0 ] / inp . max ( ) if nr_per_dec < 0 : pts_per_dec = 1 / np . log ( filt . factor ) nout = int ( np . ceil ( np . log ( outma... | r Return required calculation points . |
24,670 | def fhti ( rmin , rmax , n , q , mu ) : r logrc = ( rmin + rmax ) / 2 nc = ( n + 1 ) / 2. dlogr = ( rmax - rmin ) / n dlnr = dlogr * np . log ( 10. ) y = 1j * np . pi / ( 2.0 * dlnr ) zp = special . loggamma ( ( mu + 1.0 + q ) / 2.0 + y ) zm = special . loggamma ( ( mu + 1.0 - q ) / 2.0 + y ) arg = np . log ( 2.0 ) / d... | r Return parameters required for FFTLog . |
24,671 | def _actual_get_cpu_info_from_cpuid ( queue ) : sys . stdout = open ( os . devnull , 'w' ) sys . stderr = open ( os . devnull , 'w' ) arch , bits = _parse_arch ( DataSource . arch_string_raw ) if not arch in [ 'X86_32' , 'X86_64' ] : queue . put ( _obj_to_b64 ( { } ) ) return cpuid = CPUID ( ) if cpuid . is_selinux_enf... | Warning! This function has the potential to crash the Python runtime . Do not call it directly . Use the _get_cpu_info_from_cpuid function instead . It will safely call this function in another process . |
24,672 | def get_cpu_info_json ( ) : import json output = None if getattr ( sys , 'frozen' , False ) : info = _get_cpu_info_internal ( ) output = json . dumps ( info ) output = "{0}" . format ( output ) else : from subprocess import Popen , PIPE command = [ sys . executable , __file__ , '--json' ] p1 = Popen ( command , stdout ... | Returns the CPU info by using the best sources of information for your OS . Returns the result in a json string |
24,673 | def get_cpu_info ( ) : import json output = get_cpu_info_json ( ) output = json . loads ( output , object_hook = _utf_to_str ) return output | Returns the CPU info by using the best sources of information for your OS . Returns the result in a dict |
24,674 | def _verbs_with_subjects ( doc ) : verb_subj = [ ] for possible_subject in doc : if ( possible_subject . dep_ == 'nsubj' and possible_subject . head . pos_ == 'VERB' ) : verb_subj . append ( [ possible_subject . head , possible_subject ] ) return verb_subj | Given a spacy document return the verbs that have subjects |
24,675 | def mangle_agreement ( correct_sentence ) : bad_sents = [ ] doc = nlp ( correct_sentence ) verbs = [ ( i , v ) for ( i , v ) in enumerate ( doc ) if v . tag_ . startswith ( 'VB' ) ] for i , v in verbs : for alt_verb in lexeme ( doc [ i ] . text ) : if alt_verb == doc [ i ] . text : continue if ( tenses ( alt_verb ) == ... | Given a correct sentence return a sentence or sentences with a subject verb agreement error |
24,676 | def _build_trigram_indices ( trigram_index ) : result = { } trigram_count = 0 for key , val in csv . reader ( open ( trigram_index ) ) : result [ key ] = int ( val ) trigram_count += 1 return result , trigram_count | Build a dictionary of trigrams and their indices from a csv |
24,677 | def _begins_with_one_of ( sentence , parts_of_speech ) : doc = nlp ( sentence ) if doc [ 0 ] . tag_ in parts_of_speech : return True return False | Return True if the sentence or fragment begins with one of the parts of speech in the list else False |
24,678 | def get_language_tool_feedback ( sentence ) : payload = { 'language' : 'en-US' , 'text' : sentence } try : r = requests . post ( LT_SERVER , data = payload ) except requests . exceptions . ConnectionError as e : raise requests . exceptions . ConnectionError ( ) if r . status_code >= 200 and r . status_code < 300 : retu... | Get matches from languagetool |
24,679 | def is_participle_clause_fragment ( sentence ) : if not _begins_with_one_of ( sentence , [ 'VBG' , 'VBN' , 'JJ' ] ) : return 0.0 if _begins_with_one_of ( sentence , [ 'JJ' ] ) : doc = nlp ( sentence ) fw = [ w for w in doc ] [ 0 ] if fw . dep_ == 'amod' : return 0.0 if _begins_with_one_of ( sentence , [ 'VBG' ] ) : doc... | Supply a sentence or fragment and recieve a confidence interval |
24,680 | def check ( sentence ) : result = Feedback ( ) is_missing_verb = detect_missing_verb ( sentence ) is_infinitive = detect_infinitive_phrase ( sentence ) is_participle = is_participle_clause_fragment ( sentence ) lang_tool_feedback = get_language_tool_feedback ( sentence ) subject_and_verb_agree = get_subject_verb_agreem... | Supply a sentence or fragment and recieve feedback |
24,681 | def list_submissions ( ) : submissions = [ ] try : submissions = session . query ( Submission ) . all ( ) except SQLAlchemyError as e : session . rollback ( ) return render_template ( 'list_submissions.html' , submissions = submissions ) | List the past submissions with information about them |
24,682 | def get_submissions ( ) : print ( request . args . to_dict ( ) ) print ( request . args . get ( 'search[value]' ) ) print ( request . args . get ( 'draw' , 1 ) ) if request . args . get ( 'correct_filter' , 'all' ) == 'all' : correct_filter = [ True , False ] elif request . args [ 'correct_filter' ] == 'correct' : corr... | API endpoint to get submissions in JSON format |
24,683 | def check_sentence ( ) : text = '' if request . method == 'POST' : text = request . form [ 'text' ] if not text : error = 'No input' flash_message = error else : fb = check ( request . form [ 'text' ] ) correct = False if request . form . get ( 'is_correct' ) and not fb . primary_error : correct = True elif not request... | Sole porcupine endpoint |
24,684 | def raise_double_modal_error ( verb_phrase_doc ) : prev_word = None for word in verb_phrase : if word . tag_ == 'MD' and prev_word . tag == 'MD' : raise ( 'DoubleModalError' ) prev_word = word | A modal auxilary verb should not follow another modal auxilary verb |
24,685 | def raise_modal_error ( verb_phrase_doc ) : verb_phrase = verb_phrase_doc . text . lower ( ) bad_strings = [ 'should had' , 'should has' , 'could had' , 'could has' , 'would ' 'had' , 'would has' ] [ "should" , "could" , "would" ] for bs in bad_strings : if bs in verb_phrase : raise ( 'ShouldCouldWouldError' ) | Given a verb phrase raise an error if the modal auxilary has an issue with it |
24,686 | def split_infinitive_warning ( sentence_str ) : sent_doc = textacy . Doc ( sentence_str , lang = 'en_core_web_lg' ) inf_pattern = r'<PART><ADV><VERB>' infinitives = textacy . extract . pos_regex_matches ( sent_doc , inf_pattern ) for inf in infinitives : if inf [ 0 ] . text . lower ( ) != 'to' : continue if inf [ - 1 ]... | Return a warning for a split infinitive else None |
24,687 | def raise_infinitive_error ( sentence_str ) : sent_doc = textacy . Doc ( sentence_str , lang = 'en_core_web_lg' ) inf_pattern = r'<PART|ADP><VERB>' infinitives = textacy . extract . pos_regex_matches ( sent_doc , inf_pattern ) for inf in infinitives : if inf [ 0 ] . text . lower ( ) != 'to' : continue if inf [ - 1 ] . ... | Given a string check that all infinitives are properly formatted |
24,688 | def drop_modifiers ( sentence_str ) : tdoc = textacy . Doc ( sentence_str , lang = 'en_core_web_lg' ) new_sent = tdoc . text unusual_char = '形' for tag in tdoc : if tag . dep_ . endswith ( 'mod' ) : new_sent = new_sent [ : tag . idx ] + unusual_char * len ( tag . text ) + new_sent [ tag . idx + len ( tag . text ) : ] n... | Given a string drop the modifiers and return a string without them |
24,689 | def cluster ( list_of_texts , num_clusters = 3 ) : pipeline = Pipeline ( [ ( "vect" , CountVectorizer ( ) ) , ( "tfidf" , TfidfTransformer ( ) ) , ( "clust" , KMeans ( n_clusters = num_clusters ) ) ] ) try : clusters = pipeline . fit_predict ( list_of_texts ) except ValueError : clusters = list ( range ( len ( list_of_... | Cluster a list of texts into a predefined number of clusters . |
24,690 | def find_topics ( token_lists , num_topics = 10 ) : dictionary = Dictionary ( token_lists ) print ( 'Number of unique words in original documents:' , len ( dictionary ) ) dictionary . filter_extremes ( no_below = 2 , no_above = 0.7 ) print ( 'Number of unique words after removing rare and common words:' , len ( diction... | Find the topics in a list of texts with Latent Dirichlet Allocation . |
24,691 | def fetch_bookshelf ( start_url , output_dir ) : try : os . mkdir ( OUTPUT_DIR + output_dir ) except OSError as e : raise ( e ) r = requests . get ( start_url ) soup = bs ( r . text , 'html.parser' ) book_links = soup . find_all ( class_ = re . compile ( "extiw" ) ) new_links = [ ] for el in book_links : link = el [ 'h... | Fetch all the books off of a gutenberg project bookshelf page |
24,692 | def lemmatize ( text , lowercase = True , remove_stopwords = True ) : doc = nlp ( text ) if lowercase and remove_stopwords : lemmas = [ t . lemma_ . lower ( ) for t in doc if not ( t . is_stop or t . orth_ . lower ( ) in STOPWORDS ) ] elif lowercase : lemmas = [ t . lemma_ . lower ( ) for t in doc ] elif remove_stopwor... | Return the lemmas of the tokens in a text . |
24,693 | def inflate ( deflated_vector ) : dv = json . loads ( deflated_vector ) result = np . zeros ( 5555 ) for n in dv [ 'indices' ] : result [ int ( n ) ] = dv [ 'indices' ] [ n ] return result | Given a defalated vector inflate it into a np array and return it |
24,694 | def text_to_vector ( sent_str ) : r = requests . get ( "{}/sva/vector" . format ( VECTORIZE_API ) , params = { 's' : sent_str } ) return inflate ( r . text ) | Given a string get it s defalted vector inflate it then return the inflated vector |
24,695 | def detect_missing_verb ( sentence ) : doc = nlp ( sentence ) for w in doc : if w . tag_ . startswith ( 'VB' ) and w . dep_ == 'ROOT' : return False return True | Return True if the sentence appears to be missing a main verb |
24,696 | def detect_infinitive_phrase ( sentence ) : if not 'to' in sentence . lower ( ) : return False doc = nlp ( sentence ) prev_word = None for w in doc : if prev_word == 'to' : if w . dep_ == 'ROOT' and w . tag_ . startswith ( 'VB' ) : return True else : return False prev_word = w . text . lower ( ) | Given a string return true if it is an infinitive phrase fragment |
24,697 | def perform_srl ( responses , prompt ) : predictor = Predictor . from_path ( "https://s3-us-west-2.amazonaws.com/allennlp/models/srl-model-2018.05.25.tar.gz" ) sentences = [ { "sentence" : prompt + " " + response } for response in responses ] output = predictor . predict_batch_json ( sentences ) full_output = [ { "sent... | Perform semantic role labeling on a list of responses given a prompt . |
24,698 | def detokenize ( s ) : print ( s ) s = re . sub ( "\s+([;:,\.\?!])" , "\\1" , s ) s = re . sub ( "\s+(n't)" , "\\1" , s ) return s | Detokenize a string by removing spaces before punctuation . |
24,699 | def start ( self ) : if self . threadPool : self . threadPool . addTask ( self ) time . sleep ( 0 ) else : raise TaskError ( "start(): nothing to start for task %s" % self ) | This method starts a task executing and returns immediately . Subclass should override this method if it has an asynchronous way to start the task and return immediately . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.