_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q44000
BuildFile.crossrefs
train
def crossrefs(self): """Returns a set of non-local targets referenced by this build file.""" # TODO: memoize this? crefs = set() for node in self.node: if node.repo != self.target.repo or node.path != self.target.path: crefs.add(node) return crefs
python
{ "resource": "" }
q44001
BuildFile.local_targets
train
def local_targets(self): """Iterator over the targets defined in this build file.""" for node in self.node: if (node.repo, node.path) == (self.target.repo, self.target.path): yield node
python
{ "resource": "" }
q44002
JsonBuildFile._parse
train
def _parse(self, stream): """Parse a JSON BUILD file. Args: builddata: dictionary of buildfile data reponame: name of the repo that it came from path: directory path within the repo """ builddata = json.load(stream) log.debug('This is a JSON build f...
python
{ "resource": "" }
q44003
Failure.from_exception
train
def from_exception(cls, exception, retain_exc_info=True, cause=None, find_cause=True): """Creates a failure object from a exception instance.""" exc_info = ( type(exception), exception, getattr(exception, '__traceback__', None) ) ...
python
{ "resource": "" }
q44004
Failure.validate
train
def validate(cls, data): """Validate input data matches expected failure ``dict`` format.""" try: jsonschema.validate( data, cls.SCHEMA, # See: https://github.com/Julian/jsonschema/issues/148 types={'array': (list, tuple)}) except jsons...
python
{ "resource": "" }
q44005
Failure.matches
train
def matches(self, other): """Checks if another object is equivalent to this object. :returns: checks if another object is equivalent to this object :rtype: boolean """ if not isinstance(other, Failure): return False if self.exc_info is None or other.exc_info ...
python
{ "resource": "" }
q44006
Failure.reraise_if_any
train
def reraise_if_any(failures, cause_cls_finder=None): """Re-raise exceptions if argument is not empty. If argument is empty list/tuple/iterator, this method returns None. If argument is converted into a list with a single ``Failure`` object in it, that failure is reraised. Else, a ...
python
{ "resource": "" }
q44007
Failure.check
train
def check(self, *exc_classes): """Check if any of ``exc_classes`` caused the failure. Arguments of this method can be exception types or type names (strings **fully qualified**). If captured exception is an instance of exception of given type, the corresponding argument is retur...
python
{ "resource": "" }
q44008
Failure.pformat
train
def pformat(self, traceback=False): """Pretty formats the failure object into a string.""" buf = six.StringIO() if not self._exc_type_names: buf.write('Failure: %s' % (self._exception_str)) else: buf.write('Failure: %s: %s' % (self._exc_type_names[0], ...
python
{ "resource": "" }
q44009
Failure.iter_causes
train
def iter_causes(self): """Iterate over all causes.""" curr = self._cause while curr is not None: yield curr curr = curr._cause
python
{ "resource": "" }
q44010
Failure.from_dict
train
def from_dict(cls, data): """Converts this from a dictionary to a object.""" data = dict(data) cause = data.get('cause') if cause is not None: data['cause'] = cls.from_dict(cause) return cls(**data)
python
{ "resource": "" }
q44011
Failure.to_dict
train
def to_dict(self, include_args=True, include_kwargs=True): """Converts this object to a dictionary. :param include_args: boolean indicating whether to include the exception args in the output. :param include_kwargs: boolean indicating whether to include the ...
python
{ "resource": "" }
q44012
explain_feature
train
def explain_feature(featurename): '''print the location of single feature and its version if the feature is located inside a git repository, this will also print the git-rev and modified files ''' import os import featuremonkey import importlib import subprocess def guess_version(...
python
{ "resource": "" }
q44013
explain_features
train
def explain_features(): '''print the location of each feature and its version if the feature is located inside a git repository, this will also print the git-rev and modified files ''' from ape import tasks import featuremonkey import os featurenames = featuremonkey.get_features_from_equat...
python
{ "resource": "" }
q44014
Version.imprint
train
def imprint(self, path=None): """Write the determined version, if any, to ``self.version_file`` or the path passed as an argument. """ if self.version is not None: with open(path or self.version_file, 'w') as h: h.write(self.version + '\n') else: ...
python
{ "resource": "" }
q44015
Version.from_file
train
def from_file(self, path=None): """Look for a version in ``self.version_file``, or in the specified path if supplied. """ if self._version is None: self._version = file_version(path or self.version_file) return self
python
{ "resource": "" }
q44016
Version.from_git
train
def from_git(self, path=None, prefer_daily=False): """Use Git to determine the package version. This routine uses the __file__ value of the caller to determine which Git repository root to use. """ if self._version is None: frame = caller(1) path = ...
python
{ "resource": "" }
q44017
Version.from_pkg
train
def from_pkg(self): """Use pkg_resources to determine the installed package version. """ if self._version is None: frame = caller(1) pkg = frame.f_globals.get('__package__') if pkg is not None: self._version = pkg_version(pkg) return se...
python
{ "resource": "" }
q44018
PeerContact.__load_dump
train
def __load_dump(self, message): """ Calls the hook method to modify the loaded peer description before giving it to the directory :param message: The received Herald message :return: The updated peer description """ dump = message.content if self._hook is...
python
{ "resource": "" }
q44019
PeerContact.herald_message
train
def herald_message(self, herald_svc, message): """ Handles a message received by Herald :param herald_svc: Herald service :param message: Received message """ subject = message.subject if subject == SUBJECT_DISCOVERY_STEP_1: # Step 1: Register the rem...
python
{ "resource": "" }
q44020
MailingListManager.api_url
train
def api_url(self): """Returns the api_url or None. """ if not self._api_url: error_msg = ( f"Email is enabled but API_URL is not set. " f"See settings.{self.api_url_attr}" ) try: self._api_url = getattr(settings,...
python
{ "resource": "" }
q44021
MailingListManager.api_key
train
def api_key(self): """Returns the api_key or None. """ if not self._api_key: error_msg = ( f"Email is enabled but API_KEY is not set. " f"See settings.{self.api_key_attr}" ) try: self._api_key = getattr(settings,...
python
{ "resource": "" }
q44022
MailingListManager.subscribe
train
def subscribe(self, user, verbose=None): """Returns a response after attempting to subscribe a member to the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") if not user.email: raise UserEmailError(f"User {user}...
python
{ "resource": "" }
q44023
MailingListManager.unsubscribe
train
def unsubscribe(self, user, verbose=None): """Returns a response after attempting to unsubscribe a member from the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") response = requests.put( f"{self.api_url}/{self...
python
{ "resource": "" }
q44024
MailingListManager.create
train
def create(self, verbose=None): """Returns a response after attempting to create the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") response = requests.post( self.api_url, auth=("api", self.api_key), ...
python
{ "resource": "" }
q44025
MailingListManager.delete
train
def delete(self): """Returns a response after attempting to delete the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") return requests.delete( f"{self.api_url}/{self.address}", auth=("api", self.api_key) )
python
{ "resource": "" }
q44026
MailingListManager.delete_member
train
def delete_member(self, user): """Returns a response after attempting to remove a member from the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") return requests.delete( f"{self.api_url}/{self.address}/members/...
python
{ "resource": "" }
q44027
Rolex._freq_parser
train
def _freq_parser(self, freq): """Parse timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() valid_keywords = [ "day...
python
{ "resource": "" }
q44028
Rolex.weekday_series
train
def weekday_series(self, start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, ...
python
{ "resource": "" }
q44029
Rolex._rnd_datetime
train
def _rnd_datetime(self, start, end): """Internal random datetime generator. """ return self.from_utctimestamp( random.randint( int(self.to_utctimestamp(start)), int(self.to_utctimestamp(end)), ) )
python
{ "resource": "" }
q44030
Rolex.add_minutes
train
def add_minutes(self, datetimestr, n): """Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ a_datetime = self.parse_datetime(dateti...
python
{ "resource": "" }
q44031
Rolex.add_hours
train
def add_hours(self, datetimestr, n): """Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ a_datetime = self.parse_datetime(datetimestr)...
python
{ "resource": "" }
q44032
Rolex.add_weeks
train
def add_weeks(self, datetimestr, n, return_date=False): """Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** ...
python
{ "resource": "" }
q44033
lint
train
def lint(ctx: click.Context, amend: bool = False, stage: bool = False): """ Runs all linters Args: ctx: click context amend: whether or not to commit results stage: whether or not to stage changes """ _lint(ctx, amend, stage)
python
{ "resource": "" }
q44034
_WaitingPost.callback
train
def callback(self, herald_svc, message): """ Tries to call the callback of the post message. Avoids errors to go outside this method. :param herald_svc: Herald service instance :param message: Received answer message """ if self.__callback is not None: ...
python
{ "resource": "" }
q44035
_WaitingPost.errback
train
def errback(self, herald_svc, exception): """ Tries to call the error callback of the post message. Avoids errors to go outside this method. :param herald_svc: Herald service instance :param exception: An exception describing/caused by the error """ if self.__err...
python
{ "resource": "" }
q44036
zpipe
train
def zpipe(ctx): """build inproc pipe for talking to threads mimic pipe used in czmq zthread_fork. Returns a pair of PAIRs connected via inproc """ a = ctx.socket(zmq.PAIR) a.linger = 0 b = ctx.socket(zmq.PAIR) b.linger = 0 socket_set_hwm(a, 1) socket_set_hwm(b, 1) iface = "...
python
{ "resource": "" }
q44037
get_country
train
def get_country(similar=False, **kwargs): """ Get a country for pycountry """ result_country = None try: if similar: for country in countries: if kwargs.get('name', '') in country.name: result_country = country break ...
python
{ "resource": "" }
q44038
get_location
train
def get_location(address=""): """ Retrieve location coordinates from an address introduced. """ coordinates = None try: geolocator = Nominatim() location = geolocator.geocode(address) coordinates = (location.latitude, location.longitude) except Exception as ex: lo...
python
{ "resource": "" }
q44039
get_address
train
def get_address(coords=None, **kwargs): """ Retrieve addres from a location in coords format introduced. """ address = None try: if (not coords) and \ ('latitude' in kwargs and 'longitude' in kwargs) or \ ('location' in kwargs): coords = kwargs.get( ...
python
{ "resource": "" }
q44040
Request.set_documents
train
def set_documents(self, documents, fully_formed=False): """ Wrap documents in the correct root tags, add id fields and convert them to xml strings. Args: documents -- If fully_formed is False (default), accepts dict where keys are document ids and values can be ether ...
python
{ "resource": "" }
q44041
Request.set_doc_ids
train
def set_doc_ids(self, doc_ids): """ Build xml documents from a list of document ids. Args: doc_ids -- A document id or a lost of those. """ if isinstance(doc_ids, list): self.set_documents(dict.fromkeys(doc_ids)) else: self.set_documen...
python
{ "resource": "" }
q44042
Request.add_property
train
def add_property(self, set_property, name, starting_value, tag_name=None): """ Set properies of atributes stored in content using stored common fdel and fget and given fset. Args: set_property -- Function that sets given property. name -- Name of the atribute this pr...
python
{ "resource": "" }
q44043
Request.set_query
train
def set_query(self, value): """ Convert a dict form of query in a string of needed and store the query string. Args: value -- A query string or a dict with query xpaths as keys and text or nested query dicts as values. """ if isinstance(value,...
python
{ "resource": "" }
q44044
Request.get_xml_request
train
def get_xml_request(self): """ Make xml request string from stored request information. Returns: A properly formated XMl request string containing all set request fields and wraped in connections envelope. """ def wrap_xml_content(xml_content): ...
python
{ "resource": "" }
q44045
Request.send
train
def send(self): """ Send an XML string version of content through the connection. Returns: Response object. """ xml_request = self.get_xml_request() if(self.connection._debug == 1): print(xml_request) Debug.warn('-' * 25) Debug.warn(self._...
python
{ "resource": "" }
q44046
format_duration
train
def format_duration(secs): """ Format a duration in seconds as minutes and seconds. """ secs = int(secs) if abs(secs) > 60: mins = abs(secs) / 60 secs = abs(secs) - (mins * 60) return '%s%im %02is' % ('-' if secs < 0 else '', mins, secs) return '%is' % secs
python
{ "resource": "" }
q44047
ClassificationTrainer.learn
train
def learn(self, numEpochs, batchsize): """Train the classifier for a given number of epochs, with a given batchsize""" for epoch in range(numEpochs): print('epoch %d' % epoch) indexes = np.random.permutation(self.trainsize) for i in range(0, self.trainsize, batchsize)...
python
{ "resource": "" }
q44048
ClassificationTrainer.evaluate
train
def evaluate(self, batchsize): """Evaluate how well the classifier is doing. Return mean loss and mean accuracy""" sum_loss, sum_accuracy = 0, 0 for i in range(0, self.testsize, batchsize): x = Variable(self.x_test[i: i + batchsize]) y = Variable(self.y_test[i: i + batchs...
python
{ "resource": "" }
q44049
ClassificationTrainer.save
train
def save(self, model_filename, optimizer_filename): """ Save the state of the model & optimizer to disk """ serializers.save_hdf5(model_filename, self.model) serializers.save_hdf5(optimizer_filename, self.optimizer)
python
{ "resource": "" }
q44050
Classifier.classify
train
def classify(self, phrase_vector): """ Run this over an input vector and see the result """ x = Variable(np.asarray([phrase_vector])) return self.model.predictor(x).data[0]
python
{ "resource": "" }
q44051
help
train
def help(route): r"""Displays help for the given route. Args: route (str): A route that resolves a member. """ help_text = getRouteHelp(route.split('/') if route else []) if help_text is None: err('Can\'t help :(') else: print '\n%s' % help_text
python
{ "resource": "" }
q44052
Base58Encoder.encode
train
def encode(data: Union[str, bytes]) -> str: """ Return Base58 string from data :param data: Bytes or string data """ return ensure_str(base58.b58encode(ensure_bytes(data)))
python
{ "resource": "" }
q44053
KDE.integrate_box
train
def integrate_box(self,low,high,forcequad=False,**kwargs): """Integrates over a box. Optionally force quad integration, even for non-adaptive. If adaptive mode is not being used, this will just call the `scipy.stats.gaussian_kde` method `integrate_box_1d`. Else, by default, it will cal...
python
{ "resource": "" }
q44054
PlugsMail.validate_context
train
def validate_context(self): """ Make sure there are no duplicate context objects or we might end up with switched data Converting the tuple to a set gets rid of the eventual duplicate objects, comparing the length of the original tuple and set tells us if we have...
python
{ "resource": "" }
q44055
PlugsMail.get_instance_of
train
def get_instance_of(self, model_cls): """ Search the data to find a instance of a model specified in the template """ for obj in self.data.values(): if isinstance(obj, model_cls): return obj LOGGER.error('Context Not Found') raise Excep...
python
{ "resource": "" }
q44056
PlugsMail.get_context
train
def get_context(self): """ Create a dict with the context data context is not required, but if it is defined it should be a tuple """ if not self.context: return else: assert isinstance(self.context, tuple), 'Expected a Tuple not {0}'.forma...
python
{ "resource": "" }
q44057
PlugsMail.get_context_data
train
def get_context_data(self): """ Context Data is equal to context + extra_context Merge the dicts context_data and extra_context and update state """ self.get_context() self.context_data.update(self.get_extra_context()) return self.context_data
python
{ "resource": "" }
q44058
PlugsMail.send
train
def send(self, to, language=None, **data): """ This is the method to be called """ self.data = data self.get_context_data() if app_settings['SEND_EMAILS']: try: if language: mail.send(to, template=self.template, context=self...
python
{ "resource": "" }
q44059
CreateAnAlertAPI.data
train
def data(self): """Parameters passed to the API containing the details to create a new alert. :return: parameters to create new alert. :rtype: dict """ data = {} data["name"] = self.name data["query"] = self.queryd data["languages"] = self.langua...
python
{ "resource": "" }
q44060
FetchMentionChildrenAPI.url
train
def url(self): """The concatenation of the `base_url` and `end_url` that make up the resultant url. :return: the `base_url` and the `end_url`. :rtype: str """ end_url = ("/accounts/{account_id}/alerts/{alert_id}/mentions/" "{mention_id}/children?") ...
python
{ "resource": "" }
q44061
CurateAMentionAPI.data
train
def data(self): """Parameters passed to the API containing the details to update a alert. :return: parameters to create new alert. :rtype: dict """ data = {} data["favorite"] = self.favorite if self.favorite else "" data["trashed"] = self.trashed if self...
python
{ "resource": "" }
q44062
call
train
def call(command, collect_missing=False, silent=True): r"""Calls a task, as if it were called from the command line. Args: command (str): A route followed by params (as if it were entered in the shell). collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to Fal...
python
{ "resource": "" }
q44063
add
train
def add(TargetGroup, NewMember, Config=None, Args=None): r"""Adds members to an existing group. Args: TargetGroup (Group): The target group for the addition. NewMember (Group / Task): The member to be added. Config (dict): The config for the member. Args (OrderedDict): ArgConfig for the NewMember, ...
python
{ "resource": "" }
q44064
do_check_pep8
train
def do_check_pep8(files, status): """ Run the python pep8 tool against the filst of supplied files. Append any linting errors to the returned status list Args: files (str): list of files to run pep8 against status (list): list of pre-receive check failures to eventually print ...
python
{ "resource": "" }
q44065
do_check
train
def do_check(func, files, status): """ Generic do_check helper method Args: func (function): Specific function to call files (list): list of files to run against status (list): list of pre-receive check failures to eventually print to the user Returns: ...
python
{ "resource": "" }
q44066
check_for_empty_defaults
train
def check_for_empty_defaults(status): """ Method to check for empty roles structure. When a role is created using ansible-galaxy it creates a default scaffolding structure. Best practice dictates that if any of these are not used then they should be removed. For example a bare main.yml with the ...
python
{ "resource": "" }
q44067
Revocation.from_inline
train
def from_inline(cls: Type[RevocationType], version: int, currency: str, inline: str) -> RevocationType: """ Return Revocation document instance from inline string Only self.pubkey is populated. You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods ...
python
{ "resource": "" }
q44068
Revocation.from_signed_raw
train
def from_signed_raw(cls: Type[RevocationType], signed_raw: str) -> RevocationType: """ Return Revocation document instance from a signed raw string :param signed_raw: raw document file in duniter format :return: """ lines = signed_raw.splitlines(True) n = 0 ...
python
{ "resource": "" }
q44069
Revocation.extract_self_cert
train
def extract_self_cert(signed_raw: str) -> Identity: """ Return self-certified Identity instance from the signed raw Revocation document :param signed_raw: Signed raw document string :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Rev...
python
{ "resource": "" }
q44070
Revocation.signed_raw
train
def signed_raw(self) -> str: """ Return Revocation signed raw document string :return: """ if not isinstance(self.identity, Identity): raise MalformedDocumentError("Can not return full revocation document created from inline") raw = self.raw() signed...
python
{ "resource": "" }
q44071
clean_text
train
def clean_text(text): """ Retrieve clean text without markdown sintax or other things. """ if text: text = html2text.html2text(clean_markdown(text)) return re.sub(r'\s+', ' ', text).strip()
python
{ "resource": "" }
q44072
clean_markdown
train
def clean_markdown(text): """ Parse markdown sintaxt to html. """ result = text if isinstance(text, str): result = ''.join( BeautifulSoup(markdown(text), 'lxml').findAll(text=True)) return result
python
{ "resource": "" }
q44073
select_regexp_char
train
def select_regexp_char(char): """ Select correct regex depending the char """ regexp = '{}'.format(char) if not isinstance(char, str) and not isinstance(char, int): regexp = '' if isinstance(char, str) and not char.isalpha() and not char.isdigit(): regexp = r"\{}".format(char) ...
python
{ "resource": "" }
q44074
exclude_chars
train
def exclude_chars(text, exclusion=None): """ Clean text string of simbols in exclusion list. """ exclusion = [] if exclusion is None else exclusion regexp = r"|".join([select_regexp_char(x) for x in exclusion]) or r'' return re.sub(regexp, '', text)
python
{ "resource": "" }
q44075
strip_accents
train
def strip_accents(text): """ Strip agents from a string. """ normalized_str = unicodedata.normalize('NFD', text) return ''.join([ c for c in normalized_str if unicodedata.category(c) != 'Mn'])
python
{ "resource": "" }
q44076
normalizer
train
def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char='-', **kwargs): """ Clean text string of simbols only alphanumeric chars. """ clean_str = re.sub(r'[^\w{}]'.format( "".join(exclusion)), separate_char, text.strip()) or '' clean_lowerbar = clean_str_without_accent...
python
{ "resource": "" }
q44077
normalize_dict
train
def normalize_dict(dictionary, **kwargs): """ Given an dict, normalize all of their keys using normalize function. """ result = {} if isinstance(dictionary, dict): keys = list(dictionary.keys()) for key in keys: result[normalizer(key, **kwargs)] = normalize_dict(dictionar...
python
{ "resource": "" }
q44078
pluralize
train
def pluralize(data_type): """ adds s to the data type or the correct english plural form """ known = { u"address": u"addresses", u"company": u"companies" } if data_type in known.keys(): return known[data_type] else: return u"%ss" % data_type
python
{ "resource": "" }
q44079
remove_properties_containing_None
train
def remove_properties_containing_None(properties_dict): """ removes keys from a dict those values == None json schema validation might fail if they are set and the type or format of the property does not match """ # remove empty properties - as validations may fail new_dict = dict() for...
python
{ "resource": "" }
q44080
dict_to_object
train
def dict_to_object(d): """Recursively converts a dict to an object""" top = type('CreateSendModel', (object,), d) seqs = tuple, list, set, frozenset for i, j in d.items(): if isinstance(j, dict): setattr(top, i, dict_to_object(j)) elif isinstance(j, seqs): setattr...
python
{ "resource": "" }
q44081
veq_samples
train
def veq_samples(R_dist,Prot_dist,N=1e4,alpha=0.23,l0=20,sigl=20): """Source for diff rot """ ls = stats.norm(l0,sigl).rvs(N) Prots = Prot_dist.rvs(N) Prots *= diff_Prot_factor(ls,alpha) return R_dist.rvs(N)*2*np.pi*RSUN/(Prots*DAY)/1e5
python
{ "resource": "" }
q44082
cleanup
train
def cleanup(): """Clean up the installation directory.""" lib_dir = os.path.join(os.environ['CONTAINER_DIR'], '_lib') if os.path.exists(lib_dir): shutil.rmtree(lib_dir) os.mkdir(lib_dir)
python
{ "resource": "" }
q44083
create_project_venv
train
def create_project_venv(): """ Create a project-level virtualenv. :raises: if virtualenv exists already :return: ``VirtualEnv`` object """ print('... creating project-level virtualenv') venv_dir = get_project_venv_dir() if os.path.exists(venv_dir): raise Exception('ERROR: virtu...
python
{ "resource": "" }
q44084
fetch_pool
train
def fetch_pool(repo_url, branch='master', reuse_existing=False): """Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object.""" repo_name = get_repo_name(repo_url) lib_dir = get_lib_dir() pool_dir = get_pool_dir(repo_name) print('... fetching %s ' % repo_name) if os.path.e...
python
{ "resource": "" }
q44085
noglobals
train
def noglobals(fn): """ decorator for functions that dont get access to globals """ return type(fn)( getattr(fn, 'func_code', getattr(fn, '__code__')), {'__builtins__': builtins}, getattr(fn, 'func_name', getattr(fn, '__name__')), getattr(fn, 'func_defaults', getattr(fn, '__defaul...
python
{ "resource": "" }
q44086
force_list
train
def force_list(element): """ Given an element or a list, concatenates every element and clean it to create a full text """ if element is None: return [] if isinstance(element, (collections.Iterator, list)): return element return [element]
python
{ "resource": "" }
q44087
flatten
train
def flatten(data, parent_key='', sep='_'): """ Transform dictionary multilevel values to one level dict, concatenating the keys with sep between them. """ items = [] if isinstance(data, list): logger.debug('Flattening list {}'.format(data)) list_keys = [str(i) for i in range(0, ...
python
{ "resource": "" }
q44088
nested_dict_to_list
train
def nested_dict_to_list(path, dic, exclusion=None): """ Transform nested dict to list """ result = [] exclusion = ['__self'] if exclusion is None else exclusion for key, value in dic.items(): if not any([exclude in key for exclude in exclusion]): if isinstance(value, dict):...
python
{ "resource": "" }
q44089
find_value_in_object
train
def find_value_in_object(attr, obj): """Return values for any key coincidence with attr in obj or any other nested dict. """ # Carry on inspecting inside the list or tuple if isinstance(obj, (collections.Iterator, list)): for item in obj: yield from find_value_in_object(attr, it...
python
{ "resource": "" }
q44090
dict2orderedlist
train
def dict2orderedlist(dic, order_list, default='', **kwargs): """ Return a list with dict values ordered by a list of key passed in args. """ result = [] for key_order in order_list: value = get_element(dic, key_order, **kwargs) result.append(value if value is not None else default) ...
python
{ "resource": "" }
q44091
get_dimension
train
def get_dimension(data): """ Get dimension of the data passed by argument independently if it's an arrays or dictionaries """ result = [0, 0] if isinstance(data, list): result = get_dimension_array(data) elif isinstance(data, dict): result = get_dimension_dict(data) re...
python
{ "resource": "" }
q44092
get_dimension_array
train
def get_dimension_array(array): """ Get dimension of an array getting the number of rows and the max num of columns. """ if all(isinstance(el, list) for el in array): result = [len(array), len(max([x for x in array], key=len,))] # elif array and isinstance(array, list): else: ...
python
{ "resource": "" }
q44093
get_ldict_keys
train
def get_ldict_keys(ldict, flatten_keys=False, **kwargs): """ Get first level keys from a list of dicts """ result = [] for ddict in ldict: if isinstance(ddict, dict): if flatten_keys: ddict = flatten(ddict, **kwargs) result.extend(ddict.keys()) r...
python
{ "resource": "" }
q44094
get_alldictkeys
train
def get_alldictkeys(ddict, parent=None): """ Get all keys in a dict """ parent = [] if parent is None else parent if not isinstance(ddict, dict): return [tuple(parent)] return reduce( list.__add__, [get_alldictkeys(v, parent + [k]) for k, v in ddict.items()], [])
python
{ "resource": "" }
q44095
clean_dictkeys
train
def clean_dictkeys(ddict, exclusions=None): """ Exclude chars in dict keys and return a clean dictionary. """ exclusions = [] if exclusions is None else exclusions if not isinstance(ddict, dict): return {} for key in list(ddict.keys()): if [incl for incl in exclusions if incl i...
python
{ "resource": "" }
q44096
authenticate
train
def authenticate(previous_token = None): """ Authenticate the client to the server """ # if we already have a session token, try to authenticate with it if previous_token != None: headers = server_connection.request("authenticate", { 'session_token' : previous_token, 'reposi...
python
{ "resource": "" }
q44097
find_local_changes
train
def find_local_changes(): """ Find things that have changed since the last run, applying ignore filters """ manifest = data_store.read_local_manifest() old_state = manifest['files'] current_state = get_file_list(config['data_dir']) current_state = [fle for fle in current_state if not ...
python
{ "resource": "" }
q44098
register_action
train
def register_action(action): """ Adds an action to the parser cli. :param action(BaseAction): a subclass of the BaseAction class """ sub = _subparsers.add_parser(action.meta('cmd'), help=action.meta('help')) sub.set_defaults(cmd=action.meta('cmd')) for (name, arg) in action.props().items(): sub.add_a...
python
{ "resource": "" }
q44099
run
train
def run(*args, **kwargs): """ Runs the parser and it executes the action handler with the provided arguments from the CLI. Also catches the BaseError interrupting the execution and showing the error message to the user. Default arguments comes from the cli args (sys.argv array) but we can force those argument...
python
{ "resource": "" }