_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q10800
Base.to_dict
train
def to_dict(self): """ Convert attributes and properties to a dict, so that it can be serialized. """ return {k: getattr(self, k) for k in filter( lambda k: not k.startswith('_') and k != 'to_dict', dir(self))}
python
{ "resource": "" }
q10801
_HtmlHeaderNode.to_dict
train
def to_dict(self): """Convert self to a dict object for serialization.""" return { 'level': self.level, 'id': self.id, 'text': self.text, 'inner_html': self.inner_html, 'children': [child.to_dict() for child in self.children] }
python
{ "resource": "" }
q10802
HtmlTocParser.toc
train
def toc(self, depth=6, lowest_level=6): """ Get table of content of currently fed HTML string. :param depth: the depth of TOC :param lowest_level: the allowed lowest level of header tag :return: a list representing the TOC """ depth = min(max(depth, 0), 6) ...
python
{ "resource": "" }
q10803
HtmlTocParser.toc_html
train
def toc_html(self, depth=6, lowest_level=6): """ Get TOC of currently fed HTML string in form of HTML string. :param depth: the depth of TOC :param lowest_level: the allowed lowest level of header tag :return: an HTML string """ toc = self.toc(depth=depth, lowest...
python
{ "resource": "" }
q10804
HtmlTocParser._get_level
train
def _get_level(tag): """ Match the header level in the given tag name, or None if it's not a header tag. """ m = re.match(r'^h([123456])$', tag, flags=re.IGNORECASE) if not m: return None return int(m.group(1))
python
{ "resource": "" }
q10805
MVisionProcess.requiredGPU_MB
train
def requiredGPU_MB(self, n): """Required GPU memory in MBytes """ from darknet.core import darknet_with_cuda if (darknet_with_cuda()): # its using cuda free = getFreeGPU_MB() print("Yolo: requiredGPU_MB: required, free", n, free) if (free == -1): # cou...
python
{ "resource": "" }
q10806
Inspect.typename
train
def typename(self): ''' get the type of val there are multiple places where we want to know if val is an object, or a string, or whatever, this method allows us to find out that information since -- 7-10-12 val -- mixed -- the value to check return -- string -...
python
{ "resource": "" }
q10807
Inspect.is_primitive
train
def is_primitive(self): """is the value a built-in type?""" if is_py2: return isinstance( self.val, ( types.NoneType, types.BooleanType, types.IntType, types.LongType, ...
python
{ "resource": "" }
q10808
Value._str_iterator
train
def _str_iterator(self, iterator, name_callback=None, prefix="\n", left_paren='[', right_paren=']', depth=0): ''' turn an iteratable value into a string representation iterator -- iterator -- the value to be iterated through name_callback -- callback -- if not None, a function that will...
python
{ "resource": "" }
q10809
ObjectValue._get_src_file
train
def _get_src_file(self, val, default='Unknown'): ''' return the source file path since -- 7-19-12 val -- mixed -- the value whose path you want return -- string -- the path, or something like 'Unknown' if you can't find the path ''' path = default try:...
python
{ "resource": "" }
q10810
handle_decode_replace
train
def handle_decode_replace(e): """this handles replacing bad characters when printing out http://www.programcreek.com/python/example/3643/codecs.register_error http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/codecs/index.html https://pymotw.com/2/codecs/ """ count = e.end - e.st...
python
{ "resource": "" }
q10811
MovementDetector.reset
train
def reset(self): """Reset analyzer state """ self.prevframe = None self.wasmoving = False self.t0 = 0 self.ismoving = False
python
{ "resource": "" }
q10812
rule
train
def rule(rules, strict_slashes=False, api_func=None, *args, **kwargs): """ Add a API route to the 'api' blueprint. :param rules: rule string or string list :param strict_slashes: same to Blueprint.route, but default value is False :param api_func: a function that returns a JSON serializable object ...
python
{ "resource": "" }
q10813
GPUHandler.findXScreens
train
def findXScreens(self): qapp = QtCore.QCoreApplication.instance() if not qapp: # QApplication has not been started return screens = qapp.screens() """ let's find out which screens are virtual screen, siblings: One big virtual desktop: ...
python
{ "resource": "" }
q10814
MyGui.generateMethods
train
def generateMethods(self): """Generate some member functions """ for i in range(1, 5): # adds member function grid_ixi_slot(self) self.make_grid_slot(i, i) for cl in self.mvision_classes: self.make_mvision_slot(cl)
python
{ "resource": "" }
q10815
MyGui.QCapsulate
train
def QCapsulate(self, widget, name, blocking = False, nude = False): """Helper function that encapsulates QWidget into a QMainWindow """ class QuickWindow(QtWidgets.QMainWindow): class Signals(QtCore.QObject): close = QtCore.Signal() show = QtCore.Si...
python
{ "resource": "" }
q10816
MyGui.make_grid_slot
train
def make_grid_slot(self, n, m): """Create a n x m video grid, show it and add it to the list of video containers """ def slot_func(): cont = container.VideoContainerNxM(gpu_handler=self.gpu_handler, filterchain_group=self.filtercha...
python
{ "resource": "" }
q10817
main_inject
train
def main_inject(args): """ mapped to pout.inject on the command line, makes it easy to make pout global without having to actually import it in your python environment .. since:: 2018-08-13 :param args: Namespace, the parsed CLI arguments passed into the application :returns: int, the return c...
python
{ "resource": "" }
q10818
main_info
train
def main_info(args): """Just prints out info about the pout installation .. since:: 2018-08-20 :param args: Namespace, the parsed CLI arguments passed into the application :returns: int, the return code of the CLI """ if args.site_packages: logger.info(SitePackagesDir()) else: ...
python
{ "resource": "" }
q10819
catch
train
def catch(func, *args, **kwargs): """ Call the supplied function with the supplied arguments, catching and returning any exception that it throws. Arguments: func: the function to run. *args: positional arguments to pass into the function. **kwargs: keyword arguments to pass int...
python
{ "resource": "" }
q10820
time
train
def time(func, *args, **kwargs): """ Call the supplied function with the supplied arguments, and return the total execution time as a float in seconds. The precision of the returned value depends on the precision of `time.time()` on your platform. Arguments: func: the function to run. ...
python
{ "resource": "" }
q10821
LmomDistrMixin.lmom_fit
train
def lmom_fit(self, data=[], lmom_ratios=[]): """ Fit the distribution function to the given data or given L-moments. :param data: Data to use in calculating the distribution parameters :type data: array_like :param lmom_ratios: L-moments (ratios) l1, l2, t3, t4, .. to use in cal...
python
{ "resource": "" }
q10822
run
train
def run(): """ Run all the test classes in the main module. Returns: exit code as an integer. The default behaviour (which may be overridden by plugins) is to return a 0 exit code if the test run succeeded, and 1 if it failed. """ plugin_list = load_plugins() module = sys.modul...
python
{ "resource": "" }
q10823
run_with_plugins
train
def run_with_plugins(plugin_list): """ Carry out a test run with the supplied list of plugin instances. The plugins are expected to identify the object to run. Parameters: plugin_list: a list of plugin instances (objects which implement some subset of PluginInterface) Returns: exit code as ...
python
{ "resource": "" }
q10824
lmom_ratios
train
def lmom_ratios(data, nmom=5): """ Estimate `nmom` number of L-moments from a sample `data`. :param data: Sequence of (sample) data :type data: list or array-like sequence :param nmom: number of L-moments to estimate :type nmom: int :return: L-moment ratios like this: l1, l2, t3, t4, t5, .....
python
{ "resource": "" }
q10825
POEditorAPI._apiv1_run
train
def _apiv1_run(self, action, headers=None, **kwargs): """ Kept for backwards compatibility of this client See "self.clear_reference_language" """ warnings.warn( "POEditor API v1 is deprecated. Use POEditorAPI._run method to call API v2", DeprecationWarning...
python
{ "resource": "" }
q10826
POEditorAPI.list_projects
train
def list_projects(self): """ Returns the list of projects owned by user. """ data = self._run( url_path="projects/list" ) projects = data['result'].get('projects', []) return [self._project_formatter(item) for item in projects]
python
{ "resource": "" }
q10827
POEditorAPI.view_project_details
train
def view_project_details(self, project_id): """ Returns project's details. """ data = self._run( url_path="projects/view", id=project_id ) return self._project_formatter(data['result']['project'])
python
{ "resource": "" }
q10828
POEditorAPI.add_language_to_project
train
def add_language_to_project(self, project_id, language_code): """ Adds a new language to project """ self._run( url_path="languages/add", id=project_id, language=language_code ) return True
python
{ "resource": "" }
q10829
POEditorAPI.update_terms
train
def update_terms(self, project_id, data, fuzzy_trigger=None): """ Updates project terms. Lets you change the text, context, reference, plural and tags. >>> data = [ { "term": "Add new list", "context": "", "new_term": "...
python
{ "resource": "" }
q10830
POEditorAPI.update_terms_translations
train
def update_terms_translations(self, project_id, file_path=None, language_code=None, overwrite=False, sync_terms=False, tags=None, fuzzy_trigger=None): """ Updates terms translations overwrite: set it to True if you want to overwr...
python
{ "resource": "" }
q10831
POEditorAPI.list_contributors
train
def list_contributors(self, project_id=None, language_code=None): """ Returns the list of contributors """ data = self._run( url_path="contributors/list", id=project_id, language=language_code ) return data['result'].get('contributors',...
python
{ "resource": "" }
q10832
POEditorAPI.remove_contributor
train
def remove_contributor(self, project_id, email, language): """ Removes a contributor """ self._run( url_path="contributors/remove", id=project_id, email=email, language=language ) return True
python
{ "resource": "" }
q10833
parse_stations
train
def parse_stations(html): """ Strips JS code, loads JSON """ html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '') html = json.loads(html) return html['suggestions']
python
{ "resource": "" }
q10834
parse_delay
train
def parse_delay(data): """ Prase the delay """ # parse data from the details view rsp = requests.get(data['details']) soup = BeautifulSoup(rsp.text, "html.parser") # get departure delay delay_departure_raw = soup.find('div', class_="routeStart").find('span', class_=["delay", "delayO...
python
{ "resource": "" }
q10835
calculate_delay
train
def calculate_delay(original, delay): """ Calculate the delay """ original = datetime.strptime(original, '%H:%M') delayed = datetime.strptime(delay, '%H:%M') diff = delayed - original return diff.total_seconds() // 60
python
{ "resource": "" }
q10836
Schiene.stations
train
def stations(self, station, limit=10): """ Find stations for given queries Args: station (str): search query limit (int): limit number of results """ query = { 'start': 1, 'S': station + '?', 'REQ0JourneyStopsB': limit ...
python
{ "resource": "" }
q10837
Schiene.connections
train
def connections(self, origin, destination, dt=datetime.now(), only_direct=False): """ Find connections between two stations Args: origin (str): origin station destination (str): destination station dt (datetime): date and time for query only_direc...
python
{ "resource": "" }
q10838
_scatter
train
def _scatter(sequence, n): """Scatters elements of ``sequence`` into ``n`` blocks.""" chunklen = int(math.ceil(float(len(sequence)) / float(n))) return [ sequence[ i*chunklen : (i+1)*chunklen ] for i in range(n) ]
python
{ "resource": "" }
q10839
SuperTaskQueue.purge
train
def purge(self): """Deletes all tasks in the queue.""" try: return self._api.purge() except AttributeError: while True: lst = self.list() if len(lst) == 0: break for task in lst: self.delete(task) self.wait() return self
python
{ "resource": "" }
q10840
TaskQueue.delete
train
def delete(self, task_id): """Deletes a task from a TaskQueue.""" if isinstance(task_id, RegisteredTask): task_id = task_id.id def cloud_delete(api): api.delete(task_id) if len(self._threads): self.put(cloud_delete) else: cloud_delete(self._api) return self
python
{ "resource": "" }
q10841
is_upload
train
def is_upload(action): """Checks if this should be a user upload :param action: :return: True if this is a file we intend to upload from the user """ return 'r' in action.type._mode and (action.default is None or getattr(action.default, 'name') not in (sys.s...
python
{ "resource": "" }
q10842
ArgParseNode.to_django
train
def to_django(self): """ This is a debug function to see what equivalent django models are being generated """ exclude = {'name', 'model'} field_module = 'models' django_kwargs = {} if self.node_attrs['model'] == 'CharField': django_kwargs['max_length...
python
{ "resource": "" }
q10843
str_dict_keys
train
def str_dict_keys(a_dict): """return a modified dict where all the keys that are anything but str get converted to str. E.g. >>> result = str_dict_keys({u'name': u'Peter', u'age': 99, 1: 2}) >>> # can't compare whole dicts in doctests >>> result['name'] u'Peter' >>> result['ag...
python
{ "resource": "" }
q10844
str_to_boolean
train
def str_to_boolean(input_str): """ a conversion function for boolean """ if not isinstance(input_str, six.string_types): raise ValueError(input_str) input_str = str_quote_stripper(input_str) return input_str.lower() in ("true", "t", "1", "y", "yes")
python
{ "resource": "" }
q10845
str_to_python_object
train
def str_to_python_object(input_str): """ a conversion that will import a module and class name """ if not input_str: return None if six.PY3 and isinstance(input_str, six.binary_type): input_str = to_str(input_str) if not isinstance(input_str, six.string_types): # gosh, we did...
python
{ "resource": "" }
q10846
str_to_classes_in_namespaces
train
def str_to_classes_in_namespaces( template_for_namespace="cls%d", name_of_class_option='cls', instantiate_classes=False ): """take a comma delimited list of class names, convert each class name into an actual class as an option within a numbered namespace. This function creates a closure over ...
python
{ "resource": "" }
q10847
str_to_list
train
def str_to_list( input_str, item_converter=lambda x: x, item_separator=',', list_to_collection_converter=None, ): """ a conversion function for list """ if not isinstance(input_str, six.string_types): raise ValueError(input_str) input_str = str_quote_stripper(input_str) resul...
python
{ "resource": "" }
q10848
arbitrary_object_to_string
train
def arbitrary_object_to_string(a_thing): """take a python object of some sort, and convert it into a human readable string. this function is used extensively to convert things like "subject" into "subject_key, function -> function_key, etc.""" # is it None? if a_thing is None: return '' ...
python
{ "resource": "" }
q10849
ConfigObjWithIncludes._expand_files
train
def _expand_files(self, file_name, original_path, indent=""): """This recursive function accepts a file name, opens the file and then spools the contents of the file into a list, examining each line as it does so. If it detects a line beginning with "+include", it assumes the string imm...
python
{ "resource": "" }
q10850
ConfigObjWithIncludes._load
train
def _load(self, infile, configspec): """this overrides the original ConfigObj method of the same name. It runs through the input file collecting lines into a list. When completed, this method submits the list of lines to the super class' function of the same name. ConfigObj proceeds, ...
python
{ "resource": "" }
q10851
ValueSource.get_values
train
def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict): """Return a nested dictionary representing the values in the ini file. In the case of this ValueSource implementation, both parameters are dummies.""" if self.delayed_parser_instantiation: try: ...
python
{ "resource": "" }
q10852
ValueSource._write_ini
train
def _write_ini(source_dict, namespace_name=None, level=0, indent_size=4, output_stream=sys.stdout): """this function prints the components of a configobj ini file. It is recursive for outputing the nested sections of the ini file.""" options = [ value ...
python
{ "resource": "" }
q10853
configuration
train
def configuration(*args, **kwargs): """this function just instantiates a ConfigurationManager and returns the configuration dictionary. It accepts all the same parameters as the constructor for the ConfigurationManager class.""" try: config_kwargs = {'mapping_class': kwargs.pop('mapping_class')...
python
{ "resource": "" }
q10854
iteritems_breadth_first
train
def iteritems_breadth_first(a_mapping, include_dicts=False): """a generator that returns all the keys in a set of nested Mapping instances. The keys take the form X.Y.Z""" subordinate_mappings = [] for key, value in six.iteritems(a_mapping): if isinstance(value, collections.Mapping): ...
python
{ "resource": "" }
q10855
DotDict.keys_breadth_first
train
def keys_breadth_first(self, include_dicts=False): """a generator that returns all the keys in a set of nested DotDict instances. The keys take the form X.Y.Z""" namespaces = [] for key in self._key_order: if isinstance(getattr(self, key), DotDict): namespace...
python
{ "resource": "" }
q10856
DotDict.assign
train
def assign(self, key, value): """an alternative method for assigning values to nested DotDict instances. It accepts keys in the form of X.Y.Z. If any nested DotDict instances don't yet exist, they will be created.""" key_split = key.split('.') cur_dict = self for k in k...
python
{ "resource": "" }
q10857
DotDict.parent
train
def parent(self, key): """when given a key of the form X.Y.Z, this method will return the parent DotDict of the 'Z' key.""" parent_key = '.'.join(key.split('.')[:-1]) if not parent_key: return None else: return self[parent_key]
python
{ "resource": "" }
q10858
Option.set_default
train
def set_default(self, val, force=False): """this function allows a default to be set on an option that dosen't have one. It is used when a base class defines an Option for use in derived classes but cannot predict what value would useful to the derived classes. This gives the derived c...
python
{ "resource": "" }
q10859
Option.copy
train
def copy(self): """return a copy""" o = Option( name=self.name, default=self.default, doc=self.doc, from_string_converter=self.from_string_converter, to_string_converter=self.to_string_converter, value=self.value, short_...
python
{ "resource": "" }
q10860
ConfigurationManager.context
train
def context(self, mapping_class=DotDictWithAcquisition): """return a config as a context that calls close on every item when it goes out of scope""" config = None try: config = self.get_config(mapping_class=mapping_class) yield config finally: ...
python
{ "resource": "" }
q10861
ConfigurationManager.output_summary
train
def output_summary(self, output_stream=sys.stdout): """outputs a usage tip and the list of acceptable commands. This is useful as the output of the 'help' option. parameters: output_stream - an open file-like object suitable for use as the target of a pri...
python
{ "resource": "" }
q10862
ConfigurationManager.write_conf
train
def write_conf(self, config_file_type, opener, skip_keys=None): """write a configuration file to a file-like object. parameters: config_file_type - a string containing a registered file type OR a for_XXX module from the value_source ...
python
{ "resource": "" }
q10863
ConfigurationManager.log_config
train
def log_config(self, logger): """write out the current configuration to a log-like object. parameters: logger - a object that implements a method called 'info' with the same semantics as the call to 'logger.info'""" logger.info("app_name: %s", self.app_name) ...
python
{ "resource": "" }
q10864
ConfigurationManager.get_option_names
train
def get_option_names(self): """returns a list of fully qualified option names. returns: a list of strings representing the Options in the source Namespace list. Each item will be fully qualified with dot delimited Namespace names. """ return [x for x...
python
{ "resource": "" }
q10865
ConfigurationManager._create_reference_value_options
train
def _create_reference_value_options(self, keys, finished_keys): """this method steps through the option definitions looking for alt paths. On finding one, it creates the 'reference_value_from' links within the option definitions and populates it with copied options.""" # a set of known ...
python
{ "resource": "" }
q10866
ConfigurationManager._overlay_expand
train
def _overlay_expand(self): """This method overlays each of the value sources onto the default in each of the defined options. It does so using a breadth first iteration, overlaying and expanding each level of the tree in turn. As soon as no changes were made to any level, the loop break...
python
{ "resource": "" }
q10867
ConfigurationManager._check_for_mismatches
train
def _check_for_mismatches(self, known_keys): """check for bad options from value sources""" for a_value_source in self.values_source_list: try: if a_value_source.always_ignore_mismatches: continue except AttributeError: # ok, th...
python
{ "resource": "" }
q10868
ConfigurationManager._generate_config
train
def _generate_config(self, mapping_class): """This routine generates a copy of the DotDict based config""" config = mapping_class() self._walk_config_copy_values( self.option_definitions, config, mapping_class ) return config
python
{ "resource": "" }
q10869
PGPooledTransaction.close
train
def close(self): """close all pooled connections""" print("PGPooledTransaction - shutting down connection pool") for name, conn in self.pool.iteritems(): conn.close() print("PGPooledTransaction - connection %s closed" % name)
python
{ "resource": "" }
q10870
find_action_name_by_value
train
def find_action_name_by_value(registry, target_action_instance): """the association of a name of an action class with a human readable string is exposed externally only at the time of argument definitions. This routine, when given a reference to argparse's internal action registry and an action, will fi...
python
{ "resource": "" }
q10871
get_args_and_values
train
def get_args_and_values(parser, an_action): """this rountine attempts to reconstruct the kwargs that were used in the creation of an action object""" args = inspect.getargspec(an_action.__class__.__init__).args kwargs = dict( (an_attr, getattr(an_action, an_attr)) for an_attr in args ...
python
{ "resource": "" }
q10872
SubparserFromStringConverter.add_namespace
train
def add_namespace(self, name, a_namespace): """as we build up argparse, the actions that define a subparser are translated into configman options. Each of those options must be tagged with the value of the subparse to which they correspond.""" # save a local copy of the namespace ...
python
{ "resource": "" }
q10873
ConfigmanSubParsersAction.add_parser
train
def add_parser(self, *args, **kwargs): """each time a subparser action is used to create a new parser object we must save the original args & kwargs. In a later phase of configman, we'll need to reproduce the subparsers exactly without resorting to copying. We save the args & kwargs in...
python
{ "resource": "" }
q10874
ArgumentParser.get_required_config
train
def get_required_config(self): """because of the exsistance of subparsers, the configman options that correspond with argparse arguments are not a constant. We need to produce a copy of the namespace rather than the actual embedded namespace.""" required_config = Namespace() ...
python
{ "resource": "" }
q10875
ArgumentParser.add_subparsers
train
def add_subparsers(self, *args, **kwargs): """When adding a subparser, we need to ensure that our version of the SubparserAction object is returned. We also need to create the corresponding configman Option object for the subparser and pack it's foreign data section with the original ar...
python
{ "resource": "" }
q10876
sequence_to_string
train
def sequence_to_string( a_list, open_bracket_char='[', close_bracket_char=']', delimiter=", " ): """a dedicated function that turns a list into a comma delimited string of items converted. This method will flatten nested lists.""" return "%s%s%s" % ( open_bracket_char, delim...
python
{ "resource": "" }
q10877
ValueSource.get_values
train
def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict): """This is the black sheep of the crowd of ValueSource implementations. It needs to know ahead of time all of the parameters that it will need, but we cannot give it. We may not know all the parameters because no...
python
{ "resource": "" }
q10878
ChemometricsPLS_LDA._cummulativefit
train
def _cummulativefit(self, x, y): """ Measure the cumulative Regression sum of Squares for each individual component. :param x: Data matrix to fit the PLS model. :type x: numpy.ndarray, shape [n_samples, n_features] :param y: Data matrix to fit the PLS model. :type y: num...
python
{ "resource": "" }
q10879
_handle_zeros_in_scale
train
def _handle_zeros_in_scale(scale, copy=True): """ Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features. """ # if we are fitting on 1D arrays, scale might be a scalar if numpy.isscalar(scale): if scale == .0: ...
python
{ "resource": "" }
q10880
ChemometricsScaler.fit
train
def fit(self, X, y=None): """ Compute the mean and standard deviation from a dataset to use in future scaling operations. :param X: Data matrix to scale. :type X: numpy.ndarray, shape [n_samples, n_features] :param y: Passthrough for Scikit-learn ``Pipeline`` compatibility. ...
python
{ "resource": "" }
q10881
ChemometricsScaler.partial_fit
train
def partial_fit(self, X, y=None): """ Performs online computation of mean and standard deviation on X for later scaling. All of X is processed as a single batch. This is intended for cases when `fit` is not feasible due to very large number of `n_samples` or because X is ...
python
{ "resource": "" }
q10882
ChemometricsScaler.transform
train
def transform(self, X, y=None, copy=None): """ Perform standardization by centering and scaling using the parameters. :param X: Data matrix to scale. :type X: numpy.ndarray, shape [n_samples, n_features] :param y: Passthrough for scikit-learn ``Pipeline`` compatibility. ...
python
{ "resource": "" }
q10883
ChemometricsScaler.inverse_transform
train
def inverse_transform(self, X, copy=None): """ Scale back the data to the original representation. :param X: Scaled data matrix. :type X: numpy.ndarray, shape [n_samples, n_features] :param bool copy: Copy the X data matrix. :return: X data matrix with the scaling operat...
python
{ "resource": "" }
q10884
_recurse_replace
train
def _recurse_replace(obj, key, new_key, sub, remove): """Recursive helper for `replace_by_key`""" if isinstance(obj, list): return [_recurse_replace(x, key, new_key, sub, remove) for x in obj] if isinstance(obj, dict): for k, v in list(obj.items()): if k == key and v in sub: ...
python
{ "resource": "" }
q10885
replace_by_key
train
def replace_by_key(pif, key, subs, new_key=None, remove=False): """Replace values that match a key Deeply traverses the pif object, looking for `key` and replacing values in accordance with `subs`. If `new_key` is set, the replaced values are assigned to that key. If `remove` is `True`, the old `...
python
{ "resource": "" }
q10886
new_keypair
train
def new_keypair(key, value, ambig, unambig): """ Check new keypair against existing unambiguous dict :param key: of pair :param value: of pair :param ambig: set of keys with ambig decoding :param unambig: set of keys with unambig decoding :return: """ if key in ambig: return...
python
{ "resource": "" }
q10887
add_child_ambig
train
def add_child_ambig(child_ambig, child_unambig, ambig, unambig): """ Add information about decodings of a child object :param child_ambig: ambiguous set from child :param child_unambig: unambiguous set from child :param ambig: set of keys storing ambig decodings :param unambig: dictionary stori...
python
{ "resource": "" }
q10888
get_client
train
def get_client(site=None): """Get a citrination client""" if 'CITRINATION_API_KEY' not in environ: raise ValueError("'CITRINATION_API_KEY' is not set as an environment variable") if not site: site = environ.get("CITRINATION_SITE", "https://citrination.com") return CitrinationClient(envir...
python
{ "resource": "" }
q10889
calculate_ideal_atomic_percent
train
def calculate_ideal_atomic_percent(pif): """ Calculates ideal atomic percents from a chemical formula string from a pif. Returns an appended pif with composition elements modified or added. :param pif: a ChemicalSystem pif :return: modified pif object """ if not isinstance(pif, ChemicalSystem):...
python
{ "resource": "" }
q10890
calculate_ideal_weight_percent
train
def calculate_ideal_weight_percent(pif): """ Calculates ideal atomic weight percents from a chemical formula string from a pif. Returns an appended pif with composition elements modified or added. :param pif: a ChemicalSystem pif :return: modified pif object """ if not isinstance(pif, ChemicalS...
python
{ "resource": "" }
q10891
_expand_hydrate_
train
def _expand_hydrate_(hydrate_pos, formula_string): """ Handles the expansion of hydrate portions of a chemical formula, and expands out the coefficent to all elements :param hydrate_pos: the index in the formula_string of the · symbol :param formula_string: the unexpanded formula string :return: a ...
python
{ "resource": "" }
q10892
_create_compositional_array_
train
def _create_compositional_array_(expanded_chemical_formaula_string): """ Splits an expanded chemical formula string into an array of dictionaries containing information about each element :param expanded_chemical_formaula_string: a clean (not necessarily emperical, but without any special characters) chemi...
python
{ "resource": "" }
q10893
_add_ideal_atomic_weights_
train
def _add_ideal_atomic_weights_(elemental_array): """ Uses elements.json to find the molar mass of the element in question, and then multiplies that by the occurances of the element. Adds the "weight" property to each of the dictionaries in elemental_array :param elemental_array: an array of dictionarie...
python
{ "resource": "" }
q10894
_add_ideal_weight_percent_
train
def _add_ideal_weight_percent_(elemental_array): """ Adds the "weight_percent" property to each of the dictionaries in elemental_array :param elemental_array: an array of dictionaries containing information about the elements in the system :return: the appended elemental_array """ t_mass = _cal...
python
{ "resource": "" }
q10895
_get_element_in_pif_composition_
train
def _get_element_in_pif_composition_(pif, elemental_symbol): """ If the element in question if in the composition array in the pif, it returns that Composition object and the position in the composition array otherwise it returns False :param pif: ChemicalSystem Pif in question :param elemental_symbol:...
python
{ "resource": "" }
q10896
parse_name_string
train
def parse_name_string(full_name): """ Parse a full name into a Name object :param full_name: e.g. "John Smith" or "Smith, John" :return: Name object """ name = Name() if "," in full_name: toks = full_name.split(",") name.family = toks[0] name.given = ",".join(toks[1:...
python
{ "resource": "" }
q10897
query_to_mdf_records
train
def query_to_mdf_records(query=None, dataset_id=None, mdf_acl=None): """Evaluate a query and return a list of MDF records If a datasetID is specified by there is no query, a simple whole dataset query is formed for the user """ if not query and not dataset_id: raise ValueError("Either query...
python
{ "resource": "" }
q10898
pif_to_mdf_record
train
def pif_to_mdf_record(pif_obj, dataset_hit, mdf_acl): """Convert a PIF into partial MDF record""" res = {} res["mdf"] = _to_meta_data(pif_obj, dataset_hit, mdf_acl) res[res["mdf"]["source_name"]] = _to_user_defined(pif_obj) return dumps(res)
python
{ "resource": "" }
q10899
_to_user_defined
train
def _to_user_defined(pif_obj): """Read the systems in the PIF to populate the user-defined portion""" res = {} # make a read view to flatten the hierarchy rv = ReadView(pif_obj) # Iterate over the keys in the read view for k in rv.keys(): name, value = _extract_key_value(rv[k].raw) ...
python
{ "resource": "" }