Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
368,600 | def remove_project(self, node):
if node.family == "Project":
self.__script_editor.remove_project(node.path)
return True
for node in foundations.walkers.nodes_walker(node, ascendants=True):
if node.family == "Project" and not node is self.__script_editor.mod... | Removes the project associated with given node.
:param node: Node.
:type node: ProjectNode or DirectoryNode or FileNode
:return: Method success.
:rtype: bool |
368,601 | def get_setting(key, *default):
if default:
return get_settings().get(key, default[0])
else:
return get_settings()[key] | Return specific search setting from Django conf. |
368,602 | def get_picture_elements(context, instance):
if hasattr(instance, ) and hasattr(instance.image, ):
aspect_ratio = compute_aspect_ratio(instance.image)
elif in instance.glossary and in instance.glossary[]:
aspect_ratio = compute_aspect_ratio_with_glossary(instance.glossary)
instan... | Create a context, used to render a <picture> together with all its ``<source>`` elements:
It returns a list of HTML elements, each containing the information to render a ``<source>``
element.
The purpose of this HTML entity is to display images with art directions. For normal images use
the ``<img>`` el... |
368,603 | def populate_username(self, request, user):
from .utils import user_username, user_email, user_field
first_name = user_field(user, )
last_name = user_field(user, )
email = user_email(user)
username = user_username(user)
if app_settings.USER_MODEL_USERNAME_FIELD:
... | Fills in a valid username, if required and missing. If the
username is already present it is assumed to be valid
(unique). |
368,604 | def reload(self, **params):
if not self.bucket:
raise ValueError()
if not self.key:
raise ValueError()
dtype, value, context = self.bucket._client._fetch_datatype(
self.bucket, self.key, **params)
if not dtype == self.type_name:
... | Reloads the datatype from Riak.
.. warning: This clears any local modifications you might have
made.
:param r: the read quorum
:type r: integer, string, None
:param pr: the primary read quorum
:type pr: integer, string, None
:param basic_quorum: whether to us... |
368,605 | def serialize(self, data):
super(Serializer, self).serialize(data)
self.resp.content_type +=
import pprint
pprint.PrettyPrinter().pprint(data) | Determine & invoke the proper serializer method
If data is a list then the serialize_datas method will
be run otherwise serialize_data. |
368,606 | def get_node_annotation_layers(docgraph):
all_layers = set()
for node_id, node_attribs in docgraph.nodes_iter(data=True):
for layer in node_attribs[]:
all_layers.add(layer)
return all_layers | WARNING: this is higly inefficient!
Fix this via Issue #36.
Returns
-------
all_layers : set or dict
the set of all annotation layers used for annotating nodes in the given
graph |
368,607 | def is_group_or_super_group(cls, obj) -> bool:
return cls._check(obj, [cls.GROUP, cls.SUPER_GROUP]) | Check chat is group or super-group
:param obj:
:return: |
368,608 | def BGPSessionState_BGPPeerState(self, **kwargs):
config = ET.Element("config")
BGPSessionState = ET.SubElement(config, "BGPSessionState", xmlns="http://brocade.com/ns/brocade-notification-stream")
BGPPeerState = ET.SubElement(BGPSessionState, "BGPPeerState")
BGPPeerState.text =... | Auto Generated Code |
368,609 | def subscribeToDeviceEvents(self, typeId="+", deviceId="+", eventId="+", msgFormat="+", qos=0):
if self._config.isQuickstart() and deviceId == "+":
self.logger.warning(
"QuickStart applications do not support wildcard subscription to events from all devices"
)
... | Subscribe to device event messages
# Parameters
typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard)
deviceId (string): deviceId for the subscription, optional. Defaults to all devices (MQTT `+` wildcard)
eventId (string): eventId fo... |
368,610 | def init(self):
if not self.export_enable:
return None
server_uri = .format(self.host, self.port)
try:
self.context = zmq.Context()
publisher = self.context.socket(zmq.PUB)
publisher.bind(server_uri)
except Exception as e:
... | Init the connection to the CouchDB server. |
368,611 | def compare_field_caches(self, replica, original):
if original is None:
original = []
if replica is None:
replica = []
self.pr_dbg("Comparing orig with %s fields to replica with %s fields" %
(len(original), len(replica)))
... | Verify original is subset of replica |
368,612 | def percent(args=None):
*
if __grains__[] == :
cmd =
elif __grains__[] == or __grains__[] == :
cmd =
else:
cmd =
ret = {}
out = __salt__[](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith()... | Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var |
368,613 | def is_cython(obj):
def check_cython(x):
return type(x).__name__ == "cython_function_or_method"
return check_cython(obj) or \
(hasattr(obj, "__func__") and check_cython(obj.__func__)) | Check if an object is a Cython function or method |
368,614 | def trade_history(
self, from_=None, count=None, from_id=None, end_id=None,
order=None, since=None, end=None, pair=None
):
return self._trade_api_call(
, from_=from_, count=count, from_id=from_id, end_id=end_id,
order=order, since=since, end=end, pair=pair
... | Returns trade history.
To use this method you need a privilege of the info key.
:param int or None from_: trade ID, from which the display starts (default 0)
:param int or None count: the number of trades for display (default 1000)
:param int or None from_id: trade ID, from which the di... |
368,615 | def extract_rows(data, *rows):
try:
out = []
for r in rows:
out.append(data[r])
return out
except IndexError:
raise IndexError("data=%s rows=%s" % (data, rows))
return out | Extract rows specified in the argument list.
>>> chart_data.extract_rows([[10,20], [30,40], [50,60]], 1, 2)
[[30,40],[50,60]] |
368,616 | def allocate(self, nodes, append=True):
nodes_demand = 0
for node in [node for node in nodes]:
if node._allocation:
node._allocation.deallocate([node])
node._allocation = self
nodes_demand = nodes_demand + node.demand()
... | Allocates all nodes from `nodes` list in this route
Parameters
----------
nodes : type
Desc
append : bool, defaults to True
Desc |
368,617 | def create_position(self, params={}):
url = "/2/positions/"
body = params
data = self._post_resource(url, body)
return self.position_from_json(data["position"]) | Creates a position
http://dev.wheniwork.com/#create-update-position |
368,618 | def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None):
output_dir = safe_mkdir(adjust_path(output_dir or join(os.getcwd(), proc_name)), )
debug( + output_dir)
work_dir = safe_mkdir(work_dir or join(output_dir, ), )
info( + work_dir)
log_fpath = set_up_log(log_dir or safe_mk... | Creates output_dir, work_dir, and sets up log |
368,619 | def _phi0(self, tau, delta):
Fi0 = self.Fi0
fio = Fi0["ao_log"][0]*log(delta)+Fi0["ao_log"][1]*log(tau)
fiot = +Fi0["ao_log"][1]/tau
fiott = -Fi0["ao_log"][1]/tau**2
fiod = 1/delta
fiodd = -1/delta**2
fiodt = 0
for n, t in zip(Fi0["ao_pow"], Fi... | Ideal gas Helmholtz free energy and derivatives
Parameters
----------
tau : float
Inverse reduced temperature Tc/T, [-]
delta : float
Reduced density rho/rhoc, [-]
Returns
-------
prop : dictionary with ideal adimensional helmholtz energy... |
368,620 | def update_eol(self, os_name):
os_name = to_text_string(os_name)
value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR")
self.set_value(value) | Update end of line status. |
368,621 | def main():
if running_under_pytest():
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
options = Mock()
options.working_directory = None
options.profile = False
options.multithreade... | Main function |
368,622 | def start_all_linking(self, mode, group):
msg = StartAllLinking(mode, group)
self.send_msg(msg) | Put the IM into All-Linking mode.
Puts the IM into All-Linking mode for 4 minutes.
Parameters:
mode: 0 | 1 | 3 | 255
0 - PLM is responder
1 - PLM is controller
3 - Device that initiated All-Linking is Controller
255 = De... |
368,623 | def _set_wmi_setting(wmi_class_name, setting, value, server):
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class(Name=server)[0]
except wmi.x_wmi as error:
... | Set the value of the setting for the provided class. |
368,624 | def all():
return [goal for _, goal in sorted(Goal._goal_by_name.items()) if goal.active] | Returns all active registered goals, sorted alphabetically by name.
:API: public |
368,625 | async def filter_by(cls, db, offset=None, limit=None, **kwargs):
if limit and type(limit) is not int:
raise InvalidQuery()
if offset and type(offset) is not int:
raise InvalidQuery()
ids_to_iterate = await cls._get_ids_filter_by(db, **kwargs)
if offset:
... | Query by attributes iteratively. Ordering is not supported
Example:
User.get_by(db, age=[32, 54])
User.get_by(db, age=23, name="guido") |
368,626 | async def write(self, writer: Any,
close_boundary: bool=True) -> None:
if not self._parts:
return
for part, encoding, te_encoding in self._parts:
await writer.write(b + self._boundary + b)
await writer.write(part._binary_headers)
... | Write body. |
368,627 | def main(args=None):
_parse_args(args)
streamsx._streams._version._mismatch_check()
srp = pkg_resources.working_set.find(pkg_resources.Requirement.parse())
if srp is not None:
srv = srp.parsed_version
location = srp.location
spkg =
else:
srv = streamsx._streams.... | Output information about `streamsx` and the environment.
Useful for support to get key information for use of `streamsx`
and Python in IBM Streams. |
368,628 | def clean_ufo(path):
if path.endswith(".ufo") and os.path.exists(path):
shutil.rmtree(path) | Make sure old UFO data is removed, as it may contain deleted glyphs. |
368,629 | def partial_derivative_scalar(self, U, V, y=0):
self.check_fit()
X = np.column_stack((U, V))
return self.partial_derivative(X, y) | Compute partial derivative :math:`C(u|v)` of cumulative density of single values. |
368,630 | def _bilinear_interp(xyref, zref, xi, yi):
if len(xyref) != 4:
raise ValueError()
if zref.shape[0] != 4:
raise ValueError(
)
xyref = [tuple(i) for i in xyref]
idx = sorted(range(len(xyref)), key=xyref.__getitem__)
x... | Perform bilinear interpolation of four 2D arrays located at
points on a regular grid.
Parameters
----------
xyref : list of 4 (x, y) pairs
A list of 4 ``(x, y)`` pairs that form a rectangle.
refdata : 3D `~numpy.ndarray`
A 3D `~numpy.ndarray` of shape ``... |
368,631 | def get_region_for_chip(x, y, level=3):
shift = 6 - 2*level
bit = ((x >> shift) & 3) + 4*((y >> shift) & 3)
mask = 0xffff ^ ((4 << shift) - 1)
nx = x & mask
ny = y & mask
region = (nx << 24) | (ny << 16) | (level << 16) | (1 << bit)
return region | Get the region word for the given chip co-ordinates.
Parameters
----------
x : int
x co-ordinate
y : int
y co-ordinate
level : int
Level of region to build. 0 is the most coarse and 3 is the finest.
When 3 is used the specified region will ONLY select the given chip,... |
368,632 | def divide(elements, by, translate=False, sep=):
outer_spans = [spans(elem) for elem in by]
return divide_by_spans(elements, outer_spans, translate=translate, sep=sep) | Divide lists `elements` and `by`.
All elements are grouped into N bins, where N denotes the elements in `by` list.
Parameters
----------
elements: list of dict
Elements to be grouped into bins.
by: list of dict
Elements defining the bins.
translate: bool (default: False)
... |
368,633 | def addContentLen(self, content, len):
libxml2mod.xmlNodeAddContentLen(self._o, content, len) | Append the extra substring to the node content. NOTE: In
contrast to xmlNodeSetContentLen(), @content is supposed to
be raw text, so unescaped XML special chars are allowed,
entity references are not supported. |
368,634 | def get_rules(self, optimized):
self.insert_start_to_accepting()
if optimized == 0:
self.insert_self_to_empty_and_insert_all_intemediate(optimized)
self.insert_symbol_pushpop()
return self.rules | Args:
optimized (bool): Enable or Disable optimization - Do not produce O(n^3)
Return:
list: The CFG rules |
368,635 | def run(self):
delay = None
router = self.siteRouter
for qmsg in self.store.query(_QueuedMessage,
sort=_QueuedMessage.storeID.ascending):
try:
self._verifySender(qmsg.sender)
except:
self.routeA... | Attmept to deliver the first outgoing L{QueuedMessage}; return a time
to reschedule if there are still more retries or outgoing messages to
send. |
368,636 | def _readline(self):
if len(self.lines) > 1:
return self.lines.pop(0)
tail =
if len(self.lines):
tail = self.lines.pop()
try:
tail += self._read()
except socket.error:
logging.exception()
time.sleep(0.1)
... | Read exactly one line from the device, nonblocking.
Returns:
None on no data |
368,637 | def _on_properties(self, properties):
self._bold, self._italic, self._underline, self._overstrike = properties
self._on_change() | Callback if properties are changed.
:param properties: (bool bold, bool italic, bool underline, bool overstrike) |
368,638 | def debug_log_repo(repo):
ds_str = juicer.utils.create_json_str(repo,
indent=4,
cls=juicer.common.Repo.RepoEncoder)
juicer.utils.Log.log_debug(ds_str) | Log to DEBUG level a Repo (or subclass) pretty-printed |
368,639 | def check_pin_trust(self, environ):
if self.pin is None:
return True
val = parse_cookie(environ).get(self.pin_cookie_name)
if not val or "|" not in val:
return False
ts, pin_hash = val.split("|", 1)
if not ts.isdigit():
return False
... | Checks if the request passed the pin test. This returns `True` if the
request is trusted on a pin/cookie basis and returns `False` if not.
Additionally if the cookie's stored pin hash is wrong it will return
`None` so that appropriate action can be taken. |
368,640 | def liftover(pass_pos, matures):
fixed_pos = []
_print_header(pass_pos)
for pos in pass_pos:
mir = pos["mature"]
db_pos = matures[pos["chrom"]]
mut = _parse_mut(pos["sv"])
print([db_pos[mir], mut, pos["sv"]])
pos[] = db_pos[mir][0] + mut[1] - 1
pos[] = li... | Make position at precursor scale |
368,641 | def fetch(self, range_start, range_end):
range_dates = {: range_start, : range_end}
url = self.URL.format(**range_dates)
xml = urllib.request.urlopen(url)
tree = ET.ElementTree(file=xml)
records = self._parse_speeches(tree.getroot())
return pd.DataFrame(records... | Fetches speeches from the ListarDiscursosPlenario endpoint of the
SessoesReunioes (SessionsReunions) API.
The date range provided should be specified as a string using the
format supported by the API (%d/%m/%Y) |
368,642 | def delete(self, image):
from .entity import Image
if not isinstance(image, Image):
raise TypeError(
+ repr(image))
self.delete_file(image.object_type, image.object_id,
image.width, image.height, image.mimetype) | Delete the file of the given ``image``.
:param image: the image to delete
:type image: :class:`sqlalchemy_imageattach.entity.Image` |
368,643 | def find_value_type(global_ns, value_type_str):
if not value_type_str.startswith():
value_type_str = + value_type_str
found = global_ns.decls(
name=value_type_str,
function=lambda decl: not isinstance(decl, calldef.calldef_t),
allow_empty=True)
... | implementation details |
368,644 | def timestamp_feature(catalog, soup):
epoch = 1318790434
catalog.timestamp = int(float(soup.title.text)) + epoch
catalog.datetime = datetime.datetime.fromtimestamp(catalog.timestamp)
logger.info( % catalog.datetime) | The datetime the xml file was last modified. |
368,645 | def plot_theta(self, colorbar=True, cb_orientation=,
cb_label=, ax=None, show=True,
fname=None, **kwargs):
if ax is None:
fig, axes = self.theta.plot(colorbar=colorbar,
cb_orientation=cb_orientation,
... | Plot the theta component of the gravity field.
Usage
-----
x.plot_theta([tick_interval, xlabel, ylabel, ax, colorbar,
cb_orientation, cb_label, show, fname, **kwargs])
Parameters
----------
tick_interval : list or tuple, optional, default = [30, 30... |
368,646 | def seek(self, position):
self._position = position
range_string = make_range_string(self._position)
logger.debug(, self._content_length, range_string)
try:
self._body.close()
except AttributeError:
pass
... | Seek to the specified position (byte offset) in the S3 key.
:param int position: The byte offset from the beginning of the key. |
368,647 | def load_module(ldr, fqname):
t
necessarily always called during an actual import:
meta tools that analyze import dependencies (such as freeze,
Installer or py2exe) dont depend on the parent package being
available in `sys.modules`.
The `load_module()` method has a few responsibi... | Load `fqname` from under `ldr.fspath`.
The `fqname` argument is the fully qualified module name,
eg. "spam.eggs.ham". As explained above, when ::
finder.find_module("spam.eggs.ham")
is called, "spam.eggs" has already been imported and added
to `sys.modules`. However, the `find_... |
368,648 | def enable_secrets_engine(self, backend_type, path=None, description=None, config=None, plugin_name=None,
options=None, local=False, seal_wrap=False):
if path is None:
path = backend_type
params = {
: backend_type,
: description... | Enable a new secrets engine at the given path.
Supported methods:
POST: /sys/mounts/{path}. Produces: 204 (empty body)
:param backend_type: The name of the backend type, such as "github" or "token".
:type backend_type: str | unicode
:param path: The path to mount the method... |
368,649 | def get_00t_magmom_with_xyz_saxis(self):
ref_direction = np.array([1.01, 1.02, 1.03])
t = abs(self)
if t != 0:
new_saxis = self.moment/np.linalg.norm(self.moment)
if np.dot(ref_direction, new_saxis) < 0:
... | For internal implementation reasons, in non-collinear calculations
VASP prefers:
MAGMOM = 0 0 total_magnetic_moment
SAXIS = x y z
to an equivalent:
MAGMOM = x y z
SAXIS = 0 0 1
This method returns a Magmom object with magnetic moment [0, 0, t],
where t... |
368,650 | def has_preview(self):
version_info = self.image_resources.get_data()
if version_info:
return version_info.has_composite
return True | Returns if the document has real merged data. When True, `topil()`
returns pre-composed data. |
368,651 | def iscm_md_append_array(self, arraypath, member):
array_path = string.split(arraypath, ".")
array_key = array_path.pop()
current = self.metadata
for k in array_path:
if not current.has_key(k):
current[k] = {}
current = current[k]
... | Append a member to a metadata array entry |
368,652 | def add_comment(self, line: str) -> None:
self._last_comment += ( if self._last_comment else ) + \
line.lstrip().strip() | Keeping track of "last comment" for section and parameter |
368,653 | def relative_abundance(coverage):
relative = {}
sums = []
for genome in coverage:
for cov in coverage[genome]:
sums.append(0)
break
for genome in coverage:
index = 0
for cov in coverage[genome]:
sums[index] += cov
index += 1
for genome in coverage:
index = 0
relative[genome] = []
for cov i... | cov = number of bases / length of genome
relative abundance = [(cov) / sum(cov for all genomes)] * 100 |
368,654 | def create_scree_plot(data, o_filename, options):
mpl.use("Agg")
import matplotlib.pyplot as plt
plt.ioff()
cumul_data = np.cumsum(data)
fig, axes = plt.subplots(2, 1, figsize=(8, 16))
fig.suptitle(options.scree_plot_title, fontsize=16, weight="bold")
fig.subplot... | Creates the scree plot.
:param data: the eigenvalues.
:param o_filename: the name of the output files.
:param options: the options.
:type data: numpy.ndarray
:type o_filename: str
:type options: argparse.Namespace |
368,655 | def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
log.debug(, groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, r... | Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h |
368,656 | def set_context(self):
results = self.rml.query()
namespaces = [Uri(row[0]).value[0]
for row in results
if isinstance(row[0], rdflib.URIRef)]
self.context = {ns[0]: ns[1] for ns in namespaces if ns[0]} | Reads throught the namespaces in the RML and generates a context for
json+ld output when compared to the RdfNsManager namespaces |
368,657 | def _insert(self, key, records, count):
if key not in self.records:
assert key not in self.counts
self.records[key] = records
self.counts[key] = count
else:
self.records[key] = np.vstack((self.records[key], records))
assert key in self... | Insert records according to key |
368,658 | def browse_httpauth_write_apis(
request,
database_name=None,
collection_name=None):
name = "Write APIs Using HTTPAuth Authentication"
if database_name and collection_name:
wapis = WriteAPIHTTPAuth.objects.filter(
database_name=database_name,
collectio... | Deprecated |
368,659 | def parse_time_derivative(self, node):
if in node.lattrib:
variable = node.lattrib[]
else:
self.raise_error()
if in node.lattrib:
value = node.lattrib[]
else:
self.raise_error("Time derivative for must specify an expression.",... | Parses <TimeDerivative>
@param node: Node containing the <TimeDerivative> element
@type node: xml.etree.Element
@raise ParseError: Raised when the time derivative does not hava a variable
name of a value. |
368,660 | def get_segment_effort(self, effort_id):
return model.SegmentEffort.deserialize(self.protocol.get(,
id=effort_id)) | Return a specific segment effort by ID.
http://strava.github.io/api/v3/efforts/#retrieve
:param effort_id: The id of associated effort to fetch.
:type effort_id: int
:return: The specified effort on a segment.
:rtype: :class:`stravalib.model.SegmentEffort` |
368,661 | def skip_class_parameters():
from ..params import Parameter
def callback(app, what, name, obj, skip, options):
if (what == ) and isinstance(obj, Parameter):
return True
return None
return callback | Can be used with :meth:`add_parametric_object_params`, this removes
duplicate variables cluttering the sphinx docs.
This is only intended to be used with *sphinx autodoc*
In your *sphinx* ``config.py`` file::
from cqparts.utils.sphinx import skip_class_parameters
def setup(app):
... |
368,662 | def search(
self,
id_list: List,
negated_classes: List,
limit: Optional[int] = 100,
method: Optional[SimAlgorithm] = SimAlgorithm.PHENODIGM) -> SimResult:
return self.filtered_search(
id_list=id_list,
negated_classes=n... | Owlsim2 search, calls search_by_attribute_set, and converts to SimResult object
:raises JSONDecodeError: If the owlsim response is not valid json. |
368,663 | def _extract_functions(resources):
result = {}
for name, resource in resources.items():
resource_type = resource.get("Type")
resource_properties = resource.get("Properties", {})
if resource_type == SamFunctionProvider._SERVERLESS_FUNCTION:
... | Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This
method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function
:param dict resources: Dictionary of SAM/CloudFormation resources
:return dict(string : samcli.com... |
368,664 | def write_header(self):
self.output.seek(0)
self.output.write(struct.pack(, self.id, self.flags,
self.counts[0], self.counts[1],
self.counts[2], self.counts[3]))
self.output.seek(0, 2) | Write the DNS message header.
Writing the DNS message header is done asfter all sections
have been rendered, but before the optional TSIG signature
is added. |
368,665 | def is_unit_upgrading_set():
try:
with unitdata.HookData()() as t:
kv = t[0]
return not(not(kv.get()))
except Exception:
return False | Return the state of the kv().get('unit-upgrading').
To help with units that don't have HookData() (testing)
if it excepts, return False |
368,666 | def get_subscription_attributes(SubscriptionArn, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = conn.get_subscription_attributes(SubscriptionArn=SubscriptionArn)
return ret[]
except botocore.exceptions.... | Returns all of the properties of a subscription.
CLI example::
salt myminion boto3_sns.get_subscription_attributes somesubscription region=us-west-1 |
368,667 | def create_task(self, task_name=None, script=None, hyper_parameters=None, saved_result_keys=None, **kwargs):
if not isinstance(task_name, str):
raise Exception("task_name should be string")
if not isinstance(script, str):
raise Exception("script should be string")
... | Uploads a task to the database, timestamp will be added automatically.
Parameters
-----------
task_name : str
The task name.
script : str
File name of the python script.
hyper_parameters : dictionary
The hyper parameters pass into the script.
... |
368,668 | def normalize_rrs(rrsets):
for rrset in rrsets:
if rrset.tag == % R53_XMLNS:
for rrs in rrset:
if rrs.tag == % R53_XMLNS:
if rrs.text.startswith():
old_text = rrs.text
new_text = % old_text[2:]
print % new_text
rrs.text = rrs.... | Lexically sort the order of every ResourceRecord in a ResourceRecords
element so we don't generate spurious changes: ordering of e.g. NS records
is irrelevant to the DNS line protocol, but XML sees it differently.
Also rewrite any wildcard records to use the ascii hex code: somewhere deep
inside route53 is som... |
368,669 | def writable(self):
return bool(lib.EnvSlotWritableP(self._env, self._cls, self._name)) | True if the Slot is writable. |
368,670 | def load_drp(self, name, entry_point=):
for drpins in self.iload(entry_point):
if drpins.name == name:
return drpins
else:
raise KeyError(.format(name)) | Load all available DRPs in 'entry_point'. |
368,671 | def send(self, request, stem=None):
if stem is not None:
request.url = request.url + "/" + stem.lstrip("/")
prepped = self.session.prepare_request(request)
settings = self.session.merge_environment_settings(url=prepped.url,
... | Prepare and send a request
Arguments:
request: a Request object that is not yet prepared
stem: a path to append to the root URL
Returns:
The response to the request |
368,672 | def squash_xml_to_text(elm, remove_namespaces=False):
leading_text = elm.text and elm.text or
result = [leading_text]
for child in elm.getchildren():
child_value = etree.tostring(child, encoding=)
child_value = child_value.decode()
result.append(chil... | Squash the given XML element (as `elm`) to a text containing XML.
The outer most element/tag will be removed, but inner elements will
remain. If `remove_namespaces` is specified, XML namespace declarations
will be removed from the text.
:param elm: XML element
:type elm: :class:`xml.etree.ElementTr... |
368,673 | def get_all_namespace_ids( self ):
cur = self.db.cursor()
namespace_ids = namedb_get_all_namespace_ids( cur )
return namespace_ids | Get the set of all existing, READY namespace IDs. |
368,674 | def _get_group_infos(self):
if self._group_infos is None:
self._group_infos = self._group_type.user_groups(
self._ldap_user, self._group_search
)
return self._group_infos | Returns a (cached) list of group_info structures for the groups that our
user is a member of. |
368,675 | def update_source(ident, data):
source = get_source(ident)
source.modify(**data)
signals.harvest_source_updated.send(source)
return source | Update an harvest source |
368,676 | def update_ports(self, ports, id_or_uri):
ports = merge_default_values(ports, {: })
uri = self._client.build_uri(id_or_uri) + "/update-ports"
return self._client.update(uri=uri, resource=ports) | Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are
supported for update.
Note:
This method is available for API version 300 or later.
Args:
ports: List of Switch Ports.
id_or_uri: Can be either the switch... |
368,677 | def wait_and_start_browser(host, port=None, cancel_event=None):
if host == :
host =
if port is None:
port = 80
if wait_for_server(host, port, cancel_event):
start_browser(.format(host, port)) | Waits for the server to run and then opens the specified address in
the browser. Set cancel_event to cancel the wait. |
368,678 | def transformToNative(obj):
if obj.isNative:
return obj
obj.isNative = True
if obj.value == :
obj.value = []
return obj
tzinfo = getTzid(getattr(obj, , None))
valueParam = getattr(obj, , "DATE-TIME").upper()
valTexts = obj.valu... | Turn obj.value into a list of dates, datetimes, or
(datetime, timedelta) tuples. |
368,679 | def set_statements_pmid(self, pmid):
for stmt in self.json_stmts:
evs = stmt.get(, [])
for ev in evs:
ev[] = pmid
for stmt in self.statements:
for ev in stmt.evidence:
ev.pmid = pmid | Set the evidence PMID of Statements that have been extracted.
Parameters
----------
pmid : str or None
The PMID to be used in the Evidence objects of the Statements
that were extracted by the processor. |
368,680 | def json_output(cls, cs, score_dict, output_filename, ds_loc, limit,
output_type=):
jsonjson_new
results = {}
if len(score_dict) > 1 and output_type != :
raise ValueError("output_type must be set to if outputting multiple datasets to a single json file o... | Generates JSON output for the ocmpliance score(s)
@param cs Compliance Checker Suite
@param score_groups List of results
@param output_filename The file path to output to
@param ds_loc List of source datasets
@param limit The degree of strictnes... |
368,681 | def get_lock(self, lockname, locktime=60, auto_renewal=False):
pid = os.getpid()
caller = inspect.stack()[0][3]
try:
rl = redis_lock.Lock(self, lockname, expire=locktime, auto_renewal=auto_renewal)
except:
if self.logger:
... | Gets a lock and returns if it can be stablished. Returns false otherwise |
368,682 | def from_int(cls, retries, redirect=True, default=None):
if retries is None:
retries = default if default is not None else cls.DEFAULT
if isinstance(retries, Retry):
return retries
redirect = bool(redirect) and None
new_retries = cls(retries, redirect=r... | Backwards-compatibility for the old retries format. |
368,683 | def imrotate(img,
angle,
center=None,
scale=1.0,
border_value=0,
auto_bound=False):
if center is not None and auto_bound:
raise ValueError()
h, w = img.shape[:2]
if center is None:
center = ((w - 1) * 0.5, (h - 1) * 0.5)
... | Rotate an image.
Args:
img (ndarray): Image to be rotated.
angle (float): Rotation angle in degrees, positive values mean
clockwise rotation.
center (tuple): Center of the rotation in the source image, by default
it is the center of the image.
scale (float): ... |
368,684 | def construct(self, **bindings):
if hasattr(self._head, ):
return self._head.construct(**bindings)
else:
raise ValueError(
% type(self._head)) | Constructs the graph and returns either a tensor or a sequence.
Note: This method requires that this SequentialLayerBuilder holds a
template.
Args:
**bindings: Arguments for every deferred parameter.
Returns:
The value that is placed into this.
Raises:
ValueError: if this doesn't... |
368,685 | def update(self, scaling_group, name=None, cooldown=None,
min_entities=None, max_entities=None, metadata=None):
if not isinstance(scaling_group, ScalingGroup):
scaling_group = self.get(scaling_group)
uri = "/%s/%s/config" % (self.uri_base, scaling_group.id)
if co... | Updates an existing ScalingGroup. One or more of the attributes can
be specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_metadata() method. |
368,686 | def _get_struct_cxformwithalpha(self):
obj = _make_object("CXformWithAlpha")
bc = BitConsumer(self._src)
obj.HasAddTerms = bc.u_get(1)
obj.HasMultTerms = bc.u_get(1)
obj.NBits = nbits = bc.u_get(4)
if obj.HasMultTerms:
obj.RedMultTerm = bc.s_get(nbi... | Get the values for the CXFORMWITHALPHA record. |
368,687 | def get_msg_count_info(self, channel=Channel.CHANNEL_CH0):
msg_count_info = MsgCountInfo()
UcanGetMsgCountInfoEx(self._handle, channel, byref(msg_count_info))
return msg_count_info.sent_msg_count, msg_count_info.recv_msg_count | Reads the message counters of the specified CAN channel.
:param int channel:
CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with number of CAN messages sent and received.
:rtype: tuple(int, int) |
368,688 | def get_touch_dict(self, ind=None, out=bool):
if self.config is None:
msg = "Config must be set in order to get touch dict !"
raise Exception(msg)
dElt = {}
ind = self._check_indch(ind, out=bool)
for ss in self.lStruct_computeInOut:
kn = "%s_... | Get a dictionnary of Cls_Name struct with indices of Rays touching
Only includes Struct object with compute = True
(as returned by self.lStruct__computeInOut_computeInOut)
Also return the associated colors
If in is not None, the indices for each Struct are split between:
... |
368,689 | def parse_object_type_extension(lexer: Lexer) -> ObjectTypeExtensionNode:
start = lexer.token
expect_keyword(lexer, "extend")
expect_keyword(lexer, "type")
name = parse_name(lexer)
interfaces = parse_implements_interfaces(lexer)
directives = parse_directives(lexer, True)
fields = parse_... | ObjectTypeExtension |
368,690 | def _resample_nu(self, tau, N_steps=100, prop_std=0.1, alpha=1, beta=1):
taus = [tau] if isinstance(tau, np.ndarray) else tau
N = 0
E_tau = 0
E_logtau = 0
for tau in taus:
bad = ~np.isfinite(tau)
N += np.sum(~bad)
E_tau += np... | Update the degree of freedom parameter with
Metropolis-Hastings. Assume a prior nu ~ Ga(alpha, beta)
and use a proposal nu' ~ N(nu, prop_std^2). If proposals
are negative, reject automatically due to likelihood. |
368,691 | def _format_attrs(self):
_bold = bold
_colorize = colorize
if not self.pretty:
_bold = lambda x: x
_colorize = lambda x, c: x
attrs = []
add_attr = attrs.append
if self.doc and hasattr(self.obj, "__doc__"):
if self... | Formats the self.attrs #OrderedDict |
368,692 | def relativize(self, absolute_address, target_region_id=None):
if target_region_id is None:
if self.is_stack:
base_address = next(self._address_to_region_id.irange(minimum=absolute_address, reverse=False))
else:
try:
... | Convert an absolute address to the memory offset in a memory region.
Note that if an address belongs to heap region is passed in to a stack region map, it will be converted to an
offset included in the closest stack frame, and vice versa for passing a stack address to a heap region.
Therefore y... |
368,693 | def lock(self, block=True):
self._locked = True
return self._lock.acquire(block) | Lock connection from being used else where |
368,694 | def download_files(file_list):
for _, source_data_file in file_list:
sql_gz_name = source_data_file[].split()[-1]
msg = % (sql_gz_name)
log.debug(msg)
new_data = objectstore.get_object(
handelsregister_conn, source_data_file, )
with open(.format(s... | Download the latest data. |
368,695 | def update_fit_boxes(self, new_fit=False):
self.update_fit_box(new_fit)
self.on_select_fit(None)
self.update_mean_fit_box() | alters fit_box and mean_fit_box lists to match with changes in
specimen or new/removed interpretations
Parameters
----------
new_fit : boolean representing if there is a new fit
Alters
------
fit_box selection, tmin_box selection, tmax_box selection,
mea... |
368,696 | def _deftype_to_py_ast(
ctx: GeneratorContext, node: DefType
) -> GeneratedPyAST:
assert node.op == NodeOp.DEFTYPE
type_name = munge(node.name)
ctx.symbol_table.new_symbol(sym.symbol(node.name), type_name, LocalType.DEFTYPE)
bases = []
for base in node.interfaces:
base_node = gen... | Return a Python AST Node for a `deftype*` expression. |
368,697 | def make_slow_waves(events, data, time, s_freq):
slow_waves = []
for ev in events:
one_sw = {: time[ev[0]],
: time[ev[1]],
: time[ev[2]],
: time[ev[3]],
: time[ev[4] - 1],
: data[ev[1]],
: da... | Create dict for each slow wave, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 5 matrix with start, trough, zero, peak, end samples
data : ndarray (dtype='float')
vector with the data
time : ndarray (dtype='float')
vector with time p... |
368,698 | def disable(states):
***
ret = {
: True,
:
}
states = salt.utils.args.split_input(states)
msg = []
_disabled = __salt__[]()
if not isinstance(_disabled, list):
_disabled = []
_changed = False
for _state in states:
if _state in _disabled:
... | Disable state runs.
CLI Example:
.. code-block:: bash
salt '*' state.disable highstate
salt '*' state.disable highstate,test.succeed_without_changes
.. note::
To disable a state file from running provide the same name that would
be passed in a state.sls call.
sa... |
368,699 | def run_command(self, data):
command = data.get("command")
if self.debug:
self.py3_wrapper.log("Running remote command %s" % command)
if command == "refresh":
self.refresh(data)
elif command == "refresh_all":
self.py3_wrapper.refresh_modules()... | check the given command and send to the correct dispatcher |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.