Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
357,700 | def dumper(self):
with open(.format(self.reportpath, self.analysistype, ), ) as referenceprofile:
referenceprofile.write(json.dumps(self.referenceprofile, sort_keys=True, indent=4, separators=(, ))) | Write :self.referenceprofile |
357,701 | def install_bundle(self, name, path=None):
with self.__bundles_lock:
for bundle in self.__bundles.values():
if bundle.get_symbolic_name() == name:
_logger.debug("Already installed bundle: %s", name)
return bundle
... | Installs the bundle with the given name
*Note:* Before Pelix 0.5.0, this method returned the ID of the
installed bundle, instead of the Bundle object.
**WARNING:** The behavior of the loading process is subject to changes,
as it does not allow to safely run multiple frameworks in the s... |
357,702 | def _generateForTokenSecurity(self):
agolToken = self._agolSecurityHandler.token
url = self._url + "/getProxyUserToken"
params = {"token" : self._agolSecurityHandler.token,
"contributorUid" : self._contributionUID}
res = self._post(url=url, param_dict=params,
... | generates a token for a feature service |
357,703 | def get_template_edit_url(self, template_id):
request = self._get_request()
return request.get(self.EMBEDDED_TEMPLATE_EDIT_URL + template_id) | Retrieves a embedded template for editing
Retrieves an embedded object containing a template url that can be opened in an iFrame.
Args:
template_id (str): The id of the template to get a signature url for
Returns:
An Embedded object |
357,704 | def macro_attachment_create(self, macro_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros
api_path = "/api/v2/macros/{macro_id}/attachments.json"
api_path = api_path.format(macro_id=macro_id)
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/macros#create-macro-attachment |
357,705 | def affine_initializer(fixed_image, moving_image, search_factor=20,
radian_fraction=0.1, use_principal_axis=False,
local_search_iterations=10, mask=None, txfn=None ):
if txfn is None:
txfn = mktemp(suffix=)
veccer = [fixed_image.dimension, fixed_im... | A multi-start optimizer for affine registration
Searches over the sphere to find a good initialization for further
registration refinement, if needed. This is a arapper for the ANTs
function antsAffineInitializer.
ANTsR function: `affineInitializer`
Arguments
---------
fixed_image : A... |
357,706 | def make_bin_array(bins) -> np.ndarray:
bins = np.asarray(bins)
if bins.ndim == 1:
return np.hstack((bins[:-1, np.newaxis], bins[1:, np.newaxis]))
elif bins.ndim == 2:
if bins.shape[1] != 2:
raise RuntimeError("Binning schema with ndim==2 must have 2 column... | Turn bin data into array understood by HistogramXX classes.
Parameters
----------
bins: array_like
Array of edges or array of edge tuples
Examples
--------
>>> make_bin_array([0, 1, 2])
array([[0, 1],
[1, 2]])
>>> make_bin_array([[0, 1], [2, 3]])
array([[0, 1],
... |
357,707 | def grab_keyfile(cert_url):
key_cache = caches[getattr(settings, , )]
pemfile = key_cache.get(cert_url)
if not pemfile:
response = urlopen(cert_url)
pemfile = response.read()
key_cache.set(cert_url, pemfile)
return pemfile | Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache |
357,708 | async def redirect_async(self, redirect, auth):
if self._ext_connection:
raise ValueError(
"Clients with a shared connection cannot be "
"automatically redirected.")
if self.message_handler:
await self.message_handler.destroy_async()
... | Redirect the client endpoint using a Link DETACH redirect
response.
:param redirect: The Link DETACH redirect details.
:type redirect: ~uamqp.errors.LinkRedirect
:param auth: Authentication credentials to the redirected endpoint.
:type auth: ~uamqp.authentication.common.AMQPAuth |
357,709 | def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma):
rho_bar = batch_to_seq(tf.minimum(1.0, rho_i), nenvs, nsteps, True)
rs = batch_to_seq(R, nenvs, nsteps, True)
ds = batch_to_seq(D, nenvs, nsteps, True)
q_is = batch_to_seq(q_i, nenvs, nsteps, True)
vs = batch_to_seq(v, nenvs, nstep... | Calculates q_retrace targets
:param R: Rewards
:param D: Dones
:param q_i: Q values for actions taken
:param v: V values
:param rho_i: Importance weight for each action
:return: Q_retrace values |
357,710 | def markdown(doc, title=True, template=):
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader(, )
)
context = display_context(doc)
return env.get_template(template).render(**context) | Markdown, specifically for the Notes field in a CKAN dataset |
357,711 | def describe_rules(listener_arn=None, rule_arns=None, client=None):
kwargs = dict()
if listener_arn:
kwargs.update(dict(ListenerArn=listener_arn))
if rule_arns:
kwargs.update(dict(RuleArns=rule_arns))
return client.describe_rules(**kwargs)[] | Permission: elasticloadbalancing:DescribeRules |
357,712 | def p_portlist(self, p):
p[0] = Portlist(ports=p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | portlist : LPAREN ports RPAREN SEMICOLON |
357,713 | def all_documents(index=INDEX_NAME):
query = {
: {
: {}
}
}
for result in raw_query(query, index=index):
yield result | Get all documents from the given index.
Returns full Elasticsearch objects so you can get metadata too. |
357,714 | def circle_level_set(image_shape, center=None, radius=None):
if center is None:
center = tuple(i // 2 for i in image_shape)
if radius is None:
radius = min(image_shape) * 3.0 / 8.0
grid = np.mgrid[[slice(i) for i in image_shape]]
grid = (grid.T - center).T
phi = radius - np.s... | Create a circle level set with binary values.
Parameters
----------
image_shape : tuple of positive integers
Shape of the image
center : tuple of positive integers, optional
Coordinates of the center of the circle given in (row, column). If not
given, it defaults to the center o... |
357,715 | def create_mask_montage(self, image, predictions):
masks = predictions.get_field("mask")
masks_per_dim = self.masks_per_dim
masks = L.interpolate(
masks.float(), scale_factor=1 / masks_per_dim
).byte()
height, width = masks.shape[-2:]
max_masks = mask... | Create a montage showing the probability heatmaps for each one one of the
detected objects
Arguments:
image (np.ndarray): an image as returned by OpenCV
predictions (BoxList): the result of the computation by the model.
It should contain the field `mask`. |
357,716 | def get_lang_class(lang):
global LANGUAGES
entry_point = get_entry_point("spacy_languages", lang)
if entry_point is not None:
LANGUAGES[lang] = entry_point
return entry_point
if lang not in LANGUAGES:
try:
module = importlib.import_module(".lang.%s" % lang, ... | Import and load a Language class.
lang (unicode): Two-letter language code, e.g. 'en'.
RETURNS (Language): Language class. |
357,717 | def new_value(self, key, value):
data = self.model.get_data()
data[key] = value
self.set_data(data) | Create new value in data |
357,718 | def _setMinAndMax(self, input, learn):
self.slidingWindow.next(input)
if self.minval is None and self.maxval is None:
self.minval = input
self.maxval = input+1
self._setEncoderParams()
elif learn:
sorted = self.slidingWindow.getSlidingWindow()
sorted.sort()
mi... | Potentially change the minval and maxval using input.
**The learn flag is currently not supported by cla regions.** |
357,719 | def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time):
try:
cloud_config = CloudConfig()
ci = None
if cloud_init:
ci = CloudInit()
cloud_controller = CloudController(cloud_config)
cloud_controller.up(ci, use_snapshots, upgrade_im... | creates a new cluster |
357,720 | def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed):
feed_item_service = client.GetService(, )
now = datetime.now()
mars_date = datetime(now.year, now.month, 1, 0, 0)
venus_date = datetime(now.year, now.month, 15, 0, 0)
time_format =
feed_item_operations = [
CreateFeedItemAd... | Creates FeedItems for the specified AdGroups.
These FeedItems contain values to use in ad customizations for the AdGroups.
Args:
client: an AdWordsClient instance.
adgroup_ids: a list containing two AdGroup Ids.
ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems
with.
... |
357,721 | def undo(self, editor):
inst = self.timemachine
if not self.is_revertible:
raise DisciplineException("You tried to undo a non-revertible action! "
"Check action.is_revertible and action.undo_errors"
" before trying to und... | Create a new Action that undos the effects of this one, or,
more accurately, reverts the object of this Action to the state
at which it was right before the Action took place. |
357,722 | def purview_indices(self, direction):
return {
Direction.CAUSE: self.cause_indices,
Direction.EFFECT: self.effect_indices
}[direction] | The indices of nodes in the purview system. |
357,723 | def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None):
if remote_files is None:
remote_files = command.map_files_raw(remote_dir=remote_dir)
for local_file in to_sync:
_sync_local_file(local_file, remote_dir, remote_files) | Sync a given list of local files to `remote_dir` dir |
357,724 | def create_experiment_fn(*args, **kwargs):
def experiment_fn(run_config, hparams):
return create_experiment(run_config, hparams, *args, **kwargs)
return experiment_fn | Wrapper for canonical experiment_fn. See create_experiment. |
357,725 | def mac_to_ipv6_linklocal(mac,prefix="fe80::"):
mac_value = int(mac.translate(str.maketrans(dict([(x,None) for x in [" ",".",":","-"]]))),16)
high2 = mac_value >> 32 & 0xffff ^ 0x0200
high1 = mac_value >> 24 & 0xff
low1 = mac_value >> 16 & 0xff
low2 = mac_value & 0xffff
... | Translate a MAC address into an IPv6 address in the prefixed network.
This function calculates the EUI (Extended Unique Identifier) from the given
MAC address and prepend the needed prefix to come up with a valid IPv6 address.
The default prefix is the link local prefix defined by RFC 4291 .
:para... |
357,726 | def __button_action(self, data=None):
if any(not x for x in (self._ename.value, self._p1.value, self._p2.value, self._file.value)):
print("Missing one of the required fields (event name, player names, file name)")
return
self.__p1chars = []
self.__p2chars = []
... | Button action event |
357,727 | def weighted_choice(choices, weight):
weights = []
for choice in choices:
choice_weight = weight(choice)
if not (isinstance(choice_weight, int) and choice_weight > 0):
raise TypeError()
weights.append(choice_weight)
selection = random.randint(0, sum(weights) - 1)
for idx, choice in enumerate(ch... | Make a random selection from the specified choices. Apply the *weight*
function to each to return a positive integer representing shares of
selection pool the choice should received. The *weight* function is passed a
single argument of the choice from the *choices* iterable.
:param choices: The choices to select f... |
357,728 | def _parse_java_version(line: str) -> tuple:
m = VERSION_RE.search(line)
version_str = m and m.group(0).replace(, ) or
if in version_str:
fst, snd = version_str.split(, maxsplit=2)
version = parse_version(fst)
return (version[1], version[2], int(snd))
else:
return ... | Return the version number found in the first line of `java -version`
>>> _parse_java_version('openjdk version "11.0.2" 2018-10-16')
(11, 0, 2) |
357,729 | def nupdated(self):
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._nupdated | Extract nupdated or nModified counter if available (lazy). |
357,730 | def register_target(repo_cmd, repo_service):
def decorate(klass):
log.debug(.format(klass.__name__) )
klass.command = repo_cmd
klass.name = repo_service
RepositoryService.service_map[repo_service] = klass
RepositoryService.command_map[repo_cmd] = repo_service
ret... | Decorator to register a class with an repo_service |
357,731 | def ping():
try:
cookie = logon()
logout(cookie)
except salt.exceptions.CommandExecutionError:
return False
except Exception as err:
log.debug(err)
return False
return True | Returns true if the device is reachable, else false. |
357,732 | def readCovariatesFile(fFile):
assert os.path.exists(fFile), %fFile
F = SP.loadtxt(fFile)
if F.ndim==1: F=F[:,SP.newaxis]
return F | reading in covariate file
cfile file containing the fixed effects as NxP matrix
(N=number of samples, P=number of covariates) |
357,733 | def Fisher(d1, d2, tag=None):
assert (
int(d1) == d1 and d1 >= 1
),
assert (
int(d2) == d2 and d2 >= 1
),
return uv(ss.f(d1, d2), tag=tag) | An F (fisher) random variate
Parameters
----------
d1 : int
Numerator degrees of freedom
d2 : int
Denominator degrees of freedom |
357,734 | def create_distributed_session(
task_spec=None, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=600,
save_summaries_steps=object(), save_summaries_secs=object(), config=None, stop_grace_period_secs=120,
log_step_count_steps=100
):
target = tas... | Creates a distributed session.
It calls `MonitoredTrainingSession` to create a :class:`MonitoredSession` for distributed training.
Parameters
----------
task_spec : :class:`TaskSpecDef`.
The task spec definition from create_task_spec_def()
checkpoint_dir : str.
Optional path to a d... |
357,735 | def delete_device_enrollment(self, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_device_enrollment_with_http_info(id, **kwargs)
else:
(data) = self.delete_device_enrollment_with_http_info(id, **kwargs)
return data | Delete an enrollment by ID. # noqa: E501
To free a device from your account you can delete the enrollment claim. To bypass the device ownership, you need to delete the enrollment and do a factory reset for the device. For more information, see [Transferring the ownership using First-to-Claim](/docs/current/co... |
357,736 | def to_naive_utc(dtime):
if not hasattr(dtime, ) or dtime.tzinfo is None:
return dtime
dtime_utc = dtime.astimezone(pytz.UTC)
dtime_naive = dtime_utc.replace(tzinfo=None)
return dtime_naive | convert a datetime object to UTC and than remove the tzinfo, if
datetime is naive already, return it |
357,737 | def parse_relationship(document, xmlcontent, rel_type):
doc = etree.fromstring(xmlcontent)
for elem in doc:
if elem.tag == _name():
rel = {: elem.attrib[],
: elem.attrib[],
: elem.attrib.get(, )}
document.relationships[rel_type][elem.... | Parse relationship document.
Relationships hold information like external or internal references for links.
Relationships are placed in file '_rels/document.xml.rels'. |
357,738 | async def main(interface=None):
qtm_ip = await choose_qtm_instance(interface)
if qtm_ip is None:
return
while True:
connection = await qtm.connect(qtm_ip, 22223, version="1.18")
if connection is None:
return
await connection.get_state()
await con... | Main function |
357,739 | def _second_pass(self):
logger.info("Running second pass for {}".format(self.input_file))
output_stream_types = []
if not self.ffmpeg_normalize.video_disable:
output_stream_types.append()
if not self.ffmpeg_normalize.subtitle_disable:
output_str... | Construct the second pass command and run it
FIXME: make this method simpler |
357,740 | def unregister(self, entity_class, entity):
EntityState.release(entity, self)
self.__entity_set_map[entity_class].remove(entity) | Unregisters the given entity for the given class and discards its
state information. |
357,741 | def _checkresponse(response):
r
results_error =
auth_error = \
rule_error = \
catch_error =
if response[][] == 1:
return response
elif response[][] == 2:
if response[][] == 0:
... | r""" Returns the data requested by the other methods assuming the response from the API is ok. If not, provides
error handling for all possible API errors. HTTP errors are handled in the get_response() function.
Arguments:
----------
None.
Returns:
--------
... |
357,742 | def get_network_ipv6(self, id_network):
if not is_valid_int_param(id_network):
raise InvalidParameterError(
u)
url = + str(id_network) +
code, xml = self.submit(None, , url)
return self.response(code, xml) | Get networkipv6
:param id_network: Identifier of the Network. Integer value and greater than zero.
:return: Following dictionary:
::
{'network': {'id': < id_networkIpv6 >,
'network_type': < id_tipo_rede >,
'ambiente_vip': < id_ambiente_viṕ >,
'vlan': <i... |
357,743 | def send_file(self,
path,
contents,
shutit_pexpect_child=None,
truncate=False,
note=None,
user=None,
echo=False,
group=None,
loglevel=logging.INFO,
encoding=None):
s... | Sends the passed-in string as a file to the passed-in path on the
target.
@param path: Target location of file on target.
@param contents: Contents of file as a string.
@param shutit_pexpect_child: See send()
@param note: See send()
@param user: Set ownership to this user (def... |
357,744 | def readline(self, max_len=-1):
buf = self._rbuf
newline, chunksize = self.NEWLINE, self.CHUNKSIZE
buf.seek(0)
text = buf.read()
if len(text) >= max_len >= 0:
buf.seek(0)
buf.truncate()
buf.write(text[max_len:])
return tex... | read from the file until a newline is encountered
.. note::
this method will block if there isn't already a full line available
from the data source
:param max_len: stop reading a single line after this many bytes
:type max_len: int
:returns:
a str... |
357,745 | def init(lang, domain):
translations_dir = _get_translations_dir()
domain = _get_translations_domain(domain)
pot = os.path.join(translations_dir, f)
return _run(f) | Initialize translations for a language code. |
357,746 | def tunnel(container, local_port, remote_port=None, gateway_port=None):
if remote_port is None:
remote_port = local_port
if gateway_port is None:
gateway_port = remote_port
remote_host = get_ip(container)
command = % {
: env.key_filename,
: local_port,
: g... | Set up an SSH tunnel into the container, using the host as a gateway host.
Args:
* container: Container name or ID
* local_port: Local port
* remote_port=None: Port on the Docker container (defaults to local_port)
* gateway_port=None: Port on the gateway host (defaults to remote_por... |
357,747 | def _send_command_wrapper(self, cmd):
cached_results = self._results_cache.get(cmd)
if not cached_results:
response = self._send_command(cmd)
self._results_cache[cmd] = response
return response
else:
return cached_results | Send command to the remote device with a caching feature to avoid sending the same command
twice based on the SSH_MAPPER_BASE dict cmd key.
Parameters
----------
cmd : str
The command to send to the remote device after checking cache.
Returns
-------
... |
357,748 | def touchstone_noise_data(obj):
r
if isinstance(obj, dict) and (not obj):
return None
if (not isinstance(obj, dict)) or (
isinstance(obj, dict)
and (sorted(obj.keys()) != sorted(["points", "freq", "nf", "rc", "res"]))
):
raise ValueError(pexdoc.pcontracts.get_exdesc())
... | r"""
Validate if an object is an :ref:`TouchstoneNoiseData` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by the name of the argument the
contract is attached to
:rtyp... |
357,749 | def adjust_positions(self, redraw=True):
checks = [self.view_positions, self.subaxes, self.subplots]
right = all( in check for check in checks)
top = all( in check for check in checks)
if not in self.subplots or not (top or right):
return
if redraw:
... | Make adjustments to the positions of subplots (if available)
relative to the main plot axes as required.
This method is called by LayoutPlot after an initial pass
used to position all the Layouts together. This method allows
LayoutPlots to make final adjustments to the axis positions. |
357,750 | def SIRode(y0, time, beta, gamma):
Xsim = rk4(SIR_D, y0, time, args=(beta,gamma,))
Xsim = Xsim.transpose()
return Xsim | Integrate SIR epidemic model
Simulate a very basic deterministic SIR system.
:param 2x1 numpy array y0: initial conditions
:param Ntimestep length numpy array time: Vector of time points that \
solution is returned at
:param float beta: transmission rate
:param float gamma: recovery rate
... |
357,751 | def format_ft_def(func, full_name:str=None)->str:
"Format and link `func` definition to show in documentation"
sig = inspect.signature(func)
name = f
fmt_params = [format_param(param) for name,param
in sig.parameters.items() if name not in (,)]
arg_str = f"({.join(fmt_params)})"
... | Format and link `func` definition to show in documentation |
357,752 | def print_plot_line(function, popt, xs, ys, name, tol=0.05, extra=):
idp = id_generator()
f = open(+str(idp), mode=)
for n in range(0, len(ys), 1):
f.write(str(xs[n]) + + str(ys[n]) + )
f.close()
tol = abs(tol)
line = "plot pointsize 4 lt 0, " % idp
line += % (popt[0], popt[0... | print the gnuplot command line to plot the x, y data with the fitted function using the popt parameters |
357,753 | def changeset(python_data: LdapObject, d: dict) -> Changeset:
table: LdapObjectClass = type(python_data)
fields = table.get_fields()
changes = Changeset(fields, src=python_data, d=d)
return changes | Generate changes object for ldap object. |
357,754 | def get_keys(self):
env = os.environ.get
if not self.consumer_key:
self.consumer_key = env()
if not self.consumer_secret:
self.consumer_secret = env()
if not self.access_token:
self.access_token = env()
if not self.access_token_secret:... | Get the Twitter API keys. Order of precedence is command line,
environment, config file. Return True if all the keys were found
and False if not. |
357,755 | def do_build(self, argv):
import SCons.Node
import SCons.SConsign
import SCons.Script.Main
options = copy.deepcopy(self.options)
options, targets = self.parser.parse_args(argv[1:], values=options)
SCons.Script.COMMAND_LINE_TARGETS = targets
if targets... | \
build [TARGETS] Build the specified TARGETS and their
dependencies. 'b' is a synonym. |
357,756 | def iter(self):
for _file in self._files:
with asHandle(_file) as fp:
for sequenceId, sequence, quality in FastqGeneralIterator(fp):
yield self.readClass(sequenceId, sequence, quality) | Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class. |
357,757 | def _delta_dir():
repo = Repo()
current_dir = os.getcwd()
repo_dir = repo.tree().abspath
delta_dir = current_dir.replace(repo_dir, )
if delta_dir:
return delta_dir +
else:
return | returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative path of the current dir ... |
357,758 | def get(cls, switch_service_payment_id,
note_attachment_bank_switch_service_netherlands_incoming_payment_id,
monetary_account_id=None, custom_headers=None):
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())... | :type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type switch_service_payment_id: int
:type
note_attachment_bank_switch_service_netherlands_incoming_payment_id: int
:type custom_headers: dict[str, str]|None
:rtype:
B... |
357,759 | def set_up_logging():
tf.logging.set_verbosity(tf.logging.INFO)
logging.getLogger().propagate = False | Configure the TensorFlow logger. |
357,760 | def configure_box(self, boxsize, root_nx=1, root_ny=1, root_nz=1):
clibrebound.reb_configure_box(byref(self), c_double(boxsize), c_int(root_nx), c_int(root_ny), c_int(root_nz))
return | Initialize the simulation box.
This function only needs to be called it boundary conditions other than "none"
are used. In such a case the boxsize must be known and is set with this function.
Parameters
----------
boxsize : float, optional
The size of one root box.
... |
357,761 | async def connect(self, *args, **kwargs):
await self.disconnect()
if not in kwargs and len(args) < 2:
if args and in kwargs:
raise TypeError()
elif args:
model_name = args[0]
else:
model_name = kwargs.pop(, No... | Connect to a juju model.
This supports two calling conventions:
The model and (optionally) authentication information can be taken
from the data files created by the Juju CLI. This convention will
be used if a ``model_name`` is specified, or if the ``endpoint``
and ``uuid`` ar... |
357,762 | def gedcom_lines(self, offset):
self._file.seek(offset)
prev_gline = None
while True:
offset = self._file.tell()
line = self._file.readline()
if not line:
break
line = line.lstrip().rstrip(b"\r\n")
match =... | Generator method for *gedcom lines*.
GEDCOM line grammar is defined in Chapter 1 of GEDCOM standard, it
consists of the level number, optional reference ID, tag name, and
optional value separated by spaces. Chaper 1 is pure grammar level,
it does not assign any semantics to tags or leve... |
357,763 | def chosen_angle_to_canonical_half_turns(
half_turns: Optional[Union[sympy.Basic, float]] = None,
rads: Optional[float] = None,
degs: Optional[float] = None,
default: float = 1.0,
) -> Union[sympy.Basic, float]:
return canonicalize_half_turns(
chosen_angle_to_half_tu... | Returns a canonicalized half_turns based on the given arguments.
At most one of half_turns, rads, degs must be specified. If none are
specified, the output defaults to half_turns=1.
Args:
half_turns: The number of half turns to rotate by.
rads: The number of radians to rotate by.
d... |
357,764 | def get_reqs(which="main"):
reqs = []
for req in all_reqs[which]:
req_str = req + ">=" + ver_tuple_to_str(min_versions[req])
if req in version_strictly:
req_str += ",<" + ver_tuple_to_str(min_versions[req][:-1]) + "." + str(min_versions[req][-1] + 1)
reqs.append(req_str)... | Gets requirements from all_reqs with versions. |
357,765 | def gene_names(self):
for record in SeqIO.parse(self.targets, ):
self.genes.append(record.id) | Extract the names of the user-supplied targets |
357,766 | def cartesianToSpherical(x, y, z):
rCylSq=x*x+y*y
r=sqrt(rCylSq+z*z)
if any(r==0.0):
raise Exception("Error: one or more of the points is at distance zero.")
phi = arctan2(y,x)
phi = where(phi<0.0, phi+2*pi, phi)
return r, phi, arctan2(z,sqrt(rCylSq)) | Convert Cartesian to spherical coordinates. The input can be scalars or 1-dimensional numpy arrays.
Note that the angle coordinates follow the astronomical convention of using elevation (declination,
latitude) rather than its complement (pi/2-elevation), which is commonly used in the mathematical
treatment of sph... |
357,767 | def result(self):
field = re.sub(REGEX_CLEANER, , self.field)
try:
value = float(self.value)
except TypeError:
value = "(%s)" % ( "".join(self.value) )
except ValueError:
value = str(self.value) \
.replace("\\", r"\\") ... | Construye la expresion |
357,768 | def heatmap(x, y, step=None, min_pt=None, max_pt=None,
colormap=, alpha=1, grid=False,
colorbar=True, scale=,
vmax=, vmin=, crop=True):
(x_vec, y_vec, hist_matrix) = calc_2d_hist(x, y, step, min_pt, max_pt)
if scale == :
for row in hist_matri... | function to take vectors x and y and hist them |
357,769 | def set_source(self, source_id):
if self.get_source_metadata().is_read_only():
raise errors.NoAccess()
if not self._is_valid_id(source_id):
raise errors.InvalidArgument()
self._my_map[] = str(source_id) | Sets the source.
arg: source_id (osid.id.Id): the new publisher
raise: InvalidArgument - ``source_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``source_id`` is ``null``
*compliance: mandatory -- This method must be implement... |
357,770 | def take_screen_shot_to_array(self, screen_id, width, height, bitmap_format):
if not isinstance(screen_id, baseinteger):
raise TypeError("screen_id can only be an instance of type baseinteger")
if not isinstance(width, baseinteger):
raise TypeError("width can only be an ... | Takes a guest screen shot of the requested size and format
and returns it as an array of bytes.
in screen_id of type int
The guest monitor to take screenshot from.
in width of type int
Desired image width.
in height of type int
Desired image height.... |
357,771 | def encode(self, encoding=None, errors=):
return ColorBytes(super(ColorStr, self).encode(encoding, errors), original_class=self.__class__) | Encode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as ... |
357,772 | def set_option(name, value):
old = get_option(name)
globals()[name] = value
return old | Set plydata option
Parameters
----------
name : str
Name of the option
value : object
New value of the option
Returns
-------
old : object
Old value of the option
See also
--------
:class:`options` |
357,773 | def register(self, recipe):
if not isinstance(recipe, (list, tuple)):
recipe = [recipe, ]
for item in recipe:
recipe = self.get_recipe_instance_from_class(item)
self._registry[recipe.slug] = recipe | Registers a new recipe class. |
357,774 | def extract_patches(images, patch_shape, samples_per_image=40, seed=0,
cycle=True):
rs = np.random.RandomState(seed)
for Xi in itr.cycle(images):
w, h = [Xi.shape[i]-patch_shape[i] for i in range(2)]
assert w > 0 and h > 0
indices = np.asarray... | Takes a set of images and yields randomly chosen patches of specified size.
Parameters
----------
images : iterable
The images have to be iterable, and each element must be a Numpy array
with at least two spatial 2 dimensions as the first and second axis.
patch_shape : tuple, length 2
... |
357,775 | def father(year=None):
june_first = datetime.date(_year, 6, 1) if not year else datetime.date(int(year), 6, 1)
weekday_seq = june_first.weekday()
return datetime.date(june_first.year, 6, (21 - weekday_seq)) | the 3rd Sunday in June
:param year: int
:return: Father's day |
357,776 | def setgraphval(delta, graph, key, val):
delta.setdefault(graph, {})[key] = val | Change a delta to say that a graph stat was set to a certain value |
357,777 | def summary(self):
if self.features is not None:
feature_count = len(self.features)
else:
feature_count = 0
feature_hash = + str(hash(tuple(self.features)))
return (str(self.estimator), feature_count, feature_hash, self.target) | Summary of model definition for labeling. Intended to be somewhat
readable but unique to a given model definition. |
357,778 | def MI_associators(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole,
propertyList):
logger... | Return instances associated to a given object.
Implements the WBEM operation Associators in terms
of the references method. A derived class will not normally
override this method. |
357,779 | def add_report(self, report, ignore_errors=False):
if not isinstance(report, SignedListReport):
if ignore_errors:
return
raise ArgumentError("You can only add SignedListReports to a UTCAssigner", report=report)
for reading in report.visible_readings:
... | Add all anchors from a report. |
357,780 | def _get_fashion_mnist(directory):
for filename in [
_MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME,
_MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME
]:
generator_utils.maybe_download(directory,
_FASHION_MNIST_LOCAL_FILE_PREFIX + filename,
... | Download all FashionMNIST files to directory unless they are there. |
357,781 | def _get_db_table(self, data_path, extension):
raise NotImplementedError, "SQL and db file formats not yet supported"
if extension == :
con = lite.connect()
con.row_factory = lite.Row
cur = con.cursor()
with open(data_path, ) a... | Query a database and return query result as a recarray
Parameters
----------
data_path : str
Path to the database file
extension : str
Type of database, either sql or db
Returns
-------
table : recarray
The database query as a... |
357,782 | def load_all(self):
try:
self.toi.load_all()
self.rosters.load_all()
self.play_by_play.load_all()
self.face_off_comp.load_all()
return self
except Exception as e:
print(e)
return None | Force all reports to be loaded and parsed instead of lazy loading on demand.
:returns: ``self`` or ``None`` if load fails |
357,783 | def strip_units_from_lines(lines):
for line in lines:
for unit in ALL_UNITS:
if line.endswith(" %s" % unit):
line = line[:-1-len(unit)]
yield line | Removes all units from the ends of the lines. |
357,784 | def xlim(self, low, high):
self.chart[][0][] = low
self.chart[][0][] = high
return self | Set xaxis limits
Parameters
----------
low : number
high : number
Returns
-------
Chart |
357,785 | def _merge_single_runs(self, other_trajectory, used_runs):
count = len(self)
run_indices = range(len(other_trajectory))
run_name_dict = OrderedDict()
to_store_groups_with_annotations = []
for idx in run_indices:
if idx... | Updates the `run_information` of the current trajectory. |
357,786 | def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding=, default=None, sort_keys=False, **kw):
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent i... | Serialize ``obj`` as a DSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If `... |
357,787 | def patch_sys_version():
if in sys.version:
sys_version = sys.version.split()
sys.version = .join([sys_version[0].strip(), sys_version[-1].strip()]) | Remove Continuum copyright statement to avoid parsing errors in IDLE |
357,788 | def terminal_cfg_line_sessionid(self, **kwargs):
config = ET.Element("config")
terminal_cfg = ET.SubElement(config, "terminal-cfg", xmlns="urn:brocade.com:mgmt:brocade-terminal")
line = ET.SubElement(terminal_cfg, "line")
sessionid = ET.SubElement(line, "sessionid")
sess... | Auto Generated Code |
357,789 | def get_sources(arxiv_id):
try:
request = requests.get(ARXIV_EPRINT_URL.format(arxiv_id=arxiv_id))
request.raise_for_status()
file_object = io.BytesIO(request.content)
return tarfile.open(fileobj=file_object)
except (RequestException, AssertionError, tarfile.TarError):
... | Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in a \
canonical... |
357,790 | def _parse_btrfs_info(data):
ret = {}
for line in [line for line in data.split("\n") if line][:-1]:
if line.startswith("Label:"):
line = re.sub(r"Label:\s+", "", line)
label, uuid_ = [tkn.strip() for tkn in line.split("uuid:")]
ret[] = label != and label or None... | Parse BTRFS device info data. |
357,791 | def _split_docker_uuid(uuid):
if uuid:
uuid = uuid.split()
if len(uuid) == 2:
tag = uuid[1]
repo = uuid[0]
return repo, tag
return None, None | Split a smartos docker uuid into repo and tag |
357,792 | def phasedlc_features(times,
mags,
errs,
period,
nbrtimes=None,
nbrmags=None,
nbrerrs=None):
s closest neighbor
(close within some small number x FWHM of telescope to check for... | This calculates various phased LC features for the object.
Some of the features calculated here come from:
Kim, D.-W., Protopapas, P., Bailer-Jones, C. A. L., et al. 2014, Astronomy
and Astrophysics, 566, A43, and references therein (especially Richards, et
al. 2011).
Parameters
----------
... |
357,793 | def _add_observation_to_variances(self, xj, yj):
term1 = (self.window_size + 1.0) / self.window_size * (xj - self._mean_x_in_window)
self._covariance_in_window += term1 * (yj - self._mean_y_in_window)
self._variance_in_window += term1 * (xj - self._mean_x_in_window) | Quickly update the variance and co-variance for the addition of one observation.
See Also
--------
_update_variance_in_window : compute variance considering full window |
357,794 | def decompose(S, n_components=None, transformer=None, sort=False, fit=True, **kwargs):
if transformer is None:
if fit is False:
raise ParameterError()
transformer = sklearn.decomposition.NMF(n_components=n_components,
**kwargs)
... | Decompose a feature matrix.
Given a spectrogram `S`, produce a decomposition into `components`
and `activations` such that `S ~= components.dot(activations)`.
By default, this is done with with non-negative matrix factorization (NMF),
but any `sklearn.decomposition`-type object will work.
Parame... |
357,795 | def __write_pub(self):
try:
self.__reorganize_author()
self.__rm_duplicate_citation_1()
if not self.noaa_data_sorted["Publication"]:
self.noaa_data_sorted["Publication"].append({"pubYear": ""})
for idx, pub in enumerate(self.n... | Write pub section. There may be multiple, so write a generic section for each one.
:return none: |
357,796 | def add_event(self, event):
assert event.dep_time_ut <= event.arr_time_ut
heappush(self.heap, event) | Add an event to the heap/priority queue
Parameters
----------
event : Event |
357,797 | def get_operation(self, operation_name, project_id=None):
return self.get_client().get_operation(project_id=project_id or self.project_id,
zone=self.location,
operation_id=operation_name) | Fetches the operation from Google Cloud
:param operation_name: Name of operation to fetch
:type operation_name: str
:param project_id: Google Cloud Platform project ID
:type project_id: str
:return: The new, updated operation from Google Cloud |
357,798 | def get_directories(
self, directory: str = None, packages: typing.List[str] = None
) -> typing.List[str]:
directories = []
if directory is not None:
directories.append(directory)
for package in packages or []:
spec = importlib.util.find_spec(package... | Given `directory` and `packages` arugments, return a list of all the
directories that should be used for serving static files from. |
357,799 | def symbolic(self, e):
if type(e) in (int, bytes, float, bool):
return False
return e.symbolic | Returns True if the expression `e` is symbolic. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.