_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q12200
get_namespace_keys
train
def get_namespace_keys(app, limit): """Get namespace keys.""" ns_query = datastore.Query('__namespace__', keys_only=True, _app=app) return list(ns_query.Run(limit=limit, batch_size=limit))
python
{ "resource": "" }
q12201
NamespaceRange.split_range
train
def split_range(self): """Splits the NamespaceRange into two nearly equal-sized ranges. Returns: If this NamespaceRange contains a single namespace then a list containing this NamespaceRange is returned. Otherwise a two-element list containing two NamespaceRanges whose total range is identica...
python
{ "resource": "" }
q12202
NamespaceRange.with_start_after
train
def with_start_after(self, after_namespace): """Returns a copy of this NamespaceName with a new namespace_start. Args: after_namespace: A namespace string. Returns: A NamespaceRange object whose namespace_start is the lexographically next namespace after the given namespace string. ...
python
{ "resource": "" }
q12203
NamespaceRange.make_datastore_query
train
def make_datastore_query(self, cursor=None): """Returns a datastore.Query that generates all namespaces in the range. Args: cursor: start cursor for the query. Returns: A datastore.Query instance that generates db.Keys for each namespace in the NamespaceRange. """ filters = {} ...
python
{ "resource": "" }
q12204
NamespaceRange.normalized_start
train
def normalized_start(self): """Returns a NamespaceRange with leading non-existant namespaces removed. Returns: A copy of this NamespaceRange whose namespace_start is adjusted to exclude the portion of the range that contains no actual namespaces in the datastore. None is returned if the Names...
python
{ "resource": "" }
q12205
NamespaceRange.to_json_object
train
def to_json_object(self): """Returns a dict representation that can be serialized to JSON.""" obj_dict = dict(namespace_start=self.namespace_start, namespace_end=self.namespace_end) if self.app is not None: obj_dict['app'] = self.app return obj_dict
python
{ "resource": "" }
q12206
NamespaceRange.split
train
def split(cls, n, contiguous, can_query=itertools.chain(itertools.repeat(True, 50), itertools.repeat(False)).next, _app=None): # pylint: disable=g-doc-args """Splits the complete NamespaceRange into n equally-sized NamespaceRa...
python
{ "resource": "" }
q12207
_RecordsPoolBase.append
train
def append(self, data): """Append data to a file.""" data_length = len(data) if self._size + data_length > self._flush_size: self.flush() if not self._exclusive and data_length > _FILE_POOL_MAX_SIZE: raise errors.Error( "Too big input %s (%s)." % (data_length, _FILE_POOL_MAX_SIZE...
python
{ "resource": "" }
q12208
GCSRecordsPool._write
train
def _write(self, str_buf): """Uses the filehandle to the file in GCS to write to it.""" self._filehandle.write(str_buf) self._buf_size += len(str_buf)
python
{ "resource": "" }
q12209
_GoogleCloudStorageBase._get_tmp_gcs_bucket
train
def _get_tmp_gcs_bucket(cls, writer_spec): """Returns bucket used for writing tmp files.""" if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec[cls.TMP_BUCKET_NAME_PARAM] return cls._get_gcs_bucket(writer_spec)
python
{ "resource": "" }
q12210
_GoogleCloudStorageBase._get_tmp_account_id
train
def _get_tmp_account_id(cls, writer_spec): """Returns the account id to use with tmp bucket.""" # pick tmp id iff tmp bucket is set explicitly if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec.get(cls._TMP_ACCOUNT_ID_PARAM, None) return cls._get_account_id(writer_spec)
python
{ "resource": "" }
q12211
_GoogleCloudStorageOutputWriterBase._generate_filename
train
def _generate_filename(cls, writer_spec, name, job_id, num, attempt=None, seg_index=None): """Generates a filename for a particular output. Args: writer_spec: specification dictionary for the output writer. name: name of the job. job_id: the ID number assigned to the ...
python
{ "resource": "" }
q12212
_GoogleCloudStorageOutputWriterBase._open_file
train
def _open_file(cls, writer_spec, filename_suffix, use_tmp_bucket=False): """Opens a new gcs file for writing.""" if use_tmp_bucket: bucket = cls._get_tmp_gcs_bucket(writer_spec) account_id = cls._get_tmp_account_id(writer_spec) else: bucket = cls._get_gcs_bucket(writer_spec) account_...
python
{ "resource": "" }
q12213
_GoogleCloudStorageOutputWriterBase.write
train
def write(self, data): """Write data to the GoogleCloudStorage file. Args: data: string containing the data to be written. """ start_time = time.time() self._get_write_buffer().write(data) ctx = context.get() operation.counters.Increment(COUNTER_IO_WRITE_BYTES, len(data))(ctx) ope...
python
{ "resource": "" }
q12214
_GoogleCloudStorageOutputWriter._create
train
def _create(cls, writer_spec, filename_suffix): """Helper method that actually creates the file in cloud storage.""" writer = cls._open_file(writer_spec, filename_suffix) return cls(writer, writer_spec=writer_spec)
python
{ "resource": "" }
q12215
GoogleCloudStorageConsistentOutputWriter._create_tmpfile
train
def _create_tmpfile(cls, status): """Creates a new random-named tmpfile.""" # We can't put the tmpfile in the same directory as the output. There are # rare circumstances when we leave trash behind and we don't want this trash # to be loaded into bigquery and/or used for restore. # # We used ma...
python
{ "resource": "" }
q12216
GoogleCloudStorageConsistentOutputWriter._try_to_clean_garbage
train
def _try_to_clean_garbage(self, writer_spec, exclude_list=()): """Tries to remove any files created by this shard that aren't needed. Args: writer_spec: writer_spec for the MR. exclude_list: A list of filenames (strings) that should not be removed. """ # Try to remove garbage (if an...
python
{ "resource": "" }
q12217
_get_weights
train
def _get_weights(max_length): """Get weights for each offset in str of certain max length. Args: max_length: max length of the strings. Returns: A list of ints as weights. Example: If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa", "ab", "b", "ba", "bb". So the weight fo...
python
{ "resource": "" }
q12218
_str_to_ord
train
def _str_to_ord(content, weights): """Converts a string to its lexicographical order. Args: content: the string to convert. Of type str. weights: weights from _get_weights. Returns: an int or long that represents the order of this string. "" has order 0. """ ordinal = 0 for i, c in enumerate(c...
python
{ "resource": "" }
q12219
_ord_to_str
train
def _ord_to_str(ordinal, weights): """Reverse function of _str_to_ord.""" chars = [] for weight in weights: if ordinal == 0: return "".join(chars) ordinal -= 1 index, ordinal = divmod(ordinal, weight) chars.append(_ALPHABET[index]) return "".join(chars)
python
{ "resource": "" }
q12220
PropertyRange._get_range_from_filters
train
def _get_range_from_filters(cls, filters, model_class): """Get property range from filters user provided. This method also validates there is one and only one closed range on a single property. Args: filters: user supplied filters. Each filter should be a list or tuple of format (<proper...
python
{ "resource": "" }
q12221
PropertyRange.split
train
def split(self, n): """Evenly split this range into contiguous, non overlapping subranges. Args: n: number of splits. Returns: a list of contiguous, non overlapping sub PropertyRanges. Maybe less than n when not enough subranges. """ new_range_filters = [] name = self.start[0] ...
python
{ "resource": "" }
q12222
PropertyRange.make_query
train
def make_query(self, ns): """Make a query of entities within this range. Query options are not supported. They should be specified when the query is run. Args: ns: namespace of this query. Returns: a db.Query or ndb.Query, depends on the model class's type. """ if issubclass(s...
python
{ "resource": "" }
q12223
OutputWriter.commit_output
train
def commit_output(cls, shard_ctx, iterator): """Saves output references when a shard finishes. Inside end_shard(), an output writer can optionally use this method to persist some references to the outputs from this shard (e.g a list of filenames) Args: shard_ctx: map_job_context.ShardContext...
python
{ "resource": "" }
q12224
KeyRangesFactory.from_json
train
def from_json(cls, json): """Deserialize from json. Args: json: a dict of json compatible fields. Returns: a KeyRanges object. Raises: ValueError: if the json is invalid. """ if json["name"] in _KEYRANGES_CLASSES: return _KEYRANGES_CLASSES[json["name"]].from_json(json)...
python
{ "resource": "" }
q12225
split_into_sentences
train
def split_into_sentences(s): """Split text into list of sentences.""" s = re.sub(r"\s+", " ", s) s = re.sub(r"[\\.\\?\\!]", "\n", s) return s.split("\n")
python
{ "resource": "" }
q12226
split_into_words
train
def split_into_words(s): """Split a sentence into list of words.""" s = re.sub(r"\W+", " ", s) s = re.sub(r"[_0-9]+", " ", s) return s.split()
python
{ "resource": "" }
q12227
index_map
train
def index_map(data): """Index demo map function.""" (entry, text_fn) = data text = text_fn() logging.debug("Got %s", entry.filename) for s in split_into_sentences(text): for w in split_into_words(s.lower()): yield (w, entry.filename)
python
{ "resource": "" }
q12228
phrases_map
train
def phrases_map(data): """Phrases demo map function.""" (entry, text_fn) = data text = text_fn() filename = entry.filename logging.debug("Got %s", filename) for s in split_into_sentences(text): words = split_into_words(s.lower()) if len(words) < PHRASE_LENGTH: yield (":".join(words), filename...
python
{ "resource": "" }
q12229
phrases_reduce
train
def phrases_reduce(key, values): """Phrases demo reduce function.""" if len(values) < 10: return counts = {} for filename in values: counts[filename] = counts.get(filename, 0) + 1 words = re.sub(r":", " ", key) threshold = len(values) / 2 for filename, count in counts.items(): if count > thre...
python
{ "resource": "" }
q12230
FileMetadata.getKeyName
train
def getKeyName(username, date, blob_key): """Returns the internal key for a particular item in the database. Our items are stored with keys of the form 'user/date/blob_key' ('/' is not the real separator, but __SEP is). Args: username: The given user's e-mail address. date: A datetime obje...
python
{ "resource": "" }
q12231
Custodian.from_spec
train
def from_spec(cls, spec): """ Load a Custodian instance where the jobs are specified from a structure and a spec dict. This allows simple custom job sequences to be constructed quickly via a YAML file. Args: spec (dict): A dict specifying job. A sample of the dict in...
python
{ "resource": "" }
q12232
Custodian.run
train
def run(self): """ Runs all jobs. Returns: All errors encountered as a list of list. [[error_dicts for job 1], [error_dicts for job 2], ....] Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return ...
python
{ "resource": "" }
q12233
Custodian._do_check
train
def _do_check(self, handlers, terminate_func=None): """ checks the specified handlers. Returns True iff errors caught """ corrections = [] for h in handlers: try: if h.check(): if h.max_num_corrections is not None \ ...
python
{ "resource": "" }
q12234
FeffModder.apply_actions
train
def apply_actions(self, actions): """ Applies a list of actions to the FEFF Input Set and rewrites modified files. Args: actions [dict]: A list of actions of the form {'file': filename, 'action': moddermodification} or {'dict': feffinput_key, ...
python
{ "resource": "" }
q12235
FileActions.file_modify
train
def file_modify(filename, settings): """ Modifies file access Args: filename (str): Filename. settings (dict): Can be "mode" or "owners" """ for k, v in settings.items(): if k == "mode": os.chmod(filename,v) if k ==...
python
{ "resource": "" }
q12236
Modder.modify
train
def modify(self, modification, obj): """ Note that modify makes actual in-place modifications. It does not return a copy. Args: modification (dict): Modification must be {action_keyword : settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}} ...
python
{ "resource": "" }
q12237
backup
train
def backup(filenames, prefix="error"): """ Backup files to a tar.gz file. Used, for example, in backing up the files of an errored run before performing corrections. Args: filenames ([str]): List of files to backup. Supports wildcards, e.g., *.*. prefix (str): prefix to the ...
python
{ "resource": "" }
q12238
get_execution_host_info
train
def get_execution_host_info(): """ Tries to return a tuple describing the execution host. Doesn't work for all queueing systems Returns: (HOSTNAME, CLUSTER_NAME) """ host = os.environ.get('HOSTNAME', None) cluster = os.environ.get('SGE_O_HOST', None) if host is None: try...
python
{ "resource": "" }
q12239
QCJob.run
train
def run(self): """ Perform the actual QChem run. Returns: (subprocess.Popen) Used for monitoring. """ qclog = open(self.qclog_file, 'w') p = subprocess.Popen(self.current_command, stdout=qclog) return p
python
{ "resource": "" }
q12240
VaspJob.setup
train
def setup(self): """ Performs initial setup for VaspJob, including overriding any settings and backing up. """ decompress_dir('.') if self.backup: for f in VASP_INPUT_FILES: shutil.copy(f, "{}.orig".format(f)) if self.auto_npar: ...
python
{ "resource": "" }
q12241
VaspJob.run
train
def run(self): """ Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring. """ cmd = list(self.vasp_cmd) if self.auto_gamma: vi = VaspInput.from_directory(".") kpts = vi["KPOINTS"] if kpts.style == Kpo...
python
{ "resource": "" }
q12242
VaspJob.postprocess
train
def postprocess(self): """ Postprocessing includes renaming and gzipping where necessary. Also copies the magmom to the incar if necessary """ for f in VASP_OUTPUT_FILES + [self.output_file]: if os.path.exists(f): if self.final and self.suffix != "": ...
python
{ "resource": "" }
q12243
VaspJob.double_relaxation_run
train
def double_relaxation_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05, half_kpts_first_relax=False, auto_continue=False): """ Returns a list of two jobs corresponding to an AFLOW style double relaxation run. Args: vasp_cmd (str): Command to run ...
python
{ "resource": "" }
q12244
VaspJob.metagga_opt_run
train
def metagga_opt_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05, half_kpts_first_relax=False, auto_continue=False): """ Returns a list of thres jobs to perform an optimization for any metaGGA functional. There is an initial calculation of the GGA wavefunction whic...
python
{ "resource": "" }
q12245
VaspJob.full_opt_run
train
def full_opt_run(cls, vasp_cmd, vol_change_tol=0.02, max_steps=10, ediffg=-0.05, half_kpts_first_relax=False, **vasp_job_kwargs): """ Returns a generator of jobs for a full optimization run. Basically, this runs an infinite series of geometry optimizatio...
python
{ "resource": "" }
q12246
VaspNEBJob.setup
train
def setup(self): """ Performs initial setup for VaspNEBJob, including overriding any settings and backing up. """ neb_dirs = self.neb_dirs if self.backup: # Back up KPOINTS, INCAR, POTCAR for f in VASP_NEB_INPUT_FILES: shutil.copy(...
python
{ "resource": "" }
q12247
VaspNEBJob.postprocess
train
def postprocess(self): """ Postprocessing includes renaming and gzipping where necessary. """ # Add suffix to all sub_dir/{items} for path in self.neb_dirs: for f in VASP_NEB_OUTPUT_SUB_FILES: f = os.path.join(path, f) if os.path.exists...
python
{ "resource": "" }
q12248
NwchemJob.setup
train
def setup(self): """ Performs backup if necessary. """ if self.backup: shutil.copy(self.input_file, "{}.orig".format(self.input_file))
python
{ "resource": "" }
q12249
NwchemJob.run
train
def run(self): """ Performs actual nwchem run. """ with zopen(self.output_file, 'w') as fout: return subprocess.Popen(self.nwchem_cmd + [self.input_file], stdout=fout)
python
{ "resource": "" }
q12250
valid_GC
train
def valid_GC(x): """type function for argparse to check GC values. Check if the supplied value for minGC and maxGC is a valid input, being between 0 and 1 """ x = float(x) if x < 0.0 or x > 1.0: raise ArgumentTypeError("{} not in range [0.0, 1.0]".format(x)) return x
python
{ "resource": "" }
q12251
filter_stream
train
def filter_stream(fq, args): """Filter a fastq file on stdin. Print fastq record to stdout if it passes - quality filter (optional) - length filter (optional) - min/maxGC filter (optional) Optionally trim a number of nucleotides from beginning and end. Record has to be longer than args.leng...
python
{ "resource": "" }
q12252
filter_using_summary
train
def filter_using_summary(fq, args): """Use quality scores from albacore summary file for filtering Use the summary file from albacore for more accurate quality estimate Get the dataframe from nanoget, convert to dictionary """ data = {entry[0]: entry[1] for entry in process_summary( summary...
python
{ "resource": "" }
q12253
master_key_required
train
def master_key_required(func): '''decorator describing methods that require the master key''' def ret(obj, *args, **kw): conn = ACCESS_KEYS if not (conn and conn.get('master_key')): message = '%s requires the master key' % func.__name__ raise core.ParseError(message) ...
python
{ "resource": "" }
q12254
ParseBase.execute
train
def execute(cls, uri, http_verb, extra_headers=None, batch=False, _body=None, **kw): """ if batch == False, execute a command with the given parameters and return the response JSON. If batch == True, return the dictionary that would be used in a batch command. """ ...
python
{ "resource": "" }
q12255
ParseBatcher.batch
train
def batch(self, methods): """ Given a list of create, update or delete methods to call, call all of them in a single batch operation. """ methods = list(methods) # methods can be iterator if not methods: #accepts also empty list (or generator) - it allows call...
python
{ "resource": "" }
q12256
Installation.update_channels
train
def update_channels(cls, installation_id, channels_to_add=set(), channels_to_remove=set(), **kw): """ Allow an application to manually subscribe or unsubscribe an installation to a certain push channel in a unified operation. this is based on: https://www...
python
{ "resource": "" }
q12257
Queryset._fetch
train
def _fetch(self, count=False): if self._result_cache is not None: return len(self._result_cache) if count else self._result_cache """ Return a list of objects matching query, or if count == True return only the number of objects matching. """ options = dict(se...
python
{ "resource": "" }
q12258
complex_type
train
def complex_type(name=None): '''Decorator for registering complex types''' def wrapped(cls): ParseType.type_mapping[name or cls.__name__] = cls return cls return wrapped
python
{ "resource": "" }
q12259
Object.schema
train
def schema(cls): """Retrieves the class' schema.""" root = '/'.join([API_ROOT, 'schemas', cls.__name__]) schema = cls.GET(root) return schema
python
{ "resource": "" }
q12260
Object.schema_delete_field
train
def schema_delete_field(cls, key): """Deletes a field.""" root = '/'.join([API_ROOT, 'schemas', cls.__name__]) payload = { 'className': cls.__name__, 'fields': { key: { '__op': 'Delete' } } } ...
python
{ "resource": "" }
q12261
login_required
train
def login_required(func): '''decorator describing User methods that need to be logged in''' def ret(obj, *args, **kw): if not hasattr(obj, 'sessionToken'): message = '%s requires a logged-in session' % func.__name__ raise ResourceRequestLoginRequired(message) return func(...
python
{ "resource": "" }
q12262
parse
train
def parse(d): """Convert iso formatted timestamps found as values in the dict d to datetime objects. :return: A shallow copy of d with converted timestamps. """ res = {} for k, v in iteritems(d): if isinstance(v, string_types) and DATETIME_ISO_FORMAT.match(v): v = dateutil.parse...
python
{ "resource": "" }
q12263
dump
train
def dump(obj, path, **kw): """Python 2 + 3 compatible version of json.dump. :param obj: The object to be dumped. :param path: The path of the JSON file to be written. :param kw: Keyword parameters are passed to json.dump """ open_kw = {'mode': 'w'} if PY3: # pragma: no cover open_k...
python
{ "resource": "" }
q12264
strip_brackets
train
def strip_brackets(text, brackets=None): """Strip brackets and what is inside brackets from text. .. note:: If the text contains only one opening bracket, the rest of the text will be ignored. This is a feature, not a bug, as we want to avoid that this function raises errors too easily....
python
{ "resource": "" }
q12265
split_text_with_context
train
def split_text_with_context(text, separators=WHITESPACE, brackets=None): """Splits text at separators outside of brackets. :param text: :param separators: An iterable of single character tokens. :param brackets: :return: A `list` of non-empty chunks. .. note:: This function leaves content in b...
python
{ "resource": "" }
q12266
split_text
train
def split_text(text, separators=re.compile('\s'), brackets=None, strip=False): """Split text along the separators unless they appear within brackets. :param separators: An iterable single characters or a compiled regex pattern. :param brackets: `dict` mapping start tokens to end tokens of what is to be \ ...
python
{ "resource": "" }
q12267
Entry.get
train
def get(self, key, default=None): """Retrieve the first value for a marker or None.""" for k, v in self: if k == key: return v return default
python
{ "resource": "" }
q12268
SFM.read
train
def read(self, filename, encoding='utf-8', marker_map=None, entry_impl=Entry, entry_sep='\n\n', entry_prefix=None, keep_empty=False): """Extend the list by parsing new entries from a file. :param filename: ...
python
{ "resource": "" }
q12269
SFM.write
train
def write(self, filename, encoding='utf-8'): """Write the list of entries to a file. :param filename: :param encoding: :return: """ with io.open(str(filename), 'w', encoding=encoding) as fp: for entry in self: fp.write(entry.__unicode__()) ...
python
{ "resource": "" }
q12270
data_url
train
def data_url(content, mimetype=None): """ Returns content encoded as base64 Data URI. :param content: bytes or str or Path :param mimetype: mimetype for :return: str object (consisting only of ASCII, though) .. seealso:: https://en.wikipedia.org/wiki/Data_URI_scheme """ if isinstance(c...
python
{ "resource": "" }
q12271
to_binary
train
def to_binary(s, encoding='utf8'): """Portable cast function. In python 2 the ``str`` function which is used to coerce objects to bytes does not accept an encoding argument, whereas python 3's ``bytes`` function requires one. :param s: object to be converted to binary_type :return: binary_type ins...
python
{ "resource": "" }
q12272
dict_merged
train
def dict_merged(d, _filter=None, **kw): """Update dictionary d with the items passed as kw if the value passes _filter.""" def f(s): if _filter: return _filter(s) return s is not None d = d or {} for k, v in iteritems(kw): if f(v): d[k] = v return d
python
{ "resource": "" }
q12273
xmlchars
train
def xmlchars(text): """Not all of UTF-8 is considered valid character data in XML ... Thus, this function can be used to remove illegal characters from ``text``. """ invalid = list(range(0x9)) invalid.extend([0xb, 0xc]) invalid.extend(range(0xe, 0x20)) return re.sub('|'.join('\\x%0.2X' % i ...
python
{ "resource": "" }
q12274
slug
train
def slug(s, remove_whitespace=True, lowercase=True): """Condensed version of s, containing only lowercase alphanumeric characters.""" res = ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') if lowercase: res = res.lower() for c in string.pun...
python
{ "resource": "" }
q12275
encoded
train
def encoded(string, encoding='utf-8'): """Cast string to binary_type. :param string: six.binary_type or six.text_type :param encoding: encoding which the object is forced to :return: six.binary_type """ assert isinstance(string, string_types) or isinstance(string, binary_type) if isinstance...
python
{ "resource": "" }
q12276
readlines
train
def readlines(p, encoding=None, strip=False, comment=None, normalize=None, linenumbers=False): """ Read a `list` of lines from a text file. :param p: File path (or `list` or `tuple` of text) :param encoding: Registered codec. :pa...
python
{ "resource": "" }
q12277
walk
train
def walk(p, mode='all', **kw): """Wrapper for `os.walk`, yielding `Path` objects. :param p: root of the directory tree to walk. :param mode: 'all|dirs|files', defaulting to 'all'. :param kw: Keyword arguments are passed to `os.walk`. :return: Generator for the requested Path objects. """ fo...
python
{ "resource": "" }
q12278
Source.bibtex
train
def bibtex(self): """Represent the source in BibTeX format. :return: string encoding the source in BibTeX syntax. """ m = max(itertools.chain(map(len, self), [0])) fields = (" %s = {%s}" % (k.ljust(m), self[k]) for k in self) return "@%s{%s,\n%s\n}" % ( geta...
python
{ "resource": "" }
q12279
Client.request
train
def request(self, path, method='GET', params=None, type=REST_TYPE): """Builds a request, gets a response and decodes it.""" response_text = self._get_http_client(type).request(path, method, params) if not response_text: return response_text response_json = json.loads(respon...
python
{ "resource": "" }
q12280
Client.message_create
train
def message_create(self, originator, recipients, body, params=None): """Create a new message.""" if params is None: params = {} if type(recipients) == list: recipients = ','.join(recipients) params.update({'originator': originator, 'body': body, 'recipients': recipients}) ...
python
{ "resource": "" }
q12281
Client.voice_message_create
train
def voice_message_create(self, recipients, body, params=None): """Create a new voice message.""" if params is None: params = {} if type(recipients) == list: recipients = ','.join(recipients) params.update({'recipients': recipients, 'body': body}) return VoiceMessage(...
python
{ "resource": "" }
q12282
Client.lookup
train
def lookup(self, phonenumber, params=None): """Do a new lookup.""" if params is None: params = {} return Lookup().load(self.request('lookup/' + str(phonenumber), 'GET', params))
python
{ "resource": "" }
q12283
Client.lookup_hlr
train
def lookup_hlr(self, phonenumber, params=None): """Retrieve the information of a specific HLR lookup.""" if params is None: params = {} return HLR().load(self.request('lookup/' + str(phonenumber) + '/hlr', 'GET', params))
python
{ "resource": "" }
q12284
Client.verify_create
train
def verify_create(self, recipient, params=None): """Create a new verification.""" if params is None: params = {} params.update({'recipient': recipient}) return Verify().load(self.request('verify', 'POST', params))
python
{ "resource": "" }
q12285
Client.verify_verify
train
def verify_verify(self, id, token): """Verify the token of a specific verification.""" return Verify().load(self.request('verify/' + str(id), params={'token': token}))
python
{ "resource": "" }
q12286
BaseList.items
train
def items(self, value): """Create typed objects from the dicts.""" items = [] for item in value: items.append(self.itemType().load(item)) self._items = items
python
{ "resource": "" }
q12287
HttpClient.request
train
def request(self, path, method='GET', params=None): """Builds a request and gets a response.""" if params is None: params = {} url = urljoin(self.endpoint, path) headers = { 'Accept': 'application/json', 'Authorization': 'AccessKey ' + self.access_key, ...
python
{ "resource": "" }
q12288
cython_debug_files
train
def cython_debug_files(): """ Cython extra debug information files """ # Search all subdirectories of sys.path directories for a # "cython_debug" directory. Note that sys_path is a variable set by # cysignals-CSI. It may differ from sys.path if GDB is run with a # different Python interprete...
python
{ "resource": "" }
q12289
ColorizedPhoXiSensor._colorize
train
def _colorize(self, depth_im, color_im): """Colorize a depth image from the PhoXi using a color image from the webcam. Parameters ---------- depth_im : DepthImage The PhoXi depth image. color_im : ColorImage Corresponding color image. Returns ...
python
{ "resource": "" }
q12290
RgbdSensorFactory.sensor
train
def sensor(sensor_type, cfg): """ Creates a camera sensor of the specified type. Parameters ---------- sensor_type : :obj:`str` the type of the sensor (real or virtual) cfg : :obj:`YamlConfig` dictionary of parameters for sensor initialization """...
python
{ "resource": "" }
q12291
FeatureMatcher.get_point_index
train
def get_point_index(point, all_points, eps = 1e-4): """ Get the index of a point in an array """ inds = np.where(np.linalg.norm(point - all_points, axis=1) < eps) if inds[0].shape[0] == 0: return -1 return inds[0][0]
python
{ "resource": "" }
q12292
RawDistanceFeatureMatcher.match
train
def match(self, source_obj_features, target_obj_features): """ Matches features between two graspable objects based on a full distance matrix. Parameters ---------- source_obj_features : :obj:`BagOfFeatures` bag of the source objects features target_obj_featu...
python
{ "resource": "" }
q12293
PointToPlaneFeatureMatcher.match
train
def match(self, source_points, target_points, source_normals, target_normals): """ Matches points between two point-normal sets. Uses the closest ip to choose matches, with distance for thresholding only. Parameters ---------- source_point_cloud : Nx3 :obj:`numpy.ndarray` ...
python
{ "resource": "" }
q12294
RealSenseSensor._config_pipe
train
def _config_pipe(self): """Configures the pipeline to stream color and depth. """ self._cfg.enable_device(self.id) # configure the color stream self._cfg.enable_stream( rs.stream.color, RealSenseSensor.COLOR_IM_WIDTH, RealSenseSensor.COLOR_IM_...
python
{ "resource": "" }
q12295
RealSenseSensor._set_depth_scale
train
def _set_depth_scale(self): """Retrieve the scale of the depth sensor. """ sensor = self._profile.get_device().first_depth_sensor() self._depth_scale = sensor.get_depth_scale()
python
{ "resource": "" }
q12296
RealSenseSensor._set_intrinsics
train
def _set_intrinsics(self): """Read the intrinsics matrix from the stream. """ strm = self._profile.get_stream(rs.stream.color) obj = strm.as_video_stream_profile().get_intrinsics() self._intrinsics[0, 0] = obj.fx self._intrinsics[1, 1] = obj.fy self._intrinsics[0,...
python
{ "resource": "" }
q12297
RealSenseSensor._read_color_and_depth_image
train
def _read_color_and_depth_image(self): """Read a color and depth image from the device. """ frames = self._pipe.wait_for_frames() if self._depth_align: frames = self._align.process(frames) depth_frame = frames.get_depth_frame() color_frame = frames.get_color_...
python
{ "resource": "" }
q12298
EnsensoSensor._set_format
train
def _set_format(self, msg): """ Set the buffer formatting. """ num_points = msg.height * msg.width self._format = '<' + num_points * 'ffff'
python
{ "resource": "" }
q12299
EnsensoSensor._set_camera_properties
train
def _set_camera_properties(self, msg): """ Set the camera intrinsics from an info msg. """ focal_x = msg.K[0] focal_y = msg.K[4] center_x = msg.K[2] center_y = msg.K[5] im_height = msg.height im_width = msg.width self._camera_intr = CameraIntrinsics(self._...
python
{ "resource": "" }