idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
3,600 | def _get_func ( cls , source_ver , target_ver ) : matches = ( func for func in cls . _upgrade_funcs if func . source == source_ver and func . target == target_ver ) try : match , = matches except ValueError : raise ValueError ( f"No migration from {source_ver} to {target_ver}" ) return match | Return exactly one function to convert from source to target | 84 | 10 |
3,601 | def get_uid ( brain_or_object ) : if is_portal ( brain_or_object ) : return '0' if is_brain ( brain_or_object ) and base_hasattr ( brain_or_object , "UID" ) : return brain_or_object . UID return get_object ( brain_or_object ) . UID ( ) | Get the Plone UID for this object | 80 | 8 |
3,602 | def get_icon ( brain_or_object , html_tag = True ) : # Manual approach, because `plone.app.layout.getIcon` does not reliable # work for Bika Contents coming from other catalogs than the # `portal_catalog` portal_types = get_tool ( "portal_types" ) fti = portal_types . getTypeInfo ( brain_or_object . portal_type ) icon ... | Get the icon of the content object | 188 | 7 |
3,603 | def get_review_history ( brain_or_object , rev = True ) : obj = get_object ( brain_or_object ) review_history = [ ] try : workflow = get_tool ( "portal_workflow" ) review_history = workflow . getInfoFor ( obj , 'review_history' ) except WorkflowException as e : message = str ( e ) logger . error ( "Cannot retrieve revi... | Get the review history for the given brain or context . | 171 | 11 |
3,604 | def get_cancellation_status ( brain_or_object , default = "active" ) : if is_brain ( brain_or_object ) : return getattr ( brain_or_object , "cancellation_state" , default ) workflows = get_workflows_for ( brain_or_object ) if 'bika_cancellation_workflow' not in workflows : return default return get_workflow_status_of (... | Get the cancellation_state of an object | 117 | 8 |
3,605 | def get_inactive_status ( brain_or_object , default = "active" ) : if is_brain ( brain_or_object ) : return getattr ( brain_or_object , "inactive_state" , default ) workflows = get_workflows_for ( brain_or_object ) if 'bika_inactive_workflow' not in workflows : return default return get_workflow_status_of ( brain_or_ob... | Get the cancellation_state of an objct | 109 | 9 |
3,606 | def set_log_level ( verbose , quiet ) : if quiet : verbose = - 1 if verbose < 0 : verbose = logging . CRITICAL elif verbose == 0 : verbose = logging . WARNING elif verbose == 1 : verbose = logging . INFO elif 1 < verbose : verbose = logging . DEBUG LOGGER . setLevel ( verbose ) | Ses the logging level of the script based on command line options . | 83 | 14 |
3,607 | def detect_pattern_format ( pattern_filename , encoding , on_word_boundaries ) : tsv = True boundaries = on_word_boundaries with open_file ( pattern_filename ) as input_file : for line in input_file : line = line . decode ( encoding ) if line . count ( '\t' ) != 1 : tsv = False if '\\b' in line : boundaries = True if b... | Automatically detects the pattern file format and determines whether the Aho - Corasick string matching should pay attention to word boundaries or not . | 103 | 28 |
3,608 | def sub_escapes ( sval ) : sval = sval . replace ( '\\a' , '\a' ) sval = sval . replace ( '\\b' , '\x00' ) sval = sval . replace ( '\\f' , '\f' ) sval = sval . replace ( '\\n' , '\n' ) sval = sval . replace ( '\\r' , '\r' ) sval = sval . replace ( '\\t' , '\t' ) sval = sval . replace ( '\\v' , '\v' ) sval = sval . repl... | Process escaped characters in sval . | 156 | 7 |
3,609 | def build_trie ( pattern_filename , pattern_format , encoding , on_word_boundaries ) : boundaries = on_word_boundaries if pattern_format == 'auto' or not on_word_boundaries : tsv , boundaries = detect_pattern_format ( pattern_filename , encoding , on_word_boundaries ) if pattern_format == 'auto' : if tsv : pattern_form... | Constructs a finite state machine for performing string rewriting . | 626 | 11 |
3,610 | def warn_prefix_values ( trie ) : for current , _parent in trie . dfs ( ) : if current . has_value and current . longest_prefix is not None : LOGGER . warn ( ( 'pattern {} (value {}) is a superstring of pattern ' '{} (value {}) and will never be matched' ) . format ( current . prefix , current . value , current . longe... | Prints warning messages for every node that has both a value and a longest_prefix . | 103 | 18 |
3,611 | def rewrite_str_with_trie ( sval , trie , boundaries = False , slow = False ) : if boundaries : sval = fsed . ahocorasick . boundary_transform ( sval ) if slow : sval = trie . replace ( sval ) else : sval = trie . greedy_replace ( sval ) if boundaries : sval = '' . join ( fsed . ahocorasick . boundary_untransform ( sva... | Rewrites a string using the given trie object . | 105 | 11 |
3,612 | def register_function ( cls , fn , label ) : if label in cls . registered_functions : log . warning ( "Overwriting existing registered function %s" , label ) fn . label = label cls . registered_functions [ fn . label ] = fn | Register a function with the pipeline . | 59 | 7 |
3,613 | def load ( cls , serialised ) : pipeline = cls ( ) for fn_name in serialised : try : fn = cls . registered_functions [ fn_name ] except KeyError : raise BaseLunrException ( "Cannot load unregistered function " . format ( fn_name ) ) else : pipeline . add ( fn ) return pipeline | Loads a previously serialised pipeline . | 77 | 8 |
3,614 | def add ( self , * args ) : for fn in args : self . warn_if_function_not_registered ( fn ) self . _stack . append ( fn ) | Adds new functions to the end of the pipeline . | 37 | 10 |
3,615 | def after ( self , existing_fn , new_fn ) : self . warn_if_function_not_registered ( new_fn ) try : index = self . _stack . index ( existing_fn ) self . _stack . insert ( index + 1 , new_fn ) except ValueError as e : six . raise_from ( BaseLunrException ( "Cannot find existing_fn" ) , e ) | Adds a single function after a function that already exists in the pipeline . | 90 | 14 |
3,616 | def run ( self , tokens ) : for fn in self . _stack : results = [ ] for i , token in enumerate ( tokens ) : # JS ignores additional arguments to the functions but we # force pipeline functions to declare (token, i, tokens) # or *args result = fn ( token , i , tokens ) if not result : continue if isinstance ( result , (... | Runs the current list of functions that make up the pipeline against the passed tokens . | 111 | 17 |
3,617 | def run_string ( self , string , metadata = None ) : token = Token ( string , metadata ) return [ str ( tkn ) for tkn in self . run ( [ token ] ) ] | Convenience method for passing a string through a pipeline and getting strings out . This method takes care of wrapping the passed string in a token and mapping the resulting tokens back to strings . | 42 | 37 |
3,618 | def get_client ( ) : with contextlib . suppress ( Exception ) : store = Storage . from_URI ( ) assert isinstance ( store , pmxbot . storage . MongoDBStorage ) return store . db . database . client | Use the same MongoDB client as pmxbot if available . | 49 | 13 |
3,619 | def create_db_in_shard ( db_name , shard , client = None ) : client = client or pymongo . MongoClient ( ) # flush the router config to ensure it's not stale res = client . admin . command ( 'flushRouterConfig' ) if not res . get ( 'ok' ) : raise RuntimeError ( "unable to flush router config" ) if shard not in get_ids (... | In a sharded cluster create a database in a particular shard . | 329 | 14 |
3,620 | def luhn_checksum ( number , chars = DIGITS ) : length = len ( chars ) number = [ chars . index ( n ) for n in reversed ( str ( number ) ) ] return ( sum ( number [ : : 2 ] ) + sum ( sum ( divmod ( i * 2 , length ) ) for i in number [ 1 : : 2 ] ) ) % length | Calculates the Luhn checksum for number | 83 | 10 |
3,621 | def luhn_calc ( number , chars = DIGITS ) : checksum = luhn_checksum ( str ( number ) + chars [ 0 ] , chars ) return chars [ - checksum ] | Calculate the Luhn check digit for number . | 46 | 11 |
3,622 | def to_decimal ( number , strip = '- ' ) : if isinstance ( number , six . integer_types ) : return str ( number ) number = str ( number ) number = re . sub ( r'[%s]' % re . escape ( strip ) , '' , number ) # hexadecimal if number . startswith ( '0x' ) : return to_decimal ( int ( number [ 2 : ] , 16 ) ) # octal elif num... | Converts a number to a string of decimals in base 10 . | 173 | 15 |
3,623 | def get_class_method ( cls_or_inst , method_name ) : cls = cls_or_inst if isinstance ( cls_or_inst , type ) else cls_or_inst . __class__ meth = getattr ( cls , method_name , None ) if isinstance ( meth , property ) : meth = meth . fget elif isinstance ( meth , cached_property ) : meth = meth . func return meth | Returns a method from a given class or instance . When the method doest not exist it returns None . Also works with properties and cached properties . | 100 | 29 |
3,624 | def manage_fits ( list_of_frame ) : import astropy . io . fits as fits import numina . types . dataframe as df refs = [ ] for frame in list_of_frame : if isinstance ( frame , str ) : ref = fits . open ( frame ) refs . append ( ref ) elif isinstance ( frame , fits . HDUList ) : refs . append ( frame ) elif isinstance ( ... | Manage a list of FITS resources | 146 | 8 |
3,625 | def logging_from_debugplot ( debugplot ) : if isinstance ( debugplot , int ) : if abs ( debugplot ) >= 10 : logging . basicConfig ( level = logging . DEBUG ) else : logging . basicConfig ( level = logging . INFO ) else : raise ValueError ( "Unexpected debugplot=" + str ( debugplot ) ) | Set debugging level based on debugplot value . | 74 | 9 |
3,626 | def ximplot ( ycut , title = None , show = True , plot_bbox = ( 0 , 0 ) , geometry = ( 0 , 0 , 640 , 480 ) , tight_layout = True , debugplot = None ) : # protections if type ( ycut ) is not np . ndarray : raise ValueError ( "ycut=" + str ( ycut ) + " must be a numpy.ndarray" ) elif ycut . ndim is not 1 : raise ValueErr... | Auxiliary function to display 1d plot . | 589 | 10 |
3,627 | def oversample1d ( sp , crval1 , cdelt1 , oversampling = 1 , debugplot = 0 ) : if sp . ndim != 1 : raise ValueError ( 'Unexpected array dimensions' ) naxis1 = sp . size naxis1_over = naxis1 * oversampling cdelt1_over = cdelt1 / oversampling xmin = crval1 - cdelt1 / 2 # left border of first pixel crval1_over = xmin + cd... | Oversample spectrum . | 353 | 5 |
3,628 | def map_borders ( wls ) : midpt_wl = 0.5 * ( wls [ 1 : ] + wls [ : - 1 ] ) all_borders = np . zeros ( ( wls . shape [ 0 ] + 1 , ) ) all_borders [ 1 : - 1 ] = midpt_wl all_borders [ 0 ] = 2 * wls [ 0 ] - midpt_wl [ 0 ] all_borders [ - 1 ] = 2 * wls [ - 1 ] - midpt_wl [ - 1 ] return all_borders | Compute borders of pixels for interpolation . | 127 | 9 |
3,629 | def import_object ( path ) : spl = path . split ( '.' ) if len ( spl ) == 1 : return importlib . import_module ( path ) # avoid last part for the moment cls = spl [ - 1 ] mods = '.' . join ( spl [ : - 1 ] ) mm = importlib . import_module ( mods ) # try to get the last part as an attribute try : obj = getattr ( mm , cls... | Import an object given its fully qualified name . | 127 | 9 |
3,630 | def make_parser ( add_help = True , exclude_args = None ) : if exclude_args is None : exclude_args = [ ] parser = argparse . ArgumentParser ( add_help = add_help ) parser . description = ( "Filter, transform and export a list of JSON " "objects on stdin to JSON or CSV on stdout" ) if "--columns" not in exclude_args : p... | Return an argparse . ArgumentParser object with losser s arguments . | 505 | 14 |
3,631 | def parse ( parser = None , args = None ) : if not parser : parser = make_parser ( ) try : parsed_args = parser . parse_args ( args ) except SystemExit as err : raise CommandLineExit ( err . code ) try : columns = parsed_args . columns except AttributeError : columns = collections . OrderedDict ( ) parsed_args . column... | Parse the command line arguments return an argparse namespace object . | 321 | 13 |
3,632 | def do ( parser = None , args = None , in_ = None , table_function = None ) : in_ = in_ or sys . stdin table_function = table_function or losser . table parsed_args = parse ( parser = parser , args = args ) # Read the input data from stdin or a file. if parsed_args . input_data : input_data = open ( parsed_args . input... | Read command - line args and stdin return the result . | 161 | 12 |
3,633 | def generate_gaussian_profile ( seeing_fwhm ) : FWHM_G = 2 * math . sqrt ( 2 * math . log ( 2 ) ) sigma = seeing_fwhm / FWHM_G amplitude = 1.0 / ( 2 * math . pi * sigma * sigma ) seeing_model = Gaussian2D ( amplitude = amplitude , x_mean = 0.0 , y_mean = 0.0 , x_stddev = sigma , y_stddev = sigma ) return seeing_model | Generate a normalized Gaussian profile from its FWHM | 121 | 12 |
3,634 | def generate_moffat_profile ( seeing_fwhm , alpha ) : scale = 2 * math . sqrt ( 2 ** ( 1.0 / alpha ) - 1 ) gamma = seeing_fwhm / scale amplitude = 1.0 / math . pi * ( alpha - 1 ) / gamma ** 2 seeing_model = Moffat2D ( amplitude = amplitude , x_mean = 0.0 , y_mean = 0.0 , gamma = gamma , alpha = alpha ) return seeing_mo... | Generate a normalized Moffat profile from its FWHM and alpha | 108 | 14 |
3,635 | def field_to_dict ( field , instance ) : # avoid a circular import from django . db . models . fields . related import ManyToManyField return ( many_to_many_field_to_dict ( field , instance ) if isinstance ( field , ManyToManyField ) else field . value_from_object ( instance ) ) | Converts a model field to a dictionary | 74 | 8 |
3,636 | def model_to_dict ( instance , fields = None , exclude = None ) : return { field . name : field_to_dict ( field , instance ) for field in chain ( instance . _meta . concrete_fields , instance . _meta . many_to_many ) # pylint: disable=W0212 if not should_exclude_field ( field , fields , exclude ) } | The same implementation as django model_to_dict but editable fields are allowed | 85 | 17 |
3,637 | def change_and_save ( self , update_only_changed_fields = False , * * changed_fields ) : bulk_change_and_save ( self , update_only_changed_fields = update_only_changed_fields , * * changed_fields ) return self . filter ( ) | Changes a given changed_fields on each object in the queryset saves objects and returns the changed objects in the queryset . | 64 | 27 |
3,638 | def extent ( self ) : return ( self . intervals [ 1 ] . pix1 - 0.5 , self . intervals [ 1 ] . pix2 - 0.5 , self . intervals [ 0 ] . pix1 - 0.5 , self . intervals [ 0 ] . pix2 - 0.5 , ) | Helper for matplotlib imshow | 69 | 7 |
3,639 | def readout ( self ) : elec = self . simulate_poisson_variate ( ) elec_pre = self . saturate ( elec ) elec_f = self . pre_readout ( elec_pre ) adu_r = self . base_readout ( elec_f ) adu_p = self . post_readout ( adu_r ) self . clean_up ( ) return adu_p | Readout the detector . | 97 | 5 |
3,640 | def parse_arg_line ( fargs ) : # Convert to literal dict fargs = fargs . strip ( ) if fargs == '' : return { } pairs = [ s . strip ( ) for s in fargs . split ( ',' ) ] # find first "=" result = [ ] for p in pairs : fe = p . find ( "=" ) if fe == - 1 : # no equal raise ValueError ( "malformed" ) key = p [ : fe ] val = p... | parse limited form of arguments of function | 171 | 7 |
3,641 | def natural_number_with_currency ( number , currency , show_decimal_place = True , use_nbsp = True ) : humanized = '{} {}' . format ( numberformat . format ( number = number , decimal_sep = ',' , decimal_pos = 2 if show_decimal_place else 0 , grouping = 3 , thousand_sep = ' ' , force_grouping = True ) , force_text ( cu... | Return a given number formatter a price for humans . | 130 | 11 |
3,642 | def extract_db_info ( self , obj , keys ) : objl = self . convert ( obj ) result = super ( DataFrameType , self ) . extract_db_info ( objl , keys ) ext = self . datamodel . extractor_map [ 'fits' ] if objl : with objl . open ( ) as hdulist : for field in keys : result [ field ] = ext . extract ( field , hdulist ) tags ... | Extract tags from serialized file | 140 | 7 |
3,643 | def readc ( prompt , default = None , valid = None , question_mark = True ) : cresult = None # Avoid PyCharm warning # question mark if question_mark : cquestion_mark = ' ? ' else : cquestion_mark = '' # main loop loop = True while loop : # display prompt if default is None : print ( prompt + cquestion_mark , end = '' ... | Return a single character read from keyboard | 259 | 7 |
3,644 | def read_value ( ftype , prompt , default = None , minval = None , maxval = None , allowed_single_chars = None , question_mark = True ) : # avoid PyCharm warning 'might be referenced before assignment' result = None # question mark if question_mark : cquestion_mark = ' ? ' else : cquestion_mark = '' # check minimum val... | Return value read from keyboard | 640 | 5 |
3,645 | def load_product_object ( self , name ) : product_entry = self . products [ name ] product = self . _get_base_object ( product_entry ) return product | Load product object according to name | 39 | 6 |
3,646 | def depsolve ( self ) : # load everything requires = { } provides = { } for mode , r in self . recipes . items ( ) : l = self . load_recipe_object ( mode ) for field , vv in l . requirements ( ) . items ( ) : if vv . type . isproduct ( ) : name = vv . type . name ( ) pe = ProductEntry ( name , mode , field ) requires [... | Load all recipes to search for products | 157 | 7 |
3,647 | def search_mode_provides ( self , product , pipeline = 'default' ) : pipeline = self . pipelines [ pipeline ] for obj , mode , field in self . iterate_mode_provides ( self . modes , pipeline ) : # extract name from obj if obj . name ( ) == product : return ProductEntry ( obj . name ( ) , mode . key , field ) else : rai... | Search the mode that provides a given product | 97 | 8 |
3,648 | def select_configuration ( self , obresult ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'calling default configuration selector' ) # get first possible image ref = obresult . get_sample_frame ( ) extr = self . datamodel . extractor_map [ 'fits' ] if ref : # get INSCONF configuration result = extr . ex... | Select instrument configuration based on OB | 339 | 6 |
3,649 | def select_profile ( self , obresult ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'calling default profile selector' ) # check configuration insconf = obresult . configuration if insconf != 'default' : key = insconf date_obs = None keyname = 'uuid' else : # get first possible image ref = obresult . ge... | Select instrument profile based on OB | 203 | 6 |
3,650 | def get_recipe_object ( self , mode_name , pipeline_name = 'default' ) : active_mode = self . modes [ mode_name ] active_pipeline = self . pipelines [ pipeline_name ] recipe = active_pipeline . get_recipe_object ( active_mode ) return recipe | Build a recipe object from a given mode name | 70 | 9 |
3,651 | def pause_debugplot ( debugplot , optional_prompt = None , pltshow = False , tight_layout = True ) : if debugplot not in DEBUGPLOT_CODES : raise ValueError ( 'Invalid debugplot value:' , debugplot ) if debugplot < 0 : debugplot_ = - debugplot pltclose = True else : debugplot_ = debugplot pltclose = False if pltshow : i... | Ask the user to press RETURN to continue after plotting . | 309 | 12 |
3,652 | def mode_half_sample ( a , is_sorted = False ) : a = np . asanyarray ( a ) if not is_sorted : sdata = np . sort ( a ) else : sdata = a n = len ( sdata ) if n == 1 : return sdata [ 0 ] elif n == 2 : return 0.5 * ( sdata [ 0 ] + sdata [ 1 ] ) elif n == 3 : ind = - sdata [ 0 ] + 2 * sdata [ 1 ] - sdata [ 2 ] if ind < 0 : ... | Estimate the mode using the Half Sample mode . | 249 | 10 |
3,653 | def overplot_ds9reg ( filename , ax ) : # read ds9 region file with open ( filename ) as f : file_content = f . read ( ) . splitlines ( ) # check first line first_line = file_content [ 0 ] if "# Region file format: DS9" not in first_line : raise ValueError ( "Unrecognized ds9 region file format" ) for line in file_cont... | Overplot a ds9 region file . | 401 | 9 |
3,654 | def find_peaks_indexes ( arr , window_width = 5 , threshold = 0.0 , fpeak = 0 ) : _check_window_width ( window_width ) if ( fpeak < 0 or fpeak + 1 >= window_width ) : raise ValueError ( 'fpeak must be in the range 0- window_width - 2' ) kernel_peak = kernel_peak_function ( threshold , fpeak ) out = generic_filter ( arr... | Find indexes of peaks in a 1d array . | 142 | 10 |
3,655 | def refine_peaks ( arr , ipeaks , window_width ) : _check_window_width ( window_width ) step = window_width // 2 ipeaks = filter_array_margins ( arr , ipeaks , window_width ) winoff = numpy . arange ( - step , step + 1 , dtype = 'int' ) peakwin = ipeaks [ : , numpy . newaxis ] + winoff ycols = arr [ peakwin ] ww = retu... | Refine the peak location previously found by find_peaks_indexes | 208 | 15 |
3,656 | def complete_config ( config ) : if not config . has_section ( 'run' ) : config . add_section ( 'run' ) values = { 'basedir' : os . getcwd ( ) , 'task_control' : 'control.yaml' , } for k , v in values . items ( ) : if not config . has_option ( 'run' , k ) : config . set ( 'run' , k , v ) return config | Complete config with default values | 101 | 5 |
3,657 | def centering_centroid ( data , xi , yi , box , nloop = 10 , toldist = 1e-3 , maxdist = 10.0 ) : # Store original center cxy = ( xi , yi ) origin = ( xi , yi ) # initial background back = 0.0 if nloop == 0 : return xi , yi , 0.0 , 0 , 'not recentering' for i in range ( nloop ) : nxy , back = _centering_centroid_loop_xy... | returns x y background status message | 298 | 7 |
3,658 | def cache_for ( * * timedelta_kw ) : max_age_timedelta = timedelta ( * * timedelta_kw ) def decorate_func ( func ) : @ wraps ( func ) def decorate_func_call ( * a , * * kw ) : callback = SetCacheControlHeadersFromTimedeltaCallback ( max_age_timedelta ) registry_provider = AfterThisRequestCallbackRegistryProvider ( ) re... | Set Cache - Control headers and Expires - header . | 136 | 11 |
3,659 | def cache ( * cache_control_items , * * cache_control_kw ) : cache_control_kw . update ( cache_control_items ) def decorate_func ( func ) : @ wraps ( func ) def decorate_func_call ( * a , * * kw ) : callback = SetCacheControlHeadersCallback ( * * cache_control_kw ) registry_provider = AfterThisRequestCallbackRegistryPr... | Set Cache - Control headers . | 134 | 6 |
3,660 | def dont_cache ( ) : def decorate_func ( func ) : @ wraps ( func ) def decorate_func_call ( * a , * * kw ) : callback = SetCacheControlHeadersForNoCachingCallback ( ) registry_provider = AfterThisRequestCallbackRegistryProvider ( ) registry = registry_provider . provide ( ) registry . add ( callback ) return func ( * a... | Set Cache - Control headers for no caching | 105 | 8 |
3,661 | def filter_empty_parameters ( func ) : @ wraps ( func ) def func_wrapper ( self , * args , * * kwargs ) : my_kwargs = { key : value for key , value in kwargs . items ( ) if value not in EMPTIES } args_is_empty = all ( arg in EMPTIES for arg in args ) if ( { 'source' , 'material' } . issuperset ( my_kwargs ) or not my_k... | Decorator that is filtering empty parameters . | 136 | 9 |
3,662 | def author_id_normalize_and_schema ( uid , schema = None ) : def _get_uid_normalized_in_schema ( _uid , _schema ) : regex , template = _RE_AUTHORS_UID [ _schema ] match = regex . match ( _uid ) if match : return template . format ( match . group ( 'uid' ) ) if idutils . is_orcid ( uid ) and schema in ( None , 'ORCID' )... | Detect and normalize an author UID schema . | 349 | 9 |
3,663 | def normalize_arxiv_category ( category ) : category = _NEW_CATEGORIES . get ( category . lower ( ) , category ) for valid_category in valid_arxiv_categories ( ) : if ( category . lower ( ) == valid_category . lower ( ) or category . lower ( ) . replace ( '-' , '.' ) == valid_category . lower ( ) ) : return valid_categ... | Normalize arXiv category to be schema compliant . | 96 | 11 |
3,664 | def valid_arxiv_categories ( ) : schema = load_schema ( 'elements/arxiv_categories' ) categories = schema [ 'enum' ] categories . extend ( _NEW_CATEGORIES . keys ( ) ) return categories | List of all arXiv categories that ever existed . | 58 | 11 |
3,665 | def classify_field ( value ) : if not ( isinstance ( value , six . string_types ) and value ) : return schema = load_schema ( 'elements/inspire_field' ) inspire_categories = schema [ 'properties' ] [ 'term' ] [ 'enum' ] for inspire_category in inspire_categories : if value . upper ( ) == inspire_category . upper ( ) : ... | Normalize value to an Inspire category . | 135 | 9 |
3,666 | def split_pubnote ( pubnote_str ) : pubnote = { } parts = pubnote_str . split ( ',' ) if len ( parts ) > 2 : pubnote [ 'journal_title' ] = parts [ 0 ] pubnote [ 'journal_volume' ] = parts [ 1 ] pubnote [ 'page_start' ] , pubnote [ 'page_end' ] , pubnote [ 'artid' ] = split_page_artid ( parts [ 2 ] ) return { key : val ... | Split pubnote into journal information . | 132 | 7 |
3,667 | def get_schema_path ( schema , resolved = False ) : def _strip_first_path_elem ( path ) : """Pass doctests. Strip the first element of the given path, returning an empty string if there are no more elements. For example, 'something/other' will end up as 'other', but passing then 'other' will return '' """ stripped_path... | Retrieve the installed path for the given schema . | 355 | 10 |
3,668 | def load_schema ( schema_name , resolved = False ) : schema_data = '' with open ( get_schema_path ( schema_name , resolved ) ) as schema_fd : schema_data = json . loads ( schema_fd . read ( ) ) return schema_data | Load the given schema from wherever it s installed . | 62 | 10 |
3,669 | def _load_schema_for_record ( data , schema = None ) : if schema is None : if '$schema' not in data : raise SchemaKeyNotFound ( data = data ) schema = data [ '$schema' ] if isinstance ( schema , six . string_types ) : schema = load_schema ( schema_name = schema ) return schema | Load the schema from a given record . | 82 | 8 |
3,670 | def validate ( data , schema = None ) : schema = _load_schema_for_record ( data , schema ) return jsonschema_validate ( instance = data , schema = schema , resolver = LocalRefResolver . from_schema ( schema ) , format_checker = inspire_format_checker , ) | Validate the given dictionary against the given schema . | 72 | 10 |
3,671 | def get_validation_errors ( data , schema = None ) : schema = _load_schema_for_record ( data , schema ) errors = Draft4Validator ( schema , resolver = LocalRefResolver . from_schema ( schema ) , format_checker = inspire_format_checker ) return errors . iter_errors ( data ) | Validation errors for a given record . | 77 | 8 |
3,672 | def normalize_collaboration ( collaboration ) : if not collaboration : return [ ] collaboration = collaboration . strip ( ) if collaboration . startswith ( '(' ) and collaboration . endswith ( ')' ) : collaboration = collaboration [ 1 : - 1 ] collaborations = _RE_AND . split ( collaboration ) collaborations = ( _RE_COL... | Normalize collaboration string . | 139 | 5 |
3,673 | def get_license_from_url ( url ) : if not url : return split_url = urlsplit ( url , scheme = 'http' ) if split_url . netloc . lower ( ) == 'creativecommons.org' : if 'publicdomain' in split_url . path : match = _RE_PUBLIC_DOMAIN_URL . match ( split_url . path ) if match is None : license = [ 'public domain' ] else : li... | Get the license abbreviation from an URL . | 257 | 9 |
3,674 | def convert_old_publication_info_to_new ( publication_infos ) : result = [ ] hidden_publication_infos = [ ] for publication_info in publication_infos : _publication_info = copy . deepcopy ( publication_info ) journal_title = _publication_info . get ( 'journal_title' ) try : journal_title = _JOURNALS_RENAMED_OLD_TO_NEW ... | Convert a publication_info value from the old format to the new . | 638 | 15 |
3,675 | def convert_new_publication_info_to_old ( publication_infos ) : def _needs_a_hidden_pubnote ( journal_title , journal_volume ) : return ( journal_title in _JOURNALS_THAT_NEED_A_HIDDEN_PUBNOTE and journal_volume in _JOURNALS_THAT_NEED_A_HIDDEN_PUBNOTE [ journal_title ] ) result = [ ] for publication_info in publication_... | Convert back a publication_info value from the new format to the old . | 606 | 16 |
3,676 | def fix_reference_url ( url ) : new_url = url new_url = fix_url_bars_instead_of_slashes ( new_url ) new_url = fix_url_add_http_if_missing ( new_url ) new_url = fix_url_replace_tilde ( new_url ) try : rfc3987 . parse ( new_url , rule = "URI" ) return new_url except ValueError : return url | Used to parse an incorect url to try to fix it with the most common ocurrences for errors . If the fixed url is still incorrect it returns None . | 102 | 34 |
3,677 | def is_arxiv ( obj ) : arxiv_test = obj . split ( ) if not arxiv_test : return False matched_arxiv = ( RE_ARXIV_PRE_2007_CLASS . match ( arxiv_test [ 0 ] ) or RE_ARXIV_POST_2007_CLASS . match ( arxiv_test [ 0 ] ) ) if not matched_arxiv : return False if not matched_arxiv . group ( 'category' ) : return True valid_arxiv... | Return True if obj contains an arXiv identifier . | 199 | 11 |
3,678 | def normalize_arxiv ( obj ) : obj = obj . split ( ) [ 0 ] matched_arxiv_pre = RE_ARXIV_PRE_2007_CLASS . match ( obj ) if matched_arxiv_pre : return ( '/' . join ( matched_arxiv_pre . group ( "extraidentifier" , "identifier" ) ) ) . lower ( ) matched_arxiv_post = RE_ARXIV_POST_2007_CLASS . match ( obj ) if matched_arxiv... | Return a normalized arXiv identifier from obj . | 139 | 10 |
3,679 | def resolve_remote ( self , uri ) : try : return super ( LocalRefResolver , self ) . resolve_remote ( uri ) except ValueError : return super ( LocalRefResolver , self ) . resolve_remote ( 'file://' + get_schema_path ( uri . rsplit ( '.json' , 1 ) [ 0 ] ) ) | Resolve a uri or relative path to a schema . | 79 | 12 |
3,680 | def set_path ( self , path ) : if os . path . isabs ( path ) : path = os . path . normpath ( os . path . join ( self . cwd , path ) ) self . path = path self . relative = os . path . relpath ( self . path , self . base ) | Set the path of the file . | 68 | 7 |
3,681 | def clone ( self , path = None , * , with_contents = True , * * options ) : file = File ( path if path else self . path , cwd = options . get ( "cwd" , self . cwd ) ) file . base = options . get ( "base" , self . base ) if with_contents : file . contents = options . get ( "contents" , self . contents ) return file | Clone the file . | 94 | 5 |
3,682 | def launch_cli ( ) : # Create the CLI argument parser parser = argparse . ArgumentParser ( prog = "pylp" , description = "Call some tasks defined in your pylpfile." ) # Version of Pylp parser . add_argument ( "-v" , "--version" , action = "version" , version = "Pylp %s" % version , help = "get the Pylp version and exit... | Launch the CLI . | 519 | 4 |
3,683 | def add_affiliation ( self , value , curated_relation = None , record = None ) : if value : affiliation = { 'value' : value } if record : affiliation [ 'record' ] = record if curated_relation is not None : affiliation [ 'curated_relation' ] = curated_relation self . _ensure_list_field ( 'affiliations' , affiliation ) | Add an affiliation . | 83 | 4 |
3,684 | def set_uid ( self , uid , schema = None ) : try : uid , schema = author_id_normalize_and_schema ( uid , schema ) except UnknownUIDSchema : # Explicit schema wasn't provided, and the UID is too little # to figure out the schema of it, this however doesn't mean # the UID is invalid pass self . _ensure_field ( 'ids' , [ ... | Set a unique ID . | 144 | 5 |
3,685 | def singleton ( klass ) : instances = { } def getinstance ( * args , * * kwargs ) : if klass not in instances : instances [ klass ] = klass ( * args , * * kwargs ) return instances [ klass ] return wraps ( klass ) ( getinstance ) | Create singleton from class | 67 | 5 |
3,686 | def translation_activate_block ( function = None , language = None ) : def _translation_activate_block ( function ) : def _decorator ( * args , * * kwargs ) : tmp_language = translation . get_language ( ) try : translation . activate ( language or settings . LANGUAGE_CODE ) return function ( * args , * * kwargs ) final... | Activate language only for one method or function | 127 | 9 |
3,687 | async def uv_protection_window ( self , low : float = 3.5 , high : float = 3.5 ) -> dict : return await self . request ( 'get' , 'protection' , params = { 'from' : str ( low ) , 'to' : str ( high ) } ) | Get data on when a UV protection window is . | 67 | 10 |
3,688 | def runstring ( self ) : cfile = self . template % self . last self . last += 1 return cfile | Return the run number and the file name . | 25 | 9 |
3,689 | def obsres_from_oblock_id ( self , obsid , configuration = None ) : este = self . ob_table [ obsid ] obsres = obsres_from_dict ( este ) _logger . debug ( "obsres_from_oblock_id id='%s', mode='%s' START" , obsid , obsres . mode ) try : this_drp = self . drps . query_by_name ( obsres . instrument ) except KeyError : rais... | Override instrument configuration if configuration is not None | 354 | 8 |
3,690 | def map_tree ( visitor , tree ) : newn = [ map_tree ( visitor , node ) for node in tree . nodes ] return visitor ( tree , newn ) | Apply function to nodes | 37 | 4 |
3,691 | def filter_tree ( condition , tree ) : if condition ( tree ) : for node in tree . nodes : # this works in python > 3.3 # yield from filter_tree(condition, node) for n in filter_tree ( condition , node ) : yield n yield tree | Return parts of the tree that fulfill condition | 59 | 8 |
3,692 | def fill_placeholders ( self , tags ) : def change_p_node_tags ( node , children ) : if isinstance ( node , Placeholder ) : value = ConstExpr ( tags [ node . name ] ) return value else : return node . clone ( children ) return map_tree ( change_p_node_tags , self ) | Substitute Placeholder nodes by its value in tags | 74 | 11 |
3,693 | def molecules2symbols ( molecules , add_hydrogen = True ) : symbols = sorted ( list ( set ( ase . symbols . string2symbols ( '' . join ( map ( lambda _x : '' . join ( ase . symbols . string2symbols ( _x ) ) , molecules ) ) ) ) ) , key = lambda _y : ase . data . atomic_numbers [ _y ] ) if add_hydrogen and 'H' not in sym... | Take a list of molecules and return just a list of atomic symbols possibly adding hydrogen | 118 | 16 |
3,694 | def construct_reference_system ( symbols , candidates = None , options = None , ) : if hasattr ( options , 'no_hydrogen' ) and options . no_hydrogen : add_hydrogen = False else : add_hydrogen = True references = { } sorted_candidates = [ 'H2' , 'H2O' , 'NH3' , 'N2' , 'CH4' , 'CO' , 'H2S' , 'HCl' , 'O2' ] if candidates ... | Take a list of symbols and construct gas phase references system when possible avoiding O2 . Candidates can be rearranged where earlier candidates get higher preference than later candidates | 530 | 32 |
3,695 | def get_stoichiometry_factors ( adsorbates , references ) : stoichiometry = get_atomic_stoichiometry ( references ) stoichiometry_factors = { } for adsorbate in adsorbates : for symbol in ase . symbols . string2symbols ( adsorbate ) : symbol_index = list ( map ( lambda _x : _x [ 0 ] , references ) ) . index ( symbol ) ... | Take a list of adsorabtes and a corresponding reference system and return a list of dictionaries encoding the stoichiometry factors converting between adsorbates and reference molecules . | 259 | 35 |
3,696 | def get_fields_dict ( self , row ) : return { k : getattr ( self , 'clean_{}' . format ( k ) , lambda x : x ) ( v . strip ( ) if isinstance ( v , str ) else None ) for k , v in zip_longest ( self . get_fields ( ) , row ) } | Returns a dict of field name and cleaned value pairs to initialize the model . Beware it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV . Whitespace around the value of the cell is stripped . | 75 | 51 |
3,697 | def process_node ( node ) : value = node [ 'value' ] mname = node [ 'name' ] typeid = node [ 'typeid' ] if typeid == 52 : # StructDataValue obj = { } for el in value [ 'elements' ] : key , val = process_node ( el ) obj [ key ] = val if value [ 'struct_type' ] != 'dict' : # Value is not a dict klass = objimp . import_ob... | Process a node in result . json structure | 315 | 8 |
3,698 | def build_result ( data ) : more = { } for key , value in data . items ( ) : if key != 'elements' : newnode = value else : newnode = { } for el in value : nkey , nvalue = process_node ( el ) newnode [ nkey ] = nvalue more [ key ] = newnode return more | Create a dictionary with the contents of result . json | 77 | 10 |
3,699 | def _finalize ( self , all_msg_errors = None ) : if all_msg_errors is None : all_msg_errors = [ ] for key in self . stored ( ) : try : getattr ( self , key ) except ( ValueError , TypeError ) as err : all_msg_errors . append ( err . args [ 0 ] ) # Raises a list of all the missing entries if all_msg_errors : raise Value... | Access all the instance descriptors | 104 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.