Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
345,900 | def get_mosaics(self):
url = self._url()
return self._get(url, models.Mosaics).get_body() | Get information for all mosaics accessible by the current user.
:returns: :py:Class:`planet.api.models.Mosaics` |
345,901 | def raw_data(self, value):
if value:
try:
value = value.read()
except AttributeError:
pass
b64 = base64.b64encode(value.encode())
self.data = b64.decode() | Set the base64 encoded data using a raw value or file object. |
345,902 | def evaluate(molecules, ensemble_chunk, sort_order, options, output_queue=None):
results = {}
for ensemble in ensemble_chunk:
results[ensemble] = calculate_performance(molecules, ensemble, sort_order, options)
if output_queue is not None:
output_queue.put(results)
else:
... | Evaluate VS performance of each ensemble in ensemble_chunk |
345,903 | def map_into_range(low, high, raw_value):
value = float(raw_value)
if low < high:
if value < low:
return 0
elif value > high:
return 1.0
elif low > high:
if value > low:
return 0
elif value < high:
return -1.0
return (v... | Map an input function into an output value, clamping such that the magnitude of the output is at most 1.0
:param low:
The value in the input range corresponding to zero.
:param high:
The value in the input range corresponding to 1.0 or -1.0, depending on whether this is higher or lower than the... |
345,904 | def cp_handler(self, args):
self.validate(, args)
source = args[1]
target = args[2]
self.s3handler().cp_files(source, target) | Handler for cp command |
345,905 | def _convert_date(date_string, date_format):
if date_format != :
return datetime.strptime(date_string, date_format).timestamp()
else:
return float(date_string) | Convert a date in a given format to epoch time. Mostly a wrapper for
datetime's strptime. |
345,906 | def _get_part_map(self, part_id):
return [p for p in self._my_map[]
if p[] == str(part_id)][0] | from self._my_map['assessmentParts'], return the one part map
with ID that matches the one passed in |
345,907 | def advertise(
self,
routers=None,
name=None,
timeout=None,
router_file=None,
jitter=None,
):
name = name or self.name
if not self.is_listening():
self.listen()
return hyperbahn.advertise(
self,
na... | Make a service available on the Hyperbahn routing mesh.
This will make contact with a Hyperbahn host from a list of known
Hyperbahn routers. Additional Hyperbahn connections will be established
once contact has been made with the network.
:param router:
A seed list of addre... |
345,908 | def parse(config_path):
config_path = os.path.expanduser(config_path)
config_file = ConfigParser.RawConfigParser()
config_file.SECTCRE = re.compile(r"\[ *(?P<header>.*) *\]")
config_file.optionxform = lambda option: option
config_file.read(config_path)
if in config_fi... | Parse the configuration file
:type config_path: str
:param config_path: Path to the configuration file |
345,909 | def histogram2d(self, counts, x_edges, y_edges, type=, style=None,
bitmap=False, colormap=None):
if counts.shape != (len(x_edges) - 1, len(y_edges) - 1):
raise RuntimeError(
)
if type not in [, , , ]:
raise RuntimeError( % type)
... | Plot a two-dimensional histogram.
The user needs to supply the histogram. This method only plots
the results. You can use NumPy's histogram2d function.
:param counts: array containing the count values.
:param x_edges: array containing the x-axis bin edges.
:param y_edges: arr... |
345,910 | def listen_on_tcp_port():
host = os.getenv(
"LISTEN_ON_HOST",
"127.0.0.1").strip().lstrip()
port = int(os.getenv(
"LISTEN_ON_PORT",
"80").strip().lstrip())
backlog = int(os.getenv(
"LISTEN_BACKLOG",
"5").strip().lstrip())
size = int(os.getenv(
... | listen_on_tcp_port
Run a simple server for processing messages over ``TCP``.
``LISTEN_ON_HOST`` - listen on this host ip address
``LISTEN_ON_PORT`` - listen on this ``TCP`` port
``LISTEN_SIZE`` - listen on to packets of this size
``LISTEN_SLEEP`` - sleep this number of seconds per loop
``L... |
345,911 | def _get_instance(project_id, instance_zone, name, service):
return service.instances().get(project=project_id,
zone=instance_zone,
instance=name).execute() | Get instance details |
345,912 | def parent_callback(self, parent_fu):
if parent_fu.done() is True:
e = parent_fu._exception
if e:
super().set_exception(e)
else:
super().set_result(self.file_obj)
return | Callback from executor future to update the parent.
Args:
- parent_fu (Future): Future returned by the executor along with callback
Returns:
- None
Updates the super() with the result() or exception() |
345,913 | def run_editmap(_):
edit_map_file =
if os.path.exists(edit_map_file):
os.remove(edit_map_file)
gen_wiki_map(edit_map_file, ext_url=)
gen_post_map(edit_map_file, ext_url=) | Generate the urls file for editing.
:param args: args
:return: None |
345,914 | def PopEvent(self):
try:
timestamp, serialized_event = heapq.heappop(self._heap)
self.data_size -= len(serialized_event)
return timestamp, serialized_event
except IndexError:
return None, None | Pops an event from the heap.
Returns:
tuple: containing:
int: event timestamp or None if the heap is empty
bytes: serialized event or None if the heap is empty |
345,915 | def get_xunit_transform_cmp(config):
skip_searches = [
"SKIPME:",
"Skipping due to these blockers",
"BZ ?[0-9]+",
"GH ?
"GH
]
skips = re.compile("(" + ")|(".join(skip_searches) + ")")
def results_transform(result):
verdict = result.get("verd... | Return result transformation function for CFME. |
345,916 | def train_sbrl(data_file, label_file, lambda_=20, eta=2, max_iters=300000, n_chains=20, alpha=1, seed=None, verbose=0):
if isinstance(alpha, int):
alphas = np.array([alpha], dtype=np.int32)
elif isinstance(alpha, list):
for a in alpha:
assert isinstance(a, int)
alphas = ... | The basic training function of the scalable bayesian rule list.
Users are suggested to use SBRL instead of this function.
It takes the paths of the pre-processed data and label files as input,
and return the parameters of the trained rule list.
Check pysbrl.utils:categorical2pysbrl_data to see how to c... |
345,917 | def sync_role_definitions(self):
from superset import conf
logging.info()
self.create_custom_permissions()
self.set_role(, self.is_admin_pvm)
self.set_role(, self.is_alpha_pvm)
self.set_role(, self.is_gamma_pvm)
self.set_role(, self.is_granter_... | Inits the Superset application with security roles and such |
345,918 | def get_request_from_view_args(self, view, args, kwargs):
req = args[1]
assert isinstance(req, falcon.Request), "Argument is not a falcon.Request"
return req | Get request from a resource method's arguments. Assumes that
request is the second argument. |
345,919 | def _handle(self, event_handler, event_name, user_args, event_timeout,
cond, cond_timeout):
if cond:
cond.wait(cond_timeout)
event = self.pop_event(event_name, event_timeout)
return event_handler(event, *user_args) | Pop an event of specified type and calls its handler on it. If
condition is not None, block until condition is met or timeout. |
345,920 | def extract_columns(self, result={}, selector=, table_headers=[], attr=, connector=, default=, verbosity=0, *args, **kwargs):
result_list = []
try:
if type(selector) in [str, unicode]:
selectors = [selector]
elif type(selector) == list:
selectors = selector[:]
else:
raise Exception("Use a l... | Column data extraction for extract_tabular |
345,921 | def roles(self):
guild = self.guild
if guild is None:
return []
return [role for role in guild.roles if self._roles.has(role.id)] | List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji.
If roles is empty, the emoji is unrestricted. |
345,922 | def fire_hooks(ctx, document, elem, element, hooks):
if not hooks:
return
for hook in hooks:
hook(ctx, document, elem, element) | Fire hooks on newly created element.
For each newly created element we will try to find defined hooks and execute them.
:Args:
- ctx (:class:`Context`): Context object
- document (:class:`ooxml.doc.Document`): Document object
- elem (:class:`ooxml.doc.Element`): Element which we serialized
... |
345,923 | def get_advanced_search_form(self, data):
if self.get_advanced_search_form_class():
self._advanced_search_form = self.get_advanced_search_form_class()(
data=data
)
return self._advanced_search_form | Hook to dynamically change the advanced search form |
345,924 | def read_local_file(filename):
frm = inspect.currentframe().f_back
if frm.f_code.co_name == :
frm = frm.f_back
path = os.path.split(frm.f_code.co_filename)[0]
return read_file(os.path.join(path, filename)) | This will read a file in the same directory as the calling function
:param filename: str of the basename of the file
:return: str of the content of the file |
345,925 | def parse_generator_doubling(config):
start = 1
if in config:
start = int(config[])
def generator():
val = start
while(True):
yield val
val = val * 2
return generator() | Returns generators that double with each value returned
Config includes optional start value |
345,926 | def primers(self, tm=60):
self.primers = coral.design.primers(self.template, tm=tm)
return self.primers | Design primers for amplifying the assembled sequence.
:param tm: melting temperature (lower than overlaps is best).
:type tm: float
:returns: Primer list (the output of coral.design.primers).
:rtype: list |
345,927 | def get_server(self, UUID):
server, IPAddresses, storages = self.get_server_data(UUID)
return Server(
server,
ip_addresses=IPAddresses,
storage_devices=storages,
populated=True,
cloud_manager=self
) | Return a (populated) Server instance. |
345,928 | def get_image_hash(image_path,
level=None,level_filter=None,
include_files=None,
skip_files=None,
version=None):
if level_filter is not None:
file_filter = level_filter
elif level is None:
file_filter = ... | get_image_hash will generate a sha1 hash of an image, depending on a level
of reproducibility specified by the user. (see function get_levels for descriptions)
the user can also provide a level_filter manually with level_filter (for custom levels)
:param level: the level of reproducibility to use, which map... |
345,929 | def _convenienceMatch(self, role, attr, match):
kwargs = {}
if match:
kwargs[attr] = match
return self.findAll(AXRole=role, **kwargs) | Method used by role based convenience functions to find a match |
345,930 | def concat(self, other, strict=False):
mdata = self.copy()
if strict:
for key in other.keys():
if key in mdata:
raise RuntimeError( +
)
for key in other.keys_nD():
if key... | Concats two metadata objects together.
Parameters
----------
other : Meta
Meta object to be concatenated
strict : bool
if True, ensure there are no duplicate variable names
Notes
-----
Uses units and name label of self if other is differe... |
345,931 | def read_text(forfn, nrows=None, verbose=True):
r
tqdm_prog = tqdm if verbose else no_tqdm
nrows = wc(forfn, nrows=nrows)
lines = np.empty(dtype=object, shape=nrows)
with ensure_open(forfn) as f:
for i, line in enumerate(tqdm_prog(f, total=nrows)):
if i >= len(lines):
... | r""" Read all the lines (up to nrows) from a text file or txt.gz file
>>> fn = os.path.join(DATA_PATH, 'mavis-batey-greetings.txt')
>>> len(read_text(fn, nrows=3))
3 |
345,932 | def sql_get(self, owner, id, query, **kwargs):
kwargs[] = True
if kwargs.get():
return self.sql_get_with_http_info(owner, id, query, **kwargs)
else:
(data) = self.sql_get_with_http_info(owner, id, query, **kwargs)
return data | SQL query (via GET)
This endpoint executes SQL queries against a dataset. SQL results are available in a variety of formats. By default, `application/json` will be returned. Set the `Accept` header to one of the following values in accordance with your preference: * `text/csv` * `application/json` * `applicat... |
345,933 | def sys_wait_for_event(
mask: int, k: Optional[Key], m: Optional[Mouse], flush: bool
) -> int:
return int(
lib.TCOD_sys_wait_for_event(
mask,
k.key_p if k else ffi.NULL,
m.mouse_p if m else ffi.NULL,
flush,
)
) | Wait for an event then return.
If flush is True then the buffer will be cleared before waiting. Otherwise
each available event will be returned in the order they're recieved.
Args:
mask (int): :any:`Event types` to wait for.
k (Optional[Key]): A tcod.Key instance which might be updated wit... |
345,934 | def has_causal_out_edges(graph: BELGraph, node: BaseEntity) -> bool:
return any(
data[RELATION] in CAUSAL_RELATIONS
for _, _, data in graph.out_edges(node, data=True)
) | Return true if the node contains any out_edges that are causal. |
345,935 | def run(self, dag):
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits()) !=... | Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG |
345,936 | def __parse_flags(self, body):
flags = []
values = []
lines = body.split()
for l in lines:
for name in self.FLAGS_REGEX:
m = re.match(self.FLAGS_REGEX[name], l)
if m:
flags.append(name)
values.a... | Parse flags from a message |
345,937 | def get_DataFrame(self, data=False, with_unit=True, with_population=True):
for key in self.__dict__:
if (key is ) and not with_unit:
continue
if (key is ) and not with_population:
continue
if type(self.__dict__[key]) is pd.DataFrame:
... | Yields all panda.DataFrames or there names
Notes
-----
For IOSystem this does not include the DataFrames in the extensions.
Parameters
----------
data : boolean, optional
If True, returns a generator which yields the DataFrames.
If False, returns... |
345,938 | def height(self):
min_height = int(bool(self))
return max([min_height] + [c.height()+1 for c, p in self.children]) | Returns height of the (sub)tree, without considering
empty leaf-nodes
>>> create(dimensions=2).height()
0
>>> create([ (1, 2) ]).height()
1
>>> create([ (1, 2), (2, 3) ]).height()
2 |
345,939 | def urlencode(params):
if not isinstance(params, dict):
raise TypeError("Only dicts are supported.")
params = flatten(params)
url_params = OrderedDict()
for param in params:
value = param.pop()
name = parametrize(param)
if isinstance(value, (list, tuple)):
... | Urlencode a multidimensional dict. |
345,940 | def special_time_extrator(self, string):
try:
if not self.year_check:
str_year = int(re.search(, string).group(1))
check_year = datetime.datetime.now().year
if str_year in range(1970, check_year + 1):
self.year = str_year
... | 特殊时间抽取,即年月日单独出现
Keyword arguments:
string -- 含有时间的文本,str类型 |
345,941 | def append(self, other):
to_concat = [self]
if isinstance(other, (list, tuple)):
to_concat = to_concat + list(other)
else:
to_concat.append(other)
for obj in to_concat:
if not isinstance(obj, Index):
raise TypeError()
... | Append a collection of Index options together.
Parameters
----------
other : Index or list/tuple of indices
Returns
-------
appended : Index |
345,942 | def setGroupBy(self, groupBy):
if groupBy and not type(groupBy) in (list, tuple):
groupBy = [nativestring(groupBy)]
elif not groupBy:
groupBy = None
self._groupBy = groupBy | Sets the grouping information for this tree.
:param groupBy | [<str> group level, ..] || None |
345,943 | def step(self, y, u, t, h):
k1 = h * self.func(t, y, u)
k2 = h * self.func(t + .5*h, y + .5*h*k1, u)
k3 = h * self.func(t + .5*h, y + .5*h*k2, u)
k4 = h * self.func(t + h, y + h*k3, u)
return y + (k1 + 2*k2 + 2*k3 + k4) / 6.0 | This is called by solve, but can be called by the user who wants to
run through an integration with a control force.
y - state at t
u - control inputs at t
t - time
h - step size |
345,944 | def zipLists(*lists):
length = len(lists[0])
for i, list_ in enumerate(lists[1:]):
if len(list_) != length:
msg = "List at index {} has length {} != {}".format(
i + 1, len(list_), length)
raise AssertionError(msg)
return zip(*lists) | Checks to see if all of the lists are the same length, and throws
an AssertionError otherwise. Returns the zipped lists. |
345,945 | def _verify_dict_list(self, values, keys, name):
keys = set(keys)
name = name.title()
for value in values:
if not isinstance(value, Mapping):
raise MessageError(.format(name))
for key in keys:
if key not in value:
... | Validate a list of `dict`, ensuring it has specific keys
and no others.
:param values: A list of `dict` to validate.
:param keys: A list of keys to validate each `dict` against.
:param name: Name describing the values, to show in error messages. |
345,946 | def has_hints(self):
for acc in ["low", "normal", "high"]:
try:
if self.hint_for_accuracy(acc) is None:
return False
except KeyError:
return False
return True | True if self provides hints on the cutoff energy. |
345,947 | def stopMessage(self, apiMsgId):
content = self.parseLegacy(self.request(, {: apiMsgId}))
return {
: content[],
: content[],
: self.getStatus(content[])
} | See parent method for documentation |
345,948 | def _collect_values(handlers, names, user, client, values):
results = {}
def visitor(claim_name, func):
data = {: user, : client}
data.update(values.get(claim_name) or {})
claim_value = func(data)
if claim_value is not None:
results[claim_... | Get the values from the handlers of the requested claims. |
345,949 | def next_items(self, n):
items = []
while len(items) < n:
if self._line_ptr >= len(self._line):
line = next(self._file).strip()
while not line or line[0] == "
line = next(self._file).strip()
... | Returns the next n items.
Throws StopIteration when there is not enough data to return n items. |
345,950 | def sphinx_extension(app, exception):
"Wrapped up as a Sphinx Extension"
if not app.builder.name in ("html", "dirhtml"):
return
if not app.config.sphinx_to_github:
if app.config.sphinx_to_github_verbose:
print("Sphinx-to-github: Disabled, doing nothing.")
return
if ... | Wrapped up as a Sphinx Extension |
345,951 | def get_all_used_vars(section):
all_used_vars = set()
for statement in section.statements:
if statement[0] == :
all_used_vars |= accessed_vars(.join(statement[1:3]))
elif statement[0] == :
all_used_vars |= accessed_vars(statement[1])
elif statement[0] == :
... | Get variables which are variables used by input statement and statements before it |
345,952 | def make_catalog_comp_info_dict(self, catalog_sources):
catalog_ret_dict = {}
split_ret_dict = {}
for key, value in catalog_sources.items():
if value is None:
continue
if value[] != :
continue
versions = value[]
... | Make the information about the catalog components
Parameters
----------
catalog_sources : dict
Dictionary with catalog source defintions
Returns
-------
catalog_ret_dict : dict
Dictionary mapping catalog_name to `model_component.CatalogInfo`
... |
345,953 | def cli(env, volume_id, new_size, new_iops, new_tier):
file_manager = SoftLayer.FileStorageManager(env.client)
if new_tier is not None:
new_tier = float(new_tier)
try:
order = file_manager.order_modified_volume(
volume_id,
new_size=new_size,
new_iop... | Modify an existing file storage volume. |
345,954 | def validate_file(fpath, md5_hash):
hasher = hashlib.md5()
with open(fpath, ) as f:
buf = f.read()
hasher.update(buf)
if str(hasher.hexdigest()) == str(md5_hash):
return True
else:
return False | Validates a file against a MD5 hash
# Arguments
fpath: path to the file being validated
md5_hash: the MD5 hash being validated against
# Returns
Whether the file is valid |
345,955 | def deselect_all(self):
if not self.is_multiple:
raise NotImplementedError("You may only deselect all options of a multi-select")
for opt in self.options:
self._unsetSelected(opt) | Clear all selected entries. This is only valid when the SELECT supports multiple selections.
throws NotImplementedError If the SELECT does not support multiple selections |
345,956 | def _set_ospf_level2(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="ospf-level2", rest_name="level-2", parent=self, choice=(u, u), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, ext... | Setter method for ospf_level2, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level2 (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_ospf_lev... |
345,957 | def print_usage():
print( + os.path.basename(sys.argv[0]) + )
print()
print()
print()
print()
print()
print() | Prints usage message. |
345,958 | def get(self, section, val):
val = val.lower()
if section in self.__config:
if val in self.__config[section]:
return self.__config[section][val]
if section in self.__defaults:
if val in self.__defaults[section]:
... | Get a setting or the default
`Returns` The current value of the setting `val` or the default, or `None` if not found
`section` (mandatory) (string) the section name in the config E.g. `"agent"`
`val` (mandatory) (string) the section name in the config E.g. `"host"` |
345,959 | def delete_avatar(self, scope=):
return _delete(
token=self.oauth.get_user_token(scope),
uri=
) | Delete the Mxit user's avatar
User authentication required with the following scope: 'avatar/write' |
345,960 | def get_node(obj, args, kwargs):
if args is None and kwargs is None:
return (obj,)
if kwargs is None:
kwargs = {}
return obj, _bind_args(obj, args, kwargs) | Create a node from arguments and return it |
345,961 | def convert_bytes_to_ints(in_bytes, num):
out_arr = []
for i in range(len(in_bytes)//num):
val = in_bytes[i * num:i * num + num]
unpacked = struct.unpack(mmtf.utils.constants.NUM_DICT[num], val)
out_arr.append(unpacked[0])
return out_arr | Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array |
345,962 | def run(self, *args):
params = self.parser.parse_args(args)
sources = params.source
code = self.autocomplete(sources)
return code | Autocomplete profile information. |
345,963 | def put_str(content, path, share=, conn=None, host=None, username=None, password=None):
if HAS_SMBPROTOCOL:
return _put_str_smbprotocol(
content, path, share, conn=conn, host=host,
username=username, password=password
)
elif HAS_IMPACKET:
return _put_str_impa... | Wrapper around impacket.smbconnection.putFile() that allows a string to be
uploaded, without first writing it as a local file |
345,964 | def set_value(self, k, v):
from ast import literal_eval
if self.engine is None or self.proxy is None:
self._trigger_set_value(k, v)
return
if v is None:
del self.proxy[k]
else:
try:
vv = literal_eval(v)
... | Set a value on the proxy, parsing it to a useful datatype if possible |
345,965 | def Email(
self,
From,
To,
Cc=None,
Bcc=None,
Subject=None,
Tag=None,
HtmlBody=None,
TextBody=None,
Metadata=None,
ReplyTo=None,
Headers=None,
TrackOpens=None,
TrackLinks="None",
Attachments=None,
... | Constructs :py:class:`Email` instance.
:return: :py:class:`Email` |
345,966 | def _get_cache_file_path(self, cache_dir=None):
if cache_dir is None:
cache_dir = self._get_writable_cache_dir()
else:
if not os.access(cache_dir, os.W_OK):
raise CacheFileError("None of cache directories is writable.")
... | Get path for cache file
:param str cache_dir: base path for TLD cache, defaults to data dir
:raises: CacheFileError when cached directory is not writable for user
:return: Full path to cached file with TLDs
:rtype: str |
345,967 | def write_wonambi(data, filename, subj_id=, dtype=):
filename = Path(filename)
json_file = filename.with_suffix()
memmap_file = filename.with_suffix()
start_time = data.start_time + timedelta(seconds=data.axis[][0][0])
start_time_str = start_time.strftime()
dataset = {: subj_id,
... | Write file in simple Wonambi format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (the extensions .won and .dat will be added)
subj_id : str
subject id
dtype : str
numpy dtype in which you wa... |
345,968 | def set_coordsys(self):
if self.coordsys.lower() in self.coordsys_mapping:
self.coordsys = self.coordsys_mapping[self.coordsys.lower()] | Mapping to astropy's coordinate system name
# TODO: needs expert attention (Most reference systems are not mapped) |
345,969 | def raw_tag(name, value):
return name.encode() + \
len(value).to_bytes(4, byteorder=) + \
value | Create a DMAP tag with raw data. |
345,970 | def assistant_initiation_actions(self):
if self._assistant_initiation_actions is None:
self._assistant_initiation_actions = AssistantInitiationActionsList(
self._version,
assistant_sid=self._solution[],
)
return self._assistant_initiation_... | Access the assistant_initiation_actions
:returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList
:rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList |
345,971 | def random_tracing():
new_id = _uniq_id()
return Tracing(
span_id=new_id,
parent_id=0,
trace_id=new_id,
traceflags=0) | Create new Tracing() tuple with random IDs. |
345,972 | def _should_set(self, key, mode):
if mode is None or mode not in ["nx", "xx"]:
return True
if mode == "nx":
if key in self.redis:
return False
elif key not in self.redis:
... | Determine if it is okay to set a key.
If the mode is None, returns True, otherwise, returns True of false based on
the value of ``key`` and the ``mode`` (nx | xx). |
345,973 | def close(self):
try:
self.parent_fd.fileno()
except io.UnsupportedOperation:
logger.debug("Not closing parent_fd - reusing existing")
else:
self.parent_fd.close() | Close file, see file.close |
345,974 | def dump_df(self, df, version=None, tags=None, ext=None, **kwargs):
if ext is None:
ext = self.default_ext
fpath = self.fpath(version=version, tags=tags, ext=ext)
fmt = SerializationFormat.by_name(ext)
fmt.serialize(df, fpath, **kwargs) | Dumps an instance of this dataset into a file.
Parameters
----------
df : pandas.DataFrame
The dataframe to dump to file.
version: str, optional
The version of the instance of this dataset.
tags : list of str, optional
The tags associated with... |
345,975 | def get_all_transitions(self, instance_cls):
transitions = self.transitions[instance_cls]
for name, transition in transitions.items():
meta = transition._django_fsm
for transition in meta.transitions.values():
yield transition | Returns [(source, target, name, method)] for all field transitions |
345,976 | def delete_orphan_unique_identities(es, sortinghat_db, current_data_source, active_data_sources):
def get_uuids_in_index(target_uuids):
page = es.search(
index=IDENTITIES_INDEX,
scroll="360m",
size=SIZE_SCROLL_IDENTITIES_INDEX,
body={
... | Delete all unique identities which appear in SortingHat, but not in the IDENTITIES_INDEX.
:param es: ElasticSearchDSL object
:param sortinghat_db: instance of the SortingHat database
:param current_data_source: current data source
:param active_data_sources: list of active data sources |
345,977 | def _cleanup_resourceprovider(self):
self.resourceprovider = ResourceProvider(self.args)
try:
self.resourceprovider.cleanup()
self.logger.info("Cleanup done.")
except Exception as error:
self.logger.error("Cleanup failed! %s", error) | Calls cleanup for ResourceProvider of this run.
:return: Nothing |
345,978 | def pass_bracket(source, start, bracket=):
e = bracket_split(source[start:], [bracket], False)
try:
cand = e.next()
except StopIteration:
return None, None
if not cand.strip():
try:
res = e.next()
return res, start + len(cand) + len(res)
exc... | Returns content of brackets with brackets and first pos after brackets
if source[start] is followed by some optional white space and brackets.
Otherwise None |
345,979 | def _normal_map_callback(self, msg):
try:
self._cur_normal_map = self._bridge.imgmsg_to_cv2(msg)
except:
self._cur_normal_map = None | Callback for handling normal maps. |
345,980 | def publish(self, message, routing_key, *, mandatory=True):
self.sender.send_BasicPublish(self.name, routing_key, mandatory, message) | Publish a message on the exchange, to be asynchronously delivered to queues.
:param asynqp.Message message: the message to send
:param str routing_key: the routing key with which to publish the message
:param bool mandatory: if True (the default) undeliverable messages result in an error (see a... |
345,981 | def FindFirst(params, ctxt, scope, stream, coord, interp):
global FIND_MATCHES_ITER
FIND_MATCHES_ITER = _find_helper(params, ctxt, scope, stream, coord, interp)
try:
first = six.next(FIND_MATCHES_ITER)
return first.start() + FIND_MATCHES_START_OFFSET
except StopIteration as e:
... | This function is identical to the FindAll function except that the
return value is the position of the first occurrence of the target
found. A negative number is returned if the value could not be found. |
345,982 | def has_end(self, stream):
for token in self.end_tokens:
if not self.has_next(token, stream):
continue
offset = len(token)
if self.has_eof(stream, offset):
return True
if self.has_whitespace(stream, offset):
... | EndStatement ::=
EndKeyword (SemiColon | WhiteSpace | Comment | EndProvidedOctetSeq) |
345,983 | def apply(filter):
def decorator(callable):
return lambda *args, **kwargs: filter(callable(*args, **kwargs))
return decorator | Manufacture decorator that filters return value with given function.
``filter``:
Callable that takes a single parameter. |
345,984 | def fetch(url: str, **kwargs) -> Selector:
kwargs.setdefault(, DEFAULT_HEADERS)
try:
res = requests.get(url, **kwargs)
res.raise_for_status()
except requests.RequestException as e:
print(e)
else:
html = res.text
tree = Selector(text=html)
return tree | Send HTTP request and parse it as a DOM tree.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions. |
345,985 | def dispatch(intent_request):
logger.debug(.format(intent_request[], intent_request[][]))
intent_name = intent_request[][]
| Called when the user specifies an intent for this bot. |
345,986 | def encodeLength(length):
if length < 128:
ored_length = length
offset = -1
elif length < 16384:
ored_length = length | 0x8000
offset = -2
elif length < 2097152:
ored_length = length | 0xC00000
offset = -3
e... | Encode given length in mikrotik format.
:param length: Integer < 268435456.
:returns: Encoded length. |
345,987 | def add_route(self, method, path, handler,
*, name=None, expect_handler=None,
swagger_data=None,
validate=None):
if name is None or name in self._named_resources:
name =
if validate is None:
validate = self._default... | Returns route
:param method: as well as in aiohttp
:param path: as well as in aiohttp
:param handler: as well as in aiohttp
and also must be str `mymodule.handler`
:param name: as well as in aiohttp
:param expect_handler: as well as in aiohttp
:param swagger_... |
345,988 | def modify_image_attribute(self, image_id, attribute=,
operation=, user_ids=None, groups=None,
product_codes=None):
params = { : image_id,
: attribute,
: operation}
if user_ids:
self.... | Changes an attribute of an image.
:type image_id: string
:param image_id: The image id you wish to change
:type attribute: string
:param attribute: The attribute you wish to change
:type operation: string
:param operation: Either add or remove (this is required for cha... |
345,989 | def ctc_label(p):
ret = []
p1 = [0] + p
for i, _ in enumerate(p):
c1 = p1[i]
c2 = p1[i+1]
if c2 in (0, c1):
continue
ret.append(c2)
return ret | Iterates through p, identifying non-zero and non-repeating values, and returns them in a list Parameters
----------
p: list of int
Returns
-------
list of int |
345,990 | def retrieve_by_name(self, name, first_certificate=None):
if not isinstance(name, x509.Name):
raise TypeError(pretty_message(
,
type_name(name)
))
if first_certificate and not isinstance(first_certificate, x509.Certificate):
... | Retrieves a list certs via their subject name
:param name:
An asn1crypto.x509.Name object
:param first_certificate:
An asn1crypto.x509.Certificate object that if found, should be
placed first in the result list
:return:
A list of asn1crypto.x509... |
345,991 | def _get_scopes(self):
if self._read_only:
scopes = (READ_ONLY_SCOPE,)
else:
scopes = (DATA_SCOPE,)
if self._admin:
scopes += (ADMIN_SCOPE,)
return scopes | Get the scopes corresponding to admin / read-only state.
Returns:
Tuple[str, ...]: The tuple of scopes. |
345,992 | def load(self, filename, bs=512):
with open(filename, ) as f:
f.seek(GPT_HEADER_OFFSET + 0x0C)
header_size = struct.unpack("<I", f.read(4))[0]
f.seek(GPT_HEADER_OFFSET)
header_data = f.read(header_size)
self.header = GPT_HEADER(header_data)
... | Loads GPT partition table.
Args:
filename (str): path to file or device to open for reading
bs (uint): Block size of the volume, default: 512
Raises:
IOError: If file does not exist or not readable |
345,993 | def tryload_stage(self, moduleName, functionName, name=None):
if name is None:
name = functionName
try:
mod = __import__(moduleName, globals(), locals(), [functionName])
except ImportError, exc:
logger.warn(
.format(name, modul... | Try to load a stage into self, ignoring errors.
If loading a module fails because of some subordinate load
failure, just give a warning and move on. On success the
stage is added to the stage dictionary.
:param str moduleName: name of the Python module
:param str functionName:... |
345,994 | def dump(u, *args, **kwargs):
return dict(
id=u.id,
email=u.email,
password=u.password,
password_salt=u.password_salt,
note=u.note,
full_name=u.full_name if hasattr(u, ) else .format(
u.given_names, u.family_name),
settings=u.settings,
... | Dump the users as a list of dictionaries.
:param u: User to be dumped.
:type u: `invenio.modules.accounts.models.User [Invenio2.x]` or namedtuple.
:returns: User serialized to dictionary.
:rtype: dict |
345,995 | def _check_global_settings():
global settings
if settings is not None:
return True
from os import getenv
result = False
if getenv("PYCI_XML") is None:
err("The environment variable PYCI_XML for the global configuration "
"has not been set.")
el... | Makes sure that the global settings environment variable and file
exist for configuration. |
345,996 | def retrieve(self, id) :
_, _, loss_reason = self.http_client.get("/loss_reasons/{id}".format(id=id))
return loss_reason | Retrieve a single reason
Returns a single loss reason available to the user by the provided id
If a loss reason with the supplied unique identifier does not exist, it returns an error
:calls: ``get /loss_reasons/{id}``
:param int id: Unique identifier of a LossReason.
:return: ... |
345,997 | def detectors(regex=None, sep=, temporary=False):
db = DBManager(temporary=temporary)
dt = db.detectors
if regex is not None:
try:
re.compile(regex)
except re.error:
log.error("Invalid regex!")
return
dt = dt[dt[].str.contains(regex) | dt[].st... | Print the detectors table |
345,998 | def read_grid_from_file(filename):
try:
f = open(filename, mode=)
full_res = ast.literal_eval(f.read())
f.close()
except SyntaxError:
print(, filename)
full_res = {: 0, : False}
except (OSError, IOError):
full_res = {: 0, : False}
return full_res | Read the results of a full set of calculations from file |
345,999 | def _fast_permalink(self):
if hasattr(self, ):
sid = self.link_id.split()[1]
else:
.format(sid, self.id)) | Return the short permalink to the comment. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.