Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
373,600 | def sync(self):
log.info("syncing %r" % self.path)
self.folder = self.jfs.get(self.path)
self.synced = True | Update state of folder from Jottacloud server |
373,601 | def get_submissions_multiple_assignments_by_sis_id(
self, is_section, sis_id, students=None, assignments=None,
**params):
if is_section:
return self.get_submissions_multiple_assignments(
is_section, self._sis_id(sis_id, ), students,
as... | List submissions for multiple assignments by course/section sis id and
optionally student
https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.for_students |
373,602 | def is_group(value):
if type(value) == str:
try:
entry = grp.getgrnam(value)
value = entry.gr_gid
except KeyError:
err_message = (.format(value))
raise validate.VdtValueError(err_message)
return value
elif type(value) == int:
... | Check whether groupname or gid as argument exists.
if this function recieved groupname, convert gid and exec validation. |
373,603 | def configure(logstash_host=None, logstash_port=None, logdir=None):
if not (logstash_host or logstash_port or logdir):
raise ValueError()
config.logstash.host = logstash_host or config.logstash.host
config.logstash.port = logstash_port or config.logstash.port
config.logdir = logdir or con... | Configuration settings. |
373,604 | def blockreplace(path,
marker_start=,
marker_end=,
content=,
append_if_not_found=False,
prepend_if_not_found=False,
backup=,
dry_run=False,
show_changes=True,
append_newline=False,
insert_before_match=None,
insert_after_match=None):... | .. versionadded:: 2014.1.0
Replace content of a text block in a file, delimited by line markers
A block of content delimited by comments can help you manage several lines
entries without worrying about old entries removal.
.. note::
This function will store two copies of the file in-memory (... |
373,605 | def add_sync_methods(cls):
for name in cls.__dict__.keys():
if name.endswith():
sync_name = name[:-6]
if not hasattr(cls, sync_name):
setattr(cls, sync_name, _make_sync_method(name))
return cls | Class decorator to add synchronous methods corresponding to async methods.
This modifies the class in place, adding additional methods to it.
If a synchronous method of a given name already exists it is not
replaced.
Args:
cls: A class.
Returns:
The same class, modified in place. |
373,606 | def to_download():
first_day = parse(interval_first)
last_day = parse(interval_last)
format_change = parse()
one_day = datetime.timedelta(1)
cur_day = first_day
url_list = []
while cur_day < last_day:
fname = filename.format(day=cur_day.strftime("%Y%m%d"))
if cur_day > f... | Build interval of urls to download.
We always get the first file of the next day.
Ex: 2013-01-01 => 2013-01-02.0000 |
373,607 | def project_new_folder(object_id, input_params={}, always_retry=True, **kwargs):
return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs) | Invokes the /project-xxxx/newFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder |
373,608 | def parent_frame_arguments():
arg_names, variable_arg_name, keyword_arg_name, local_vars = (
tf_inspect._inspect.getargvalues(
tf_inspect._inspect.stack()[1][0]))
local_vars.pop(variable_arg_name, {})
keyword_args = local_vars.pop(keyword_arg_name, {})
final_args = {... | Returns parent frame arguments.
When called inside a function, returns a dictionary with the caller's function
arguments. These are positional arguments and keyword arguments (**kwargs),
while variable arguments (*varargs) are excluded.
When called at global scope, this will return an empty dictionary, since ... |
373,609 | def _generate_annotation_type_class(self, ns, annotation_type):
self.emit(.format(
class_name_for_annotation_type(annotation_type, ns)))
with self.indent():
if annotation_type.has_documented_type_or_params():
self.emit()
self.emit()
... | Defines a Python class that represents an annotation type in Stone. |
373,610 | def G(self, T):
h = self.DHref
s = self.Sref
for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):
h = h + self._Cp_records[str(Tmax)].H(T)
s = s + self._Cp_records[str(Tmax)].S(T)
if T <= Tmax:
return h - T * s + self.G... | Calculate the heat capacity of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The Gibbs free energy of the compound phase. |
373,611 | def create(ctx, name, description, tags, private, init):
try:
tags = tags.split() if tags else None
project_dict = dict(name=name, description=description, is_public=not private, tags=tags)
project_config = ProjectConfig.from_dict(project_dict)
except ValidationError:
Printe... | Create a new project.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon project create --name=cats-vs-dogs --description="Image Classification with DL"
``` |
373,612 | def _write_source_data(self, sources):
for i, source in enumerate(sources):
self._write_source(source) | See src/jjk/measure3 |
373,613 | def join_pretty_tensors(tensors, output, join_function=None, name=):
if not tensors:
raise ValueError()
with output.g.name_scope(name):
if join_function is None:
last_dim = len(tensors[0].shape) - 1
return output.with_tensor(tf.concat(tensors, last_dim))
else:
return output.w... | Joins the list of pretty_tensors and sets head of output_pretty_tensor.
Args:
tensors: A sequence of Layers or SequentialLayerBuilders to join.
output: A pretty_tensor to set the head with the result.
join_function: A function to join the tensors, defaults to concat on the
last dimension.
name:... |
373,614 | def _add_error(self, *args, **kwargs):
if kwargs.get(, None):
error = ConfigError.create_from_yaml_node(
*args,
**kwargs
)
elif self._value_node:
error = ConfigError.create_from_yaml_node(
... | Convenience function to add an error to this object, with line numbers
An error title or description should not accidentally leak self._value, for privacy/redaction purposes.
:rtype: None |
373,615 | def set_weather_from_metar(
metar: typing.Union[Metar.Metar, str],
in_file: typing.Union[str, Path],
out_file: typing.Union[str, Path] = None
) -> typing.Tuple[typing.Union[str, None], typing.Union[str, None]]:
error, metar = custom_metar.CustomMetar.get_metar(metar)
if error:
... | Applies the weather from a METAR object to a MIZ file
Args:
metar: metar object
in_file: path to MIZ file
out_file: path to output MIZ file (will default to in_file)
Returns: tuple of error, success |
373,616 | def SensorsTriggersNotificationsDelete(self, sensor_id, trigger_id, notification_id):
if self.__SenseApiCall__(.format(sensor_id, trigger_id, notification_id), ):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Disconnect a notification from a sensor-trigger combination.
@param sensor_id (int) - Sensor id if the sensor-trigger combination.
@param trigger_id (int) - Trigger id of the sensor-trigger combination.
@param notification_id (int) - Notification id of the notificati... |
373,617 | def write_users(dburl):
data = {
: ,
: ,
: ,
:
r
r,
}
for p in PERMISSIONS:
data[p] =
db = redis.StrictRedis.from_url(dburl)
db.hmset(, data)
db.hset(, , )
if not db.exists():
db.incr()
print("Username: admi... | Write users to the DB. |
373,618 | def to_dict(self):
data = {: self.aid, : self.number, : self.element}
for coord in {, , }:
if getattr(self, coord) is not None:
data[coord] = getattr(self, coord)
if self.charge is not 0:
data[] = self.charge
return data | Return a dictionary containing Atom data. |
373,619 | def _disappeared(self, fd, path, **params):
log = self._getparam(, self._discard, **params)
log.debug("Path %r removed or renamed, handling removal", path)
self._close(fd)
if self._mode == WF_POLLING and fd in self._poll_stat:
del self._poll_stat[fd]
if self... | Called when an open path is no longer acessible. This will either
move the path to pending (if the 'missing' param is set for the
file), or fire an exception. |
373,620 | def set_timestamp_to_current(self):
self.timestamp = pytz.UTC.localize(datetime.datetime.utcnow()) | Set timestamp to current time utc
:rtype: None |
373,621 | def seat_button_count(self):
if self.type != EventType.TABLET_TOOL_BUTTON:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_tool_get_seat_button_count(
self._handle) | The total number of buttons pressed on all devices on
the associated seat after the the event was triggered.
For events that are not of type
:attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property
raises :exc:`AttributeError`.
Returns:
int: The seat wide pressed button count for the key of... |
373,622 | def replace_pipe(self, name, component):
if name not in self.pipe_names:
raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
self.pipeline[self.pipe_names.index(name)] = (name, component) | Replace a component in the pipeline.
name (unicode): Name of the component to replace.
component (callable): Pipeline component.
DOCS: https://spacy.io/api/language#replace_pipe |
373,623 | def sendNotification(snmpDispatcher, authData, transportTarget,
notifyType, *varBinds, **options):
sysUpTime = v2c.apiTrapPDU.sysUpTime
snmpTrapOID = v2c.apiTrapPDU.snmpTrapOID
def _ensureVarBinds(varBinds):
if not varBinds or varBinds[0][0] != sysUpTime:
... | Creates a generator to send SNMP notification.
When iterator gets advanced by :py:mod:`asyncio` main loop,
SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4.2.6`).
The iterator yields :py:class:`asyncio.Future` which gets done whenever
response arrives or error occurs.
Parameters
... |
373,624 | def swo_set_emu_buffer_size(self, buf_size):
buf = ctypes.c_uint32(buf_size)
res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_EMU,
ctypes.byref(buf))
if res < 0:
raise errors.JLinkException(res)
... | Sets the size of the buffer used by the J-Link to collect SWO data.
Args:
self (JLink): the ``JLink`` instance
buf_size (int): the new size of the emulator buffer
Returns:
``None``
Raises:
JLinkException: on error |
373,625 | async def fetch(self, *args, timeout=None):
r
data = await self.__bind_execute(args, 0, timeout)
return data | r"""Execute the statement and return a list of :class:`Record` objects.
:param str query: Query text
:param args: Query arguments
:param float timeout: Optional timeout value in seconds.
:return: A list of :class:`Record` instances. |
373,626 | def _get_crawled_urls(self, handle, request):
try:
content = six.text_type(handle.open(request).read(), "utf-8",
errors="replace")
soup = BeautifulSoup(content, "html.parser")
tags = soup()
for tag in tqdm(tags):
... | Main method where the crawler html content is parsed with
beautiful soup and out of the DOM, we get the urls |
373,627 | def get_account_db_class(cls) -> Type[BaseAccountDB]:
if cls.account_db_class is None:
raise AttributeError("No account_db_class set for {0}".format(cls.__name__))
return cls.account_db_class | Return the :class:`~eth.db.account.BaseAccountDB` class that the
state class uses. |
373,628 | def encodeValue(value):
if isinstance(value, (list, tuple)):
return [common.AttributeValue(string_value=str(v)) for v in value]
else:
return [common.AttributeValue(string_value=str(value))] | TODO |
373,629 | def breadth_first(problem, graph_search=False, viewer=None):
return _search(problem,
FifoList(),
graph_search=graph_search,
viewer=viewer) | Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. |
373,630 | def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None):
assert {old_representation, new_representation} < {"storage", "editor", "view", "export_view"}
request_data = {"value": str(content_data), "representation": old_representatio... | Converts between content body representations.
Not all representations can be converted to/from other formats. Supported conversions:
Source Representation | Destination Representation Supported
--------------------------------------------------------------
"storage" | ... |
373,631 | def type_to_string(f, map_types):
if f.type in [1]:
return "double"
elif f.type in [2]:
return "float"
elif f.type in [3]:
return "long"
elif f.type in [4]:
return "uint64"
elif f.type in [5]:
return "integer"
elif f.type in [6]:
return "fixed... | Convert type info to pretty names, based on numbers from from FieldDescriptorProto
https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor.pb |
373,632 | def filter_labels(sent: Sequence[str], labels: Set[str] = None) -> List[str]:
if labels:
return [tok for tok in sent if tok in labels]
return list(sent) | Returns only the tokens present in the sentence that are in labels. |
373,633 | def update_function_code(FunctionName, ZipFile=None, S3Bucket=None, S3Key=None,
S3ObjectVersion=None, Publish=False,
region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
if Zi... | Upload the given code to the named lambda function.
Returns {updated: true} if the function was updated and returns
{updated: False} if the function was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip |
373,634 | def _validate_min(self, proposal):
min = proposal[]
if min > self.max:
raise TraitError()
if min > self.value:
self.value = min
return min | Enforce min <= value <= max |
373,635 | def wait_for_logs_matching(self, matcher, timeout=10, encoding=,
**logs_kwargs):
wait_for_logs_matching(
self.inner(), matcher, timeout=timeout, encoding=encoding,
**logs_kwargs) | Wait for logs matching the given matcher. |
373,636 | def _to_chimera(M, N, L, q):
"Converts a qubit's linear index to chimera coordinates."
return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L) | Converts a qubit's linear index to chimera coordinates. |
373,637 | def from_credentials(cls: Type[SigningKeyType], salt: Union[str, bytes], password: Union[str, bytes],
scrypt_params: Optional[ScryptParams] = None) -> SigningKeyType:
if scrypt_params is None:
scrypt_params = ScryptParams()
salt = ensure_bytes(salt)
... | Create a SigningKey object from credentials
:param salt: Secret salt passphrase credential
:param password: Secret password credential
:param scrypt_params: ScryptParams instance |
373,638 | def _write_entries(self, stream, entries, converter, properties=None):
def iter_entries():
for c in entries:
entry = converter(c)
if entry is None:
continue
if properties is not None:
entry = OrderedDict... | Write iterable of entries as YAML object to stream.
Args:
stream: File-like object.
entries: Iterable of entries.
converter: Conversion function from entry to YAML object.
properties: Set of compartment properties to output (or None to
output all)... |
373,639 | async def scroll(self, value, mode=):
self._check_executed()
if mode == :
if value < 0:
raise NotSupportedError("Backwards scrolling not supported "
"by this cursor")
for _ in range(value):
await ... | Scroll the cursor in the result set to a new position
according to mode . Same as :meth:`Cursor.scroll`, but move cursor
on server side one by one row. If you want to move 20 rows forward
scroll will make 20 queries to move cursor. Currently only forward
scrolling is supported.
... |
373,640 | def var_added(self, v):
self.add_variable(v)
self.window.set_size_request(400, 35 * len(self.widgets.keys()))
self.window.show_all() | var was added in the bot while it ran, possibly
by livecoding
:param v:
:return: |
373,641 | def mmGetCellActivityPlot(self, title="", showReset=False,
resetShading=0.25, activityType="activeCells"):
cellTrace = copy.deepcopy(self._mmTraces[activityType].data)
for i in xrange(len(cellTrace)):
cellTrace[i] = self.getCellIndices(cellTrace[i])
return self.mmGet... | Returns plot of the cell activity.
@param title (string) an optional title for the figure
@param showReset (bool) if true, the first set of cell activities
after a reset will have a gray background
@param resetShading (float) if showReset is true, this fl... |
373,642 | def get_matching_indexes(self, possible_hash, possible_range):
matches = [
index
for index in self.iter_query_indexes()
if index.hash_key in possible_hash
]
range_matches = [
index for index in matches if index.range_key in possible_range
... | Get all indexes that could be queried on using a set of keys.
If any indexes match both hash AND range keys, indexes that only match
the hash key will be excluded from the result.
Parameters
----------
possible_hash : set
The names of fields that could be used as th... |
373,643 | def do_transform(self):
if not self.transform:
return
try:
self.latest_value = utils.Transform(
expr=self.transform, value=self.latest_value,
timedelta=self.time_between_updates().total_seconds()).result()
except (TypeError, ValueE... | Apply the transformation (if it exists) to the latest_value |
373,644 | def links(xmrs):
links = []
prelinks = []
_eps = xmrs._eps
_hcons = xmrs._hcons
_vars = xmrs._vars
lsh = xmrs.labelset_heads
lblheads = {v: lsh(v) for v, vd in _vars.items() if in vd[]}
top = xmrs.top
if top is not None:
prelinks.append((0, top, ... | Return the list of Links for the *xmrs*. |
373,645 | def brightness_prob(self, clip=True):
thresh = 0.11
bp = np.minimum(thresh, self.nir) / thresh
if clip:
bp[bp > 1] = 1
bp[bp < 0] = 0
return bp | The brightest water may have Band 5 reflectance
as high as LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF.11
Equation 10 (Zhu and Woodcock, 2012)
Parameters
----------
nir: ndarray
clip: boolean
Output
------
ndarray:
brightness p... |
373,646 | def put( self, path_or_tuple, folder_id=,
overwrite=None, downsize=None, bits_api_fallback=True ):
api_overwrite = self._translate_api_flag(overwrite, , [])
api_downsize = self._translate_api_flag(downsize, )
name, src = self._process_upload_source(path_or_tuple)
if not isinstance(bits_api_fallback, (int... | Upload a file (object), possibly overwriting (default behavior)
a file with the same "name" attribute, if it exists.
First argument can be either path to a local file or tuple
of "(name, file)", where "file" can be either a file-like object
or just a string of bytes.
overwrite option can be set to F... |
373,647 | def export_image3d(input, output, size=(800, 600), pcb_rotate=(0, 0, 0), timeout=20, showgui=False):
showgui
input = norm_path(input)
output = norm_path(output)
ext = os.path.splitext(input)[1]
if ext not in []:
raise ValueError( + str(input))
commands = []
eagle3d = Path(__file__)... | Exporting eagle .brd file into 3D image file
using Eagle3D and povray.
GUI is not displayed if ``pyvirtualdisplay`` is installed.
If export is blocked somehow (e.g. popup window is displayed) then after timeout operation is canceled with exception.
Problem can be investigated by setting 'showgui' flag.
... |
373,648 | def stdout_avail(self):
data = self.interpreter.stdout_write.empty_queue()
if data:
self.write(data) | Data is available in stdout, let's empty the queue and write it! |
373,649 | def removeOutliers(points, radius):
isactor = False
if isinstance(points, vtk.vtkActor):
isactor = True
poly = points.GetMapper().GetInput()
else:
src = vtk.vtkPointSource()
src.SetNumberOfPoints(len(points))
src.Update()
vpts = src.GetOutput().GetPoints(... | Remove outliers from a cloud of points within the specified `radius` search.
.. hint:: |clustering| |clustering.py|_ |
373,650 | def get(self, key, env=None):
if env is None:
env = self.environment
try:
ret = self._settings[env][key]
except KeyError:
ret = None
if ret is None:
if key == "identity_class":
env_var ... | Returns the config setting for the specified environment. If no
environment is specified, the value for the current environment is
returned. If an unknown key or environment is passed, None is returned. |
373,651 | async def strings(self, request: Optional[]=None) \
-> List[Tuple[Text, ...]]:
if request:
locale = await request.get_locale()
else:
locale = None
return self.db.get(self.key, locale) | For the given request, find the list of strings of that intent. If the
intent does not exist, it will raise a KeyError. |
373,652 | def collect(self):
for root, dirname, files in walk(self.migration_home):
for file_name in file_filter(files, "*.py"):
file_name = file_name.replace(, )
file = None
try:
if file_name == :
continue
... | Walks self.migration_home and load all potential migration modules |
373,653 | def result(self,num):
try:
return self.all[num].result
except KeyError:
error( % num) | result(N) -> return the result of job N. |
373,654 | def reporter(self):
logging.info()
header = .format(.join(self.headers))
data = str()
for sample in self.metadata:
data += GenObject.returnattr(sample, )
data += GenObject.returnattr(sample.run, )
... | Creates the metadata report by pulling specific attributes from the metadata objects |
373,655 | def cfg_to_dot(self, filename):
with open(filename, , encoding=) as f:
f.write()
for node in self.nodes:
f.write(.format(node.node_id, str(node)))
for son in node.sons:
f.write(.format(node.node_id, son.node_id))
f... | Export the function to a dot file
Args:
filename (str) |
373,656 | def _and_join(self, terms):
if len(terms) > 1:
return .join([self._or_join(t) for t in terms])
else:
return self._or_join(terms[0]) | Joins terms using AND operator.
Args:
terms (list): terms to join
Examples:
self._and_join(['term1']) -> 'term1'
self._and_join(['term1', 'term2']) -> 'term1 AND term2'
self._and_join(['term1', 'term2', 'term3']) -> 'term1 AND term2 AND term3'
R... |
373,657 | def log_source(self, loglevel=):
ll = loglevel.upper()
if ll == :
return
else:
if "run_keyword_and_ignore_error" not in [check_error_ignored[3] for check_error_ignored in inspect.stack()]:
source = self._current_application().page_source
... | Logs and returns the entire html source of the current page or frame.
The `loglevel` argument defines the used log level. Valid log levels are
`WARN`, `INFO` (default), `DEBUG`, `TRACE` and `NONE` (no logging). |
373,658 | def _population_load_script(work_bams, names, chrom, pairmode, items):
bed_file = _get_regional_bed_file(items[0])
if bed_file:
return _population_prep_targeted.format(bam_file_str=",".join(work_bams), names_str=",".join(names),
chrom=chrom, num_cores... | Prepare BAMs for assessing CNVs in a population. |
373,659 | def _chain_future(source, dest):
if not isinstance(source, (asyncio.Future, concurrent.futures.Future)):
raise TypeError()
if not isinstance(dest, (asyncio.Future, concurrent.futures.Future)):
raise TypeError()
source_loop = source._loop if isinstance(source, asyncio.Future) else None
... | Chain two futures so that when one completes, so does the other.
The result (or exception) of source will be copied to destination.
If destination is cancelled, source gets cancelled too.
Compatible with both asyncio.Future and concurrent.futures.Future. |
373,660 | def shutdown(self):
if self.cycle is None or self.cycle.response_complete:
self.transport.close()
else:
self.cycle.keep_alive = False | Called by the server to commence a graceful shutdown. |
373,661 | def vq_gating(x,
num_experts,
k,
bneck,
hparams=None,
name="vq_gating"):
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
if hparams.use_scales:
scales = tf.get_variable(
"scales", [num_experts],
tf.float32,
... | VQ gating.
Args:
x: input Tensor with shape [batch_size, input_size]
num_experts: an integer
k: an integer - number of experts per example
bneck: a bottleneck object
hparams: optional hparams
name: an optional string
Returns:
gates: a Tensor with shape [batch_size, num_experts]
loa... |
373,662 | def _set_pg(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("pgid",pg.pg, yang_name="pg", rest_name="pg", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: {u: u, u: None, u: u, u: u... | Setter method for pg, mapped from YANG variable /rbridge_id/ag/pg (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_pg is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_pg() directly. |
373,663 | def topology_mdtraj(traj):
import mdtraj as md
top = {}
top[] = [a.element.symbol for a in traj.topology.atoms]
top[] = [a.name for a in traj.topology.atoms]
top[] = [(a.index, b.index) for a, b in traj.topology.bonds]
top[] = md.compute_dssp(traj[0])[0]
top[] = [r.name for r in traj.t... | Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj. |
373,664 | def bulk_history_create(self, objs, batch_size=None):
historical_instances = [
self.model(
history_date=getattr(instance, "_history_date", now()),
history_user=getattr(instance, "_history_user", None),
history_change_reason=getattr(instance, ... | Bulk create the history for the objects specified by objs |
373,665 | def get_changed_files(self) -> List[str]:
out = shell_tools.output_of(
,
,
,
self.compare_commit_id,
self.actual_commit_id,
,
cwd=self.destination_directory)
return [e for e in out.split() if e.strip()] | Get the files changed on one git branch vs another.
Returns:
List[str]: File paths of changed files, relative to the git repo
root. |
373,666 | def stage_http_response1(self, conn_id, version, status, reason, headers):
self._http_response_version = version
self._http_response_status = status
self._http_response_reason = reason
self._http_response_headers = headers | Set response http info including headers, status, etc.
conn_id unused here. Used in log |
373,667 | def str_numerator(self):
if not self.undefined:
return None
unit_numerator, unit = self._unit_class(self.numerator).auto
formatter = if unit_numerator == self.numerator else
numerator = locale.format(formatter, unit_numerator, grouping=True)
return .format(... | Returns the numerator with formatting. |
373,668 | def mount(name=None, **kwargs):
-a***
flags = []
opts = {}
if kwargs.get(, False):
flags.append()
if kwargs.get(, False):
opts[] = kwargs.get()
if name in [None, ]:
if name == :
salt.utils.versions.warn_until... | Mounts ZFS file systems
name : string
name of the filesystem, having this set to None will mount all filesystems. (this is the default)
overlay : boolean
perform an overlay mount.
options : string
optional comma-separated list of mount options to use temporarily for
the dura... |
373,669 | def _act(self, utterance: str) -> list:
if self.stateful:
utterance = [[utterance], [self.key]]
else:
utterance = [[utterance]]
agent_response: list = self.agent(*utterance)
return agent_response | Infers DeepPavlov agent with raw user input extracted from Alexa request.
Args:
utterance: Raw user input extracted from Alexa request.
Returns:
response: DeepPavlov agent response. |
373,670 | def find_by_tag(self, tag, params={}, **options):
path = "/tags/%s/tasks" % (tag)
return self.client.get_collection(path, params, **options) | Returns the compact task records for all tasks with the given tag.
Parameters
----------
tag : {Id} The tag in which to search for tasks.
[params] : {Object} Parameters for the request |
373,671 | def urlvoid_check(name, api_key):
if not is_fqdn(name):
return None
url = .format(key=api_key, name=name)
response = requests.get(url)
tree = ET.fromstring(response.text)
if tree.find():
return [e.text for e in tree.find()]
else:
return None | Checks URLVoid.com for info on a domain |
373,672 | def _validate_readonly(self, readonly, field, value):
if readonly:
if not self._is_normalized:
self._error(field, errors.READONLY_FIELD)
has_error = errors.READONLY_FIELD in \
self.document_error_tree.fetch_e... | {'type': 'boolean'} |
373,673 | def remove_sub(self, sub):
for _sid in self.get(, sub):
self.remove(, _sid, sub)
self.delete(, sub) | Remove all references to a specific Subject ID
:param sub: A Subject ID |
373,674 | def convert_pronouns( mrf_lines ):
_P_s mrf to
syntactic analyzer
i = 0
while ( i < len(mrf_lines) ):
line = mrf_lines[i]
if in line:
for [pattern, replacement] in _pronConversions:
lastline = line
line = re.sub(pattern, replacement, line... | Converts pronouns (analysis lines with '_P_') from Filosoft's mrf to
syntactic analyzer's mrf format;
Uses the set of predefined pronoun conversion rules from _pronConversions;
_pronConversions should be a list of lists, where each outer list stands
for a single conversion rul... |
373,675 | def K_value(P=None, Psat=None, phi_l=None, phi_g=None, gamma=None, Poynting=1):
rs law,
or an equation of state model, or an activity coefficient model,
or a combined equation of state-activity model.
The calculation procedure will use the most advanced approach with the
provided inputs:
*... | r'''Calculates the equilibrium K-value assuming Raoult's law,
or an equation of state model, or an activity coefficient model,
or a combined equation of state-activity model.
The calculation procedure will use the most advanced approach with the
provided inputs:
* If `P`, `Psat`, `phi_l`, `phi... |
373,676 | def run(self, i_str, start_count=0, start_chunk_time=None):
try:
if not os.path.exists(self.tmp_dir_path):
os.makedirs(self.tmp_dir_path)
if start_chunk_time is None:
start_chunk_time = time.time()
i_chunk = self.reader(... | Run the pipeline.
This runs all of the steps described in the pipeline constructor,
reading from some input and writing to some output.
:param str i_str: name of the input file, or other reader-specific
description of where to get input
:param int start_count: index of the fi... |
373,677 | def next(self) -> Future:
self._running_future = Future()
if self._finished:
self._return_result(self._finished.popleft())
return self._running_future | Returns a `.Future` that will yield the next available result.
Note that this `.Future` will not be the same object as any of
the inputs. |
373,678 | def all_after_notification(self, model, prop_name, info):
self.logger.debug(NotificationOverview(info)) | The method logs all changes that notified recursively trough the hierarchies of the states after the change
occurs in the rafcon.core object. The method register as observer of observable
StateMachineModel.state_machine of any observed StateMachineModel.
:param model: StateMachineModel that is r... |
373,679 | def alien_filter(name, location, size, unsize):
(fname, flocation, fsize, funsize) = ([] for i in range(4))
for n, l, s, u in zip(name, location, size, unsize):
if "slackbuilds" != l:
fname.append(n)
flocation.append(l)
fsize.append(s)
funsize.append(... | Fix to avoid packages include in slackbuilds folder |
373,680 | def _check_triple(self, triple):
subj, pred, obj = triple
if self._should_ignore_predicate(pred):
log.info("Ignoring triple with predicate "
.format(self._field_name_from_uri(pred)))
return
classes = []
log.warning("Possible member ... | compare triple to ontology, return error or None |
373,681 | def _get_pos_name(pos_code, names=, english=True, pos_map=POS_MAP):
pos_code = pos_code.lower()
if names not in (, , ):
raise ValueError("names must be one of , , or "
"; not ".format(names))
logger.debug("Getting {} POS name for formatted as .".format(
... | Gets the part of speech name for *pos_code*. |
373,682 | def keys_present(name, number, save_dir, region=None, key=None, keyid=None, profile=None,
save_format="{2}\n{0}\n{3}\n{1}\n"):
key-{number}
ret = {: name, : True, : , : {}}
if not __salt__[](name, region, key, keyid, profile):
ret[] = False
ret[] = .format(name)
retu... | .. versionadded:: 2015.8.0
Ensure the IAM access keys are present.
name (string)
The name of the new user.
number (int)
Number of keys that user should have.
save_dir (string)
The directory that the key/keys will be saved. Keys are saved to a file named according
to t... |
373,683 | def get_installed_distributions(local_only=True, skip=(, , )):
if local_only:
local_test = dist_is_local
else:
local_test = lambda d: True
return [d for d in pkg_resources.working_set if local_test(d) and d.key not in skip] | Return a list of installed Distribution objects.
If ``local_only`` is True (default), only return installations
local to the current virtualenv, if in a virtualenv.
``skip`` argument is an iterable of lower-case project names to
ignore; defaults to ('setuptools', 'pip', 'python'). [FIXME also
skip... |
373,684 | def draw_points_heatmap_array(self, image_shape, alpha=1.0,
size=1, raise_if_out_of_image=False):
assert len(image_shape) == 2 or (
len(image_shape) == 3 and image_shape[-1] == 1), (
"Expected (H,W) or (H,W,1) as image_shape, got %s." % (
... | Draw the points of the line string as a heatmap array.
Parameters
----------
image_shape : tuple of int
The shape of the image onto which to draw the point mask.
alpha : float, optional
Opacity of the line string points. Higher values denote a more
v... |
373,685 | def validate_args(f):
def wrapper(self, args):
arg_types = set([type(arg) for arg in args])
if len(arg_types) > 1:
raise TypeError("Mixed input types are not allowed")
elif list(arg_types)[0] not in (dict, str):
raise TypeError("Only dict and str types accepted... | Ensures that *args consist of a consistent type
:param f: any client method with *args parameter
:return: function f |
373,686 | def get_tmaster(self, topologyName, callback=None):
isWatching = False
ret = {
"result": None
}
if callback:
isWatching = True
else:
def callback(data):
ret["result"] = data
self._get_tmaster_with_watch(topologyName, callback, isWatching)
... | get tmaster |
373,687 | def to_primitive(self, value, context=None):
if context and context.get():
epoch = dt(1970, 1, 1)
value = (value - epoch).total_seconds()
return int(value)
elif context and context.get():
return value
else:
return super(Type, ... | Schematics serializer override
If epoch_date is true then convert the `datetime.datetime`
object into an epoch `int`. |
373,688 | def configure(self):
logger.debug( + hex(self.get_address())
+ + str(self.get_channel())
+ + str(self.get_resolution())
+ + str(self.get_gain()))
self.bus.write_byte(self.address, self.config) | Configure the device.
Send the device configuration saved inside the MCP342x object to the target device. |
373,689 | def get_id(date=None, project: str = ,
instance_id: int = None) -> str:
if date is None:
date = datetime.datetime.utcnow()
if isinstance(date, datetime.datetime):
date = date.strftime()
if instance_id is None:
instance_id = randint(0,... | Get a SBI Identifier.
Args:
date (str or datetime.datetime, optional): UTC date of the SBI
project (str, optional ): Project Name
instance_id (int, optional): SBI instance identifier
Returns:
str, Scheduling Block Instance (SBI) ID. |
373,690 | def evaluate(
loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir,
agent_type, eval_mode, eval_with_learner, log_every_steps, debug_video_path,
num_debug_videos=1, random_starts_step_limit=None,
report_fn=None, report_metric=None
):
if eval_with_learner:
assert agent_type == ... | Evaluate. |
373,691 | def get_word_id (root):
global UNIQ_WORDS
if root not in UNIQ_WORDS:
UNIQ_WORDS[root] = len(UNIQ_WORDS)
return UNIQ_WORDS[root] | lookup/assign a unique identify for each word root |
373,692 | def user_has_permission(self, user, name):
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return False
for group in targetRecord.groups:
if self.has_permission(group.role, name):
return True
... | verify user has permission |
373,693 | def _handle_union(self, node, scope, ctxt, stream):
self._dlog("handling union")
union_cls = StructUnionDef("union", self, node)
return union_cls | TODO: Docstring for _handle_union.
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO |
373,694 | def generate_all(sumlevel, d):
from geoid.civick import GVid
from geoid.tiger import TigerGeoid
from geoid.acs import AcsGeoid
sumlevel = int(sumlevel)
d = dict(d.items())
if in d:
d[] = d[]
del d[]
if in d:
d[] = d[]
del d[]
if in d:
... | Generate a dict that includes all of the available geoid values, with keys
for the most common names for those values. |
373,695 | def plate_exchanger_identifier(self):
LAB
s = ( + str(round(self.wavelength*1000, 2))
+ + str(round(self.amplitude*1000, 2))
+ + .join([str(i) for i in self.chevron_angles]))
return s | Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places. |
373,696 | def _process_wave_param(self, pval):
return self._process_generic_param(
pval, self._internal_wave_unit, equivalencies=u.spectral()) | Process individual model parameter representing wavelength. |
373,697 | def safe_int_conv(number):
try:
return int(np.array(number).astype(int, casting=))
except TypeError:
raise ValueError(.format(number)) | Safely convert a single number to integer. |
373,698 | def is_for_driver_task(self):
return all(
len(x) == 0
for x in [self.module_name, self.class_name, self.function_name]) | See whether this function descriptor is for a driver or not.
Returns:
True if this function descriptor is for driver tasks. |
373,699 | def list(self, **filters):
LOG.debug(u, self.model_class.__name__, filters)
query = self.__queryset__()
perm = build_permission_name(self.model_class, )
LOG.debug(u"Checking if user %s has_perm %s" % (self.user, perm))
query_with_permission = filter(lambda o: self.user.h... | Returns a queryset filtering object by user permission. If you want,
you can specify filter arguments.
See https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter for more details |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.