Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
355,000
def touch(path): with open(path, ) as f: os.utime(path, None) f.close()
Creates a file located at the given path.
355,001
def extend(self, items): print(.join(items)) super(MyList, self).extend(items)
extend items and print them to stdout using the new line separator
355,002
def _with_error_handling(resp, error, mode, response_format): def safe_parse(r): try: return APIWrapper._parse_resp(r, response_format) except (ValueError, SyntaxError) as ex: log.error(ex) r.parsed = None return r ...
Static method for error handling. :param resp - API response :param error - Error thrown :param mode - Error mode :param response_format - XML or json
355,003
def named_module(name): module = __import__(name) packages = name.split(".")[1:] m = module for p in packages: m = getattr(m, p) return m
Returns a module given its name.
355,004
def value2json(obj, pretty=False, sort_keys=False, keep_whitespace=True): if FIND_LOOPS: obj = scrub(obj, scrub_text=_keep_whitespace if keep_whitespace else _trim_whitespace()) try: json = json_encoder(obj, pretty=pretty) if json == None: Log.note(str(type(obj)) + " is ...
:param obj: THE VALUE TO TURN INTO JSON :param pretty: True TO MAKE A MULTI-LINE PRETTY VERSION :param sort_keys: True TO SORT KEYS :param keep_whitespace: False TO strip() THE WHITESPACE IN THE VALUES :return:
355,005
def receive_messages_from_queue(self, wait_time=15, num_messages=1): return self.queue.receive_messages(MaxNumberOfMessages=num_messages, WaitTimeSeconds=wait_time)
Returns the first (according to FIFO) element in the queue; if none, then returns None.
355,006
def logp_gradient_of_set(variable_set, calculation_set=None): logp_gradients = {} for variable in variable_set: logp_gradients[variable] = logp_gradient(variable, calculation_set) return logp_gradients
Calculates the gradient of the joint log posterior with respect to all the variables in variable_set. Calculation of the log posterior is restricted to the variables in calculation_set. Returns a dictionary of the gradients.
355,007
def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]: string_linking_scores: Dict[str, List[int]] = defaultdict(list) for index, token in enumerate(tokenized_utterance): for string in ATIS_TRIGGER_DICT.get(token.text.lower(), []): string_linking_scor...
Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to.
355,008
def _compute_finite_fault_correction(self, mag): mw_j96 = mblg_to_mw_johnston_96(mag) mw_ab87 = mblg_to_mw_atkinson_boore_87(mag) t1 = np.exp(-1.25 + 0.227 * mw_j96) t2 = np.exp(-1.25 + 0.227 * mw_ab87) return np.sqrt(t1 * t2)
Compute finite fault correction term as geometric mean of correction terms obtained from Mw values calculated with Johnston 1996 and Atkinson and Boore 1987 conversion equations. Implement equations as in lines 1653 - 1658 in hazgridXnga2.f
355,009
def send_pending_requests(self): try: with self._lock: if not self._can_send_recv(): return Errors.NodeNotReadyError(str(self)) data = self._protocol.send_bytes() total_byt...
Can block on network if request is larger than send_buffer_bytes
355,010
def find_tags_from_xml( self, xml_name, tag_name, **attribute_filter ): xml = self.xml[xml_name] if xml is None: return [] if xml.tag == tag_name: if self.is_tag_matched( xml.tag, **attribute_filter ): retur...
Return a list of all the matched tags in a specific xml w :param str xml_name: specify from which xml to pick the tag from :param str tag_name: specify the tag name
355,011
def preprocess_plain_text_string(self, text, pmid, extra_annotations): output_file = % self.next_file_id output_file = os.path.join(self.preprocessed_dir, output_file) sentences = nltk.sent_tokenize(text) first_sentence = True with codecs.open(output...
Preprocess plain text string for use by ISI reader. Preprocessing is done by tokenizing into sentences and writing each sentence on its own line in a plain text file. All other preprocessing functions ultimately call this one. Parameters ---------- text : str ...
355,012
def deserialize(stream_or_string, **options): try: if not isinstance(stream_or_string, (bytes, six.string_types)): return toml.load(stream_or_string, **options) if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode() return toml.lo...
Deserialize from TOML into Python data structure. :param stream_or_string: toml stream or string to deserialize. :param options: options given to lower pytoml module.
355,013
def _uri_to_etext(cls, uri_ref): try: return validate_etextno(int(os.path.basename(uri_ref.toPython()))) except InvalidEtextIdException: return None
Converts the representation used to identify a text in the meta-data RDF graph to a human-friendly integer text identifier.
355,014
def compose(self, *args, **kwargs): linebreak = kwargs.pop("linebreak", "\n") if len(args) > 0: self.args = args self._update(**kwargs) fkwargs = {} modtmpl = [] for line in self: cline = ...
Generate a file from the current template and given arguments. Warning: Make certain to check the formatted editor for correctness! Args: args: Positional arguments to update the template kwargs: Keyword arguments to update the template Returns: ...
355,015
def add_timestamp(logger_class, log_method, event_dict): event_dict[] = calendar.timegm(time.gmtime()) return event_dict
Attach the event time, as unix epoch
355,016
def _syscall(self, command, input=None, env=None, *params): return Popen([command] + list(params), stdout=PIPE, stdin=PIPE, stderr=STDOUT, env=env or os.environ).communicate(input=input)
Call an external system command.
355,017
def get_banks_by_item(self, item_id): mgr = self._get_provider_manager(, local=True) lookup_session = mgr.get_bank_lookup_session(proxy=self._proxy) return lookup_session.get_banks_by_ids( self.get_bank_ids_by_item(item_id))
Gets the list of ``Banks`` mapped to an ``Item``. arg: item_id (osid.id.Id): ``Id`` of an ``Item`` return: (osid.assessment.BankList) - list of banks raise: NotFound - ``item_id`` is not found raise: NullArgument - ``item_id`` is ``null`` raise: OperationFailed - unable to...
355,018
def _writable_dir(path): return os.path.isdir(path) and os.access(path, os.W_OK)
Whether `path` is a directory, to which the user has write access.
355,019
def engines(opts, functions, runners, utils, proxy=None): pack = {: functions, : runners, : proxy, : utils} return LazyLoader( _module_dirs(opts, ), opts, tag=, pack=pack, )
Return the master services plugins
355,020
def setDefaultIREncoding(encoding): try: b.decode(encoding) except: raise ValueError( %(str(encoding), )) global defaultIREncoding defaultIREncoding = encoding
setDefaultIREncoding - Sets the default encoding used by IndexedRedis. This will be the default encoding used for field data. You can override this on a per-field basis by using an IRField (such as IRUnicodeField or IRRawField) @param encoding - An encoding (like utf-8)
355,021
def process_messages_loop_internal(self): while self.receiving_messages: self.work_request = None self.connection.receive_loop_with_callback(self.queue_name, self.save_work_request_and_close) if self.work_request: self.process_work_reques...
Busy loop that processes incoming WorkRequest messages via functions specified by add_command. Disconnects while servicing a message, reconnects once finished processing a message Terminates if a command runs shutdown method
355,022
def to_image(self, digest, blob, mime_type, index, size=500): if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" converted = self.cache.get(cache_key) if converted: return converted for hand...
Convert a file to a list of images. Returns image at the given index.
355,023
def remove(name=None, pkgs=None, jail=None, chroot=None, root=None, all_installed=False, force=False, glob=False, dryrun=False, recurse=False, regex=False, pcre=False, **kwargs): *****...
Remove a package from the database and system .. note:: This function can accessed using ``pkg.delete`` in addition to ``pkg.remove``, to more closely match the CLI usage of ``pkg(8)``. name The package to remove CLI Example: .. code-block:: bash salt '*...
355,024
def add_pythonpath(path): pythonpath = os.environ.setdefault(, ) if path not in pythonpath.split(os.pathsep): pythonpath = os.environ[] = \ (path + os.pathsep + pythonpath) if pythonpath else path return pythonpath
Prepend given path to environment variable PYTHONPATH. :param path: Path to add to PYTHONPATH. :return: New PYTHONPATH value.
355,025
def timedelta_range(start=None, end=None, periods=None, freq=None, name=None, closed=None): if freq is None and com._any_none(periods, start, end): freq = freq, freq_infer = dtl.maybe_infer_freq(freq) tdarr = TimedeltaArray._generate_range(start, end, periods, freq, ...
Return a fixed frequency TimedeltaIndex, with day as the default frequency Parameters ---------- start : string or timedelta-like, default None Left bound for generating timedeltas end : string or timedelta-like, default None Right bound for generating timedeltas periods : integ...
355,026
def deploy_branch_exists(deploy_branch): remote_name = branch_names = subprocess.check_output([, , ]).decode().split() return .format(remote_name, deploy_branch) in branch_names
Check if there is a remote branch with name specified in ``deploy_branch``. Note that default ``deploy_branch`` is ``gh-pages`` for regular repos and ``master`` for ``github.io`` repos. This isn't completely robust. If there are multiple remotes and you have a ``deploy_branch`` branch on the non-defau...
355,027
def amplitude_by_fft(self, data_frame): signal_length = len(data_frame.filtered_signal) normalised_transformed_signal = data_frame.transformed_signal.values / signal_length k = np.arange(signal_length) T = signal_length / self.sampling_frequency f = k / T f =...
This methods extract the fft components and sum the ones from lower to upper freq as per \ :cite:`Kassavetis2015` :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ampl: the ampl :rtype ampl: float :return freq: the freq...
355,028
def _get_center(self): w, h = self.layout.get_pixel_size() x = (self.x + w / 2) y = (self.y + h / 2) return x, y
Returns the center point of the path, disregarding transforms.
355,029
def _mb_model(self, beta, mini_batch): Y = np.array(self.data[self.max_lag:]) sample = np.random.choice(len(Y), mini_batch, replace=False) Y = Y[sample] X = self.X[:, sample] z = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k i...
Creates the structure of the model (model matrices etc) for mini batch model Parameters ---------- beta : np.ndarray Contains untransformed starting values for the latent variables mini_batch : int Mini batch size for the data sampling Returns -...
355,030
def play(self, uri=None): if uri: self.av_transport.SetAVTransportURI( InstanceID=1, CurrentURI=uri, CurrentURIMetaData="") else: self.av_transport.Play(InstanceID=1, Speed=2)
Start playing :param uri: (optional) play a specific uri
355,031
def addFeatureSA(self, callback, default=None, name=None): if name is None: featureName = callback.__name__ else: featureName = name featureValues = callback(self) setattr(self, "_%s_values" % featureName, featureValues) setattr(self, "%s_default...
Add a feature to the suffix array. The callback must return a sequence such that the feature at position i is attached to the suffix referenced by self.SA[i]. It is called with one argument: the instance of SuffixArray self. The callback may traverse self.SA in any fashion. ...
355,032
def detect_control_flow(self, offset, op, extended_arg): code = self.code parent = self.structs[0] start = parent[] end = parent[] for struct in self.structs: current_start = struct[] current_end = struct[] i...
Detect type of block structures and their boundaries to fix optimized jumps in python2.3+
355,033
def create_subject_access_review(self, body, **kwargs): kwargs[] = True if kwargs.get(): return self.create_subject_access_review_with_http_info(body, **kwargs) else: (data) = self.create_subject_access_review_with_http_info(body, **kwargs) return dat...
create a SubjectAccessReview This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_subject_access_review(body, async_req=True) >>> result = thread.get() :param async_req bool :par...
355,034
def make_replacement_visitor(find_expression, replace_expression): def visitor_fn(expression): if expression == find_expression: return replace_expression else: return expression return visitor_fn
Return a visitor function that replaces every instance of one expression with another one.
355,035
def walknset_vars(self, task_class=None, *args, **kwargs): def change_task(task): if task_class is not None and task.__class__ is not task_class: return False return True if self.is_work: for task in self: if not change_task(task): continue ...
Set the values of the ABINIT variables in the input files of the nodes Args: task_class: If not None, only the input files of the tasks belonging to class `task_class` are modified. Example: flow.walknset_vars(ecut=10, kptopt=4)
355,036
def performAction(self, action): self.t += 1 Task.performAction(self, action) self.samples += 1
Execute one action.
355,037
def cli(*args, **kwargs): content = convert.convert(kwargs["input_file"], **kwargs) if kwargs["serve"]: convert.serve(content) elif kwargs["output_file"]: if (not kwargs["overwrite"] and not prompt_overwrite(kwargs["output_file"])): r...
CSVtoTable commandline utility.
355,038
def get_milestones(session, project_ids=[], milestone_ids=[], user_details=None, limit=10, offset=0): get_milestones_data = {} if milestone_ids: get_milestones_data[] = milestone_ids if project_ids: get_milestones_data[] = project_ids get_milestones_data[] = limit get_milestones...
Get the list of milestones
355,039
def change_encryption(self, current_password, cipher, new_password, new_password_id): if not isinstance(current_password, basestring): raise TypeError("current_password can only be an instance of type basestring") if not isinstance(cipher, basestring): raise TypeError("c...
Starts encryption of this medium. This means that the stored data in the medium is encrypted. This medium will be placed to :py:attr:`MediumState.locked_write` state. Please note that the results can be either returned straight away, or later as the result of t...
355,040
def getProcessDatabase(self): info_dict = {} cur = self._conn.cursor() cur.execute() rows = cur.fetchall() if rows: for row in rows: db = row[3] info_dict[db] = info_dict.get(db, 0) + 1 return info_dict
Returns number of processes discriminated by database name. @return: Dictionary mapping database name to number of processes.
355,041
def _prefix_from_prefix_string(self, prefixlen_str): try: if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): raise ValueError prefixlen = int(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): raise ValueError ...
Turn a prefix length string into an integer. Args: prefixlen_str: A decimal string containing the prefix length. Returns: The prefix length as an integer. Raises: NetmaskValueError: If the input is malformed or out of range.
355,042
def get_market_tops(symbols=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_market_tops", "iexdata.get_tops")) return TOPS(symbols, **kwargs).fetch()
MOVED to iexfinance.iexdata.get_tops
355,043
def wrap_get_user(cls, response): json = response.json() u = cls.wrap_json(json) return u
Wrap the response from getting a user into an instance and return it :param response: The response from getting a user :type response: :class:`requests.Response` :returns: the new user instance :rtype: :class:`list` of :class:`User` :raises: None
355,044
def hmget(self, key, field, *fields, encoding=_NOTSET): return self.execute(b, key, field, *fields, encoding=encoding)
Get the values of all the given fields.
355,045
def dynamic_part_name(raml_resource, route_name, pk_field): subresources = get_resource_children(raml_resource) dynamic_uris = [res.path for res in subresources if is_dynamic_uri(res.path)] if dynamic_uris: dynamic_part = extract_dynamic_part(dynamic_uris[0]) else: ...
Generate a dynamic part for a resource :raml_resource:. A dynamic part is generated using 2 parts: :route_name: of the resource and the dynamic part of first dynamic child resources. If :raml_resource: has no dynamic child resources, 'id' is used as the 2nd part. E.g. if your dynamic part on route ...
355,046
def pop(self, timeout=0): pipe = self.server.pipeline() pipe.multi() pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0) results, count = pipe.execute() if results: return self._decode_request(results[0])
Pop a request timeout not support in this queue class
355,047
def _get_sk(**kwargs): config = _get_config(**kwargs) key = salt.utils.stringutils.to_str(config[]) sk_file = config[] if not key and sk_file: with salt.utils.files.fopen(sk_file, ) as keyf: key = salt.utils.stringutils.to_unicode(keyf.read()).rstrip() if key is None: ...
Return sk
355,048
def jrepr(value): if value is None: return repr(value) t = type(value) if t.__repr__ is not object.__repr__: return repr(value) return + t.__name__
customized `repr()`.
355,049
def __post_save_receiver(self, instance, **kwargs): logger.debug(, instance.__class__) self.save_record(instance, **kwargs)
Signal handler for when a registered model has been saved.
355,050
def guard(ctx, opts=""): return test(ctx, include_slow=True, loop_on_fail=True, opts=opts)
Execute all tests and then watch for changes, re-running.
355,051
def add_it(workbench, file_list, labels): md5s = [] for filename in file_list: if filename != : with open(filename, ) as pe_file: base_name = os.path.basename(filename) md5 = workbench.store_sample(pe_file.read(), base_name, ) workbench.ad...
Add the given file_list to workbench as samples, also add them as nodes. Args: workbench: Instance of Workbench Client. file_list: list of files. labels: labels for the nodes. Returns: A list of md5s.
355,052
def tune(runner, kernel_options, device_options, tuning_options): results = [] cache = {} method = tuning_options.method tuning_options["scaling"] = True bounds, x0, _ = get_bounds_x0_eps(tuning_options) kwargs = setup_method_arguments(method, bounds) options = setup_method_opt...
Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: kernel_tuner.interface.Options :param device_options...
355,053
def searchTag(self,HTAG=" self.t = Twython(app_key =self.app_key , app_secret =self.app_secret , oauth_token =self.oauth_token , oauth_token_secret =self.oauth_token_secret) ...
Set Twitter search or stream criteria for the selection of tweets
355,054
def set_labels(self, subj_labels): if len(subj_labels) != self.n_subjs: raise ValueError() self.labels = subj_labels
Parameters ---------- subj_labels: list of int or str This list will be checked to have the same size as files list (self.items)
355,055
def prepare_headers(self, headers, cache_info=None): if self.use_advanced and cache_info: hkeys = headers.keys() if cache_info.access_time and "If-Modified-Since" not in hkeys: headers[] = cache_info.access_time.strftime( "%a, %d %b %Y %H:%M:%...
Prepare headers object for request (add cache information :param headers: Headers object :type headers: dict :param cache_info: Cache information to add :type cache_info: floscraper.models.CacheInfo :return: Prepared headers :rtype: dict
355,056
def get_definition(self, project, definition_id, revision=None, min_metrics_time=None, property_filters=None, include_latest_builds=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if definition_id is not None: ro...
GetDefinition. Gets a definition, optionally at a specific revision. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :param int revision: The revision number to retrieve. If this is not specified, the latest version will be returned. ...
355,057
def dump(self, data, stream=None): yaml_text = yaml.dump( data, default_flow_style=False, allow_unicode=True) return self.dump_raw(yaml_text, stream=stream)
Encrypt data and print stdout or write to stream.
355,058
def get_iso3_country_code_fuzzy(cls, country, use_live=True, exception=None): countriesdata = cls.countriesdata(use_live=use_live) iso3 = cls.get_iso3_country_code(country, use_live=use_live) if iso3 is not None: return is...
Get ISO3 code for cls. A tuple is returned with the first value being the ISO3 code and the second showing if the match is exact or not. Args: country (str): Country for which to get ISO3 code use_live (bool): Try to get use latest data from web rather than file in package. Defa...
355,059
def multinomial_like(x, n, p): R x = np.atleast_2d(x) p = np.atleast_2d(p) return flib.multinomial(x, n, p)
R""" Multinomial log-likelihood. Generalization of the binomial distribution, but instead of each trial resulting in "success" or "failure", each one results in exactly one of some fixed finite number k of possible outcomes over n independent trials. 'x[i]' indicates the number of times outcome...
355,060
def prepend_to_list(self, key, *value, pipeline=False): if pipeline: self._pipeline.lpush(key, *value) else: self._db.lpush(key, *value)
Add new element to the start of the list stored at key. Args: key (str): Key where the list is stored value: Value to add to the list pipeline (bool): True, start a transaction block. Default false.
355,061
def refresh_state(self, id_or_uri, configuration, timeout=-1): uri = self._client.build_uri(id_or_uri) + self.REFRESH_STATE_PATH return self._client.update(resource=configuration, uri=uri, timeout=timeout)
Refreshes a drive enclosure. Args: id_or_uri: Can be either the resource ID or the resource URI. configuration: Configuration timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops ...
355,062
def settings_module_update(self, mode_audiopin_enable=None, mode_audiopass_enable=None, mode_default=None): body = { "auth_password": self._password } if mode_audiopin_enable: bod...
Set Module settings. Uses PUT to /settings/modules interface. :Args: * *mode_audiopin_enable*: (bool) Turn on and off the AudioPIN feature * *mode_audiopass_enable*: (bool) Turn on and off the AudioPass feature * *mode_default*: (str) Set the default verification mode. Either '...
355,063
def phase3(self): fcomp = filecmp.cmpfiles(self.left, self.right, self.common_files, shallow=False) self.same_files, self.diff_files, self.funny_files = fcomp
Find out differences between common files. Ensure we are using content comparison with shallow=False.
355,064
def _get_layout_as_etree(layout_dict): if layout_dict is None: return None layout = etree.Element("layout") layout_dict = eval(layout_dict) for k, v in layout_dict.items(): item = etree.SubElement(layout, "item") name = etree.SubElement(item, "name") name.text = k ...
Convert something that looks like this: { 'color' : ['red'], 'shapefile' : ['blah.shp'] } Into something that looks like this: <layout> <item> <name>color</name> <value>red</value> </item> <item> <name>shapefile</name> ...
355,065
def last_first(self): return "{}, {} ".format(self.last_name, self.first_name) + ("({})".format(self.nickname) if self.nickname else "")
Return a name in the format of: Lastname, Firstname [(Nickname)]
355,066
def _remove_uri_scheme_from_textbuffer(self, scheme): length = len(scheme) while length: if length < len(self._textbuffer[-1]): self._textbuffer[-1] = self._textbuffer[-1][:-length] break length -= len(self._textbuffer[-1]) sel...
Remove the URI scheme of a new external link from the textbuffer.
355,067
def zPushLens(self, update=None): self.SaveAs(self._sync_ui_file) OpticalSystem._dde_link.zLoadFile(self._sync_ui_file) OpticalSystem._dde_link.zPushLens(update)
Push lens in ZOS COM server to UI
355,068
def translate_to_stackdriver(self, trace): set_attributes(trace) spans_json = trace.get() trace_id = trace.get() for span in spans_json: span_name = .format( self.project_id, trace_id, span.get()) span_json = { : span_nam...
Translate the spans json to Stackdriver format. See: https://cloud.google.com/trace/docs/reference/v2/rest/v2/ projects.traces/batchWrite :type trace: dict :param trace: Trace dictionary :rtype: dict :returns: Spans in Google Cloud StackDriver Trace format.
355,069
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc_128(): hparams = imagetransformer_sep_channels_12l_16h_imagenet_large() hparams.num_hidden_layers = 16 hparams.local_attention = True hparams.batch_size = 1 hparams.block_length = 128 return hparams
separate rgb embeddings.
355,070
def install_webpi(name, install_args=None, override_args=False): ** return install(name, source=, install_args=install_args, override_args=override_args)
Instructs Chocolatey to install a package via the Microsoft Web PI service. name The name of the package to be installed. Only accepts a single argument. install_args A list of install arguments you want to pass to the installation process i.e product key or feature list override_...
355,071
def mouseMoveEvent( self, event ): self.setValue(self.valueAt(event.pos().x()))
Sets the value for the slider at the event position. :param event | <QMouseEvent>
355,072
def describe_spot_price_history(DryRun=None, StartTime=None, EndTime=None, InstanceTypes=None, ProductDescriptions=None, Filters=None, AvailabilityZone=None, MaxResults=None, NextToken=None): pass
Describes the Spot price history. For more information, see Spot Instance Pricing History in the Amazon Elastic Compute Cloud User Guide . When you specify a start and end time, this operation returns the prices of the instance types within the time range that you specified and the time when the price changed. The ...
355,073
def strip_tweet(text, remove_url=True): if remove_url: text = url_pattern.sub(, text) else: text = expand_url(text) text = mention_pattern.sub(, text) text = html_parser.unescape(text) text = text.strip() return text
Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet message :rtype: :class:`str`
355,074
def _init_offsets(self, batchsize): upper_offsets = previous_lower_offsets = self._lower_offsets if not upper_offsets: upper_offsets = self.latest_offsets self._upper_offsets = {p: o for p, o in upper_offsets.items() if o > self._min_lower_offsets[p]} if se...
Compute new initial and target offsets and do other maintenance tasks
355,075
def _setup_metrics(self): path = os.environ.get("prometheus_multiproc_dir") if not os.path.exists(self.metrics_dir): try: log.info("Creating metrics directory") os.makedirs(self.metrics_dir) except OSError: log.error("Faile...
Start metric exposition
355,076
def delete(self, uri): try: self.connect(uri, method=) return True except urllib.error.HTTPError: return False
Method deletes a Fedora Object in the repository Args: uri(str): URI of Fedora Object
355,077
def pydoc_cli_monkey_patched(port): def input(_): while 1: time.sleep(1.0) import builtins builtins.input = input sys.argv += ["-p", port] pydoc.cli()
In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process.
355,078
def types(self): neurites = self._obj.neurites if hasattr(self._obj, ) else (self._obj,) return (neu.type for neu in neurites)
Returns an iterator over the types of the neurites in the object. If the object is a tree, then one value is returned.
355,079
def all(self, data={}, **kwargs): return super(Order, self).all(data, **kwargs)
Fetch all Order entities Returns: Dictionary of Order data
355,080
def extract_ids(text, extractors): for extractor in extractors: for id in extractor.extract(text): yield id
Uses `extractors` to extract citation identifiers from a text. :Parameters: text : str The text to process extractors : `list`(`extractor`) A list of extractors to apply to the text :Returns: `iterable` -- a generator of extracted identifiers
355,081
def total_charges(self): selected_charges = Charge.objects \ .filter(invoice=self) \ .charges() \ .exclude(product_code=CARRIED_FORWARD) return total_amount(selected_charges)
Represents the 'goods' acquired in the invoice.
355,082
def get_occupation(self, atom_index, orbital): orbital_index = self.orbitals.index(orbital) return {spin: np.sum(d[:, :, atom_index, orbital_index] * self.weights[:, None]) for spin, d in self.data.items()}
Returns the occupation for a particular orbital of a particular atom. Args: atom_num (int): Index of atom in the PROCAR. It should be noted that VASP uses 1-based indexing for atoms, but this is converted to 0-based indexing in this parser to be consi...
355,083
def create_configwidget(self, parent): if self.CONFIGWIDGET_CLASS is not None: configwidget = self.CONFIGWIDGET_CLASS(self, parent) configwidget.initialize() return configwidget
Create configuration dialog box page widget
355,084
def check_unique_named_object_has_class(root, name, class_name): assert class_name == get_unique_named_object(root, name).__class__.__name__
checks the type (type name) of an unique named object (no fully qualified name) Args: root: start of search name: name of object class_name: the name of the type to be checked Returns: nothing (if not unique, raises an error)
355,085
def solve(self): if self.world_coords is None: log.warning("solving for Assembly without world coordinates set: %r", self) for (component, world_coords) in solver(self.constraints, self.world_coords): component.world_coords = world_coords
Run the solver and assign the solution's :class:`CoordSystem` instances as the corresponding part's world coordinates.
355,086
def get_item_position(self, analysis_uid): str_position = self.uids_strpositions.get(analysis_uid, "") tokens = str_position.split(":") if len(tokens) != 2: return None return [to_int(tokens[0]), to_int(tokens[1])]
Returns a list with the position for the analysis_uid passed in within the current worksheet in accordance with the current layout, where the first item from the list returned is the slot and the second is the position of the analysis within the slot. :param analysis_uid: uid of the ana...
355,087
def add_space(self, line): if not isinstance(self.last_item, Space): space = Space(self._structure) self._structure.append(space) self.last_item.add_line(line) return self
Add a Space object to the section Used during initial parsing mainly Args: line (str): one line that defines the space, maybe whitespaces
355,088
def unwrap(self): if self._error: raise compat.saved_exc(self._error) elif self._closing or self._handle.closed: raise TransportError() self._close_on_unwrap = False self._write_backlog.append([b, False]) self._process_write_backlog()
Remove the security layer. Use this method only if you want to send plaintext data on the connection after the security layer has been removed. In all other cases, use :meth:`close`. If the unwrap is initiated by us, then any data sent after it will be buffered until the corres...
355,089
def iodp_dscr_lore(dscr_file,dscr_ex_file="", dir_path=".", input_dir_path="",volume=7,noave=False,\ meas_file="measurements.txt", offline_meas_file="",spec_file="specimens.txt"): version_num = pmag.get_version() input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path,...
Convert IODP discrete measurement files in MagIC file(s). This program assumes that you have created the specimens, samples, sites and location files using convert_2_magic.iodp_samples_csv from files downloaded from the LIMS online repository and that all samples are in that file. If there are offline ...
355,090
def admin_footer(parser, token): )) return AdminFooterNode()
Template tag that renders the footer information based on the authenticated user's permissions.
355,091
def get_CV_prediction(self): predict_vec = np.zeros((self._n_rows, self._concise_model._num_tasks)) for fold, train, test in self._kf: acc = self._cv_model[fold].get_accuracy() predict_vec[test, :] = acc["y_test_prediction"] return pred...
Returns: np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`).
355,092
def _add_entity_id(self, config, co_name): base_entity_id = config[] co_entity_id = "{}/{}".format(base_entity_id, quote_plus(co_name)) config[] = co_entity_id return config
Use the CO name to construct the entity ID for the virtual IdP for the CO. The entity ID has the form {base_entity_id}/{co_name} :type config: satosa.satosa_config.SATOSAConfig :type co_name: str :rtype: satosa.satosa_config.SATOSAConfig :param config: satosa ...
355,093
def write_hdf5_dict(flags, output, path=None, append=False, overwrite=False, **kwargs): if path: try: parent = output[path] except KeyError: parent = output.create_group(path) else: parent = output for name in flags: ...
Write this `DataQualityFlag` to a `h5py.Group`. This allows writing to an HDF5-format file. Parameters ---------- output : `str`, :class:`h5py.Group` path to new output file, or open h5py `Group` to write to. path : `str` the HDF5 group path in which to write a new group for this ...
355,094
def allocate_clusters(self, eps = 0.01, indexes = None, iteration = None): return self.allocate_sync_ensembles(eps, indexes, iteration);
! @brief Returns list of clusters in line with state of ocillators (phases). @param[in] eps (double): Tolerance level that define maximal difference between phases of oscillators in one cluster. @param[in] indexes (list): List of real object indexes and it should be equal to amount ...
355,095
def getPlannedFor(self, plannedfor_name, projectarea_id=None, projectarea_name=None, archived=False, returned_properties=None): if not isinstance(plannedfor_name, six.string_types) or not plannedfor_name: excp_msg = "Ple...
Get :class:`rtcclient.models.PlannedFor` object by its name :param plannedfor_name: the plannedfor name :param projectarea_id: the :class:`rtcclient.project_area.ProjectArea` id :param projectarea_name: the project area name :param archived: (default is False) whether the pl...
355,096
def smart_truncate(string, max_length=0, word_boundary=False, separator=, save_order=False): string = string.strip(separator) if not max_length: return string if len(string) < max_length: return string if not word_boundary: return string[:max_length].strip(separator) ...
Truncate a string. :param string (str): string for modification :param max_length (int): output string length :param word_boundary (bool): :param save_order (bool): if True then word order of output string is like input string :param separator (str): separator between words :return:
355,097
def do_list(self): if (self._args.probes, self._args.targets, self._args.boards) == (False, False, False): self._args.probes = True session = Session(None, project_dir=self._args.project_dir, config_f...
! @brief Handle 'list' subcommand.
355,098
def enter_password_change(self, username=None, old_password=None): from fabric.state import connections from fabric.network import disconnect_all r = self.local_renderer r.genv.user = r.genv.user or username r.pc() r.env.old_password = r.env.default_passwords[s...
Responds to a forced password change via `passwd` prompts due to password expiration.
355,099
def user_activity_stats(self, username, format=None): request_url = "{}/api/0/user/{}/activity/stats".format(self.instance, username) payload = {} if username is not None: payload[] = username if format is not None: payload[] = format return_val...
Retrieve the activity stats about a specific user over the last year. Params: username (string): filters the username of the user whose activity you are interested in. format (string): Allows changing the of the date/time returned from iso format to unix tim...