Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
347,600 | def install(modal):
if _state.get("installed"):
sys.stdout.write("Already installed, uninstalling..\n")
uninstall()
use_threaded_wrapper = not modal
install_callbacks()
install_host(use_threaded_wrapper)
_state["installed"] = True | Perform first time install |
347,601 | def stat(filename, use_cache_only=False):
filename = pyc2py(filename)
if filename not in file_cache:
if not use_cache_only: cache_file(filename)
if filename not in file_cache:
return None
pass
return file_cache[filename].stat | Return stat() info for *filename*. If *use_cache_only* is *False*,
we will try to fetch the file if it is not cached. |
347,602 | def get_fixed_holidays(self, year):
days = []
for month, day, label in self.FIXED_HOLIDAYS:
days.append((date(year, month, day), label))
return days | Return the fixed days according to the FIXED_HOLIDAYS class property |
347,603 | def main(argv=None):
if argv is None:
argv = sys.argv
parser = U.OptionParser(version="%prog version: $Id$",
usage=usage,
description=globals()["__doc__"])
group = U.OptionGroup(parser, "extract-specific options")
group.a... | script main.
parses command line options in sys.argv, unless *argv* is given. |
347,604 | def attr_matches(self, text):
import re
m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
if not m:
return []
expr, attr = m.group(1, 3)
try:
obj = eval(expr, self.namespace)
except:
try:
obj = eval(exp... | Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in self.namespace or self.global_namespace, it will be
evaluated and its attributes (as revealed by dir()) are used as
possible completions. (For class instances, class me... |
347,605 | def _set_group_prio(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("group_prio_id",group_prio.group_prio, yang_name="group-prio", rest_name="prio", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=... | Setter method for group_prio, mapped from YANG variable /qos/cpu/slot/port_group/group/group_config_shaper_wfq/group_prio (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_group_prio is considered as a private
method. Backends looking to populate this variable should
... |
347,606 | def get_parameters(rq, variables, endpoint, query_metadata, auth=None):
internal_matcher = re.compile("__agg_\d+__")
variable_matcher = re.compile(
"(?P<required>[_]{1,2})(?P<name>[^_]+)_?(?P<type>[a-zA-Z0-9]+)?_?(?P<userdefined>[a-zA-Z0-9]+)?.*$")
parameters = {}
for v in... | ?_name The variable specifies the API mandatory parameter name. The value is incorporated in the query as plain literal.
?__name The parameter name is optional.
?_name_iri The variable is substituted with the parameter value as a IRI (also: number or literal).
?_name_en The parameter value is co... |
347,607 | def parse_time(self, input_str, reference_time=):
return self._parse(input_str, dim=Dim.TIME,
reference_time=reference_time) | Parses input with Duckling for occurences of times.
Args:
input_str: An input string, e.g. 'Let's meet at 11:45am'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
... |
347,608 | def set_lineno(self, lineno, override=False):
todo = deque([self])
while todo:
node = todo.popleft()
if in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
... | Set the line numbers of the node and children. |
347,609 | def update_role_mappings(obj, wfs=None, reindex=True):
wftool = api.get_tool("portal_workflow")
if wfs is None:
wfs = get_workflows()
chain = wftool.getChainFor(obj)
for wfid in chain:
wf = wfs[wfid]
wf.updateRoleMappingsFor(obj)
if reindex is True:
obj.reindexOb... | Update the role mappings of the given object |
347,610 | def runtime(self):
warnings.warn("admm.ADMM.runtime attribute has been replaced by "
"an upgraded timer class: please see the documentation "
"for admm.ADMM.solve method and util.Timer class",
PendingDeprecationWarning)
return s... | Transitional property providing access to the new timer
mechanism. This will be removed in the future. |
347,611 | def send(self, **kwargs):
return_full_object = kwargs.get(, False)
_verbose = kwargs.get(, False)
traversal = kwargs.get(, None)
timeout = kwargs.get(, 5)
self.output[] = self.render_url()
with VerboseContextManager(verbose=_verbose):
try:
... | Send the request defined by the data stored in the object. |
347,612 | def activated(self, include_extras=True, extra_dists=None):
if not extra_dists:
extra_dists = []
original_path = sys.path
original_prefix = sys.prefix
parent_path = vistir.compat.Path(__file__).absolute().parent
vendor_dir = parent_path.joinpath("vendor").as... | Helper context manager to activate the environment.
This context manager will set the following variables for the duration
of its activation:
* sys.prefix
* sys.path
* os.environ["VIRTUAL_ENV"]
* os.environ["PATH"]
In addition, it will make any ... |
347,613 | def deserialize_durable_record_to_current_model(record, current_model):
if record.get(EVENT_TOO_BIG_FLAG):
return get_full_current_object(record[][][][], current_model)
new_image = remove_durable_specific_fields(record[][])
data = {}
for item, value in new_image.items():
... | Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object.
This will properly deserialize the ugly Dynamo datatypes away.
:param record:
:param current_model:
:return: |
347,614 | def get_tname(self, var, coords=None):
if coords is not None:
coord = self.get_variable_by_axis(var, , coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.t.intersection(var.dims))
if dimlist:
... | Get the name of the t-dimension
This method gives the name of the time dimension
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
t... |
347,615 | def transcripts_by_gene(self, build=):
hgnc_transcripts = {}
LOG.info("Fetching all transcripts")
for transcript in self.transcript_collection.find({:build}):
hgnc_id = transcript[]
if not hgnc_id in hgnc_transcripts:
hgnc_transcripts[hgnc_id] = [... | Return a dictionary with hgnc_id as keys and a list of transcripts as value
Args:
build(str)
Returns:
hgnc_transcripts(dict) |
347,616 | def _PrintStorageInformationAsJSON(self, storage_reader):
serializer = json_serializer.JSONAttributeContainerSerializer
storage_counters = self._CalculateStorageCounters(storage_reader)
storage_counters_json = json.dumps(storage_counters)
self._output_writer.Write()
self._output_writer.Write(.f... | Writes a summary of sessions as machine-readable JSON.
Args:
storage_reader (StorageReader): storage reader. |
347,617 | def raw_corpus_rougel(hypotheses: Iterable[str], references: Iterable[str]) -> float:
return rouge.rouge_l(hypotheses, references) | Simple wrapper around ROUGE-L implementation.
:param hypotheses: Hypotheses stream.
:param references: Reference stream.
:return: ROUGE-L score as float between 0 and 1. |
347,618 | def _set_defaults(self):
self.contents.setdefault(, [])
self.contents.setdefault(, None)
self.contents.setdefault(, None) | Set some default values in the manifest.
This method should be called after loading from disk, but before
checking the integrity of the reference package. |
347,619 | def count(self):
total = 0
for test in self.protocol_model.allTests():
total += test.traceCount()*test.loopCount()*test.repCount() + test.repCount()
return total | Total number of all tests/traces/reps currently in this protocol
:returns: int -- the total |
347,620 | def to_kaf(self):
if self.type == :
for node in self.node.findall():
node.set(,node.get())
del node.attrib[] | Converts the element to NAF |
347,621 | def isMsgFromPrimary(self, msg, sender: str) -> bool:
if self.isMsgForCurrentView(msg):
return self.primaryName == sender
try:
return self.primaryNames[msg.viewNo] == sender
except KeyError:
return False | Return whether this message was from primary replica
:param msg:
:param sender:
:return: |
347,622 | def from_dict(cls, d):
return Dos(d["efermi"], d["energies"],
{Spin(int(k)): v
for k, v in d["densities"].items()}) | Returns Dos object from dict representation of Dos. |
347,623 | def index():
stats = dict((k, {"count": 0}) for k, tt in conf.InputTables)
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
for input, table in [(x, t) for x, tt in conf.InputTables for t in tt]:
row = db.fetchone("counts", countminmax, type=table)
if not r... | Handler for showing the GUI index page. |
347,624 | def start(config, args):
global mode
if core.is_standalone():
from glances.standalone import GlancesStandalone as GlancesMode
elif core.is_client():
if core.is_client_browser():
from glances.client_browser import GlancesClientBrowser as GlancesMode
else:
... | Start Glances. |
347,625 | def new(self, bootstrap_with=None, use_timer=False, with_proof=False):
if not self.lingeling:
self.lingeling = pysolvers.lingeling_new()
if bootstrap_with:
for clause in bootstrap_with:
self.add_clause(clause)
self.use_timer = u... | Actual constructor of the solver. |
347,626 | def remove_user(user):
def processor(action, argument):
ActionUsers.query_by_action(action, argument=argument).filter(
ActionUsers.user_id == user.id
).delete(synchronize_session=False)
return processor | Remove a action for a user. |
347,627 | def update_certificate_issuer(self, certificate_issuer_id, certificate_issuer_update_request, **kwargs):
kwargs[] = True
if kwargs.get():
return self.update_certificate_issuer_with_http_info(certificate_issuer_id, certificate_issuer_update_request, **kwargs)
else:
... | Update certificate issuer. # noqa: E501
Update a certificate issuer. <br> **Example usage:** ``` curl -X PUT \\ -H 'authorization: <valid access token>' \\ -H 'content-type: application/json;charset=UTF-8' \\ https://api.us-east-1.mbedcloud.com/v3/certificate-issuers/01621560be51507b9d48a91b00000000 \\ -d '{... |
347,628 | def _setup_container_filesystem(self, temp_dir, output_dir, memlimit, memory_nodes):
temp_base = self._get_result_files_base(temp_dir).encode()
temp_dir = temp_dir.encode()
tmpfs_opts = ["size=" + str(memlimit or "100%")]
if memory_nodes:
tmpfs_opts.append... | Setup the filesystem layout in the container.
As first step, we create a copy of all existing mountpoints in mount_base, recursively,
and as "private" mounts (i.e., changes to existing mountpoints afterwards won't propagate
to our copy).
Then we iterate over all mountpoints and change t... |
347,629 | def chunks(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size)) | simple two-line alternative to `ubelt.chunks` |
347,630 | def zoom(x, zoom_range=(0.9, 1.1), flags=None, border_mode=):
zoom_matrix = affine_zoom_matrix(zoom_range=zoom_range)
h, w = x.shape[0], x.shape[1]
transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)
x = affine_transform_cv2(x, transform_matrix, flags=flags, border_mode=border_mode... | Zooming/Scaling a single image that height and width are changed together.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
zoom_range : float or tuple of 2 floats
The zooming/scaling ratio, greater than 1 means larger.
- float... |
347,631 | def ltcube_sun(self, **kwargs):
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
kwargs_copy[] = kwargs.get(, self.dataset(**kwargs))
self._replace_none(kwargs_copy)
localpath = NameFactory.ltcubesun_format.format(**kwargs_copy)
if kwargs.... | return the name of a livetime cube file |
347,632 | def visitComparisonExpression(self, ctx):
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context)
if isinstance(arg1, str):
compared = (arg1.lower() > arg2.lower()) - (arg1.lower() < arg2.lower())
else:... | expression: expression (LTE | LT | GTE | GT) expression |
347,633 | def serialize_acquire_mutex(self, spec):
elem = etree.Element()
self.serialize_task_spec(spec, elem)
SubElement(elem, ).text = spec.mutex
return elem | Serializer for :meth:`SpiffWorkflow.specs.AcquireMutex`. |
347,634 | def toggle_concatenate(self):
if not (self.chunk[].isChecked() and
self.lock_to_staging.get_value()):
for i,j in zip([self.idx_chan, self.idx_cycle, self.idx_stage,
self.idx_evt_type],
[self.cat[], self.cat[],
... | Enable and disable concatenation options. |
347,635 | def as_list(self):
if hasattr(self, ):
return self.cust_list
if hasattr(self, ):
self.attr_check()
cls_bltns = set(dir(self.__class__))
ret = [a for a in dir(self) if a not in cls_bltns and getattr(self, a)]
return ret | returns a list version of the object, based on it's attributes |
347,636 | def FilterGeneratorCore(x_up=1, x_down=1, x_ap=1, x_cut=100,
y_up=1, y_down=1, y_ap=1, y_cut=100):
def filter_1D(up, down, ap, cut_adj):
nyquist_freq = float(min(up, down)) / float(2 * up * down)
cut_adj = float(cut_adj) / 100.0
coefs = []
n = 1
w... | Classic filter generator core.
Alternative to the :py:class:`FilterGenerator` component that can be
used to make a non-reconfigurable resizer::
resize = Resize(xup=2)
resize.filter(FilterGeneratorCore(xup=2, xaperture=16))
...
start(..., resize, ...)
...
:keyword i... |
347,637 | def visit_ifexp(self, node):
return "%s if %s else %s" % (
self._precedence_parens(node, node.body, is_left=True),
self._precedence_parens(node, node.test, is_left=True),
self._precedence_parens(node, node.orelse, is_left=False),
) | return an astroid.IfExp node as string |
347,638 | def fill(self, config, section):
if config.has_section(section):
default_url = self.DEFAULT_REPOSITORIES.get(self.name, )
self.url = RepositoryURL(config_get(config, section, , default_url))
self.username = config_get(config, section, , )
self.password = ... | Fill data from a given configuration section.
Args:
config (configparser): the configuration file
section (str): the section to use |
347,639 | def close_all_pages(self):
states_to_be_closed = []
for state_identifier in self.tabs:
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | Closes all tabs of the states editor |
347,640 | def is_url(value):
"Must start with http:// or https:// and contain JUST a URL"
if not isinstance(value, str):
return False
if not value.startswith() and not value.startswith():
return False
if whitespace_re.search(value):
return False
return True | Must start with http:// or https:// and contain JUST a URL |
347,641 | def send_request(self, request_object, timeout=None, retries=1, **kwargs):
if not isinstance(request_object, RWSRequest):
raise ValueError("Request object must be a subclass of RWSRequest")
full_url = make_url(self.base_url, request_object.url_path())
if request_ob... | Send request to RWS endpoint. The request object passed provides the URL endpoint and the HTTP method.
Takes the text response from RWS and allows the request object to modify it for return. This allows the request
object to return text, an XML document object, a CSV file or anything else that can... |
347,642 | def _prefix_from_ip_string(self, ip_str):
try:
ip_int = self._ip_int_from_string(ip_str)
except AddressValueError:
self._report_invalid_netmask(ip_str)
try:
return self._prefix_from_ip_int(ip_int)
except Va... | Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask |
347,643 | def nodes_touching_edge(edge_coord):
a, b = hex_digit(edge_coord, 1), hex_digit(edge_coord, 2)
if a % 2 == 0 and b % 2 == 0:
return [coord_from_hex_digits(a, b + 1),
coord_from_hex_digits(a + 1, b)]
else:
return [coord_from_hex_digits(a, b),
coord_from_he... | Returns the two node coordinates which are on the given edge coordinate.
:return: list of 2 node coordinates which are on the given edge coordinate, list(int) |
347,644 | def fill_profile(profile, array, weights=None, return_indices=False):
import ROOT
array = np.asarray(array, dtype=np.double)
if array.ndim != 2:
raise ValueError("array must be 2-dimensional")
if array.shape[1] != profile.GetDimension() + 1:
raise ValueError(
"there must... | Fill a ROOT profile with a NumPy array.
Parameters
----------
profile : ROOT TProfile, TProfile2D, or TProfile3D
The ROOT profile to fill.
array : numpy array of shape [n_samples, n_dimensions]
The values to fill the histogram with. There must be one more column
than the dimensi... |
347,645 | def SetRawFields(self, raw_fields):
self._raw_fields = raw_fields
if raw_fields:
logger.debug()
else:
logger.debug() | Set raw (non-analyzed) fields.
This is used for sorting and aggregations in Elasticsearch.
https://www.elastic.co/guide/en/elasticsearch/guide/current/
multi-fields.html
Args:
raw_fields (bool): True if raw (non-analyzed) fields should be added. |
347,646 | def forward(self, x):
if not self.training or not self.p:
return x
x = x.clone()
mask = x.new_empty(1, x.size(1), x.size(2), requires_grad=False).bernoulli_(1 - self.p)
mask = mask.div_(1 - self.p)
mask = mask.expand_as(x)
return x * mask | Args:
x (:class:`torch.FloatTensor` [batch size, sequence length, rnn hidden size]): Input to
apply dropout too. |
347,647 | def getOverlayTransformTrackedDeviceComponent(self, ulOverlayHandle, pchComponentName, unComponentNameSize):
fn = self.function_table.getOverlayTransformTrackedDeviceComponent
punDeviceIndex = TrackedDeviceIndex_t()
result = fn(ulOverlayHandle, byref(punDeviceIndex), pchComponentName, ... | Gets the transform information when the overlay is rendering on a component. |
347,648 | def FileEntryExistsByPathSpec(self, path_spec):
location = getattr(path_spec, , None)
if (location is None or
not location.startswith(self.LOCATION_ROOT)):
return False
if len(location) == 1:
return True
try:
self._zip_file.getinfo(location[1:])
return True
ex... | Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification of the file entry.
Returns:
bool: True if the file entry exists. |
347,649 | def extract_data(neurons, feature, params=None):
if params is None:
params = {}
feature_data = [get(FEATURE_MAP[feature], n, **params) for n in neurons]
feature_data = list(chain(*feature_data))
return stats.optimal_distribution(feature_data) | Extracts feature from a list of neurons
and transforms the fitted distribution in the correct format.
Returns the optimal distribution and corresponding parameters.
Normal distribution params (mean, std)
Exponential distribution params (loc, scale)
Uniform distribution params (min, ra... |
347,650 | def write_debug_log(self, file_path):
with open(file_path, "wb+") as fh:
fh.write(system.get_system_info().encode())
self._debug_stream.seek(0)
fh.write(self._debug_stream.read().encode())
fh.write("The following errors occured:\n".encode())
... | Write the debug log to a file |
347,651 | def get_incidence_matrix(self, fmt=):
r
if fmt in self._im.keys():
im = self._im[fmt]
elif self._im.keys():
im = self._am[list(self._im.keys())[0]]
tofmt = getattr(im, +fmt)
im = tofmt()
self._im[fmt] = im
else:
im =... | r"""
Returns an incidence matrix in the specified sparse format, with 1's
indicating the non-zero values.
Parameters
----------
fmt : string, optional
The sparse storage format to return. Options are:
**'coo'** : (default) This is the native format of O... |
347,652 | def _build_env(venv_dir):
prefix = getattr(sys, , sys.prefix)
python = Path(prefix) / /
command = .format(python, venv_dir)
try:
log.info(, command)
subprocess.run(command.split(),
stdout=subprocess.PIPE,
stderr=sub... | Create a new virtual environment in `venv_dir`.
This uses the base prefix of any virtual environment that you may be using
when you call this. |
347,653 | def create_shapes(feed: "Feed", *, all_trips: bool = False) -> "Feed":
feed = feed.copy()
if all_trips:
trip_ids = feed.trips["trip_id"]
else:
trip_ids = feed.trips[feed.trips["shape_id"].isnull()]["trip_id"]
f = feed.stop_times[feed.stop_times["trip_id"].isin(trip_ids)][
... | Given a feed, create a shape for every trip that is missing a
shape ID.
Do this by connecting the stops on the trip with straight lines.
Return the resulting feed which has updated shapes and trips
tables.
If ``all_trips``, then create new shapes for all trips by
connecting stops, and remove th... |
347,654 | def backend_fields(self, fields):
dfields = self.dfields
processed = set()
names = []
atts = []
pkname = self.pkname()
for name in fields:
if name == pkname or name in processed:
continue
elif name in dfields:
... | Return a two elements tuple containing a list
of fields names and a list of field attribute names. |
347,655 | def dict_to_object(desired_type: Type[T], contents_dict: Dict[str, Any], logger: Logger,
options: Dict[str, Dict[str, Any]], conversion_finder: ConversionFinder = None,
is_dict_of_dicts: bool = False) -> T:
check_var(desired_type, var_types=type, var_name=)
check_var(c... | Utility method to create an object from a dictionary of constructor arguments. Constructor arguments that dont have
the correct type are intelligently converted if possible
:param desired_type:
:param contents_dict:
:param logger:
:param options:
:param conversion_finder:
:param is_dict_of_... |
347,656 | async def anext(self):
try:
f = next(self._iter)
except StopIteration as exc:
raise StopAsyncIteration() from exc
return await f | Fetch the next value from the iterable. |
347,657 | def schema_map(schema):
mapper = {}
for name in getFieldNames(schema):
mapper[name] = name
return mapper | Return a valid ICachedItemMapper.map for schema |
347,658 | def get_scene_suggestions(self, current):
l = []
if isinstance(current, djadapter.models.Asset):
l.append(current)
l.extend(list(current.assets.all()))
return l | Return a list with elements for reftracks for the current scene with this type.
For every element returned, the reftrack system will create a :class:`Reftrack` with the type
of this interface, if it is not already in the scene.
E.g. if you have a type that references whole scenes, you might su... |
347,659 | def setup_prefix_logging(logdir):
if not os.path.exists(logdir):
os.mkdir(logdir)
file_handler = logging.FileHandler(
filename=os.path.join(logdir, ),
)
file_formatter = get_default_log_formatter()
file_handler.setFormatter(file_formatter)
logging.root.addHandler(file_handl... | Sets up a file logger that will create a log in the given logdir (usually a
lago prefix)
Args:
logdir (str): path to create the log into, will be created if it does
not exist
Returns:
None |
347,660 | def _median(imageObjectList, paramDict):
newmasks = paramDict[]
comb_type = paramDict[].lower()
nlow = paramDict[]
nhigh = paramDict[]
grow = paramDict[] if in comb_type else 0
maskpt = paramDict[]
proc_units = paramDict[]
compress = paramDict[]
bufsizeMB = paramDict[]
sig... | Create a median image from the list of image Objects
that has been given. |
347,661 | def _create_structure(self):
if os.path.exists(self._abspath):
raise(StorageBrokerOSError(
"Path already exists: {}".format(self._abspath)
))
parent, _ = os.path.split(self._abspath)
if not os.path.isdir(parent):
ra... | Create necessary structure to hold a dataset. |
347,662 | def set_log_format(log_format, server=_DEFAULT_SERVER):
*Microsoft IIS Log File Format
setting =
log_format_types = get_log_format_types()
format_id = log_format_types.get(log_format, None)
if not format_id:
message = ("Invalid log format specified. Valid formats:"
).fo... | Set the active log format for the SMTP virtual server.
:param str log_format: The log format name.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_smtp_server.set_log_f... |
347,663 | def __reorganize_authors(authors):
l = []
s = authors.split(";")
for author in s:
try:
l.append({"name": author.strip()})
except AttributeError:
logger_noaa_lpd.warning("reorganize_authors: AttributeError: authors incorrec... | Separate the string of authors and put it into a BibJSON compliant list
:param str authors:
:return list: List of dictionaries of author names. |
347,664 | def _get_port_center_position(self, width):
x, y = self.pos.x.value, self.pos.y.value
if self.side is SnappedSide.TOP or self.side is SnappedSide.BOTTOM:
if x - width / 2. < 0:
x = width / 2
elif x + width / 2. > self.parent.width:
x = sel... | Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on the position of the
port and the width of the rec... |
347,665 | def build_xoauth_string(url, consumer, token=None):
request = Request.from_consumer_and_token(consumer, token,
"GET", url)
signing_method = SignatureMethod_HMAC_SHA1()
request.sign_request(signing_method, consumer, token)
params = []
for k, v in sorted(request.items()):
if v i... | Build an XOAUTH string for use in SMTP/IMPA authentication. |
347,666 | def get_new_connection(self, conn_params):
connection = ldap.ldapobject.ReconnectLDAPObject(
uri=conn_params[],
retry_max=conn_params[],
retry_delay=conn_params[],
bytes_mode=False)
options = conn_params[]
for opt, value in options.items(... | Build a connection from its parameters. |
347,667 | def _prep_snippet_for_pandoc(self, latex_text):
replace_cite = CitationLinker(self.bib_db)
latex_text = replace_cite(latex_text)
return latex_text | Process a LaTeX snippet of content for better transformation
with pandoc.
Currently runs the CitationLinker to convert BibTeX citations to
href links. |
347,668 | def Network_setUserAgentOverride(self, userAgent):
assert isinstance(userAgent, (str,)
), "Argument must be of type str. Received type: " % type(
userAgent)
subdom_funcs = self.synchronous_command(,
userAgent=userAgent)
return subdom_funcs | Function path: Network.setUserAgentOverride
Domain: Network
Method name: setUserAgentOverride
Parameters:
Required arguments:
'userAgent' (type: string) -> User agent to use.
No return value.
Description: Allows overriding user agent with the given string. |
347,669 | def pack_rows(rows, bitdepth):
assert bitdepth < 8
assert 8 % bitdepth == 0
spb = int(8 / bitdepth)
def make_byte(block):
res = 0
for v in block:
res = (res << bitdepth) + v
return res
for row in rows:
a = bytearray(row)
... | Yield packed rows that are a byte array.
Each byte is packed with the values from several pixels. |
347,670 | def click(self, data):
modules = data.get("module")
for module_name in self.find_modules(modules):
module = self.py3_wrapper.output_modules[module_name]
if module["type"] == "py3status":
name = module["module"].module_name
instance = modul... | send a click event to the module(s) |
347,671 | def get_links(self, ticket_id):
msg = self.__request(.format(str(ticket_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
msg = msg.split()
if (len(msg) > 2) and self.RE_PATTERNS[].match(msg[2]):
re... | Gets the ticket links for a single ticket.
:param ticket_id: ticket ID
:returns: Links as lists of strings in dictionary with these keys
(just those which are defined):
* id
* Members
* MemberOf
*... |
347,672 | def step_it_should_pass_with(context):
assert context.text is not None, "ENSURE: multiline text is provided."
step_command_output_should_contain(context)
assert_that(context.command_result.returncode, equal_to(0),
context.command_result.output) | EXAMPLE:
...
when I run "behave ..."
then it should pass with:
"""
TEXT
""" |
347,673 | def _sin_to_angle(result, deriv, side=1):
v = np.arcsin(np.clip(result[0], -1, 1))
sign = side
if sign == -1:
if v < 0:
offset = -np.pi
else:
offset = np.pi
else:
offset = 0.0
if deriv == 0:
return v*sign + offset,
if abs(result[0]) >=... | Convert a sine and its derivatives to an angle and its derivatives |
347,674 | def get_argument_values(
type_def: Union[GraphQLField, GraphQLDirective],
node: Union[FieldNode, DirectiveNode],
variable_values: Dict[str, Any] = None,
) -> Dict[str, Any]:
coerced_values: Dict[str, Any] = {}
arg_defs = type_def.args
arg_nodes = node.arguments
if not arg_defs or arg_no... | Get coerced argument values based on provided definitions and nodes.
Prepares an dict of argument values given a list of argument definitions and list
of argument AST nodes. |
347,675 | def Builder(**kw):
composite = None
if in kw:
if in kw:
raise UserError("You must not specify both an action and a generator.")
kw[] = SCons.Action.CommandGeneratorAction(kw[], {})
del kw[]
elif in kw:
source_ext_match = kw.get(, 1)
if in kw:
... | A factory for builder objects. |
347,676 | def validate(ref_time, ref_freqs, est_time, est_freqs):
util.validate_events(ref_time, max_time=MAX_TIME)
util.validate_events(est_time, max_time=MAX_TIME)
if ref_time.size == 0:
warnings.warn("Reference times are empty.")
if ref_time.ndim != 1:
raise ValueError("Reference times h... | Checks that the time and frequency inputs are well-formed.
Parameters
----------
ref_time : np.ndarray
reference time stamps in seconds
ref_freqs : list of np.ndarray
reference frequencies in Hz
est_time : np.ndarray
estimate time stamps in seconds
est_freqs : list of np... |
347,677 | def assert_is_lat(val):
assert type(val) is float or type(val) is int, "Value must be a number"
if val < -90.0 or val > 90.0:
raise ValueError("Latitude value must be between -90 and 90") | Checks it the given value is a feasible decimal latitude
:param val: value to be checked
:type val: int of float
:returns: `None`
:raises: *ValueError* if value is out of latitude boundaries, *AssertionError* if type is wrong |
347,678 | def show_vpnservice(self, vpnservice, **_params):
return self.get(self.vpnservice_path % (vpnservice), params=_params) | Fetches information of a specific VPN service. |
347,679 | def alt(self):
if self.override_alt != and self.override_alt is not None:
return self.override_alt
elif self.override_caption != and self.override_caption is not None:
return self.override_caption
else:
return self.get_metadata_display() | Returns object metadata suitable for use as the HTML ``alt``
attribute. You can use this method in templates::
<img src="{{ node.file.url }}" alt="{{ node.alt }}" /> |
347,680 | def select_by_key(self, key):
for item in self.children.values():
if in item.attributes:
del item.attributes[]
self.children[key].attributes[] =
self._selected_key = key
self._selected_item = self.children[key] | Selects an item by its unique string identifier.
Args:
key (str): Unique string identifier of the DropDownItem that have to be selected. |
347,681 | def _get_vswitch_name(self, network_type, physical_network):
if network_type != constants.TYPE_LOCAL:
vswitch_name = self._get_vswitch_for_physical_network(
physical_network)
else:
vswitch_name = self._local_network_vswitch
if vswitch_name:
... | Get the vswitch name for the received network information. |
347,682 | def run(self):
self.log.error("failed to get pid lock, already running?")
return 1
finally:
for mod in self.joins:
self.log.debug("stopping %s", mod.name)
mod.on_stop() | run daemon |
347,683 | def without_operations_touching(self, qubits: Iterable[raw_types.Qid]):
qubits = frozenset(qubits)
if not self.operates_on(qubits):
return self
return Moment(
operation for operation in self.operations
if qubits.isdisjoint(frozenset(operation.qubits))... | Returns an equal moment, but without ops on the given qubits.
Args:
qubits: Operations that touch these will be removed.
Returns:
The new moment. |
347,684 | def reset(db, aid, episode):
params = {
: aid,
: get_eptype(db, ).id,
: 1,
: episode,
}
with db:
cur = db.cursor()
cur.execute(
,
params)
params[] = 0
cur.execute(
,
params)
cache_sta... | Reset episode count for anime. |
347,685 | def make_mid_color(self, color1, color2, distance, long_route=False):
def fade(a, b):
x = b * distance
x += a * (1 - distance)
return x
h1, s1, v1 = color1
h2, s2, v2 = color2
hue_diff = h1 - h2
if long_route:
if hue_dif... | Generate a mid color between color1 and color2.
Colors should be a tuple (hue, saturation, value).
distance is a float between 0.0 and 1.0 describing how far between
color1 and color2 we want to return the color. 0.0 would return color1,
1.0 color2, and 0.5 a color midway.
long... |
347,686 | def handle_exception (self):
etype, evalue = sys.exc_info()[:2]
log.debug(LOG_CHECK, "Error in %s: %s %s", self.url, etype, evalue, exception=True)
if (etype in ExcNoCacheList) or \
(etype == socket.error and evalue.args[0]==errno.EBADF) or \
not evalue:
... | An exception occurred. Log it and set the cache flag. |
347,687 | def download(url, filename=None):
if not filename:
url_parts = urllib.parse.urlparse(url)
filename = os.path.basename(url_parts.path)
url_h = urllib.request.urlopen(url)
with open(filename, ) as file_h:
shutil.copyfileobj(url_h, file_h)
url_h.close()
return | Download a file from a url and save it to disk.
:param str url: The URL to fetch the file from.
:param str filename: The destination file to write the data to. |
347,688 | def in1d_sorted(ar1, ar2):
if ar1.shape[0] == 0 or ar2.shape[0] == 0:
return []
inds = ar2.searchsorted(ar1)
inds[inds == len(ar2)] = 0
return ar2[inds] == ar1 | Does the same than np.in1d but uses the fact that ar1 and ar2 are sorted. Is therefore much faster. |
347,689 | def _handle_special_yaml_cases(v):
if "::" in v:
out = {}
for part in v.split("::"):
k_part, v_part = part.split(":")
out[k_part] = v_part.split(";")
v = out
elif ";" in v:
v = [x for x in v.split(";") if x != ""]
elif isinstance(v, list)... | Handle values that pass integer, boolean, list or dictionary values. |
347,690 | def _results(self, product, path, cls=Results, **kwargs):
if product != and self.rate_limit and not self.limits_set and not self.limits:
self._rate_limit()
uri = .join((.format( if self.https else ), path.lstrip()))
parameters = self.default_parameters.copy()
param... | Returns _results for the specified API path with the specified **kwargs parameters |
347,691 | def modify_ip(self, ip_addr, ptr_record):
body = {
: {
: ptr_record
}
}
res = self.request(, + str(ip_addr), body)
return IPAddress(cloud_manager=self, **res[]) | Modify an IP address' ptr-record (Reverse DNS).
Accepts an IPAddress instance (object) or its address (string). |
347,692 | def default_roles(*role_list):
def selectively_attach(func):
if not env.roles and not env.hosts:
return roles(*role_list)(func)
else:
if env.hosts:
func = hosts(*env.hosts)(func)
if env.roles:
func = roles(*en... | Decorate task with these roles by default, but override with -R, -H |
347,693 | def _get_filekey(self):
if not os.path.exists(self.keyfile):
raise KPError()
try:
with open(self.keyfile, ) as handler:
handler.seek(0, os.SEEK_END)
size = handler.tell()
handler.seek(0, os.SEEK_SET)
if si... | This method creates a key from a keyfile. |
347,694 | def _normalize_options(self, options):
for key, value in list(options.items()):
if in key:
normalized_key = self._normalize_arg(key)
else:
normalized_key = % self._normalize_arg(key)
if isinstance(value, (list, tuple)):
... | Generator of 2-tuples (option-key, option-value).
When options spec is a list, generate a 2-tuples per list item.
:param options: dict {option: value}
returns:
iterator (option-key, option-value)
- option names lower cased and prepended with
'--' if necessary. Non... |
347,695 | def save_root(histogram: HistogramBase, path: str, name: Optional[str] = None):
if name is None:
name = histogram.name
if os.path.isfile(path):
hfile = uproot.write.TFile.TFileUpdate(path)
else:
hfile = uproot.write.TFile.TFileCreate(path)
write_root(histogram, hfil... | Write histogram to a (new) ROOT file.
Parameters
----------
histogram : Any histogram
path: path for the output file (perhaps should not exist?)
name : The name of the histogram inside the file |
347,696 | def get_construction_table(self, fragment_list=None,
use_lookup=None,
perform_checks=True):
if use_lookup is None:
use_lookup = settings[][]
if fragment_list is None:
self.get_bonds(use_lookup=use_lookup)
... | Create a construction table for a Zmatrix.
A construction table is basically a Zmatrix without the values
for the bond lengths, angles and dihedrals.
It contains the whole information about which reference atoms
are used by each atom in the Zmatrix.
The absolute references in c... |
347,697 | def get_histories_fix_params(self, exp, rep, tag, **kwargs):
subexps = self.get_exps(exp)
tagvalues = [re.sub("0+$", , %(k, kwargs[k])) for k in kwargs]
histories = [self.get_history(se, rep, tag) for se in subexps if all(map(lambda tv: tv in se, tagvalues))]
params = [self.ge... | this function uses get_history(..) but returns all histories where the
subexperiments match the additional kwargs arguments. if alpha=1.0,
beta = 0.01 is given, then only those experiment histories are returned,
as a list. |
347,698 | def manage_finished_checks(self, queue):
to_del = []
wait_time = 1.0
now = time.time()
logger.debug("--- manage finished checks")
for action in self.checks:
logger.debug("--- checking: last poll: %s, now: %s, wait_time: %s, action: %s",
... | Check the status of checks
if done, return message finished :)
REF: doc/alignak-action-queues.png (5)
:return: None |
347,699 | def convert_depthtospace(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
blksize = int(attrs.get("block_size", 0))
node = onnx.helper.make_node(
"DepthToSpace",
input_nodes,
[name],
blocksize=blksize,
name=name,
)
return [node] | Map MXNet's depth_to_space operator attributes to onnx's
DepthToSpace operator and return the created node. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.