Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
381,300 | def threshold_img(data, threshold, mask=None, mask_out=):
if mask is not None:
mask = threshold_img(mask, threshold, mask_out=mask_out)
return data * mask.astype(bool)
if mask_out.startswith():
data[data < threshold] = 0
elif mask_out.startswith():
data[data > threshold]... | Threshold data, setting all values in the array above/below threshold
to zero.
Args:
data (ndarray): The image data to threshold.
threshold (float): Numeric threshold to apply to image.
mask (ndarray): Optional 1D-array with the same length as the data. If
passed, the thresho... |
381,301 | def devices(self):
devices = None
with self.socket.Connect():
devices = self._command("host:devices")
return parse_device_list(devices) | Return a list of connected devices in the form (*serial*, *status*) where status can
be any of the following:
1. device
2. offline
3. unauthorized
:returns: A list of tuples representing connected devices |
381,302 | def _get_griddistrict(ding0_filepath):
grid_district = os.path.basename(ding0_filepath)
grid_district_search = re.search(, grid_district)
if grid_district_search:
grid_district = int(grid_district_search.group(0)[2:])
return grid_district
else:
raise (KeyError(.format(grid_d... | Just get the grid district number from ding0 data file path
Parameters
----------
ding0_filepath : str
Path to ding0 data ending typically
`/path/to/ding0_data/"ding0_grids__" + str(``grid_district``) + ".xxx"`
Returns
-------
int
grid_district number |
381,303 | def validate_scopes(self, client_id, scopes, client, request,
*args, **kwargs):
if hasattr(client, ):
return client.validate_scopes(scopes)
return set(client.default_scopes).issuperset(set(scopes)) | Ensure the client is authorized access to requested scopes. |
381,304 | def create_spot_instances(ec2, price, image_id, spec, num_instances=1, timeout=None, tentative=False, tags=None):
def spotRequestNotFound(e):
return e.error_code == "InvalidSpotInstanceRequestID.NotFound"
for attempt in retry_ec2(retry_for=a_long_time,
retry_while=inco... | :rtype: Iterator[list[Instance]] |
381,305 | def as_dict(self):
return {
"destination": self.destination,
"packet_transmit": self.packet_transmit,
"packet_receive": self.packet_receive,
"packet_loss_count": self.packet_loss_count,
"packet_loss_rate": self.packet_loss_rate,
"... | ping statistics.
Returns:
|dict|:
Examples:
>>> import pingparsing
>>> parser = pingparsing.PingParsing()
>>> parser.parse(ping_result)
>>> parser.as_dict()
{
"destination": "google.com",
"packet_tr... |
381,306 | def disable(self):
self.ticker_text_label.hide()
if self.current_observed_sm_m:
self.stop_sm_m_observation(self.current_observed_sm_m) | Relieve all state machines that have no active execution and hide the widget |
381,307 | def add_api_compression(self, api_id, min_compression_size):
self.apigateway_client.update_rest_api(
restApiId=api_id,
patchOperations=[
{
: ,
: ,
: str(min_compression_size)
}
... | Add Rest API compression |
381,308 | def _profile(self, frame, event, arg):
if event.startswith():
return
time1 = self.timer()
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.... | The callback function to register by :func:`sys.setprofile`. |
381,309 | def unmount(self, client):
getattr(client, self.unmount_fun)(mount_point=self.path) | Unmounts a backend within Vault |
381,310 | def check_version(server, version, filename, timeout=SHORT_TIMEOUT):
address = VERSION_ENDPOINT.format(server=server)
print()
log.info(, version)
log.info(, address)
try:
response = requests.get(address, timeout=timeout)
response.raise_for_status()
except (requests.except... | Check for the latest version of OK and update accordingly. |
381,311 | def _stinespring_to_choi(data, input_dim, output_dim):
trace_dim = data[0].shape[0] // output_dim
stine_l = np.reshape(data[0], (output_dim, trace_dim, input_dim))
if data[1] is None:
stine_r = stine_l
else:
stine_r = np.reshape(data[1], (output_dim, trace_dim, input_dim))
retur... | Transform Stinespring representation to Choi representation. |
381,312 | def _cdf(self, xloc, left, right, cache):
left = evaluation.get_forward_cache(left, cache)
right = evaluation.get_forward_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise evaluation.DependencyError(
"under-... | Cumulative distribution function.
Example:
>>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0.5 1. 1. ]
>>> print(chaospy.Add(chaospy.Uniform(), 1).fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0. 0.5 1. ]
>>> print(chaospy.Add(1, chaospy.Uniform()).... |
381,313 | def dup_idx(arr):
_, b = np.unique(arr, return_inverse=True)
return np.nonzero(np.logical_or.reduce(
b[:, np.newaxis] == np.nonzero(np.bincount(b) > 1),
axis=1))[0] | Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Examples
--------
>>> from root_numpy import dup_idx... |
381,314 | def get_feature_sequence(self, feature_id, organism=None, sequence=None):
data = {
: ,
: [
{: feature_id}
]
}
data = self._update_data(data, organism, sequence)
return self.post(, data) | [CURRENTLY BROKEN] Get the sequence of a feature
:type feature_id: str
:param feature_id: Feature UUID
:type organism: str
:param organism: Organism Common Name
:type sequence: str
:param sequence: Sequence Name
:rtype: dict
:return: A standard apollo ... |
381,315 | def SelfReferenceProperty(label=None, collection_name=None, **attrs):
if in attrs:
raise ConfigurationError(
)
return ReferenceProperty(_SELF_REFERENCE, label, collection_name, **attrs) | Create a self reference. |
381,316 | def update(self):
self._tmpdir = tempfile.mkdtemp()
try:
self._rebase_file = self._tmpdir +
print
url =
header = {: }
req = urllib2.Request(url, headers=header)
con = urllib2.urlopen(req)
with open(s... | Update definitions. |
381,317 | def mktmp(self):
try:
if not os.path.isdir(self.location):
os.makedirs(self.location)
except:
log.debug(self.location, exc_info=1)
return self | Make the I{location} directory if it doesn't already exits. |
381,318 | def _call_variants_samtools(align_bams, ref_file, items, target_regions, tx_out_file):
config = items[0]["config"]
mpileup = prep_mpileup(align_bams, ref_file, config,
target_regions=target_regions, want_bcf=True)
bcftools = config_utils.get_program("bcftools", config)
sa... | Call variants with samtools in target_regions.
Works around a GATK VCF 4.2 compatibility issue in samtools 1.0
by removing addition 4.2-only isms from VCF header lines. |
381,319 | def action_create(self, courseid, taskid, path):
path = path.strip()
if not path.startswith("/"):
path = "/" + path
want_directory = path.endswith("/")
wanted_path = self.verify_path(courseid, taskid, path, True)
if wanted_path is None:
... | Delete a file or a directory |
381,320 | def set_device_name(self, newname):
return self.write(request.SetDeviceName(self.seq, *self.prep_str(newname))) | Sets internal device name. (not announced bluetooth name).
requires utf-8 encoded string. |
381,321 | def construct_rest_of_worlds(self, excluded, fp=None, use_mp=True, simplify=True):
geoms = {}
raw_data = []
for key in sorted(excluded):
locations = excluded[key]
for location in locations:
assert location in self.locations, "Can't find location {... | Construct many rest-of-world geometries and optionally write to filepath ``fp``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``. |
381,322 | def parse_qtype(self, param_type, param_value):
if param_type == :
return self._parse_quniform(param_value)
if param_type == :
param_value[:2] = np.log(param_value[:2])
return list(np.exp(self._parse_quniform(param_value)))
raise RuntimeError("Not su... | parse type of quniform or qloguniform |
381,323 | def _integrate_scipy(self, intern_xout, intern_y0, intern_p,
atol=1e-8, rtol=1e-8, first_step=None, with_jacobian=None,
force_predefined=False, name=None, **kwargs):
from scipy.integrate import ode
ny = intern_y0.shape[-1]
nx = intern_xo... | Do not use directly (use ``integrate('scipy', ...)``).
Uses `scipy.integrate.ode <http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html>`_
Parameters
----------
\*args :
See :meth:`integrate`.
name : str (default: 'lsoda'/'dopri5' when jacobia... |
381,324 | def from_dict(config):
return ProxyConfig(
http=config.get(),
https=config.get(),
ftp=config.get(),
no_proxy=config.get(),
) | Instantiate a new ProxyConfig from a dictionary that represents a
client configuration, as described in `the documentation`_.
.. _the documentation:
https://docs.docker.com/network/proxy/#configure-the-docker-client |
381,325 | def set_value(self, value: datetime):
assert isinstance(value, datetime)
self.value = value | Sets the current value |
381,326 | def absent(name, orgname=None, profile=):
grafana
if isinstance(profile, string_types):
profile = __salt__[](profile)
ret = {: name, : None, : None, : {}}
datasource = __salt__[](name, orgname, profile)
if not datasource:
ret[] = True
ret[] = .format(name)
return re... | Ensure that a data source is present.
name
Name of the data source to remove.
orgname
Name of the organization from which the data source should be absent.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'. |
381,327 | def plot(self,
resolution_constant_regions=20,
resolution_smooth_regions=200):
if self.eps == 0:
x = []; y = []
for I, value in zip(self._indicator_functions, self._values):
x.append(I.L)
y.append(value)
x... | Return arrays x, y for plotting the piecewise constant function.
Just the minimum number of straight lines are returned if
``eps=0``, otherwise `resolution_constant_regions` plotting intervals
are insed in the constant regions with `resolution_smooth_regions`
plotting intervals in the sm... |
381,328 | def trim_sparse(M, n_std=3, s_min=None, s_max=None):
try:
from scipy.sparse import coo_matrix
except ImportError as e:
print(str(e))
print("I am peforming dense normalization by default.")
return trim_dense(M.todense())
r = M.tocoo()
sparsity = np.array(r.sum(axis=1... | Apply the trimming procedure to a sparse matrix. |
381,329 | def main():
parser = arg_parser(usage=)
parser.add_option(, , type=, default=10,
help=
)
parser.add_option(, , action=,
help=(
))
parser.add_option... | Provide the entry point to the subreddit_stats command. |
381,330 | def create_encoder_config(args: argparse.Namespace,
max_seq_len_source: int,
max_seq_len_target: int,
config_conv: Optional[encoder.ConvolutionalEmbeddingConfig],
num_embed_source: int) -> Tuple[encoder.EncoderConfig... | Create the encoder config.
:param args: Arguments as returned by argparse.
:param max_seq_len_source: Maximum source sequence length.
:param max_seq_len_target: Maximum target sequence length.
:param config_conv: The config for the convolutional encoder (optional).
:param num_embed_source: The size... |
381,331 | def adjustReplicas(self,
old_required_number_of_instances: int,
new_required_number_of_instances: int):
replica_num = old_required_number_of_instances
while replica_num < new_required_number_of_instances:
self.replicas.add_repli... | Add or remove replicas depending on `f` |
381,332 | def InitFromHuntObject(self,
hunt_obj,
hunt_counters=None,
with_full_summary=False):
self.urn = rdfvalue.RDFURN("hunts").Add(str(hunt_obj.hunt_id))
self.hunt_id = hunt_obj.hunt_id
if (hunt_obj.args.hunt_type ==
rdf_hunt... | Initialize API hunt object from a database hunt object.
Args:
hunt_obj: rdf_hunt_objects.Hunt to read the data from.
hunt_counters: Optional db.HuntCounters object with counters information.
with_full_summary: if True, hunt_runner_args, completion counts and a few
other fields will be fil... |
381,333 | def run_single(workflow, *, registry, db_file, always_cache=True):
with JobDB(db_file, registry) as db:
job_logger = make_logger("worker", push_map, db)
result_logger = make_logger("worker", pull_map, db)
@pull
def pass_job(source):
for msg in source():... | Run workflow in a single thread, storing results in a Sqlite3
database.
:param workflow: Workflow or PromisedObject to be evaluated.
:param registry: serialization Registry function.
:param db_file: filename of Sqlite3 database, give `':memory:'` to
keep the database in memory only.
:param ... |
381,334 | def shape(self):
if len(self) == 0:
return ()
elif self.is_power_space:
try:
sub_shape = self[0].shape
except AttributeError:
sub_shape = ()
else:
sub_shape = ()
return (len(self),) + sub_shape | Total spaces per axis, computed recursively.
The recursion ends at the fist level that does not have a shape.
Examples
--------
>>> r2, r3 = odl.rn(2), odl.rn(3)
>>> pspace = odl.ProductSpace(r2, r3)
>>> pspace.shape
(2,)
>>> pspace2 = odl.ProductSpace(p... |
381,335 | def close(self):
if self._image is None:
return
empty_image = fits.HDUList()
for u in self._image:
empty_image.append(u.__class__(data=None, header=None))
self._image.close()
self._image = empty_image | Close the object nicely and release all the data
arrays from memory YOU CANT GET IT BACK, the pointers
and data are gone so use the getData method to get
the data array returned for future use. You can use
putData to reattach a new data array to the imageObject. |
381,336 | def list_of_mined(cls):
result = []
if PyFunceble.CONFIGURATION["mining"]:
if PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["mined"]:
for element in PyFunceble.INTERN["mined"][
PyFunceble.INTERN[... | Provide the list of mined so they can be added to the list
queue.
:return: The list of mined domains or URL.
:rtype: list |
381,337 | def render(self, container, descender, state, space_below=0,
first_line_only=False):
indent_first = (float(self.get_style(, container))
if state.initial else 0)
line_width = float(container.width)
line_spacing = self.get_style(, container)
... | Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting the
rest of the paragraph when this method is called with a n... |
381,338 | def get_example(cls) -> list:
if cls.example is not None:
return cls.example
if cls.items is not None:
if isinstance(cls.items, list):
return [item.get_example() for item in cls.items]
else:
return [cls.items.get_example()]
... | Returns an example value for the Array type.
If an example isn't a defined attribute on the class we return
a list of 1 item containing the example value of the `items` attribute.
If `items` is None we simply return a `[1]`. |
381,339 | def _flush(self, close=False):
for channel in self.forward_channels:
if close is True:
channel.queue.put_next(None)
channel.queue._flush_writes()
for channels in self.shuffle_channels:
for channel in channels:
if close is True:... | Flushes remaining output records in the output queues to plasma.
None is used as special type of record that is propagated from sources
to sink to notify that the end of data in a stream.
Attributes:
close (bool): A flag denoting whether the channel should be
also mar... |
381,340 | def put(self, message):
return self.connection.put(, data=dict(message=message)) | Simply test Put a string
:param message: str of the message
:return: str of the message |
381,341 | def expand(data):
namejohnversionv1namejohnversionv2namelisaversionv1namelisaversionv2ll iterate over it for every possible
combination of elements in the lists. If the element in question is not a
list, then it is considered unique and repeated for each yielded
configuration set. Example
.. code-block:: yam... | Generates configuration sets based on the YAML input contents
For an introduction to the YAML mark-up, just search the net. Here is one of
its references: https://en.wikipedia.org/wiki/YAML
A configuration set corresponds to settings for **all** variables in the
input template that needs replacing. For exampl... |
381,342 | def diffusion_coeff_counts(self):
return [(key, len(list(group)))
for key, group in itertools.groupby(self.diffusion_coeff)] | List of tuples of (diffusion coefficient, counts) pairs.
The order of the diffusion coefficients is as in self.diffusion_coeff. |
381,343 | def getLayout(self, algorithmName, verbose=None):
response=api(url=self.___url++str(algorithmName)+, method="H", verbose=verbose, parse_params=False)
return response | Returns all the details, including names, parameters, and compatible column types for the Layout algorithm specified by the `algorithmName` parameter.
:param algorithmName: Name of the Layout algorithm
:param verbose: print more
:returns: 200: successful operation |
381,344 | def FromJsonString(self, value):
timezone_offset = value.find()
if timezone_offset == -1:
timezone_offset = value.find()
if timezone_offset == -1:
timezone_offset = value.rfind()
if timezone_offset == -1:
raise ParseError(
)
time_value = value[0:timezone_offset]
... | Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
Raises:
ParseError: On parsing ... |
381,345 | def cli(ctx, resource):
log = logging.getLogger()
assert isinstance(ctx, Context)
resource = str(resource).lower()
if resource == :
resource = IpsManager(ctx)
for r in resource.versions.values():
click.secho(r.version.vstring, bold=True)
return
if resource... | Displays all locally cached <resource> versions available for installation.
\b
Available resources:
ips (default)
dev_tools |
381,346 | def update_user_type(self):
if self.rb_tutor.isChecked():
self.user_type =
elif self.rb_student.isChecked():
self.user_type =
self.accept() | Return either 'tutor' or 'student' based on which radio
button is selected. |
381,347 | def preferred_height(self, cli, width, max_available_height, wrap_lines):
complete_state = cli.current_buffer.complete_state
column_width = self._get_column_width(complete_state)
column_count = max(1, (width - self._required_margin) // column_width)
return int(math.ceil(len(com... | Preferred height: as much as needed in order to display all the completions. |
381,348 | def _get_default(self, obj):
if self.name in obj._property_values:
raise RuntimeError("Bokeh internal error, does not handle the case of self.name already in _property_values")
is_themed = obj.themed_values() is not None and self.name in obj.themed_values()
de... | Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc. |
381,349 | def doDirectPayment(self, params):
defaults = {"method": "DoDirectPayment", "paymentaction": "Sale"}
required = ["creditcardtype",
"acct",
"expdate",
"cvv2",
"ipaddress",
"firstname",
... | Call PayPal DoDirectPayment method. |
381,350 | def process(self):
print(.format(len(self.file_path_list)))
print(.format(self.file_path_list))
hunt_action = flows_pb2.FileFinderAction(
action_type=flows_pb2.FileFinderAction.DOWNLOAD)
hunt_args = flows_pb2.FileFinderArgs(
paths=self.file_path_list, action=hunt_action)
return ... | Construct and start a new File hunt.
Returns:
The newly created GRR hunt object.
Raises:
RuntimeError: if no items specified for collection. |
381,351 | def get_poll(self, arg, *, request_policy=None):
if isinstance(arg, str):
match = self._url_re.match(arg)
if match:
arg = match.group()
return self._http_client.get(.format(self._POLLS, arg),
request_poli... | Retrieves a poll from strawpoll.
:param arg: Either the ID of the poll or its strawpoll url.
:param request_policy: Overrides :attr:`API.requests_policy` for that \
request.
:type request_policy: Optional[:class:`RequestsPolicy`]
:raises HTTPException: Requesting the poll faile... |
381,352 | def get_last_config_update_time_output_last_config_update_time(self, **kwargs):
config = ET.Element("config")
get_last_config_update_time = ET.Element("get_last_config_update_time")
config = get_last_config_update_time
output = ET.SubElement(get_last_config_update_time, "output"... | Auto Generated Code |
381,353 | def h_kinetic(T, P, MW, Hvap, f=1):
r
return (2*f)/(2-f)*(MW/(1000*2*pi*R*T))**0.5*(Hvap**2*P*MW)/(1000*R*T**2) | r'''Calculates heat transfer coefficient for condensation
of a pure chemical inside a vertical tube or tube bundle, as presented in
[2]_ according to [1]_.
.. math::
h = \left(\frac{2f}{2-f}\right)\left(\frac{MW}{1000\cdot 2\pi R T}
\right)^{0.5}\left(\frac{H_{vap}^2 P \cdot MW}{1000\cdot R... |
381,354 | def graph_from_voxels(fg_markers,
bg_markers,
regional_term = False,
boundary_term = False,
regional_term_args = False,
boundary_term_args = False):
logger = Logger.getInstance()
... | Create a graph-cut ready graph to segment a nD image using the voxel neighbourhood.
Create a `~medpy.graphcut.maxflow.GraphDouble` object for all voxels of an image with a
:math:`ndim * 2` neighbourhood.
Every voxel of the image is regarded as a node. They are connected to their immediate
neig... |
381,355 | def source_filename(self, docname: str, srcdir: str):
docpath = Path(srcdir, docname)
parent = docpath.parent
imgpath = parent.joinpath(self.filename)
if not imgpath.exists():
msg = f
raise SphinxError(msg)
return imgpath | Get the full filename to referenced image |
381,356 | def settings_system_update(self, data):
data["auth_password"] = self._password
response = self._put(url.settings_system, body=data)
self._check_response(response, 200) | Set system settings. Uses PUT to /settings/system interface
:Args:
* *data*: (dict) Settings dictionary as specified `here <https://cloud.knuverse.com/docs/api/#api-System_Settings-Set_System_Settings>`_.
:Returns: None |
381,357 | def state_by_node2state_by_state(tpm):
tpm = np.array(tpm)
tpm = to_multidimensional(tpm)
N = tpm.shape[-1]
S = 2**N
sbs_tpm = np.zeros((S, S))
if not np.any(np.logical_and(tpm < 1, tpm > 0)):
for previous_state_index in range(S):
... | Convert a state-by-node TPM to a state-by-state TPM.
.. important::
A nondeterministic state-by-node TPM can have more than one
representation as a state-by-state TPM. However, the mapping can be
made to be one-to-one if we assume the TPMs to be conditionally
independent. Therefore,... |
381,358 | def exception(self, e):
self.logged_exception(e)
self.logger.exception(e) | Log an error messsage.
:param e: Exception to log. |
381,359 | def sync_header_chain(cls, path, bitcoind_server, last_block_id ):
current_block_id = SPVClient.height( path )
if current_block_id is None:
assert USE_TESTNET
current_block_id = -1
assert (current_block_id >= 0 and USE_MAINNET) or USE_TESTNET
if current... | Synchronize our local block headers up to the last block ID given.
@last_block_id is *inclusive*
@bitcoind_server is host:port or just host |
381,360 | def _set_time_property(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=time_property.time_property, is_container=, presence=False, yang_name="time-property", rest_name="time-property", parent=self, path_helper=self._path_helper, extmethods=self._extme... | Setter method for time_property, mapped from YANG variable /ptp_state/time_property (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_time_property is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._s... |
381,361 | def _onMouseWheel(self, evt):
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
delta = evt.GetWheelDelta()
rotation = evt.GetWheelRotation()
rate = evt.GetLinesPerAction()
step = rate*float(rotation)/delta
evt... | Translate mouse wheel events into matplotlib events |
381,362 | def get_all_chains(self):
return [self.get_chain(i) for i in range(len(self.leaves))] | Assemble and return a list of all chains for all leaf nodes to the merkle root. |
381,363 | def from_string(cls, string, *, default_func=None):
if not isinstance(string, str):
raise TypeError(f)
parts = string.split(, 1)
if len(parts) == 2:
protocol, address = parts
else:
item, = parts
protocol = None
if defa... | Construct a Service from a string.
If default_func is provided and any ServicePart is missing, it is called with
default_func(protocol, part) to obtain the missing part. |
381,364 | def asset_view_atype(self, ):
if not self.cur_asset:
return
atype = self.cur_asset.atype
self.view_atype(atype) | View the project of the current atype
:returns: None
:rtype: None
:raises: None |
381,365 | def delete_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
tenant_name = fw_dict.get()
ret = self._delete_service_nwk(tenant_id, tenant_name, )
if ret:
res = fw_const.DCNM_OUT_NETWORK_DEL_SUCCESS
LOG.info("out Service network deleted for tenant %s",
... | Delete the DCNM OUT network and update the result. |
381,366 | def __add_item(self, item, keys=None):
if(not keys or not len(keys)):
raise Exception(
% (self.__class__.__name__, str(item)))
direct_key = tuple(keys)
for key in keys:
key_type = str(type(key))
if(no... | Internal method to add an item to the multi-key dictionary |
381,367 | def get_plugin(cls, name=None, **kwargs):
if isinstance(name, KurtPlugin):
return name
if in kwargs:
kwargs[] = kwargs[].lower()
if name:
kwargs["name"] = name
if not kwargs:
raise ValueError, "No arguments"
for plugin i... | Returns the first format plugin whose attributes match kwargs.
For example::
get_plugin(extension="scratch14")
Will return the :class:`KurtPlugin` whose :attr:`extension
<KurtPlugin.extension>` attribute is ``"scratch14"``.
The :attr:`name <KurtPlugin.name>` is used as th... |
381,368 | def getid(self, idtype):
memorable_id = None
while memorable_id in self._ids:
l=[]
for _ in range(4):
l.append(str(randint(0, 19)))
memorable_id = .join(l)
self._ids.append(memorable_id)
return idtype + + memorable_id | idtype in Uniq constants |
381,369 | def gather_layer_info(self):
for i in range(len(self.cc[0])):
layer_radii = [x[i].tags[] for x in self.cc]
self.radii_layers.append(layer_radii)
layer_alpha = [x[i].tags[] for x in self.cc]
self.alpha_layers.append(layer_alpha)
layer_ca = [x[i... | Extracts the tagged coiled-coil parameters for each layer. |
381,370 | def authentication_required(meth):
def check(cls, *args, **kwargs):
if cls.authenticated:
return meth(cls, *args, **kwargs)
raise Error("Authentication required")
return check | Simple class method decorator.
Checks if the client is currently connected.
:param meth: the original called method |
381,371 | def make_data():
a = { (1,1):.25, (1,2):.15, (1,3):.2,
(2,1):.3, (2,2):.3, (2,3):.1,
(3,1):.15, (3,2):.65, (3,3):.05,
(4,1):.1, (4,2):.05, (4,3):.8
}
epsilon = 0.01
I,p = multidict({1:5, 2:6, 3:8, 4:20})
K,LB = multidict({1:.2, 2:.3, 3:.2})
return I,K... | creates example data set |
381,372 | def apply(self, data_source):
dataframe = self.__get_dataframe(data_source, use_target=False)
dataframe = self.__cleaner.apply(dataframe)
dataframe = self.__transformer.apply(dataframe)
return dataframe | Called with the predict data (new information).
@param data_source: Either a pandas.DataFrame or a file-like object. |
381,373 | def implemented(cls, for_type):
for function in cls.required():
if not function.implemented_for_type(for_type):
raise TypeError(
"%r doesn't implement %r so it cannot participate in "
"the protocol %r." %
(for_type... | Assert that protocol 'cls' is implemented for type 'for_type'.
This will cause 'for_type' to be registered with the protocol 'cls'.
Subsequently, protocol.isa(for_type, cls) will return True, as will
isinstance, issubclass and others.
Raises:
TypeError if 'for_type' doesn't... |
381,374 | def get_api_link(self):
url = self._api_link
if url:
qs = self.get_qs()
url = "%s?type=choices" % url
if qs:
url = "%s&%s" % (url, u.join([u % (k, urllib.quote(unicode(v).encode())) \
... | Adds a query string to the api url. At minimum adds the type=choices
argument so that the return format is json. Any other filtering
arguments calculated by the `get_qs` method are then added to the
url. It is up to the destination url to respect them as filters. |
381,375 | def get_tac_permissions(calendar_id):
return _process_get_perm_resp(
get_permissions_url,
post_tac_resource(get_permissions_url,
_create_get_perm_body(calendar_id)),
TrumbaCalendar.TAC_CAMPUS_CODE,
calendar_id) | Return a list of sorted Permission objects representing
the user permissions of a given Tacoma calendar.
:return: a list of trumba.Permission objects
corresponding to the given campus calendar.
None if error, [] if not exists
raise DataFailureException or a corresponding TrumbaExce... |
381,376 | def _adjacent_tri(self, edge, i):
if not np.isscalar(i):
i = [x for x in i if x not in edge][0]
try:
pt1 = self._edges_lookup[edge]
pt2 = self._edges_lookup[(edge[1], edge[0])]
except KeyError:
return None
if pt1 == i... | Given a triangle formed by edge and i, return the triangle that shares
edge. *i* may be either a point or the entire triangle. |
381,377 | def injector_gear_2_json(self):
LOGGER.debug("InjectorCachedGear.injector_gear_2_json")
json_obj = {
: self.id,
: self.name,
: self.admin_queue,
: self.description,
: if self.running else
}
return json_obj | transform this local object to JSON.
:return: the JSON from this local object |
381,378 | def get_property(obj, name):
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
try:
for property_name in dir(obj):
i... | Gets value of object property specified by its name.
:param obj: an object to read property from.
:param name: a name of the property to get.
:return: the property value or null if property doesn't exist or introspection failed. |
381,379 | def apply_filters(self, filters):
_configs = self.configs
_stats = self.stats
self.configs = {}
self.stats = {}
for f in filters:
if f in _configs:
self.configs[f] = _configs[f]
elif f in _stats:
self.stats[f] = _st... | It applies a specified filters. The filters are used to reduce the control groups
which are accessed by get_confgs, get_stats, and get_defaults methods. |
381,380 | def sun_declination(day):
day_of_year = day.toordinal() - date(day.year, 1, 1).toordinal()
day_angle = 2 * pi * day_of_year / 365
declination_radians = sum([
0.006918,
0.001480*sin(3*day_angle),
0.070257*sin(day_angle),
0.000907*sin(2*day_angle),
-0.399912*cos(da... | Compute the declination angle of the sun for the given date.
Uses the Spencer Formula
(found at http://www.illustratingshadows.com/www-formulae-collection.pdf)
:param day: The datetime.date to compute the declination angle for
:returns: The angle, in degrees, of the angle of declination |
381,381 | def send_video_note(chat_id, video_note,
duration=None, length=None, reply_to_message_id=None, reply_markup=None, disable_notification=False,
**kwargs):
files = None
if isinstance(video_note, InputFile):
files = [video_note]
video = None
elif not ... | Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
:param video_note: Video to send. Pass a file_id as String to send a video t... |
381,382 | def read_hotkey(suppress=True):
queue = _queue.Queue()
fn = lambda e: queue.put(e) or e.event_type == KEY_DOWN
hooked = hook(fn, suppress=suppress)
while True:
event = queue.get()
if event.event_type == KEY_UP:
unhook(hooked)
with _pressed_events_lock:
... | Similar to `read_key()`, but blocks until the user presses and releases a
hotkey (or single key), then returns a string representing the hotkey
pressed.
Example:
read_hotkey()
# "ctrl+shift+p" |
381,383 | def get_mimetype(self):
if hasattr(self, ):
if (isinstance(self._mimetype, (tuple, list,)) and
len(self._mimetype) == 2):
return self._mimetype
else:
raise NodeError(
)
mtype, encoding = mime... | Mimetype is calculated based on the file's content. If ``_mimetype``
attribute is available, it will be returned (backends which store
mimetypes or can easily recognize them, should set this private
attribute to indicate that type should *NOT* be calculated). |
381,384 | def timeit(output):
b = time.time()
yield
print output, % (time.time()-b) | If output is string, then print the string and also time used |
381,385 | def gps_rtk_send(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses, force_mavlink1=False):
return self.send(self.gps_rtk_encode(time_last_baseline_ms, rtk_re... | RTK GPS data. Gives information on the relative baseline calculation
the GPS is reporting
time_last_baseline_ms : Time since boot of last baseline message received in ms. (uint32_t)
rtk_receiver_id : Identification of connected RTK receiver. (uint8_t)
... |
381,386 | def init_db_conn(connection_name, HOSTS=None):
el = elasticsearch.Elasticsearch(hosts=HOSTS)
el_pool.connections[connection_name] = ElasticSearchClient(el) | Initialize a redis connection by each connection string
defined in the configuration file |
381,387 | def executor(self) -> "ThreadPoolExecutor":
if not isinstance(self.__executor, ThreadPoolExecutor) or self.__executor.is_shutdown:
self.configure()
return self.__executor | Executor instance.
:rtype: ThreadPoolExecutor |
381,388 | def has_stack(self, stack_name):
cf = self.cf_client
try:
resp = cf.describe_stacks(StackName=stack_name)
if len(resp["Stacks"]) != 1:
return False
msg = str(e)
if "Stack with id {0} does no... | Checks if a CloudFormation stack with given name exists
:param stack_name: Name or ID of the stack
:return: True if stack exists. False otherwise |
381,389 | def update_hosts(self, host_names):
if self.host_access:
curr_hosts = [access.host.name for access in self.host_access]
else:
curr_hosts = []
if set(curr_hosts) == set(host_names):
log.info(
)
return None
n... | Primarily for puppet-unity use.
Update the hosts for the lun if needed.
:param host_names: specify the new hosts which access the LUN. |
381,390 | def getMachine(self, machineName):
url = self._url + "/%s" % machineName
return Machine(url=url,
securityHandler=self._securityHandler,
initialize=True,
proxy_url=self._proxy_url,
proxy_port=self._proxy_... | returns a machine object for a given machine
Input:
machineName - name of the box ex: SERVER.DOMAIN.COM |
381,391 | def pairs(args):
import jcvi.formats.bed
p = OptionParser(pairs.__doc__)
p.set_pairs()
opts, targs = p.parse_args(args)
if len(targs) != 1:
sys.exit(not p.print_help())
samfile, = targs
bedfile = samfile.rsplit(".", 1)[0] + ".bed"
if need_update(samfile, bedfile):
... | See __doc__ for OptionParser.set_pairs(). |
381,392 | def svg(self, value):
if len(value) < 500:
self._svg = value
return
try:
root = ET.fromstring(value)
except ET.ParseError as e:
log.error("Canxmlnsxmlns:xlink', "http://www.w3.org/1999/xlink")
if len(root.findall("{http://www.w3... | Set SVG field value.
If the svg has embed base64 element we will extract them
to disk in order to avoid duplication of content |
381,393 | def job_file(self):
job_file_name = % (self.name)
job_file_path = os.path.join(self.initial_dir, job_file_name)
self._job_file = job_file_path
return self._job_file | The path to the submit description file representing this job. |
381,394 | def add_permission(self, perm):
self.Permissions(permission=perm)
PermissionCache.flush()
self.save() | Soyut Role Permission nesnesi tanımlamayı sağlar.
Args:
perm (object): |
381,395 | def start_record():
global record, playback, current
if record:
raise StateError("Already recording.")
if playback:
raise StateError("Currently playing back.")
record = True
current = ReplayData()
install(RecordingHTTPConnection, RecordingHTTPSConnection) | Install an httplib wrapper that records but does not modify calls. |
381,396 | def zoomedHealpixMap(title, map, lon, lat, radius,
xsize=1000, **kwargs):
reso = 60. * 2. * radius / xsize
hp.gnomview(map=map, rot=[lon, lat, 0], title=title, xsize=xsize, reso=reso, degree=False, **kwargs) | Inputs: lon (deg), lat (deg), radius (deg) |
381,397 | def _make_sql_params(self,kw):
return [ %k for k in kw.keys() ]
for k,v in kw.iteritems():
vals.append( %k)
return vals | Make a list of strings to pass to an SQL statement
from the dictionary kw with Python types |
381,398 | def dasopr(fname):
fname = stypes.stringToCharP(fname)
handle = ctypes.c_int()
libspice.dasopr_c(fname, ctypes.byref(handle))
return handle.value | Open a DAS file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html
:param fname: Name of a DAS file to be opened.
:type fname: str
:return: Handle assigned to the opened DAS file.
:rtype: int |
381,399 | def _execute_cell(args, cell_body):
env = google.datalab.utils.commands.notebook_environment()
config = google.datalab.utils.commands.parse_config(cell_body, env, False) or {}
parameters = config.get() or []
if parameters:
jsonschema.validate({: parameters}, BigQuerySchema.QUERY_PARAMS_SCHEMA)
table_na... | Implements the BigQuery cell magic used to execute BQ queries.
The supported syntax is:
%%bq execute <args>
[<inline SQL>]
Args:
args: the optional arguments following '%%bq execute'.
cell_body: optional contents of the cell
Returns:
QueryResultsTable containing query result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.