Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
350,600 | async def move_rel(self, mount: top_types.Mount, delta: top_types.Point,
speed: float = None):
if not self._current_position:
raise MustHomeError
await self._cache_and_maybe_retract_mount(mount)
z_axis = Axis.by_mount(mount)
try:
... | Move the critical point of the specified mount by a specified
displacement in a specified direction, at the specified speed.
'speed' sets the speed of all axes to the given value. So, if multiple
axes are to be moved, they will do so at the same speed |
350,601 | def err_func(params, x, y, func, w=None, func_list=None):
err = y - func(x, *params)
if w is not None:
err = err * w
if func_list is not None:
err2 = 0
for f in func_list:
this_err = (y - f[0](x, *[params[ii] for ii in f[1]]))
if f[2] is not None:
... | Error function for fitting a function
Parameters
----------
params : tuple
A tuple with the parameters of `func` according to their order of
input
x : float array
An independent variable.
y : float array
The dependent variable.
func : function
... |
350,602 | def visitNodeConstraintLiteral(self, ctx: ShExDocParser.NodeConstraintLiteralContext):
self.nodeconstraint.nodeKind =
self.visitChildren(ctx) | nodeConstraint: KW_LITERAL xsFacet* # nodeConstraintLiteral |
350,603 | def iter_leaves(self) -> Iterable[BaseEntity]:
for node in self.graph:
if self.tag in self.graph.nodes[node]:
continue
if not any(self.tag not in self.graph.nodes[p] for p in self.graph.predecessors(node)):
yield node | Return an iterable over all nodes that are leaves.
A node is a leaf if either:
- it doesn't have any predecessors, OR
- all of its predecessors have a score in their data dictionaries |
350,604 | def close_client_stream(client_stream, unix_path):
try:
client_stream.shutdown(socket.SHUT_RDWR)
if unix_path:
logger.debug(, unix_path)
else:
peer = client_stream.getpeername()
logger.debug(, peer[0], peer[1])
except (socket.error, OSError) as ex... | Closes provided client stream |
350,605 | def rescale(self, now):
old_start_time = self.start_time
self.start_time = self.current_time_in_fractional_seconds()
self.next_scale_time = now + RESCALE_THRESHOLD_S
new_values = treap.treap()
for key in self.values.keys():
new_key = key * math.exp(
... | "A common feature of the above techniques—indeed, the key technique
that allows us to track the decayed weights efficiently—is that they
maintain counts and other quantities based on g(ti − L), and only scale
by g(t − L) at query time. But while g(ti −L)/g(t−L) is guaranteed to
lie betwe... |
350,606 | def param_names(scipy_dist):
if not isinstance(scipy_dist, rv_continuous):
raise TypeError
names = [, ]
if scipy_dist.shapes is not None:
names += scipy_dist.shapes.split()
return names | Get names of fit parameters from a ``scipy.rv_*`` distribution. |
350,607 | def updateNewCredentialValues(self):
credentials_base = "disk.0.os.credentials."
new_credentials_base = "disk.0.os.credentials.new."
for elem in [, , ]:
if self.getValue(new_credentials_base + elem):
self.setValue(credentials_base + elem, self.getValue(new_... | Set the new credential values to the credentials to use, and delete the new ones |
350,608 | def separated(self):
separated_lls = collections.defaultdict(LabelList)
for label in self.labels:
separated_lls[label.value].add(label)
for ll in separated_lls.values():
ll.idx = self.idx
return separated_lls | Create a separate Label-List for every distinct label-value.
Returns:
dict: A dictionary with distinct label-values as keys.
Every value is a LabelList containing only labels with the same value.
Example:
>>> ll = LabelList(idx='some', labels=[
>>>... |
350,609 | def help(self, *args, **kwargs):
if len(args) > 0 or len(kwargs) > 0:
import pydoc
pydoc.help(*args, **kwargs)
else:
hstr = helpstr
for i in hstr.split("\n"):
self.logger.info(i)
return True | Print Automate help if no parameter is given. Otherwise,
act as pydoc.help() |
350,610 | def status(self, value):
if self._bug.get(, None):
if value in VALID_STATUS:
self._bug[] = value
else:
raise BugException("Invalid status type was used")
else:
raise BugException("Can not set status unless there is a bug id."
... | Property for getting or setting the bug status
>>> bug.status = "REOPENED" |
350,611 | def encode(self, x):
if not self.encoding_network:
self.encoding_network = NeuralNetwork(self.input_dim, self.input_tensor)
self.encoding_network.input_variables = self.input_variables
for layer in self.encoding_layes:
self.encoding_network.stack_laye... | Encode given input. |
350,612 | async def SetHostMachineNetworkConfig(self, config, tag):
_params = dict()
msg = dict(type=,
request=,
version=7,
params=_params)
_params[] = config
_params[] = tag
reply = await self.rpc(msg)
retu... | config : typing.Sequence[~NetworkConfig]
tag : str
Returns -> None |
350,613 | def get_by(cls, field, value):
redis = cls.get_redis()
key = cls.cls_key()++field
id = redis.hget(key, value)
if id:
return cls.get(debyte_string(id))
return None | Tries to retrieve an isinstance of this model from the database
given a value for a defined index. Return None in case of failure |
350,614 | def set_attrs(self, username, attrs):
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = self._byte_p2(tmp[0])
old_attrs = tmp[1]
for attr in attr... | set user attributes |
350,615 | def send_confirm_password_email(person):
url = % (
settings.REGISTRATION_BASE_URL, person.username)
context = CONTEXT.copy()
context.update({
: url,
: person,
})
to_email = person.email
subject, body = render_email(, context)
send_mail(subject, body, settings... | Sends an email to user allowing them to confirm their password. |
350,616 | def remove_router_interface(self, context, router_id, interface_info):
router_to_del = (
super(AristaL3ServicePlugin, self).remove_router_interface(
context,
router_id,
interface_info)
)
core = directory.get_plug... | Remove a subnet of a network from an existing router. |
350,617 | def postinit(self, func=None, args=None, keywords=None):
self.func = func
self.args = args
self.keywords = keywords | Do some setup after initialisation.
:param func: What is being called.
:type func: NodeNG or None
:param args: The positional arguments being given to the call.
:type args: list(NodeNG) or None
:param keywords: The keyword arguments being given to the call.
:type keywo... |
350,618 | def validate_with_tags(self, tags, confidence):
result = {: self.name}
intent_confidence = 0.0
local_tags = tags[:]
used_tags = []
for require_type, attribute_name in self.requires:
required_tag, canonical_form, confidence = find_first_tag(local_tags, requir... | Validate weather tags has required entites for this intent to fire
Args:
tags(list): Tags and Entities used for validation
confidence(float): ?
Returns:
intent, tags: Returns intent and tags used by the intent on
falure to meat required entities then... |
350,619 | def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque):
event_str, detail_str = _get_domain_event_detail(event, detail)
_salt_send_domain_event(opaque, conn, domain, opaque[], {
: event_str,
: detail_str
}) | Domain lifecycle events handler |
350,620 | def save_cursor(self):
self.savepoints.append(Savepoint(copy.copy(self.cursor),
self.g0_charset,
self.g1_charset,
self.charset,
mo.DECOM in... | Push the current cursor position onto the stack. |
350,621 | def encode_data_frame(name, df, run):
pandas = get_module("pandas")
fastparquet = get_module("fastparquet")
if not pandas or not fastparquet:
raise wandb.Error(
"Failed to save data frame: unable to import either pandas or fastparquet.")
data_frame_id = generate_id()
... | Encode a Pandas DataFrame into the JSON/backend format.
Writes the data to a file and returns a dictionary that we use to represent
it in `Summary`'s.
Arguments:
name (str): Name of the DataFrame, eg. the summary key in which it's
stored. This is for convenience, so people exploring th... |
350,622 | def get_matching_blocks(self):
if self.matching_blocks is not None:
return self.matching_blocks
matching_blocks = _cdifflib.matching_blocks(self)
matching_blocks.append((len(self.a), len(self.b), 0))
self.matching_blocks = matching_blocks
return map(_Match.... | Same as SequenceMatcher.get_matching_blocks, but calls through to a
faster loop for find_longest_match. The rest is the same. |
350,623 | def fetch_rrlyrae_fitdata(**kwargs):
save_loc = _get_download_or_cache(, **kwargs)
dtype = [(, ), (, ), (, ), (, ),
(, ), (, ),
(, ), (, ), (, ),
(, ), (, ), (, ),
(, ), (, ),
(, ), (, )]
return np.loadtxt(save_loc, dtype=dtype) | Fetch data from table 3 of Sesar 2010
This table includes parameters derived from template fits to all the
Sesar 2010 lightcurves. |
350,624 | def broadcast(cls, s1: ParamsList, s2: ParamsList) -> BroadcastTuple:
s official documentation available at the following URLs:
1. https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
2. https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast.html
Args:
... | It broadcasts the smaller scope over the larger scope.
It handles scope intersection as well as differences in scopes
in order to output a resulting scope so that input scopes are
contained within it (i.e., input scopes are subscopes of the
output scope). Also, if necessary, it outputs ... |
350,625 | def export_mt_variants(variants, sample_id):
document_lines = []
for variant in variants:
line = []
position = variant.get()
change = .join([variant.get(),variant.get()])
line.append(position)
line.append(change)
line.append(str(position)+change)
gene... | Export mitochondrial variants for a case to create a MT excel report
Args:
variants(list): all MT variants for a case, sorted by position
sample_id(str) : the id of a sample within the case
Returns:
document_lines(list): list of lines to include in the document |
350,626 | def generateCertificate(self, alias,
commonName, organizationalUnit,
city, state, country,
keyalg="RSA", keysize=1024,
sigalg="SHA256withRSA",
validity=90
... | Use this operation to create a self-signed certificate or as a
starting point for getting a production-ready CA-signed
certificate. The portal will generate a certificate for you and
store it in its keystore. |
350,627 | def GetLaunchedFlows(self, flow_type="outstanding"):
result = None
all_clients = set(self.ListAllClients())
finished_clients = set(self.ListFinishedClients())
outstanding_clients = all_clients - finished_clients
if flow_type == "all":
result = all_clients
elif flow_type == "finished"... | Returns the session IDs of all the flows we launched.
Args:
flow_type: The type of flows to fetch. Can be "all", "outstanding" or
"finished".
Returns:
A list of flow URNs. |
350,628 | def values(self):
current_nodes = [self]
has_more_nodes = True
values = []
while has_more_nodes:
has_more_nodes = False
next_nodes = []
for node in current_nodes:
if node is None:
values.append(None)
... | Return the `list representation`_ of the binary tree.
.. _list representation:
https://en.wikipedia.org/wiki/Binary_tree#Arrays
:return: List representation of the binary tree, which is a list of
node values in breadth-first order starting from the root (current
nod... |
350,629 | def get_maintenance_response(request):
if settings.MAINTENANCE_MODE_REDIRECT_URL:
return redirect(settings.MAINTENANCE_MODE_REDIRECT_URL)
context = {}
if settings.MAINTENANCE_MODE_GET_TEMPLATE_CONTEXT:
try:
get_request_context_func = import_string(
settings... | Return a '503 Service Unavailable' maintenance response. |
350,630 | def get_geoms_for_bounds(self, bounds):
params = { : ,
: ,
: self._feature_name,
: ,
: ,
: .join((str(b) for b in wkt.loads(bounds).bounds))}
raw_geojson_response = reques... | Helper method to get geometries within a certain bounds (as WKT).
Returns GeoJSON (loaded as a list of python dictionaries). |
350,631 | def space_delete(args):
message = "WARNING: this will delete workspace: \n\t{0}/{1}".format(
args.project, args.workspace)
if not args.yes and not _confirm_prompt(message):
return 0
r = fapi.delete_workspace(args.project, args.workspace)
fapi._check_response_code(r, [200, 202, 204,... | Delete a workspace. |
350,632 | def bytes2human(n, fmt=, symbols=):
n = int(n)
if n < 0:
raise ValueError("n < 0")
symbols = SYMBOLS[symbols]
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i+1)*10
for symbol in reversed(symbols[1:]):
if n >= prefix[symbol]:
value = ol... | Convert n bytes into a human readable string based on format.
symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
see: http://goo.gl/kTQMs |
350,633 | def get_shutit_pexpect_session_id(self, shutit_pexpect_child):
shutit_global.shutit_global_object.yield_to_draw()
if not isinstance(shutit_pexpect_child, pexpect.pty_spawn.spawn):
self.fail(,throw_exception=True)
for key in self.shutit_pexpect_sessions:
if self.shutit_pexpect_sessions[key].pexpect_child... | Given a pexpect child object, return the shutit_pexpect_session_id object. |
350,634 | def multi_replace(instr, search_list=[], repl_list=None):
repl_list = [] * len(search_list) if repl_list is None else repl_list
for ser, repl in zip(search_list, repl_list):
instr = instr.replace(ser, repl)
return instr | Does a string replace with a list of search and replacements
TODO: rename |
350,635 | def _set_instance_ip(self):
try:
ip_address = self.network.public_ip_addresses.get(
self.running_instance_id, self.public_ip_name
).ip_address
except Exception:
try:
ip_address = self.network.network_interfaces.get(
... | Get the IP address based on instance ID.
If public IP address not found attempt to get private IP. |
350,636 | def SizeInBytes(sized_field, length, encoder=ENC_INT_DEFAULT, fuzzable=False, name=None):
return Size(sized_field=sized_field, length=length, calc_func=lambda x: len(x) // 8, encoder=encoder, fuzzable=fuzzable, name=name) | :rtype: :class:`~kitty.model.low_level.calculated.Size`
:return: Size field, which holds the size in bytes of the sized field |
350,637 | def get_es_ids(self):
search = self.search.source([]).sort([])
es_ids = [item.meta.id for item in search.scan()]
return es_ids | reads all the elasticssearch ids for an index |
350,638 | def to_dict(self, converter=None):
if converter is None:
converter = self.stringify
out = dict()
for k, v in self.iteritems():
out[k] = converter(v)
return out | Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`. |
350,639 | def custom_filter_text(self, value, search):
if isinstance(value, list):
value = .join(value)
should = [
Q(, slug={: value, : , : 10.0}),
Q(, **{: {: value, : , : 5.0}}),
Q(, name={: value, : , : 10.0}),
Q(, **{: {: value, : , : 5.0}}... | Support general query using the 'text' attribute. |
350,640 | def choose_intronic_effect_class(
variant,
nearest_exon,
distance_to_exon):
assert distance_to_exon > 0, \
"Expected intronic effect to have distance_to_exon > 0, got %d" % (
distance_to_exon,)
if nearest_exon.strand == "+":
start_before = varia... | Infer effect of variant which does not overlap any exon of
the given transcript. |
350,641 | def handle_basic_executor_options(options, parser):
logLevel = logging.INFO
if options.debug:
logLevel = logging.DEBUG
elif options.quiet:
logLevel = logging.WARNING
util.setup_logging(level=logLevel) | Handle the options specified by add_basic_executor_options(). |
350,642 | def is_header(self, elem, font_size, node, style=None):
if hasattr(style, ):
fnt_size = _get_font_size(self.doc, style)
from .importer import calculate_weight
weight = calculate_weight(self.do... | Used for checking if specific element is a header or not.
:Returns:
True or False |
350,643 | def encode_password(password):
log = logging.getLogger(mod_logger + )
log.debug(.format(p=password))
encoded_password =
for c in password:
encoded_password += encode_character(char=c)
log.debug(.format(p=encoded_password))
return encoded_password | Performs URL encoding for passwords
:param password: (str) password to encode
:return: (str) encoded password |
350,644 | def get_extend_fmt(self):
command = const.CMD_OPTIONS_RRQ
command_string = b
response_size = 1024
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_response.get():
fmt = (self.__data.split(b, 1)[-1].split(b)[0])
re... | determine extend fmt |
350,645 | def get_modifiers(state):
ret = []
if state & xproto.ModMask.Shift:
ret.append()
if state & xproto.ModMask.Lock:
ret.append()
if state & xproto.ModMask.Control:
ret.append()
if state & xproto.ModMask._1:
ret.append()
if state & xproto.ModMask._2:
ret... | Takes a ``state`` (typically found in key press or button press events)
and returns a string list representation of the modifiers that were pressed
when generating the event.
:param state: Typically from ``some_event.state``.
:return: List of modifier string representations.
:rtype: [str] |
350,646 | def states_close(state0: State, state1: State,
tolerance: float = TOLERANCE) -> bool:
return vectors_close(state0.vec, state1.vec, tolerance) | Returns True if states are almost identical.
Closeness is measured with the metric Fubini-Study angle. |
350,647 | def pixel_image(shape, sd=None, init_val=None):
if sd is not None and init_val is not None:
warnings.warn(
"`pixel_image` received both an initial value and a sd argument. Ignoring sd in favor of the supplied initial value."
)
sd = sd or 0.01
init_val = init_val or np.rando... | A naive, pixel-based image parameterization.
Defaults to a random initialization, but can take a supplied init_val argument
instead.
Args:
shape: shape of resulting image, [batch, width, height, channels].
sd: standard deviation of param initialization noise.
init_val: an initial value to... |
350,648 | def set(self, instance, items, prices=None, specs=None, hidden=None, **kw):
new_analyses = []
analyses = instance.objectValues("Analysis")
non_open_analyses = filter(lambda an: not an.isOpen(), analyses)
non_open_analyses = filter(
... | Set/Assign Analyses to this AR
:param items: List of Analysis objects/brains, AnalysisService
objects/brains and/or Analysis Service uids
:type items: list
:param prices: Mapping of AnalysisService UID -> price
:type prices: dict
:param specs: List of Analy... |
350,649 | def remove(self, obj_or_string, commit=True):
if not self.setup_complete:
try:
self.setup()
except elasticsearch.TransportError as e:
if not self.silently_fail:
raise
doc_id = get_identifier(obj_or_string)
... | Removes an object from the index.
:param obj_or_string:
:param commit: |
350,650 | def get_field_info(self) -> FieldInfo:
byte_buffer = self.game.UpdateFieldInfoFlatbuffer()
if byte_buffer.size >= 4:
proto_string = ctypes.string_at(byte_buffer.ptr, byte_buffer.size)
self.game.Free(byte_buffer.ptr)
self.game_st... | Gets the field information from the interface.
:return: The field information |
350,651 | def prev_this_next(it, sentinel=None):
i1, i2, i3 = tee(it, 3)
next(i3, None)
return zip(chain([sentinel], i1), i2, chain(i3, [sentinel])) | Utility to return (prev, this, next) tuples from an iterator |
350,652 | async def publish(self, message):
try:
self.write(.format(message))
await self.flush()
except StreamClosedError:
self.finished = True | Pushes data to a listener. |
350,653 | def predict(self, data, unkown=None):
assert self.classifier is not None,
bmus = self._som.bmus(data)
return self._predict_from_bmus(bmus, unkown) | \
Classify data according to previous calibration.
:param data: sparse input matrix (ideal dtype is `numpy.float32`)
:type data: :class:`scipy.sparse.csr_matrix`
:param unkown: the label to attribute if no label is known
:returns: the labels guessed for data
:rtype: `num... |
350,654 | def remove_network_profile(self, obj, params):
network_id = -1
profiles = self.network_profiles(obj)
for profile in profiles:
if profile == params:
network_id = profile.id
if network_id != -1:
self._send_cmd_to_wpas(obj[],
... | Remove the specified AP profiles |
350,655 | def _arg(__decorated__, **Config):
r
if isinstance(__decorated__, tuple):
__decorated__[1].insert(0, Config)
return __decorated__
else:
return __decorated__, [Config] | r"""The worker for the arg decorator. |
350,656 | def get_assessments_by_bank(self, bank_id):
mgr = self._get_provider_manager(, local=True)
lookup_session = mgr.get_assessment_lookup_session_for_bank(bank_id, proxy=self._proxy)
lookup_session.use_isolated_bank_view()
return lookup_session.get_assessments() | Gets the list of ``Assessments`` associated with a ``Bank``.
arg: bank_id (osid.id.Id): ``Id`` of the ``Bank``
return: (osid.assessment.AssessmentList) - list of related
assessments
raise: NotFound - ``bank_id`` is not found
raise: NullArgument - ``bank_id`` is ``nu... |
350,657 | def inputs_options_defaults():
if os.path.isfile(GPF_CONSTANTS_FILENAME):
modtime = int(os.path.getmtime(GPF_CONSTANTS_FILENAME))
curtime = int(time.time())
)
json.dump(def_dict, f)
return def_dict | Handles scraping options for play finder form.
:returns: {'name1': {'value': val, 'options': [opt1, ...] }, ... } |
350,658 | def cos(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_cos,
(BigFloat._implicit_convert(x),),
context,
) | Return the cosine of ``x``. |
350,659 | def spectral_rolloff(y=None, sr=22050, S=None, n_fft=2048, hop_length=512,
win_length=None, window=, center=True, pad_mode=,
freq=None, roll_percent=0.85):
Roll-off frequencyHzlogtimelog Power spectrogram
if not 0.0 < roll_percent < 1.0:
raise ParameterError()
... | Compute roll-off frequency.
The roll-off frequency is defined for each frame as the center frequency
for a spectrogram bin such that at least roll_percent (0.85 by default)
of the energy of the spectrum in this frame is contained in this bin and
the bins below. This can be used to, e.g., approximate th... |
350,660 | def minimumLabelWidth(self):
min_w = 0
metrics = QFontMetrics(self.labelFont())
for label in self.labels():
min_w = max(min_w, metrics.width(label))
return max(self._minimumLabelWidth,
min_w + self.horizontalLabelPadding()) | Returns the minimum label width required on this renderers font size.
:param labels | [<str>, ..] |
350,661 | def is_valid_categorical_partition_object(partition_object):
if partition_object is None or ("weights" not in partition_object) or ("values" not in partition_object):
return False
if len(partition_object[]) == len(partition_object[]) and \
np.allclose(np.sum(partition_object[]), 1)... | Tests whether a given object is a valid categorical partition object.
:param partition_object: The partition_object to evaluate
:return: Boolean |
350,662 | def vocab_counter(args):
if isinstance(args.input, TextFiles):
v = CountedVocabulary.from_textfiles(args.input, workers=args.workers)
else:
v = CountedVocabulary.from_textfile(args.input, workers=args.workers)
if args.min_count > 1:
v = v.min_count(args.min_count)
if args.most_freq > 0:
v = ... | Calculate the vocabulary. |
350,663 | def check_calendar(self, ds):
valid_calendars = [
,
,
,
,
,
,
,
,
,
]
ret_val = []
for time_var in ds.get_variables_by_attributes(calendar... | Check the calendar attribute for variables defining time and ensure it
is a valid calendar prescribed by CF.
CF §4.4.1 In order to calculate a new date and time given a base date, base
time and a time increment one must know what calendar to use.
The values currently defined for calend... |
350,664 | def inspect_bucket(bucket):
state = db.db()
found = None
for b in state.buckets():
if b.name == bucket:
found = b
if not found:
click.echo("no bucket named: %s" % bucket)
return
click.echo("Bucket: %s" % found.name)
click.echo("Account: %s" % found.accou... | Show all information known on a bucket. |
350,665 | def wrap(self, value):
attrib = getattr(value, , {})
S, NS = divmod(time.time(), 1.0)
value = numpy.asarray(value)
dims = list(value.shape)
dims.reverse()
if not in attrib:
if value.ndim==2:
attrib[] = 0
... | Wrap numpy.ndarray as Value |
350,666 | def read(self, size = None):
r = self._buffer
self._buffer = bytes()
if size is not None:
size -= len(r)
r = r + self._response.read(size)
return r | Reads a given number of characters from the response.
:param size: The number of characters to read, or "None" to read the
entire response.
:type size: ``integer`` or "None" |
350,667 | def load_external_stages(self, path):
mod = imp.load_source(, path)
self.update(mod.Stages) | Add external stages from the Python module in `path`.
`path` must be a path to a Python module source that contains
a `Stages` dictionary, which is a map from stage name to callable.
:param str path: path to the module file |
350,668 | def transform_field(field):
field.name = field.attname
if isinstance(field, models.AutoField):
field.__class__ = models.IntegerField
elif isinstance(field, models.FileField):
field.auto_now = False
field.auto_now_add = False
if field.primary_key or field.unique:
... | Customize field appropriately for use in historical model |
350,669 | def MultivariateGaussian(mu: vertex_constructor_param_types, covariance: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().MultivariateGaussianVertex, label, cast_to_double_vertex(mu), cast_to_double_vertex(covariance)) | Matches a mu and covariance of some shape to a Multivariate Gaussian
:param mu: the mu of the Multivariate Gaussian
:param covariance: the covariance matrix of the Multivariate Gaussian |
350,670 | def get_mark(self, mark_id):
if mark_id in self.idx:
return Cmarkable(self.idx[mark_id], self.type)
else:
return None | Returns the markable object for the supplied identifier
@type mark_id: string
@param mark_id: term identifier |
350,671 | def Akmaev_adjustment(theta, q, beta, n_k, theta_k, s_k, t_k):
L = q.size
k = 1
n_k[k-1] = 1
theta_k[k-1] = theta[k-1]
l = 2
while True:
n = 1
thistheta = theta[l-1]
while True:
if theta_k[k-1] <= thistheta:
... | Single column only. |
350,672 | def Uniform(x_min: vertex_constructor_param_types, x_max: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().UniformVertex, label, cast_to_double_vertex(x_min), cast_to_double_vertex(x_max)) | One to one constructor for mapping some shape of mu and sigma to
a matching shaped Uniform Vertex
:param x_min: the inclusive lower bound of the Uniform with either the same shape as specified for this vertex or a scalar
:param x_max: the exclusive upper bound of the Uniform with either the same shape ... |
350,673 | def hmac(key, message, tag=None, alg=hashlib.sha256):
return HMAC.new(str(key), str(tag) + str(message), digestmod=alg).digest() | Generates a hashed message authentication code (HMAC) by prepending the
specified @tag string to a @message, then hashing with to HMAC
using a cryptographic @key and hashing @alg -orithm. |
350,674 | def K(self,X,X2,target):
AX = np.dot(X,self.transform)
if X2 is None:
X2 = X
AX2 = AX
else:
AX2 = np.dot(X2, self.transform)
self.k.K(X,X2,target)
self.k.K(AX,X2,target)
self.k.K(X,AX2,target)
self.k.K(AX,AX2,target) | Compute the covariance matrix between X and X2. |
350,675 | def clone_from(self, other):
for other_finfo in other.data:
self.clone_editor_from(other_finfo, set_current=True)
self.set_stack_index(other.get_stack_index()) | Clone EditorStack from other instance |
350,676 | def child(self,index):
"helper for __getitem__/__setitem__"
if isinstance(index,tuple):
attr,i = index
return getattr(self,attr)[i]
else: return getattr(self,index) | helper for __getitem__/__setitem__ |
350,677 | def ready_message():
title = m.Heading(tr(), **PROGRESS_UPDATE_STYLE)
notes = m.Paragraph(
tr(),
m.EmphasizedText(tr(), **KEYWORD_STYLE),
tr())
message = m.Message(LOGO_ELEMENT, title, notes)
return message | Helper to create a message indicating inasafe is ready.
:returns Message: A localised message indicating we are ready to run. |
350,678 | def remote(ctx):
with command():
m = RepoManager(ctx.obj[])
click.echo(m.github_repo().repo_path) | Display repo github path |
350,679 | def user_compliance_deletion_statuses(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users
api_path = "/api/v2/users/{id}/compliance_deletion_statuses.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/users#show-compliance-deletion-statuses |
350,680 | def read_sync(self, timeout=None):
if self.saved_data:
return self.saved_data.pop(0)
self._sync_ioloop_running = True
self._read_sync_future = self._read_sync(timeout)
self.io_loop.start()
self._sync_ioloop_running = False
ret_future = self._read_sy... | Read a message from an IPC socket
The socket must already be connected.
The associated IO Loop must NOT be running.
:param int timeout: Timeout when receiving message
:return: message data if successful. None if timed out. Will raise an
exception for all other error con... |
350,681 | def list_all_braintree_gateways(cls, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._list_all_braintree_gateways_with_http_info(**kwargs)
else:
(data) = cls._list_all_braintree_gateways_with_http_info(**kwargs)
return data | List BraintreeGateways
Return a list of BraintreeGateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_braintree_gateways(async=True)
>>> result = thread.get()
:param asyn... |
350,682 | def up(tgt=, tgt_type=, timeout=None, gather_job_timeout=None):
ret = status(
output=False,
tgt=tgt,
tgt_type=tgt_type,
timeout=timeout,
gather_job_timeout=gather_job_timeout
).get(, [])
return ret | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print a list of all of the minions that are up
CLI Example:
.. code-block:: bash
salt-run manage.up
salt-run manage.up tgt="webservers" tgt_t... |
350,683 | def put_scaling_policy(AutoScalingGroupName=None, PolicyName=None, PolicyType=None, AdjustmentType=None, MinAdjustmentStep=None, MinAdjustmentMagnitude=None, ScalingAdjustment=None, Cooldown=None, MetricAggregationType=None, StepAdjustments=None, EstimatedInstanceWarmup=None):
pass | Creates or updates a policy for an Auto Scaling group. To update an existing policy, use the existing policy name and set the parameters you want to change. Any existing parameter not changed in an update to an existing policy is not changed in this update request.
If you exceed your maximum limit of step adjustmen... |
350,684 | def _get_decoder(self, units, vocab_size, embed, prefix):
with self.name_scope():
decoder = nn.HybridSequential(prefix=prefix)
decoder.add(nn.Dense(units, flatten=False))
decoder.add(GELU())
decoder.add(BERTLayerNorm(in_channels=units))
decode... | Construct a decoder for the masked language model task |
350,685 | def parsed(self):
if not self._parsed:
self._parsed = compile(self.content, self.path, )
return self._parsed | Get the code object which represents the compiled Python file.
This property is cached and only parses the content once. |
350,686 | def delete_result(self, client, check):
self._request(, .format(client, check))
return True | Deletes an check result data for a given check on a given client. |
350,687 | def get_perm_by_code(perm_code,**kwargs):
try:
perm = db.DBSession.query(Perm).filter(Perm.code==perm_code).one()
return perm
except NoResultFound:
raise ResourceNotFoundError("Permission not found (perm_code={})".format(perm_code)) | Get a permission by its code |
350,688 | def _setup_tls_files(self, files):
for file_type in TLSFileType:
if file_type.value in files:
file_path = files[file_type.value]
setattr(self, file_type.value,
TLSFile(file_path, file_type=file_type)) | Initiates TLSFIle objects with the paths given to this bundle |
350,689 | def p_word(self, p):
try:
term = self._get_term(p[1 if len(p) == 2 else 2])
except TermNotFoundInDictionary as e:
raise CannotParse(self._ieml, str(e))
if len(p) == 5:
p[0] = Word(term, literals=p[4])
else:
p[0] = Word(term) | word : TERM
| LBRACKET TERM RBRACKET
| LBRACKET TERM RBRACKET literal_list |
350,690 | def AddTask(self,
target,
args=(),
name="Unnamed task",
blocking=True,
inline=True):
if not self.started:
raise ThreadPoolNotStartedError(self.name)
if self.max_threads == 0:
target(*args)
return
if inline:
... | Adds a task to be processed later.
Args:
target: A callable which should be processed by one of the workers.
args: A tuple of arguments to target.
name: The name of this task. Used to identify tasks in the log.
blocking: If True we block until the task is finished, otherwise we raise
... |
350,691 | def copy_object(self, source_bucket, source_object_name, dest_bucket=None,
dest_object_name=None, metadata={}, amz_headers={}):
dest_bucket = dest_bucket or source_bucket
dest_object_name = dest_object_name or source_object_name
amz_headers["copy-source"] = "/%s/%s" ... | Copy an object stored in S3 from a source bucket to a destination
bucket.
@param source_bucket: The S3 bucket to copy the object from.
@param source_object_name: The name of the object to copy.
@param dest_bucket: Optionally, the S3 bucket to copy the object to.
Defaults to ... |
350,692 | def _token_at_col_in_line(line, column, token, token_len=None):
if not token_len:
token_len = len(token)
remaining_len = len(line) - column
return (remaining_len >= token_len and
line[column:column + token_len] == token) | True if token is at column. |
350,693 | def running_apps(self):
ps = self.adb_shell(RUNNING_APPS_CMD)
if ps:
return [line.strip().rsplit(, 1)[-1] for line in ps.splitlines() if line.strip()]
return [] | Return a list of running user applications. |
350,694 | def average(self, axis):
axis = self.get_axis_number(axis)
avg_hist = np.ma.average(self.all_axis_bin_centers(axis),
weights=self.histogram, axis=axis)
if self.dimensions == 2:
new_hist = Hist1d
else:
new_hist = Histdd
... | Returns d-1 dimensional histogram of (estimated) mean value of axis
NB this is very different from averaging over the axis!!! |
350,695 | def tobinarray(self, start=None, end=None, size=None):
bin = array()
if self._buf == {} and None in (start, end):
return bin
if size is not None and size <= 0:
raise ValueError("tobinarray: wrong value for size")
start, end = self._get_start_end(start,... | Convert this object to binary form as array (of 2-bytes word data).
If start and end unspecified, they will be inferred from the data.
@param start start address of output data.
@param end end address of output data (inclusive).
@param size size of the block (number of words)... |
350,696 | def tempfile(cls, suffix=, prefix=None, dir=None, text=False):
if prefix is None:
prefix = tempfile.template
if dir is not None:
dir = str(Path(dir))
fd, filename = tempfile.mkstemp(suffix, prefix, dir, text)
return fd, cls(filen... | Returns a new temporary file.
The return value is a pair (fd, path) where fd is the file descriptor
returned by :func:`os.open`, and path is a :class:`~rpaths.Path` to it.
:param suffix: If specified, the file name will end with that suffix,
otherwise there will be no suffix.
... |
350,697 | def update(self, id, data):
self.db.execute([
,
.join(key + + for key in data),
],
list(data.values()) + [id])
return self.get(id) | Update comment :param:`id` with values from :param:`data` and return
updated comment. |
350,698 | def edge_to_bel(u: BaseEntity, v: BaseEntity, data: EdgeData, sep: Optional[str] = None) -> str:
sep = sep or
u_str = _decanonicalize_edge_node(u, data, node_position=SUBJECT)
v_str = _decanonicalize_edge_node(v, data, node_position=OBJECT)
return sep.join((u_str, data[RELATION], v_str)) | Take two nodes and gives back a BEL string representing the statement.
:param u: The edge's source's PyBEL node data dictionary
:param v: The edge's target's PyBEL node data dictionary
:param data: The edge's data dictionary
:param sep: The separator between the source, relation, and target. Defaults t... |
350,699 | def _set_description(self, node):
hostname = socket.getfqdn() or platform.node()
descr = etree.SubElement(node, )
author = etree.SubElement(descr, )
author.text = "salt.modules.node on {0}".format(hostname)
contact = etree.SubElement(descr, )
contact.text = .for... | Create a system description.
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.