Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
368,500 | def build_css_class(localized_fieldname, prefix=):
bits = localized_fieldname.split()
css_class =
if len(bits) == 1:
css_class = str(localized_fieldname)
elif len(bits) == 2:
css_class = .join(bits)
elif len(bits) > 2:
... | Returns a css class based on ``localized_fieldname`` which is easily
splitable and capable of regionalized language codes.
Takes an optional ``prefix`` which is prepended to the returned string. |
368,501 | def connection_factory(self, endpoint, *args, **kwargs):
kwargs = self._make_connection_kwargs(endpoint, kwargs)
return self.connection_class.factory(endpoint, self.connect_timeout, *args, **kwargs) | Called to create a new connection with proper configuration.
Intended for internal use only. |
368,502 | def symbols():
symbols = []
for line in symbols_stream():
symbols.append(line.decode().strip())
return symbols | Return a list of symbols. |
368,503 | def languages(self):
languages = []
for language in self.cache[]:
language = Structure(
id = language[],
name = language[]
)
languages.append(language)
return languages | A list of strings describing the user's languages. |
368,504 | def fetch(self):
params = values.of({})
payload = self._version.fetch(
,
self._uri,
params=params,
)
return CompositionSettingsInstance(self._version, payload, ) | Fetch a CompositionSettingsInstance
:returns: Fetched CompositionSettingsInstance
:rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance |
368,505 | def strip_transcript_versions(fasta, out_file):
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
with open(fasta) as in_handle:
for line in in_handle:
if line.... | strip transcript versions from a FASTA file. these appear like this:
>ENST00000434970.2 cdna chromosome:GRCh38:14:22439007:22439015:1 etc |
368,506 | def _dihedral_affine(k:partial(uniform_int,0,7)):
"Randomly flip `x` image based on `k`."
x = -1 if k&1 else 1
y = -1 if k&2 else 1
if k&4: return [[0, x, 0.],
[y, 0, 0],
[0, 0, 1.]]
return [[x, 0, 0.],
[0, y, 0],
[0, 0, 1.]] | Randomly flip `x` image based on `k`. |
368,507 | def check_minions(self,
expr,
tgt_type=,
delimiter=DEFAULT_TARGET_DELIM,
greedy=True):
public keys
stored for authentication. This should return a set of ids which
match the regex, this will then be used to ... | Check the passed regex against the available minions' public keys
stored for authentication. This should return a set of ids which
match the regex, this will then be used to parse the returns to
make sure everyone has checked back in. |
368,508 | def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False):
if bias_x:
x = nd.concat(x, nd.ones((1, seq_len, batch_size)), dim=0)
if bias_y:
y = nd.concat(y, nd.ones((1, seq_len, batch_size)), dim=0)
nx, ny = input_size + bias_x, input_size + bias... | Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
input_size : int
input dimension
seq_len : int
sequence length
batch_size : int
... |
368,509 | def add_page(self, pattern, classname):
if not self._loaded:
raise PluginManagerNotLoadedException()
self._app.add_mapping(pattern, classname) | Add a new page to the web application. Only available after that the Plugin Manager is loaded |
368,510 | def _request_delete(self, path, params=None, url=BASE_URL):
url = urljoin(url, path)
headers = self._get_request_headers()
response = requests.delete(
url, params=params, headers=headers, timeout=DEFAULT_TIMEOUT)
response.raise_for_status()
if response.stat... | Perform a HTTP DELETE request. |
368,511 | def copy(self):
cpy = self.__class__()
cpy._autostep = self._autostep
cpy.padding = self.padding
cpy.update(self)
return cpy | Return a shallow copy of a RangeSet. |
368,512 | def remove_objects(self, bucket_name, objects_iter):
is_valid_bucket_name(bucket_name)
if isinstance(objects_iter, basestring):
raise TypeError(
)
objects_iter = itertools.chain(objects_iter)
obj_batch = []
... | Removes multiple objects from a bucket.
:param bucket_name: Bucket from which to remove objects
:param objects_iter: A list, tuple or iterator that provides
objects names to delete.
:return: An iterator of MultiDeleteError instances for each
object that had a delete error. |
368,513 | def get_collection(cls):
if g.get():
return getattr(
cls.get_db(),
.format(collection=cls._collection)
)
return getattr(cls.get_db(), cls._collection) | Return a reference to the database collection for the class |
368,514 | def _dep_map(self):
try:
return self.__dep_map
except AttributeError:
self.__dep_map = self._filter_extras(self._build_dep_map())
return self.__dep_map | A map of extra to its list of (direct) requirements
for this distribution, including the null extra. |
368,515 | def upload(self, f):
if hasattr(f, ):
needs_closing = False
else:
f = open(f, )
needs_closing = True
md5 = md5_file(f)
data = {
: ,
: md5
}
files = {
: (filename, f)
... | Upload a file to the Puush account.
Parameters:
* f: The file. Either a path to a file or a file-like object. |
368,516 | def _distance_matrix_generic(x, centering, exponent=1):
_check_valid_dcov_exponent(exponent)
x = _transform_to_2d(x)
a = distances.pairwise_distances(x, exponent=exponent)
a = centering(a, out=a)
return a | Compute a centered distance matrix given a matrix. |
368,517 | def BE64(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
return UInt64(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) | 64-bit field, Big endian encoded |
368,518 | def save(self, filename, binary=True):
filename = os.path.abspath(os.path.expanduser(filename))
file_mode = True
ftype = filename[-3:]
if ftype == :
writer = vtk.vtkPLYWriter()
elif ftype == :
writer = vtk.vtkXMLPolyDataWriter()
... | Writes a surface mesh to disk.
Written file may be an ASCII or binary ply, stl, or vtk mesh file.
Parameters
----------
filename : str
Filename of mesh to be written. File type is inferred from
the extension of the filename unless overridden with
ft... |
368,519 | def temporal_louvain(tnet, resolution=1, intersliceweight=1, n_iter=100, negativeedge=, randomseed=None, consensus_threshold=0.5, temporal_consensus=True, njobs=1):
r
tnet = process_input(tnet, [, , ], )
resolution = resolution / tnet.T
supranet = create_supraadjacency_matrix(
tnet, inters... | r"""
Louvain clustering for a temporal network.
Parameters
-----------
tnet : array, dict, TemporalNetwork
Input network
resolution : int
resolution of Louvain clustering ($\gamma$)
intersliceweight : int
interslice weight of multilayer clustering ($\omega$). Must be pos... |
368,520 | def get_size(self, value=None):
if value is None:
if not self:
return 0
elif issubclass(type(self[0]), GenericType):
return len(self) * self[0].get_size()
return sum(item... | Return the size in bytes.
Args:
value: In structs, the user can assign other value instead of
this class' instance. Here, in such cases, ``self`` is a class
attribute of the struct.
Returns:
int: The size in bytes. |
368,521 | def kruskal_mst(graph):
edges_accepted = 0
ds = DisjointSet()
pq = PriorityQueue()
accepted_edges = []
label_lookup = {}
nodes = graph.get_all_node_ids()
num_vertices = len(nodes)
for n in nodes:
label = ds.add_set()
label_lookup[n] = label
edges = graph.get_al... | Implements Kruskal's Algorithm for finding minimum spanning trees.
Assumes a non-empty, connected graph. |
368,522 | def multicategory_scatterplot(output_directory, file_prefix, df,
x_series_index, y_series_index, category_series_index,
series_color, plot_title = ,
x_axis_label = , y_axis_label = ,
min_predicted_ddg... | This function was adapted from the covariation benchmark. |
368,523 | def send(self, to, subject, body, reply_to=None, **kwargs):
if not self.sender:
raise AttributeError("Sender email or is not provided")
kwargs["to_addresses"] = to
kwargs["subject"] = subject
kwargs["body"] = body
kwargs["source"] = self._get_sender(self.s... | Send email via AWS SES.
:returns string: message id
***
Composes an email message based on input data, and then immediately
queues the message for sending.
:type to: list of strings or string
:param to: The To: field(s) of the message.
:type subject: string
... |
368,524 | def command_clean(string, vargs):
valid_chars, invalid_chars = remove_invalid_ipa_characters(
unicode_string=string,
return_invalid=True,
single_char_parsing=vargs["single_char_parsing"]
)
print(u"".join(valid_chars))
print_invalid_chars(invalid_chars, vargs) | Remove characters that are not IPA valid from the given string,
and print the remaining string.
:param str string: the string to act upon
:param dict vargs: the command line arguments |
368,525 | def ls_command(
endpoint_plus_path,
recursive_depth_limit,
recursive,
long_output,
show_hidden,
filter_val,
):
endpoint_id, path = endpoint_plus_path
client = get_client()
autoactivate(client, endpoint_id, if_expires_in=60)
ls_params = {"show_hidden": int(sh... | Executor for `globus ls` |
368,526 | def _get_footer_size(file_obj):
file_obj.seek(-8, 2)
tup = struct.unpack(b"<i", file_obj.read(4))
return tup[0] | Read the footer size in bytes, which is serialized as little endian. |
368,527 | def fit(self, X, y, n_iter=None):
self.n_iter = self.n_iter if n_iter is None else n_iter
X = getattr(X, , X).reshape(len(X), 1)
X_1 = self.homogenize(X)
for i in range(self.n_iter):
for i in range(0, len(X), 10):
batch = slice(i, min(i + 10, len(X)... | w = w + α * δ * X |
368,528 | def set_line_width(self, width):
cairo.cairo_set_line_width(self._pointer, width)
self._check_status() | Sets the current line width within the cairo context.
The line width value specifies the diameter of a pen
that is circular in user space,
(though device-space pen may be an ellipse in general
due to scaling / shear / rotation of the CTM).
.. note::
When the descript... |
368,529 | def _init_level_set(init_level_set, image_shape):
if isinstance(init_level_set, str):
if init_level_set == :
res = checkerboard_level_set(image_shape)
elif init_level_set == :
res = circle_level_set(image_shape)
else:
raise ValueError("`init_level_set... | Auxiliary function for initializing level sets with a string.
If `init_level_set` is not a string, it is returned as is. |
368,530 | def write_bytes(self, where, data, force=False):
mp = self.memory.map_containing(where)
can_write_raw = type(mp) is AnonMap and \
isinstance(data, (str, bytes)) and \
(mp.end - mp.start + 1) >= len(data) >= 1024 and \
not ... | Write a concrete or symbolic (or mixed) buffer to memory
:param int where: address to write to
:param data: data to write
:type data: str or list
:param force: whether to ignore memory permissions |
368,531 | def t_BIN(self, t):
r
if t.value[0] == :
t.value = t.value[1:]
else:
t.value = t.value[:-1]
t.value = int(t.value, 2)
t.type =
return t | r'(%[01]+)|([01]+[bB]) |
368,532 | def save(name, data, rc_file=):
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
if not conf.has_section(name):
conf.add_section(name)
for key in data:
value = data[key]
conf.set(name, key, str(value))
with open(os.path.expanduser(rc_file), ) as file_:
... | Save the `data` session configuration under the name `name`
in the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.save(
... 'foo',
... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc',
... 'port': 8069, 'timeout': 120, 'database': 'db_name'
... 'user': '... |
368,533 | def add_vertex(self, vertex, **attr):
self.vertices[vertex] = []
if attr:
self.nodes[vertex] = attr | Add vertex and update vertex attributes |
368,534 | def add_chart(self, component):
if getattr(component, "name") != "Chart":
raise Exception("Component is not an instance of Chart")
self.charts.append(component) | Add a chart to the layout. |
368,535 | def build_module(name, doc=None):
node = nodes.Module(name, doc, pure_python=False)
node.package = False
node.parent = None
return node | create and initialize an astroid Module node |
368,536 | def preorder(self, skip_seed=False):
for node in self._tree.preorder_node_iter():
if skip_seed and node is self._tree.seed_node:
continue
yield node | Return a generator that yields the nodes of the tree in preorder.
If skip_seed=True then the root node is not included. |
368,537 | def delete_volume(target, stop=True):
*
volinfo = info()
if target not in volinfo:
log.error(, target)
return False
running = (volinfo[target][] == )
if not stop and running:
log.error(, target)
return False
if running:
if not stop_volume(... | Deletes a gluster volume
target
Volume to delete
stop : True
If ``True``, stop volume before delete
CLI Example:
.. code-block:: bash
salt '*' glusterfs.delete_volume <volume> |
368,538 | def set_setting(name, value):
Credential ValidationSuccess and FailureCredential ValidationNo Auditing
if name.lower() not in _get_valid_names():
raise KeyError(.format(name))
for setting in settings:
if value.lower() == setting.lower():
cmd = .format(name, settings[setting]... | Set the configuration for the named audit setting
Args:
name (str):
The name of the setting to configure
value (str):
The configuration for the named value. Valid options are:
- No Auditing
- Success
- Failure
- Success and ... |
368,539 | def _make_value(self, value):
if isinstance(value, self._child_spec):
new_value = value
elif issubclass(self._child_spec, Any):
if isinstance(value, Asn1Value):
new_value = value
else:
raise ValueError(unwrap(
... | Constructs a _child_spec value from a native Python data type, or
an appropriate Asn1Value object
:param value:
A native Python value, or some child of Asn1Value
:return:
An object of type _child_spec |
368,540 | def create_application(self):
return application.Application(self.settings,
self.namespace.routes,
self.port) | Create and return a new instance of tinman.application.Application |
368,541 | def update_value_from_mapping(source_resource_attr_id, target_resource_attr_id, source_scenario_id, target_scenario_id, **kwargs):
user_id = int(kwargs.get())
rm = aliased(ResourceAttrMap, name=)
mapping = db.DBSession.query(rm).filter(
or_(
and_(
rm.resource_a... | Using a resource attribute mapping, take the value from the source and apply
it to the target. Both source and target scenarios must be specified (and therefor
must exist). |
368,542 | def _initialise(self, feed_type="linear"):
self._filenames = filenames = _create_filenames(self._filename_schema,
feed_type)
self._files = files = _open_fits_files(filenames)
self._axes = axes = _create_axes(filenames, files)
... | Initialise the object by generating appropriate filenames,
opening associated file handles and inspecting the FITS axes
of these files. |
368,543 | def uniqid(iface=, is_hex=True):
m_ = get_addr(iface)
m_ = .join(m_.split()) if m_ else m_
if m_ and not is_hex:
m_ = str(int(m_.upper(), 16))
return m_ | 使用网卡的物理地址 ``默认wlan0`` 来作为标识
- 置位 ``is_hex``, 来确定返回 ``16进制/10进制格式``
:param iface: ``网络接口(默认wlan0)``
:type iface: str
:param is_hex: ``True(返回16进制)/False(10进制)``
:type is_hex: bool
:return: ``mac地址/空``
:rtype: str |
368,544 | def add_reader(self, fd, callback):
" Start watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
self._read_fds[h] = callback | Start watching the file descriptor for read availability. |
368,545 | def get_shape_str(tensors):
if isinstance(tensors, (list, tuple)):
for v in tensors:
assert isinstance(v, (tf.Tensor, tf.Variable)), "Not a tensor: {}".format(type(v))
shape_str = ",".join(
map(lambda x: str(x.get_shape().as_list()), tensors))
else:
assert is... | Internally used by layer registry, to print shapes of inputs/outputs of layers.
Args:
tensors (list or tf.Tensor): a tensor or a list of tensors
Returns:
str: a string to describe the shape |
368,546 | def get_parameter(self):
self._parameter.value = self._input.value()
return self._parameter | Obtain the parameter object from the current widget state.
:returns: A BooleanParameter from the current state of widget |
368,547 | def refreshUi( self ):
widget = self.uiContentsTAB.currentWidget()
is_content = isinstance(widget, QWebView)
if is_content:
self._currentContentsIndex = self.uiContentsTAB.currentIndex()
history = widget.page().history()
else:
... | Refreshes the interface based on the current settings. |
368,548 | def serialize_to_file(obj, file_name, append=False):
logging.info("Serializing to file %s.", file_name)
with tf.gfile.Open(file_name, "a+" if append else "wb") as output_file:
pickle.dump(obj, output_file)
logging.info("Done serializing to file %s.", file_name) | Pickle obj to file_name. |
368,549 | def NormalizePath(path, sep="/"):
if not path:
return sep
path = SmartUnicode(path)
path_list = path.split(sep)
if path_list[0] in [".", "..", ""]:
path_list.pop(0)
i = 0
while True:
list_len = len(path_list)
for i in range(i, len(path_list)):
if path_lis... | A sane implementation of os.path.normpath.
The standard implementation treats leading / and // as different leading to
incorrect normal forms.
NOTE: Its ok to use a relative path here (without leading /) but any /../ will
still be removed anchoring the path at the top level (e.g. foo/../../../../bar
=> bar)... |
368,550 | def __track_vars(self, command_result):
command_env = command_result.environment()
for var_name in self.tracked_vars():
if var_name in command_env.keys():
self.__vars[var_name] = command_env[var_name] | Check if there are any tracked variable inside the result. And keep them for future use.
:param command_result: command result tot check
:return: |
368,551 | def unicode_wrapper(self, property, default=ugettext()):
try:
value = getattr(self, property)
except ValueError:
logger.warn(
u,
self._meta.object_name
)
value = None
if not value:
val... | Wrapper to allow for easy unicode representation of an object by
the specified property. If this wrapper is not able to find the
right translation of the specified property, it will return the
default value instead.
Example::
def __unicode__(self):
return uni... |
368,552 | def print_markdown(data, title=None):
def excl_value(value):
return isinstance(value, basestring_) and Path(value).exists()
if isinstance(data, dict):
data = list(data.items())
markdown = ["* **{}:** {}".format(l, unicode_(v))
for l, v in data if not excl_value... | Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2. |
368,553 | def suggest(self, index=None, body=None, params=None):
_, data = yield self.transport.perform_request(,
_make_path(index,
),
pa... | The suggest feature suggests similar looking terms based on a provided
text by using a suggester.
`<http://elasticsearch.org/guide/reference/api/search/suggest/>`_
:arg index: A comma-separated list of index names to restrict the
operation; use `_all` or empty string to perform the ... |
368,554 | def convert_value(v):
if v and isinstance(v, six.string_types):
v = v.strip()
if (v.startswith() and v.endswith()) or (v.startswith() and v.endswith()):
try:
return json.loads(v)
except Exception as e:
logger.error(e)
return v | 默认使用Json转化数据,凡以[或{开始的,均载入json
:param v:
:return: |
368,555 | def course_feature(catalog, soup):
courses = {}
course_crns = {}
for course in soup.findAll():
c = Course.from_soup_tag(course)
courses[str(c)] = c
catalog.courses = courses
catalog.courses
logger.info( % len(courses)) | Parses all the courses (AKA, the most important part). |
368,556 | def subscribe(self, channel_name):
data = {: channel_name}
if channel_name.startswith():
data[] = self._generate_presence_key(
self.connection.socket_id,
self.key,
channel_name,
self.secret,
self.user_d... | Subscribe to a channel
:param channel_name: The name of the channel to subscribe to.
:type channel_name: str
:rtype : Channel |
368,557 | def _write(self, command, future):
def on_written():
self._on_written(command, future)
try:
self._stream.write(command.command, callback=on_written)
except iostream.StreamClosedError as error:
future.set_exception(exceptions.ConnectionError(error))
... | Write a command to the socket
:param Command command: the Command data structure |
368,558 | def _get_key_from_raw_synset(raw_synset):
pos = raw_synset.pos
literal = raw_synset.variants[0].literal
sense = "%02d"%raw_synset.variants[0].sense
return .join([literal,pos,sense]) | Derives synset key in the form of `lemma.pos.sense_no` from the provided eurown.py Synset class,
Notes
-----
Internal function. Do not call directly.
Parameters
----------
raw_synset : eurown.Synset
Synset representation from which lemma, part-of-speech and sense is derived.
Return... |
368,559 | def API_GET(self, courseid, taskid, submissionid):
with_input = "input" in web.input()
return _get_submissions(self.course_factory, self.submission_manager, self.user_manager, self.app._translations, courseid, taskid, with_input, submissionid) | List all the submissions that the connected user made. Returns list of the form
::
[
{
"id": "submission_id1",
"submitted_on": "date",
"status" : "done", #can be "done", "waiting", "error" ... |
368,560 | def get_possible_combos_for_transition(trans, model, self_model, is_external=False):
from_state_combo = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING)
from_outcome_combo = Gtk.ListStore(GObject.TYPE_STRING)
to_state_combo = Gtk.ListStore(GObject.TYPE_STRING)
to_outcome_... | The function provides combos for a transition and its respective
:param trans:
:param model:
:param self_model:
:param is_external:
:return: |
368,561 | def do_videoplaceholder(parser, token):
name, params = parse_placeholder(parser, token)
return VideoPlaceholderNode(name, **params) | Method that parse the imageplaceholder template tag. |
368,562 | def build_dependencies(self) -> "Dependencies":
validate_build_dependencies_are_present(self.manifest)
dependencies = self.manifest["build_dependencies"]
dependency_packages = {}
for name, uri in dependencies.items():
try:
validate_build_dependency(n... | Return `Dependencies` instance containing the build dependencies available on this Package.
The ``Package`` class should provide access to the full dependency tree.
.. code:: python
>>> owned_package.build_dependencies['zeppelin']
<ZeppelinPackage> |
368,563 | def capability(cap, *wrap_exceptions):
if isinstance(cap, WNetworkClientCapabilities) is True:
cap = cap.value
elif isinstance(cap, str) is False:
raise TypeError()
def first_level_decorator(decorated_function):
def second_level_decorator(original_function, *args, **kwargs):
if len(wrap_exceptio... | Return a decorator, that registers function as capability. Also, all specified exceptions are
caught and instead of them the :class:`.WClientCapabilityError` exception is raised
:param cap: target function capability (may be a str or :class:`.WNetworkClientCapabilities` class )
:param wrap_exceptions: exceptions... |
368,564 | def on_success(self, retval, task_id, args, kwargs):
log.info(("{} SUCCESS - retval={} task_id={} "
"args={} kwargs={}")
.format(
self.log_label,
retval,
task_id,
args,
... | on_success
http://docs.celeryproject.org/en/latest/reference/celery.app.task.html
:param retval: return value
:param task_id: celery task id
:param args: arguments passed into task
:param kwargs: keyword arguments passed into task |
368,565 | def complete_set_acls(self, cmd_param_text, full_cmd, *rest):
possible_acl = [
"digest:",
"username_password:",
"world:anyone:c",
"world:anyone:cd",
"world:anyone:cdr",
"world:anyone:cdrw",
"world:anyone:cdrwa",
... | FIXME: complete inside a quoted param is broken |
368,566 | def get_config_node(self):
default_ns =
config_node = etree.Element(config_tag, nsmap={: nc_url})
for index, url_piece in enumerate(self._url_pieces):
if index == len(self._url_pieces)-1:
config_node_parent = self.copy(config_node)
node_name, va... | get_config_node
High-level api: get_config_node returns an Element node in the config
tree, which is corresponding to the URL in the Restconf GET reply.
Returns
-------
Element
A config node. |
368,567 | def _get_chat(self) -> Dict:
if in self._update:
query = self._update[]
if in query:
return query[][]
else:
return {: query[]}
elif in self._update:
return patch_dict(
self._update[][],
... | As Telegram changes where the chat object is located in the response,
this method tries to be smart about finding it in the right place. |
368,568 | def _serialiseServices(self, jobStore, jobGraph, rootJobGraph):
def processService(serviceJob, depth):
if depth == len(jobGraph.services):
jobGraph.services.append([])
for childServiceJob in serviceJob.service._childServices:
... | Serialises the services for a job. |
368,569 | def regressfile(filename):
_storybook().in_filename(filename).with_params(
**{"python version": "2.7.14"}
).ordered_by_name().play()
_storybook().with_params(**{"python version": "3.7.0"}).in_filename(
filename
).ordered_by_name().play() | Run all stories in filename 'filename' in python 2 and 3.
Rewrite stories if appropriate. |
368,570 | def is_temple_project():
if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE):
msg = .format(temple.constants.TEMPLE_CONFIG_FILE)
raise temple.exceptions.InvalidTempleProjectError(msg) | Raises `InvalidTempleProjectError` if repository is not a temple project |
368,571 | def copy_module(target_path, my_directory_full_path, my_module):
s directory
my_module : string
String, name of the module to copy
Returns
-------
none
qQyY':
copy_tree(my_directory_full_path, target_path)
else:
print("Goodbye!")
... | Helper function for copy_module_to_local(). Provides the actual copy
functionality, with highly cautious safeguards against copying over
important things.
Parameters
----------
target_path : string
String, file path to target location
my_directory_full_path: string
String, full... |
368,572 | def _fn_with_diet_vars(fn, args, params):
vs_ctr = []
def grad_fn(inputs, variables, outputs, output_grads):
del outputs
with common_layers.fn_device_dependency("diet_grad",
output_grads[0].device) as out_dep:
with tf.variable_scope(vs_ctr[0], re... | Call function with args; use diet variables according to params. |
368,573 | def create_chunked_body_end(trailers=None):
chunk = []
chunk.append()
if trailers:
for name, value in trailers:
chunk.append(name)
chunk.append()
chunk.append(value)
chunk.append()
chunk.append()
return s2b(.join(chunk)) | Create the ending that terminates a chunked body. |
368,574 | def sg_rnn_layer_func(func):
r
@wraps(func)
def wrapper(tensor, **kwargs):
r
opt = tf.sg_opt(kwargs) + sg_get_context()
try:
shape = tensor.get_shape().as_list()
opt += tf.sg_opt(shape=shape, in_dim=shape[-1], dim=shape[-1], do... | r"""Decorates function as sg_rnn_layer functions.
Args:
func: function to decorate |
368,575 | def parse(self, text, html=True):
self._urls = []
self._users = []
self._lists = []
self._tags = []
reply = REPLY_REGEX.match(text)
reply = reply.groups(0)[0] if reply is not None else None
parsed_html = self._html(text) if html else self._text(text)
... | Parse the text and return a ParseResult instance. |
368,576 | def add(self, node):
if node.parent_id != _node.Root.ID:
raise exception.InvalidException()
self._nodes[node.id] = node
self._nodes[node.parent_id].append(node, False) | Register a top level node (and its children) for syncing up to the server. There's no need to call this for nodes created by
:py:meth:`createNote` or :py:meth:`createList` as they are automatically added.
LoginException: If :py:meth:`login` has not been called.
Args:
node (gkeep... |
368,577 | def read_config(self):
with open(self.config_file) as cfg:
try:
self.config.read_file(cfg)
except AttributeError:
self.config.readfp(cfg)
self.client_id = self.config.get(, )
self.client_secret = self.config.get(, )
self.a... | Read credentials from the config file |
368,578 | def call_openssl(cmd, message, silent=False):
if silent:
with open(os.devnull, ) as devnull:
return subprocess.check_call(cmd, shell=True, stdout=devnull,
stderr=subprocess.STDOUT)
else:
print message
return subprocess.check_call(... | call openssl
:param cmd: a string of command send to openssl
:param message: a string to print out if not silent
:param silent: a boolean for whether to suppress output from openssl |
368,579 | def custom_size(self, minimum: int = 40, maximum: int = 62) -> int:
return self.random.randint(minimum, maximum) | Generate clothing size using custom format.
:param minimum: Minimum value.
:param maximum: Maximum value.
:return: Clothing size. |
368,580 | def guard_handler(instance, transition_id):
if not instance:
return True
clazz_name = instance.portal_type
wf_module = _load_wf_module(.format(clazz_name.lower()))
if not wf_module:
return True
key = .format(transition_id)
guard = getattr(wf_module, key, False)
... | Generic workflow guard handler that returns true if the transition_id
passed in can be performed to the instance passed in.
This function is called automatically by a Script (Python) located at
bika/lims/skins/guard_handler.py, which in turn is fired by Zope when an
expression like "python:here.guard_h... |
368,581 | def _maintain_parent(self, request, response):
location = response._headers.get("location")
parent = request.GET.get("parent")
if parent and location and "?" not in location[1]:
url = "%s?parent=%s" % (location[1], parent)
return HttpResponseRedirect(url)
... | Maintain the parent ID in the querystring for response_add and
response_change. |
368,582 | def unlock(self):
return self._encode_invoke(lock_unlock_codec, thread_id=thread_id(),
reference_id=self.reference_id_generator.get_and_increment()) | Releases the lock. |
368,583 | def delete_data(self, url, *args, **kwargs):
res = self._conn.delete(url, headers=self._prepare_headers(**kwargs))
if res.status_code == 200 or res.status_code == 202:
return True
else:
return False | Deletes data under provided url
Returns status as boolean.
Args:
**url**: address of file to be deleted
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used with request
Returns:
Boolean. ... |
368,584 | def send(self, stanza, *, timeout=None, cb=None):
if not self.running:
raise ConnectionError("client is not running")
if not self.established:
self.logger.debug("send(%s): stream not established, waiting",
stanza)
s... | Send a stanza.
:param stanza: Stanza to send
:type stanza: :class:`~.IQ`, :class:`~.Presence` or :class:`~.Message`
:param timeout: Maximum time in seconds to wait for an IQ response, or
:data:`None` to disable the timeout.
:type timeout: :class:`~numbers.Real` o... |
368,585 | def generate_VJ_junction_transfer_matrices(self):
nt2num = {: 0, : 1, : 2, : 3}
Tvj = {}
for aa in self.codons_dict.keys():
current_Tvj = np.zeros((4, 4))
for init_nt in :
for codon in self.codons_dic... | Compute the transfer matrices for the VJ junction.
Sets the attributes Tvj, Svj, Dvj, lTvj, and lDvj. |
368,586 | def create_graph(grid):
try:
import numpy as np
except ImportError:
print(
"NumPY is not installed. segraph needs NumPY to function. Please use to install numpy.")
exit(0)
print("Creating a graph using segmented grid..")
try:
vertices = np.unique(gr... | This function creates a graph of vertices and edges from segments returned by SLIC.
:param array grid: A grid of segments as returned by the slic function defined in skimage library
:return: A graph as [vertices, edges] |
368,587 | def decorate_event_js(js_code):
def add_annotation(method):
setattr(method, "__is_event", True )
setattr(method, "_js_code", js_code )
return method
return add_annotation | setup a method as an event, adding also javascript code to generate
Args:
js_code (str): javascript code to generate the event client-side.
js_code is added to the widget html as
widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'} |
368,588 | def getWorkersName(data):
names = [fichier for fichier in data.keys()]
names.sort()
try:
names.remove("broker")
except ValueError:
pass
return names | Returns the list of the names of the workers sorted alphabetically |
368,589 | def validate(schema, data, owner=None):
schema._validate(data=data, owner=owner) | Validate input data with input schema.
:param Schema schema: schema able to validate input data.
:param data: data to validate.
:param Schema owner: input schema parent schema.
:raises: Exception if the data is not validated. |
368,590 | def solve_resolve(expr, vars):
objs, _ = __solve_for_repeated(expr.lhs, vars)
member = solve(expr.rhs, vars).value
try:
results = [structured.resolve(o, member)
for o in repeated.getvalues(objs)]
except (KeyError, AttributeError):
raise errors.EfilterKey... | Use IStructured.resolve to get member (rhs) from the object (lhs).
This operation supports both scalars and repeated values on the LHS -
resolving from a repeated value implies a map-like operation and returns a
new repeated values. |
368,591 | def set_title(self, title, subtitle=):
self.title = title
self.subtitle = subtitle | Set the title and the subtitle of the suite. |
368,592 | def pole_error(ax, fit, **kwargs):
ell = normal_errors(fit.axes, fit.covariance_matrix)
lonlat = -N.array(ell)
n = len(lonlat)
codes = [Path.MOVETO]
codes += [Path.LINETO]*(n-1)
vertices = list(lonlat)
plot_patch(ax, vertices, codes, **kwargs) | Plot the error to the pole to a plane on a `mplstereonet`
axis object. |
368,593 | def stop(self):
self.listener.setsockopt(LINGER, 1)
self.loop = False
with nslock:
self.listener.close() | Stop the name server. |
368,594 | def pyeapi_nxos_api_args(**prev_kwargs):
*
kwargs = {}
napalm_opts = salt.utils.napalm.get_device_opts(__opts__, salt_obj=__salt__)
optional_args = napalm_opts[]
kwargs[] = napalm_opts[]
kwargs[] = napalm_opts[]
kwargs[] = napalm_opts[]
kwargs[] = napalm_opts[]
kwargs[] = optional_ar... | .. versionadded:: 2019.2.0
Return the key-value arguments used for the authentication arguments for the
:mod:`pyeapi execution module <salt.module.arista_pyeapi>`.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_nxos_api_args |
368,595 | def constcase(text, acronyms=None):
words, _case, _sep = case_parse.parse_case(text, acronyms)
return .join([w.upper() for w in words]) | Return text in CONST_CASE style (aka SCREAMING_SNAKE_CASE).
Args:
text: input string to convert case
detect_acronyms: should attempt to detect acronyms
acronyms: a list of acronyms to detect
>>> constcase("hello world")
'HELLO_WORLD'
>>> constcase("helloHTMLWorld", True, ["HTML... |
368,596 | def to_string_with_default(value, default_value):
result = StringConverter.to_nullable_string(value)
return result if result != None else default_value | Converts value into string or returns default when value is None.
:param value: the value to convert.
:param default_value: the default value.
:return: string value or default when value is null. |
368,597 | def best(cls):
writer_lookup = dict(
executable=WindowsExecutableLauncherWriter,
natural=cls,
)
launcher = os.environ.get(, )
return writer_lookup[launcher] | Select the best ScriptWriter suitable for Windows |
368,598 | def _inject_specs(self, specs):
if not specs:
return
logger.debug(, self, specs)
with self._resolve_context():
thts, = self._scheduler.product_request(TransitiveHydratedTargets,
[specs])
self._index(thts.closure)
for hydrated_target i... | Injects targets into the graph for the given `Specs` object.
Yields the resulting addresses. |
368,599 | def multivariate_normality(X, alpha=.05):
from scipy.stats import lognorm
X = np.asarray(X)
assert X.ndim == 2,
X = X[~np.isnan(X).any(axis=1)]
n, p = X.shape
assert n >= 3,
assert p >= 2,
S = np.cov(X, rowvar=False, bias=True)
S_inv = np.linalg.pinv(S)
difT =... | Henze-Zirkler multivariate normality test.
Parameters
----------
X : np.array
Data matrix of shape (n_samples, n_features).
alpha : float
Significance level.
Returns
-------
normal : boolean
True if X comes from a multivariate normal distribution.
p : float
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.