Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
7,400 | def load_kwargs(*args, **kwargs):
def handle_scene():
scene = Scene()
scene.geometry.update({k: load_kwargs(v) for
k, v in kwargs[].items()})
for k in kwargs[]:
if isinstance(k, dict):
scene.graph.update(**k)
... | Load geometry from a properly formatted dict or kwargs |
7,401 | def Runs(self):
with self._accumulators_mutex:
items = list(six.iteritems(self._accumulators))
return {run_name: accumulator.Tags() for run_name, accumulator in items} | Return all the run names in the `EventMultiplexer`.
Returns:
```
{runName: { scalarValues: [tagA, tagB, tagC],
graph: true, meta_graph: true}}
``` |
7,402 | def emit(self, event, *args, **kwargs):
for func in self._registered_events[event].values():
func(*args, **kwargs) | Send out an event and call it's associated functions
:param event: Name of the event to trigger |
7,403 | def _generate_normals(polygons):
if isinstance(polygons, np.ndarray):
n = polygons.shape[-2]
i1, i2, i3 = 0, n//3, 2*n//3
v1 = polygons[..., i1, :] - polygons[..., i2, :]
v2 = polygons[..., i2, :] - polygons[..., i3, :]
else:
v1 = np.empty(... | Takes a list of polygons and return an array of their normals.
Normals point towards the viewer for a face with its vertices in
counterclockwise order, following the right hand rule.
Uses three points equally spaced around the polygon.
This normal of course might not make sense for polygons with more th... |
7,404 | def _as_rescale(self, get, targetbitdepth):
width, height, pixels, meta = get()
maxval = 2**meta[] - 1
targetmaxval = 2**targetbitdepth - 1
factor = float(targetmaxval) / float(maxval)
meta[] = targetbitdepth
def iterscale(rows):
for row in rows:
... | Helper used by :meth:`asRGB8` and :meth:`asRGBA8`. |
7,405 | def _file_model_from_db(self, record, content, format):
path = to_api_path(record[] + record[])
model = base_model(path)
model[] =
model[] = model[] = record[]
if content:
bcontent = record[]
model[], model[], model[] = from_b64(
... | Build a file model from database record. |
7,406 | def fetch_routing_info(self, address):
metadata = {}
records = []
def fail(md):
if md.get("code") == "Neo.ClientError.Procedure.ProcedureNotFound":
raise RoutingProtocolError("Server {!r} does not support routing".format(address))
else:
... | Fetch raw routing info from a given router address.
:param address: router address
:return: list of routing records or
None if no connection could be established
:raise ServiceUnavailable: if the server does not support routing or
if routing s... |
7,407 | def show_pattern(syncpr_output_dynamic, image_height, image_width):
number_pictures = len(syncpr_output_dynamic);
iteration_math_step = 1.0;
if (number_pictures > 50):
iteration_math_step = number_pictures / 50.0;
number_pictures = 50;
number_col... | !
@brief Displays evolution of phase oscillators as set of patterns where the last one means final result of recognition.
@param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr network.
@param[in] image_height (uint): Height of the pattern (image_height * image_wi... |
7,408 | def status(request):
token = request.GET.get("token", "")
if not token or token != settings.STATUS_TOKEN:
raise Http404()
info = {}
check_mapping = {
: (get_redis_info, ),
: (get_elasticsearch_info, ),
: (get_pg_info, ),
: (get_celery_info, ),
: (g... | Status |
7,409 | def shapeless_placeholder(x, axis, name):
shp = x.get_shape().as_list()
if not isinstance(axis, list):
axis = [axis]
for a in axis:
if shp[a] is None:
raise ValueError("Axis {} of shape {} is already unknown!".format(a, shp))
shp[a] = None
x = tf.placeholder_with... | Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape than x.
See also `tensorflow#5680 <https://github.... |
7,410 | def p_select_from_where_statement_1(self, p):
p[0] = SelectFromWhereNode(cardinality=p[2],
variable_name=p[3],
key_letter=p[7],
where_clause=p[9]) | statement : SELECT ANY variable_name FROM INSTANCES OF identifier WHERE expression
| SELECT MANY variable_name FROM INSTANCES OF identifier WHERE expression |
7,411 | def to_ds9(self, coordsys=, fmt=, radunit=):
valid_symbols_reverse = {y: x for x, y in valid_symbols_ds9.items()}
ds9_strings = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
:
}
outp... | Converts a list of ``regions.Shape`` objects to ds9 region strings.
Parameters
----------
coordsys : str
This overrides the coordinate system frame for all regions.
fmt : str
A python string format defining the output precision.
Default is .6f, which ... |
7,412 | def htmlDocContentDumpFormatOutput(self, cur, encoding, format):
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.htmlDocContentDumpFormatOutput(self._o, cur__o, encoding, format) | Dump an HTML document. |
7,413 | def registry_hostname(registry):
if registry.startswith() or registry.startswith():
return urlparse(registry).netloc
else:
return registry | Strip a reference to a registry to just the hostname:port |
7,414 | def insert_successor(self, successor):
self.feature += successor.feature;
self.successors.append(successor);
successor.parent = self; | !
@brief Insert successor to the node.
@param[in] successor (cfnode): Successor for adding. |
7,415 | def start(self, version=None, **kwargs):
if not version:
version = self.mostRecentVersion
pysc2Version = lib.Version(
version.version,
version.baseVersion,
version.dataHash,
version.fixedHash)
return sc_process.StarcraftProcess(
self,
... | Launch the game process. |
7,416 | def get_message(self, dummy0, sock_info, use_cmd=False):
ns = self.namespace()
ctx = sock_info.compression_context
if use_cmd:
spec = self.as_command(sock_info)[0]
if sock_info.op_msg_enabled:
request_id, msg, size, _ = _op_msg(
... | Get a getmore message. |
7,417 | def read_header(file):
file_type = _file_type(file)
if file_type in ["txt", "plain", "bat"]:
file_temp = open(file, "r")
header = file_temp.readlines()[1]
file_temp.close()
header = ast.literal_eval(header.split("
... | -----
Brief
-----
Universal function for reading the header of .txt, .h5 and .edf files generated by OpenSignals.
-----------
Description
-----------
Each file generated by the OpenSignals software (available at https://www.biosignalsplux.com/en/software) owns a set
of metadata that all... |
7,418 | def org_find_members(object_id, input_params={}, always_retry=True, **kwargs):
return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs) | Invokes the /org-xxxx/findMembers API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FfindMembers |
7,419 | def patch_namespaced_replica_set_scale(self, name, namespace, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.patch_namespaced_replica_set_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_replica_set_scale_w... | partially update scale of the specified ReplicaSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_replica_set_scale(name, namespace, body, async_req=True)
>>> result = thread.get(... |
7,420 | def addRelationships(
self,
data: list,
LIMIT: int = 20,
_print: bool = True,
crawl: bool = False,
) -> list:
url_base = self.base_url +
relationships = []
for relationship in data:
relationship.update({
: rela... | data = [{
"term1_id", "term2_id", "relationship_tid",
"term1_version", "term2_version",
"relationship_term_version",}] |
7,421 | def __sort_stats(self, sortedby=None):
return sort_stats(self.stats, sortedby,
reverse=glances_processes.sort_reverse) | Return the stats (dict) sorted by (sortedby). |
7,422 | def get_firmware(self):
firmware_uri = "{}/firmware".format(self.data["uri"])
return self._helper.do_get(firmware_uri) | Gets baseline firmware information for a SAS Logical Interconnect.
Returns:
dict: SAS Logical Interconnect Firmware. |
7,423 | def signature(cls):
snake_scope = cls.options_scope.replace(, )
partial_construct_optionable = functools.partial(_construct_optionable, cls)
partial_construct_optionable.__name__ = .format(snake_scope)
return dict(
output_type=cls.optionable_cls,
input_selectors=tuple(),
fun... | Returns kwargs to construct a `TaskRule` that will construct the target Optionable.
TODO: This indirection avoids a cycle between this module and the `rules` module. |
7,424 | def hash_contents(contents):
assert isinstance(contents, GroupNode)
result = hashlib.sha256()
def _hash_int(value):
result.update(struct.pack(">L", value))
def _hash_str(string):
assert isinstance(string, string_types)
_hash_int(len(string))
result.update(string.e... | Creates a hash of key names and hashes in a package dictionary.
"contents" must be a GroupNode. |
7,425 | def _dequeue_function(self):
from UcsBase import WriteUcsWarning, _GenericMO, WriteObject, UcsUtils
while len(self._wbs):
lowestTimeout = None
for wb in self._wbs:
pollSec = wb.params["pollSec"]
managedObject = wb.params["managedObject"]
timeoutSec = wb.params["timeoutSec"]
transientValue ... | Internal method to dequeue to events. |
7,426 | def find_elements_by_xpath(self, xpath):
return self.find_elements(by=By.XPATH, value=xpath) | Finds multiple elements by xpath.
:Args:
- xpath - The xpath locator of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_... |
7,427 | async def create_webhook(self, *, name, avatar=None, reason=None):
if avatar is not None:
avatar = utils._bytes_to_base64_data(avatar)
data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason)
return Webhook.from_state(data, state=... | |coro|
Creates a webhook for this channel.
Requires :attr:`~.Permissions.manage_webhooks` permissions.
.. versionchanged:: 1.1.0
Added the ``reason`` keyword-only parameter.
Parameters
-------------
name: :class:`str`
The webhook's name.
... |
7,428 | def classify_by_name(names):
if len(names) > 3:
if len(set(config.RNA).intersection(set(names))) != 0:
ligtype =
elif len(set(config.DNA).intersection(set(names))) != 0:
ligtype =
else:
ligtype = "POLYMER"
else:
ligtype =
for nam... | Classify a (composite) ligand by the HETID(s) |
7,429 | def unbroadcast(a, b):
spa = sps.issparse(a)
spb = sps.issparse(b)
if spa and spb: return (a,b)
elif spa or spb:
def fix(sp,nm):
nm = np.asarray(nm)
dnm = len(nm.shape)
nnm = np.prod(nm.shape)
if dnm == 0: return (sp, np... | unbroadcast(a, b) yields a tuple (aa, bb) that is equivalent to (a, b) except that aa and bb
have been reshaped such that arithmetic numpy operations such as aa * bb will result in
row-wise operation instead of column-wise broadcasting. |
7,430 | def get_replication_command_history(self, schedule_id, limit=20, offset=0,
view=None):
params = {
: limit,
: offset,
}
if view:
params[] = view
return self._get("replications/%s/history" % schedule_id,
ApiReplicationComm... | Retrieve a list of commands for a replication schedule.
@param schedule_id: The id of the replication schedule.
@param limit: Maximum number of commands to retrieve.
@param offset: Index of first command to retrieve.
@param view: View to materialize. Valid values are 'full', 'summary', 'export', 'expor... |
7,431 | def _get_index(n_items, item_size, n):
index = np.arange(n_items)
index = np.repeat(index, item_size)
index = index.astype(np.float64)
assert index.shape == (n,)
return index | Prepare an index attribute for GPU uploading. |
7,432 | def list_views(app, appbuilder):
_appbuilder = import_application(app, appbuilder)
echo_header("List of registered views")
for view in _appbuilder.baseviews:
click.echo(
"View:{0} | Route:{1} | Perms:{2}".format(
view.__class__.__name__, view.route_base, view.base_pe... | List all registered views |
7,433 | def last_modified(self) -> Optional[datetime.datetime]:
httpdate = self._headers.get(hdrs.LAST_MODIFIED)
if httpdate is not None:
timetuple = parsedate(httpdate)
if timetuple is not None:
return datetime.datetime(*timetuple[:6],
... | The value of Last-Modified HTTP header, or None.
This header is represented as a `datetime` object. |
7,434 | def get_version_naive(cls, name, ignore=):
match = cls._get_regex_search(name, cls.REGEX_VERSION.format(SEP=cls.REGEX_SEPARATORS), ignore=ignore)
if match is not None:
if len(match) > 1:
for m in match:
m.update({: int(m[].upper().replace(, ))})
... | Checks a string for a possible version of an object (no prefix, no suffix) without filtering date out
Assumes only up to 4 digit padding
:param name: str, string that represents a possible name of an object
:return: (float, int, list(str), None), gets the version number then the string matc... |
7,435 | def get_ref_indices(self):
ixn_obj = self
ref_indices = []
while ixn_obj != ixn_obj.root:
ref_indices.append(ixn_obj.ref.split()[-1])
ixn_obj = ixn_obj.parent
return ref_indices[::-1] | :return: list of all indices in object reference. |
7,436 | def jboss_standalone_main_config_files(broker):
ps = broker[DefaultSpecs.ps_auxww].content
results = []
search = re.compile(r"\-Djboss\.server\.base\.dir=(\S+)").search
for p in ps:
if in p:
match = search(p)
... | Command: JBoss standalone main config files |
7,437 | def construct_xblock_from_class(self, cls, scope_ids, field_data=None, *args, **kwargs):
return self.mixologist.mix(cls)(
runtime=self,
field_data=field_data,
scope_ids=scope_ids,
*args, **kwargs
) | Construct a new xblock of type cls, mixing in the mixins
defined for this application. |
7,438 | def run(self):
self.statsAndLogging.start()
if self.config.metrics:
self.toilMetrics = ToilMetrics(provisioner=self.provisioner)
try:
self.serviceManager.start()
try:
if self.clusterScaler is n... | This runs the leader process to issue and manage jobs.
:raises: toil.leader.FailedJobsException if at the end of function their remain \
failed jobs
:return: The return value of the root job's run function.
:rtype: Any |
7,439 | def _find_class_construction_fn(cls):
for base in type.mro(cls):
if in base.__dict__:
return base.__init__
if in base.__dict__:
return base.__new__ | Find the first __init__ or __new__ method in the given class's MRO. |
7,440 | def getdata(self):
if self.bounding_box:
return self.image.crop(self.bounding_box).getdata() | A sequence of pixel data relating to the changes that occurred
since the last time :py:func:`redraw_required` was last called.
:returns: A sequence of pixels or ``None``.
:rtype: iterable |
7,441 | def get_file_size(file_object):
position = file_object.tell()
file_object.seek(0, 2)
file_size = file_object.tell()
file_object.seek(position, 0)
return file_size | Returns the size, in bytes, of a file. Expects an object that supports
seek and tell methods.
Args:
file_object (file_object) - The object that represents the file
Returns:
(int): size of the file, in bytes |
7,442 | def _make_regex(self):
return re.compile("|".join(map(re.escape, self.keys()))) | Build a re object based on keys in the current dictionary |
7,443 | def load_word_file(filename):
words_file = resource_filename(__name__, "words/%s" % filename)
handle = open(words_file, )
words = handle.readlines()
handle.close()
return words | Loads a words file as a list of lines |
7,444 | def cache(self, f):
if self._memory is None:
logger.debug("Joblib is not installed: skipping cacheing.")
return f
assert f
if in inspect.getargspec(f).args:
ignore = []
else:
ignore = None
disk_cached = self._me... | Cache a function using the context's cache directory. |
7,445 | def cosi_posterior(vsini_dist,veq_dist,vgrid=None,npts=100,vgrid_pts=1000):
if vgrid is None:
vgrid = np.linspace(min(veq_dist.ppf(0.001),vsini_dist.ppf(0.001)),
max(veq_dist.ppf(0.999),vsini_dist.ppf(0.999)),
vgrid_pts)
logging.debug(.for... | returns posterior of cosI given dists for vsini and veq (incorporates unc. in vsini) |
7,446 | def find_recipes(folders, pattern=None, base=None):
manifest = find_folder_recipes(base_folder=base_folder,
pattern=custom_pattern or pattern,
manifest=manifest,
base=base)
... | find recipes will use a list of base folders, files,
or patterns over a subset of content to find recipe files
(indicated by Starting with Singularity
Parameters
==========
base: if defined, consider folders recursively below this level. |
7,447 | def validate(self):
if not self.conf.get():
raise PacketManagerException()
if not self.conf.get():
raise PacketManagerException()
projects = self.conf.get()
if not projects.keys():
raise PacketManagerException()
failure = False
... | Perform some basic configuration validation. |
7,448 | def __intermediate_addresses(self, interface):
address_list = self.get_copy(interface, )
if not address_list:
return [{: }]
result = []
static = {}
dhcp = []
for address in address_list:
family = address.get()
... | converts NetJSON address to
UCI intermediate data structure |
7,449 | def set_duty_cycle(self, pin, dutycycle):
if dutycycle < 0.0 or dutycycle > 100.0:
raise ValueError()
if pin not in self.pwm:
raise ValueError(.format(pin))
self.pwm[pin].ChangeDutyCycle(dutycycle) | Set percent duty cycle of PWM output on specified pin. Duty cycle must
be a value 0.0 to 100.0 (inclusive). |
7,450 | def add_dicts(d1, d2):
if d1 is None:
return d2
if d2 is None:
return d1
keys = set(d1)
keys.update(set(d2))
ret = {}
for key in keys:
v1 = d1.get(key)
v2 = d2.get(key)
if v1 is None:
ret[key] = v2
elif v2 is None:
ret[... | Merge two dicts of addable values |
7,451 | def intersects_any(self,
ray_origins,
ray_directions):
first = self.intersects_first(ray_origins=ray_origins,
ray_directions=ray_directions)
hit = first != -1
return hit | Check if a list of rays hits the surface.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vector) of rays
Returns
----------
hit: (n,) bool, did each ray hit the surface |
7,452 | def _simplify_feature_value(self, name, value):
if name == :
channel_modes, channel_chars = value.split()
channel_modes = channel_modes[1:]
value = OrderedDict(list(zip(channel_modes, channel_chars))[::-1])
return value
elif name =... | Return simplified and more pythonic feature values. |
7,453 | def perl_cmd():
perl = which(os.path.join(get_bcbio_bin(), "perl"))
if perl:
return perl
else:
return which("perl") | Retrieve path to locally installed conda Perl or first in PATH. |
7,454 | def _check_backends(self):
backends = self.backends_params.keys()
for b in self.roles.get_backends():
if b not in backends:
raise MissingBackend(b, )
for b in self.attributes.get_backends():
if b not in backends:
raise MissingBacke... | Check that every backend in roles and attributes
is declared in main configuration |
7,455 | def hybrid_threaded_worker(selector, workers):
result_queue = Queue()
job_sink = {k: w.sink() for k, w in workers.items()}
@push
def dispatch_job():
default_sink = result_queue.sink()
while True:
msg = yield
if msg is EndOfQueue:
for k in ... | Runs a set of workers, each in a separate thread.
:param selector:
A function that takes a hints-tuple and returns a key
indexing a worker in the `workers` dictionary.
:param workers:
A dictionary of workers.
:returns:
A connection for the scheduler.
:rtype: Connection
... |
7,456 | def to_zhuyin(s, delimiter=, all_readings=False, container=):
numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False)
zhuyin = pinyin_to_zhuyin(numbered_pinyin)
return zhuyin | Convert a string's Chinese characters to Zhuyin readings.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings*... |
7,457 | def get_default_config(self):
config = super(VMSFSCollector, self).get_default_config()
config.update({
:
})
return config | Returns the default collector settings |
7,458 | def make_slash_number(self):
if self.partitioning == and self.codon_positions == :
return
elif self.partitioning in [, ] and self.codon_positions in [, None]:
return
else:
return | Charset lines have \2 or \3 depending on type of partitioning and codon
positions requested for our dataset.
:return: |
7,459 | def enable_hostgroup_passive_svc_checks(self, hostgroup):
for host_id in hostgroup.get_hosts():
if host_id in self.daemon.hosts:
for service_id in self.daemon.hosts[host_id].services:
if service_id in self.daemon.services:
self.ena... | Enable service passive checks for a hostgroup
Format of the line that triggers function call::
ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS;<hostgroup_name>
:param hostgroup: hostgroup to enable
:type hostgroup: alignak.objects.hostgroup.Hostgroup
:return: None |
7,460 | def _get_audio_duration_seconds(self, audio_abs_path):
HHMMSS_duration = subprocess.check_output(
(
).format(
audio_abs_path, "Duration"),
shell=True, universal_newlines=True).rstrip()
total_seconds = sum(
[float(x) * 60 ** (2 - i... | Parameters
----------
audio_abs_path : str
Returns
-------
total_seconds : int |
7,461 | def toString(value, mode):
string = angle.toString(value)
sign = string[0]
separator = CHAR[mode][sign]
string = string.replace(, separator, 1)
return string[1:] | Converts angle float to string.
Mode refers to LAT/LON. |
7,462 | def flick(self, x, y, speed):
self._driver.flick(self, x, y, speed) | Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead.
Flick on the touch screen using finger motion events.
This flickcommand starts at a particulat screen location.
Support:
iOS
Args:
x(float}: The x offset in pixels to flick by... |
7,463 | def batch_update_conversations(self, event, conversation_ids):
path = {}
data = {}
params = {}
data["conversation_ids"] = conversation_ids
self._validate_enum(event, ["mark_as_read", "mark_as_unread", "star", "unstar", "arc... | Batch update conversations.
Perform a change on a set of conversations. Operates asynchronously; use the {api:ProgressController#show progress endpoint}
to query the status of an operation. |
7,464 | def hypergraph(raw_events, entity_types=None, opts={}, drop_na=True, drop_edge_attrs=False, verbose=True, direct=False):
from . import hyper
return hyper.Hypergraph().hypergraph(PyGraphistry, raw_events, entity_types, opts, drop_na, drop_edge_attrs, verbose, direct) | Transform a dataframe into a hypergraph.
:param Dataframe raw_events: Dataframe to transform
:param List entity_types: Optional list of columns (strings) to turn into nodes, None signifies all
:param Dict opts: See below
:param bool drop_edge_attrs: Whether to include each row's attribu... |
7,465 | def load(target, source_module=None):
module, klass, function = _get_module(target)
if not module and source_module:
module = source_module
if not module:
raise MissingModule(
"No module name supplied or source_module provided.")
actual_module = sys.modules[module]
i... | Get the actual implementation of the target. |
7,466 | def _get_document_data(f, image_handler=None):
if image_handler is None:
def image_handler(image_id, relationship_dict):
return relationship_dict.get(image_id)
document_xml = None
numbering_xml = None
relationship_xml = None
styles_xml = None
parser = etree.XMLParser(st... | ``f`` is a ``ZipFile`` that is open
Extract out the document data, numbering data and the relationship data. |
7,467 | def volume_mesh(mesh, count):
points = (np.random.random((count, 3)) * mesh.extents) + mesh.bounds[0]
contained = mesh.contains(points)
samples = points[contained][:count]
return samples | Use rejection sampling to produce points randomly distributed
in the volume of a mesh.
Parameters
----------
mesh: Trimesh object
count: int, number of samples desired
Returns
----------
samples: (n,3) float, points in the volume of the mesh.
where: n <= count |
7,468 | def B(self,value):
assert value.shape[0]==self._K,
assert value.shape[1]==1,
self._B = value
self.clear_cache(,) | set phenotype |
7,469 | def get_storage(self):
if self.storage:
return self.storage
self.storage = self.reconnect_redis()
return self.storage | Get the storage instance.
:return Redis: Redis instance |
7,470 | def default_headers(self):
_headers = {
"User-Agent": "Pyzotero/%s" % __version__,
"Zotero-API-Version": "%s" % __api_version__,
}
if self.api_key:
_headers["Authorization"] = "Bearer %s" % self.api_key
return _headers | It's always OK to include these headers |
7,471 | def find_input(self, stream):
for i, input_x in enumerate(self.inputs):
if input_x[0].matches(stream):
return i | Find the input that responds to this stream.
Args:
stream (DataStream): The stream to find
Returns:
(index, None): The index if found or None |
7,472 | def run(
self,
cluster_config,
rg_parser,
partition_measurer,
cluster_balancer,
args,
):
self.cluster_config = cluster_config
self.args = args
with ZK(self.cluster_config) as self.zk:
self.log.debug(... | Initialize cluster_config, args, and zk then call run_command. |
7,473 | def open(self):
if self._table_exists():
self.mode = "open"
self._get_table_info()
self.types = dict([ (f[0],self.conv_func[f[1].upper()])
for f in self.fields if f[1].upper() in self.conv_func ])
return self
... | Open an existing database |
7,474 | def add(name, device):
*
cmd = .format(name, device)
if __salt__[](cmd) == 0:
return True
return False | Add new device to RAID array.
CLI Example:
.. code-block:: bash
salt '*' raid.add /dev/md0 /dev/sda1 |
7,475 | def load_yaml_file(filename):
try:
with open(filename, ) as f:
return yaml.safe_load(f)
except IOError as e:
raise ParserError( + filename + + e.message)
except ValueError as e:
raise ParserError(
.format(filename, e.message)) | Load a YAML file from disk, throw a ParserError on failure. |
7,476 | def add_activity_form(self, activity_pattern, is_active):
if is_active:
if activity_pattern not in self.active_forms:
self.active_forms.append(activity_pattern)
else:
if activity_pattern not in self.inactive_forms:
self.inactive_forms.appe... | Adds the pattern as an active or inactive form to an Agent.
Parameters
----------
activity_pattern : dict
A dictionary of site names and their states.
is_active : bool
Is True if the given pattern corresponds to an active state. |
7,477 | def _kip(self, cycle_end, mix_thresh, xaxis, sparse):
original_cyclelist = self.se.cycles
cyclelist = original_cyclelist[0:cycle_end:sparse]
xx = self.se.ages[:cycle_end:sparse]
totalmass = []
m_ini = float(self.se.get())
fig = pl.figure(1)
ax = pl.su... | *** Should be used with care, therefore has been flagged as
a private routine ***
This function uses a threshold diffusion coefficient, above
which the the shell is considered to be convective, to plot a
Kippenhahn diagram.
Parameters
----------
cycle_end : integ... |
7,478 | def pointAt(self, **axis_values):
scene_point = self.renderer().pointAt(self.axes(), axis_values)
chart_point = self.uiChartVIEW.mapFromScene(scene_point)
return self.uiChartVIEW.mapToParent(chart_point) | Returns the point on the chart where the inputed values are located.
:return <QPointF> |
7,479 | def delete_cluster_role_binding(self, name, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_cluster_role_binding_with_http_info(name, **kwargs)
else:
(data) = self.delete_cluster_role_binding_with_http_info(name, **kwargs)
return ... | delete_cluster_role_binding # noqa: E501
delete a ClusterRoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_cluster_role_binding(name, async_req=True)
>>> re... |
7,480 | def _delocalize_logging_command(self, logging_path, user_project):
logging_prefix = os.path.splitext(logging_path.uri)[0]
if logging_path.file_provider == job_model.P_LOCAL:
mkdir_cmd = % os.path.dirname(logging_prefix)
cp_cmd =
elif logging_path.file_provider == job_model.P_G... | Returns a command to delocalize logs.
Args:
logging_path: location of log files.
user_project: name of the project to be billed for the request.
Returns:
eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12' |
7,481 | def points_from_xywh(box):
x, y, w, h = box[], box[], box[], box[]
return "%i,%i %i,%i %i,%i %i,%i" % (
x, y,
x + w, y,
x + w, y + h,
x, y + h
) | Constructs a polygon representation from a rectangle described as a dict with keys x, y, w, h. |
7,482 | def get_certs(context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE):
*
ret = dict()
cmd = list()
blacklist_keys = []
store_path = r.format(context, store)
_validate_cert_path(name=store_path)
cmd.append(r"Get-ChildItem -Path | Select-Object".format(store_path))
cmd.append()
items = _cm... | Get the available certificates in the given store.
:param str context: The name of the certificate store location context.
:param str store: The name of the certificate store.
:return: A dictionary of the certificate thumbprints and properties.
:rtype: dict
CLI Example:
.. code-block:: bash
... |
7,483 | def get_choices(cls, condition=None, order_by=None, query=None, value_field=None, text_field=None):
result = []
if query is None:
query = cls.filter(condition).order_by(order_by)
for row in query:
if not value_field:
value = row._key
e... | Get [(value, text),...] list
:param condition:
:param value_field: default is primary_key
:param text_field: default is unicode(obj)
:return: |
7,484 | def json_decode(s: str) -> Any:
try:
return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s)
except json.JSONDecodeError:
log.warning("Failed to decode JSON (returning None): {!r}", s)
return None | Decodes an object from JSON using our custom decoder. |
7,485 | def get_ref(self, cat, refname):
if cat not in self.defs:
raise errors.GramFuzzError("referenced definition category ({!r}) not defined".format(cat))
if refname == "*":
refname = rand.choice(self.defs[cat].keys())
if refname not in self.defs... | Return one of the rules in the category ``cat`` with the name
``refname``. If multiple rule defintions exist for the defintion name
``refname``, use :any:`gramfuzz.rand` to choose a rule at random.
:param str cat: The category to look for the rule in.
:param str refname: The name of the... |
7,486 | def write_networking_file(version, pairs):
vmnets = OrderedDict(sorted(pairs.items(), key=lambda t: t[0]))
try:
with open(VMWARE_NETWORKING_FILE, "w", encoding="utf-8") as f:
f.write(version)
for key, value in vmnets.items():
f.write("answer {} {}\n".format(... | Write the VMware networking file. |
7,487 | def _opcode_set(*names):
s = set()
for name in names:
try:
s.add(_opcode(name))
except KeyError:
pass
return s | Return a set of opcodes by the names in `names`. |
7,488 | def request_client_list(self, req, msg):
clients = self._client_conns
num_clients = len(clients)
for conn in clients:
addr = conn.address
req.inform(addr)
return req.make_reply(, str(num_clients)) | Request the list of connected clients.
The list of clients is sent as a sequence of #client-list informs.
Informs
-------
addr : str
The address of the client as host:port with host in dotted quad
notation. If the address of the client could not be determined
... |
7,489 | def write_properties(self, properties, file_datetime):
with self.__lock:
absolute_file_path = self.__file_path
make_directory_if_needed(os.path.dirname(absolute_file_path))
exists = os.path.exists(absolute_file_path)
if exists:
... | Write properties to the ndata file specified by reference.
:param reference: the reference to which to write
:param properties: the dict to write to the file
:param file_datetime: the datetime for the file
The properties param must not change during this method. Callers... |
7,490 | def validate_unwrap(self, value):
if not isinstance(value, dict):
self._fail_validation_type(value, dict)
for k, v in value.items():
self._validate_key_unwrap(k)
try:
self.value_type.validate_unwrap(v)
except BadValueException as b... | Checks that value is a ``dict``, that every key is a valid MongoDB
key, and that every value validates based on DictField.value_type |
7,491 | def delivery_note_pdf(self, delivery_note_id):
return self._create_get_request(resource=DELIVERY_NOTES, billomat_id=delivery_note_id, command=PDF) | Opens a pdf of a delivery note
:param delivery_note_id: the delivery note id
:return: dict |
7,492 | def show_instance(name, session=None, call=None):
if call == :
raise SaltCloudException(
)
log.debug(, name, session)
if session is None:
session = _get_session()
vm = _get_vm(name, session=session)
record = session.xenapi.VM.get_record(vm)
if not record... | Show information about a specific VM or template
.. code-block:: bash
salt-cloud -a show_instance xenvm01
.. note:: memory is memory_dynamic_max |
7,493 | def spksub(handle, descr, identin, begin, end, newh):
assert len(descr) is 5
handle = ctypes.c_int(handle)
descr = stypes.toDoubleVector(descr)
identin = stypes.stringToCharP(identin)
begin = ctypes.c_double(begin)
end = ctypes.c_double(end)
newh = ctypes.c_int(newh)
libspice.spksub... | Extract a subset of the data in an SPK segment into a
separate segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spksub_c.html
:param handle: Handle of source segment.
:type handle: int
:param descr: Descriptor of source segment.
:type descr: 5-Element Array of floats
:param... |
7,494 | def _dqdv_split_frames(cell, tidy=False, **kwargs):
charge_dfs, cycles, minimum_v, maximum_v = _collect_capacity_curves(
cell,
direction="charge"
)
ica_charge_dfs = _make_ica_charge_curves(
charge_dfs, cycles, minimum_v, maximum_v,
**kwargs,
)
ica_char... | Returns dqdv data as pandas.DataFrames for all cycles.
Args:
cell (CellpyData-object).
tidy (bool): return in wide format if False (default),
long (tidy) format if True.
Returns:
(charge_ica_frame, discharge_ica_frame) where the frames are
... |
7,495 | def get_token(self, request):
return stripe.Token.create(
card={
"number": request.data["number"],
"exp_month": request.data["exp_month"],
"exp_year": request.data["exp_year"],
"cvc": request.data["cvc"]
}
... | Create a stripe token for a card |
7,496 | async def create_proof(self, proof_req: dict, briefs: Union[dict, Sequence[dict]], requested_creds: dict) -> str:
LOGGER.debug(
,
proof_req,
briefs,
requested_creds)
if not self.wallet.handle:
LOGGER.debug(, self.name)
ra... | Create proof as HolderProver.
Raise:
* AbsentLinkSecret if link secret not set
* CredentialFocus on attempt to create proof on no briefs or multiple briefs for a credential definition
* AbsentTails if missing required tails file
* | BadRevStateTime if a timestamp... |
7,497 | def transfer_sanity_check( name, consensus_hash ):
if name is not None and (not is_b40( name ) or "+" in name or name.count(".") > 1):
raise Exception("Name has non-base-38 characters" % name)
if name is not None and (len(name) > LENGTHS[]):
raise Exception("Name is too long; expe... | Verify that data for a transfer is valid.
Return True on success
Raise Exception on error |
7,498 | def _fracRoiSparse(self):
self.frac_roi_sparse = np.min([self.mask_1.frac_roi_sparse,self.mask_2.frac_roi_sparse],axis=0)
return self.frac_roi_sparse | Calculate an approximate pixel coverage fraction from the two masks.
We have no way to know a priori how much the coverage of the
two masks overlap in a give pixel. For example, masks that each
have frac = 0.5 could have a combined frac = [0.0 to 0.5].
The limits will be:
ma... |
7,499 | def process_file(pyfile_name):
print( + pyfile_name)
with open(pyfile_name) as fpyfile:
pyfile_str = fpyfile.readlines()
file_dict = {: pyfile_name.replace(, )}
if pyfile_str[0].startswith("summary_comment")
else:
file_dict[] = pyfile_name
file_dict[] = []... | Process a Python source file with Google style docstring comments.
Reads file header comment, function definitions, function docstrings.
Returns dictionary encapsulation for subsequent writing.
Args:
pyfile_name (str): file name to read.
Returns:
Dictionary object containing summary c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.