Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
352,200 | def _check_stringify_year_column(self, column_index):
table_column = TableTranspose(self.table)[column_index]
prior_year = None
for row_index in range(self.start[0]+1, self.end[0]):
current_year = table_column[row_index]
if not self._check_years(current_... | Same as _check_stringify_year_row but for columns. |
352,201 | def send_terrain_data_bit(self, bit):
lat = self.current_request.lat * 1.0e-7
lon = self.current_request.lon * 1.0e-7
bit_spacing = self.current_request.grid_spacing * 4
(lat, lon) = mp_util.gps_offset(lat, lon,
east=bit_spacing * (bit % 8... | send some terrain data |
352,202 | def add_relationship_panels(self):
from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler
from wagtailplus.wagtailrelations.edit_handlers import RelatedPanel
for model in self.applicable_models:
add_panel_to_edit_handler(model, RelatedPanel, _(u)) | Add edit handler that includes "related" panels to applicable
model classes that don't explicitly define their own edit handler. |
352,203 | def get_stats_str(list_=None, newlines=False, keys=None, exclude_keys=[], lbl=None,
precision=None, axis=0, stat_dict=None, use_nan=False,
align=False, use_median=False, **kwargs):
from utool.util_str import repr4
import utool as ut
if stat_dict is None:
... | Returns the string version of get_stats
DEPRICATE in favor of ut.repr3(ut.get_stats(...))
if keys is not None then it only displays chosen keys
excluded keys are always removed
CommandLine:
python -m utool.util_dev --test-get_stats_str
Example:
>>> # ENABLE_DOCTEST
>>> f... |
352,204 | def _create_save_scenario_action(self):
icon = resources_path(, , )
self.action_save_scenario = QAction(
QIcon(icon),
self.tr(), self.iface.mainWindow())
message = self.tr()
self.action_save_scenario.setStatusTip(message)
self.action_save_scenario... | Create action for save scenario dialog. |
352,205 | def owns_data_key(self, data_key: DataKey) -> bool:
return data_key.key_provider.provider_id in self._allowed_provider_ids | Determine whether the data key is owned by a ``null`` or ``zero`` provider.
:param data_key: Data key to evaluate
:type data_key: :class:`aws_encryption_sdk.structures.DataKey`,
:class:`aws_encryption_sdk.structures.RawDataKey`,
or :class:`aws_encryption_sdk.structures.Encrypted... |
352,206 | def verify_hmac(self, data):
hmac = HMAC(self.SK_ar, digestmod=sha256)
hmac_theirs = data[-MACLEN:]
hmac.update(data[:-MACLEN])
hmac_ours = hmac.digest()[:MACLEN]
logger.debug(.format(
binascii.hexlify(hmac_ours), binascii.hexlify(hmac_theirs)))
if hm... | Verifies the HMAC signature of an encrypted (SK, 46) payload using self.SK_ar
:param data: bytes(payloads.SK())
:raise IkeError: if calculated signature does not match the one in the payload |
352,207 | def _GenOpenApiSpecCallback(args, openapi_func=_GenOpenApiSpec):
openapi_paths = openapi_func(args.service, args.output,
hostname=args.hostname,
application_path=args.application,
x_google_api_name=args.x_google_api_name)
... | Generate OpenAPI (Swagger) specs to files.
Args:
args: An argparse.Namespace object to extract parameters from
openapi_func: A function that generates OpenAPI specs and stores them to
files, accepting a list of service names and an output directory. |
352,208 | def from_xml(cls, xml_bytes):
root = XML(xml_bytes)
return cls(root.findtext(),
root.findtext(),
root.findtext()) | Create an instance of this from XML bytes.
@param xml_bytes: C{str} bytes of XML to parse
@return: an instance of L{MultipartInitiationResponse} |
352,209 | def _get_thumbnail_options(self, context, instance):
width, height = None, None
subject_location = False
placeholder_width = context.get(, None)
placeholder_height = context.get(, None)
if instance.use_autoscale and placeholder_width:
width = int... | Return the size and options of the thumbnail that should be inserted |
352,210 | def with_line_numbers(code):
max_number_length = str(len(str(len(code))))
format_str = "{:>" + max_number_length + "d}: {:}"
return "\n".join([format_str.format(line_number + 1, line) for line_number, line in enumerate(code.split("\n"))]) | Adds line numbers to each line of a source code fragment
Parameters
----------
code : string
any multiline text, such as as (fragments) of source code
Returns
-------
str : string
The input with added <n>: for each line
Example
-------
code = "def do_stuff(x):\n\tpri... |
352,211 | def write(self, data_to_write, overwrite=False):
if overwrite or not path.isfile(self.file):
with open(self.file, "w", encoding="utf-8", newline="\n") as file:
if data_to_write and isinstance(data_to_write, str):
... | Write or append data into the given file path.
:param data_to_write: The data to write.
:type data_to_write: str
:param overwrite:
Tell us if we have to overwrite the
content of the file we are working with.
:type overwrite: bool |
352,212 | def update_state_by_id(cls, state_id, state, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._update_state_by_id_with_http_info(state_id, state, **kwargs)
else:
(data) = cls._update_state_by_id_with_http_info(state_id, state, **kwargs)
return d... | Update State
Update attributes of State
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_state_by_id(state_id, state, async=True)
>>> result = thread.get()
:param async bool
... |
352,213 | def get_shape(spans, loci):
width = 0
for idx in xrange(loci.shape[0]):
width += spans[loci[idx], 1] - spans[loci[idx], 0]
return width | get shape of new bootstrap resampled locus array |
352,214 | def pgm(X, prox_f, step_f, accelerated=False, relax=None, e_rel=1e-6, max_iter=1000, traceback=None):
stepper = utils.NesterovStepper(accelerated=accelerated)
if relax is not None:
assert relax > 0 and relax < 1.5
if traceback is not None:
traceback.update_history(0, X=X, step_f... | Proximal Gradient Method
Adapted from Combettes 2009, Algorithm 3.4.
The accelerated version is Algorithm 3.6 with modifications
from Xu & Yin (2015).
Args:
X: initial X, will be updated
prox_f: proxed function f (the forward-backward step)
step_f: step size, < 1/L with L being... |
352,215 | def check_validity(self, checks=None, report=True):
if report:
reportpoints = []
allchecks = []
checks_specified=False
if isinstance(checks, (str, unicode)):
checks = [checks]
checks_specified ... | Runs a Symbol's validity checks.
Parameters
----------
checks : str, [str,], optional
Only run certain checks.
report : bool, optional
If set to False, the method will return only the result of the
check checks (True/False). Set to ... |
352,216 | def closest(self, dt1, dt2):
dt1 = self.__class__(dt1.year, dt1.month, dt1.day)
dt2 = self.__class__(dt2.year, dt2.month, dt2.day)
if self.diff(dt1).in_seconds() < self.diff(dt2).in_seconds():
return dt1
return dt2 | Get the closest date from the instance.
:type dt1: Date or date
:type dt2: Date or date
:rtype: Date |
352,217 | def mount(self, path, fs):
if isinstance(fs, text_type):
from .opener import open_fs
fs = open_fs(fs)
if not isinstance(fs, FS):
raise TypeError("fs argument must be an FS object or a FS URL")
if fs is self:
raise ValueError("U... | Mounts a host FS object on a given path.
Arguments:
path (str): A path within the MountFS.
fs (FS or str): A filesystem (instance or URL) to mount. |
352,218 | def _get_ids_from_name_public(self, name):
results = self.list_public_images(name=name)
return [result[] for result in results] | Get public images which match the given name. |
352,219 | def show_stack_depth(self, record, frame):
logger = self
depths = [-1]
msg = record.getMessage()
while logger:
to_match = getattr(logger, "show_stack_regexes", ())
for regex, depth, once, min_level in to_match:
if record.levelno... | Compute the maximum stack depth to show requested by any hooks,
returning -1 if there are none matching, or if we've already emitted
one for the line of code referred to. |
352,220 | def get_rate(self, zipcode, city=None, state=None, multiple_rates=False):
data = self.make_request_data(zipcode, city, state)
r = requests.get(self.url, params=data)
resp = r.json()
return self.process_response(resp, multiple_rates) | Finds sales tax for given info.
Returns Decimal of the tax rate, e.g. 8.750. |
352,221 | def _run_qc_tools(bam_file, data):
from bcbio.qc import (atropos, contamination, coverage, damage, fastqc, kraken,
qsignature, qualimap, samtools, picard, srna, umi, variant,
viral, preseq, chipseq)
tools = {"fastqc": fastqc.run,
"atropos": a... | Run a set of third party quality control tools, returning QC directory and metrics.
:param bam_file: alignments in bam format
:param data: dict with all configuration information
:returns: dict with output of different tools |
352,222 | def repository_type(self, repository_type):
allowed_values = ["MAVEN", "NPM", "COCOA_POD", "GENERIC_PROXY"]
if repository_type not in allowed_values:
raise ValueError(
"Invalid value for `repository_type` ({0}), must be one of {1}"
.format(repository_... | Sets the repository_type of this TargetRepositoryRest.
:param repository_type: The repository_type of this TargetRepositoryRest.
:type: str |
352,223 | def blend(self, other, ratio=0.5):
keep = 1.0 - ratio
if not self.space == other.space:
raise Exception("Colors must belong to the same color space.")
values = tuple(((u * keep) + (v * ratio)
for u, v in zip(self.values, other.values)))
return self.__clas... | Blend this color with another color in the same color space.
By default, blends the colors half-and-half (ratio: 0.5).
:param Color other: The color to blend.
:param float ratio: How much to blend (0 -> 1).
:rtype: Color
:returns: A new spectra.Color |
352,224 | def get_nodesitemtypeinsertion(cls, itemgroup, indent) -> str:
blanks = * (indent * 4)
subs = [
f,
f,
f,
f,
f,
f]
type_ = if itemgroup == else
for name in (, , , ):
subs.extend([
... | Return a string defining the required types for the given
combination of an exchange item group and |Node| objects.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_nodesitemtypeinsertion(
... 'setitems', 1)) # doctest: +ELLIPSIS
<complexType name... |
352,225 | def import_laid_out_tensor(mesh, laid_out_tensor, shape, name=None):
return ImportLaidOutTensorOperation(
mesh, laid_out_tensor, convert_to_shape(shape), name=name).outputs[0] | Import a laid_out_tensor.
For expert users.
The input must be laid out appropriately given the eventual MeshImpl,
and layout.
Args:
mesh: a Mesh
laid_out_tensor: a LaidOutTensor
shape: a mtf.Shape
name: an optional string
Returns:
a mtf.Tensor |
352,226 | def hicexplorer_basic_statistics(self):
data = {}
for file in self.mod_data:
max_distance_key =
total_pairs = self.mod_data[file][][0]
try:
self.mod_data[file][max_distance_key][0]
except KeyError:
max_distance_key... | Create the general statistics for HiCExplorer. |
352,227 | def replace_in_file(filename: str, text_from: str, text_to: str) -> None:
log.info("Amending {}: {} -> {}",
filename, repr(text_from), repr(text_to))
with open(filename) as infile:
contents = infile.read()
contents = contents.replace(text_from, text_to)
with open(filename, ) as... | Replaces text in a file.
Args:
filename: filename to process (modifying it in place)
text_from: original text to replace
text_to: replacement text |
352,228 | def StreamingShell(self, command, timeout_ms=None):
return self.protocol_handler.StreamingCommand(
self._handle, service=b, command=command,
timeout_ms=timeout_ms) | Run command on the device, yielding each line of output.
Args:
command: Command to run on the target.
timeout_ms: Maximum time to allow the command to run.
Yields:
The responses from the shell command. |
352,229 | def language(s):
s = decode_utf8(s)
s = set(w.strip(PUNCTUATION) for w in s.replace(" ").split())
n = float(len(s) or 1)
p = {}
for xx in LANGUAGES:
lexicon = _module(xx).__dict__["lexicon"]
p[xx] = sum(1 for w in s if w in lexicon) / n
return max(p.items(), key=lambda kv: (... | Returns a (language, confidence)-tuple for the given string. |
352,230 | def middlename(self, value, case, gender=None):
u
if not value:
raise ValueError()
return self.__inflect(value, case, , gender) | u"""
Склонение отчества
:param value: Значение для склонения
:param case: Падеж для склонения (значение из класса Case)
:param gender: Грамматический род |
352,231 | def load_df(
self,
df,
table,
field_dict=None,
delimiter=,
encoding=,
pandas_kwargs=None, **kwargs):
def _infer_field_types_from_df(df):
DTYPE_KIND_HIVE_TYPE = {
: ,
: , ... | Loads a pandas DataFrame into hive.
Hive data types will be inferred if not passed but column names will
not be sanitized.
:param df: DataFrame to load into a Hive table
:type df: pandas.DataFrame
:param table: target Hive table, use dot notation to target a
specifi... |
352,232 | def _get_signed_params(conv):
conv["sign_mask"] = 2 ** (conv["bits"] - 1)
conv["int_min"] = -1 * (2 ** (conv["bits"] - 1 - conv["bin_point"]))
conv["int_mask"] = sum([2 ** i
for i in range(conv["bin_point"], conv["bits"] - 1)])
conv["int_max"] = sum([2 ** i for i in range(conv["bits"] -
... | Fill the sign-dependent params of the conv structure in case of signed
conversion
@param conv: the structure to be filled |
352,233 | def quaternion_conjugate(quaternion):
return numpy.array((-quaternion[0], -quaternion[1],
-quaternion[2], quaternion[3]), dtype=numpy.float64) | Return conjugate of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_conjugate(q0)
>>> q1[3] == q0[3] and all(q1[:3] == -q0[:3])
True |
352,234 | def encode(self, message, k=None):
if not k: k = self.k
message, _ = self.pad(message, k=k)
if self.algo == 1:
mesecc = self.ecc_manager.encode(message, k=k)
elif self.algo == 2:
mesecc = self.ecc_manager.encode_fast(message, k=k)
elif self.algo =... | Encode one message block (up to 255) into an ecc |
352,235 | def set_state_transition_func(self, func):
if self._connected.value:
logging.error("freshroastsr700.set_state_transition_func must be "
"called before freshroastsr700.auto_connect()."
" Not registering func.")
return False
... | THIS FUNCTION MUST BE CALLED BEFORE CALLING
freshroastsr700.auto_connect().
Set, or re-set, the state transition function callback.
The supplied function will be called from a separate thread within
freshroastsr700, triggered by a separate, internal child process.
This function ... |
352,236 | def deregister_job(self, id, purge=None):
params = None
if purge is not None:
if not isinstance(purge, bool):
raise nomad.api.exceptions.InvalidParameters("purge is invalid "
"(expected type %s but got %s)"%(type(bool()), type(purge)))
... | Deregisters a job, and stops all allocations part of it.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- purge (bool), optionally specifies whether the job should be
stopped and purged immediately (`purge=True`) or deferred to the
... |
352,237 | def repository_contributors(self, **kwargs):
path = % self.get_id()
return self.manager.gitlab.http_list(path, **kwargs) | Return a list of contributors for the project.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): If set to False an... |
352,238 | def _prepare_vts_results_dir(self, vts):
vt_set_results_dir = os.path.join(self.versioned_workdir, , vts.cache_key.hash)
safe_mkdir(vt_set_results_dir)
return vt_set_results_dir | Given a `VergetTargetSet`, prepare its results dir. |
352,239 | def load_bookmark(self, slot_num):
bookmarks = CONF.get(, )
if slot_num in bookmarks:
filename, line_num, column = bookmarks[slot_num]
else:
return
if not osp.isfile(filename):
self.last_edit_cursor_pos = None
return
... | Set cursor to bookmarked file and position. |
352,240 | def iter_csv_stream(input_stream, fieldnames=None, sniff=False, *args, **kwargs):
if not in kwargs and sniff:
kwargs[] = csv.Sniffer().sniff(input_stream.read(1024))
input_stream.seek(0)
if in kwargs and kwargs[] is None:
kwargs[] = csv.QUOTE_MINIMAL
if fieldnames:
... | Read CSV content as a table (list of lists) from an input stream |
352,241 | def get_create_index_sql(self, index, table):
if isinstance(table, Table):
table = table.get_quoted_name(self)
name = index.get_quoted_name(self)
columns = index.get_quoted_columns(self)
if not columns:
raise DBALException()
if index.is_primary... | Returns the SQL to create an index on a table on this platform.
:param index: The index
:type index: Index
:param table: The table
:type table: Table or str
:rtype: str |
352,242 | def _append_defects(self, part, part_content_type):
part_defects = {}
for e in part.defects:
defects = "{}: {}".format(e.__class__.__name__, e.__doc__)
self._defects_categories.add(e.__class__.__name__)
part_defects.setdefault(part_content_type, []).append(... | Add new defects and defects categories to object attributes.
The defects are a list of all the problems found
when parsing this message.
Args:
part (string): mail part
part_content_type (string): content type of part |
352,243 | def _convert_xml_to_ranges(response):
if response is None or response.body is None:
return None
ranges = list()
ranges_element = ETree.fromstring(response.body)
for range_element in ranges_element.findall():
range = FileRange(int(range_element.findtext()), int(range_eleme... | <?xml version="1.0" encoding="utf-8"?>
<Ranges>
<Range>
<Start>Start Byte</Start>
<End>End Byte</End>
</Range>
<Range>
<Start>Start Byte</Start>
<End>End Byte</End>
</Range>
</Ranges> |
352,244 | def parser(input_args=None):
parser = argparse.ArgumentParser(
description="sick, the spectroscopic inference crank", epilog="Use "
" for information on a specific command."
" Documentation and examples available at "
"https://github.com/andycasey/sick")
p... | Command line parser for *sick*. |
352,245 | def parse_report_file(input_, nameservers=None, dns_timeout=2.0,
strip_attachment_payloads=False, parallel=False):
if type(input_) == str:
file_object = open(input_, "rb")
elif type(input_) == bytes:
file_object = BytesIO(input_)
else:
file_object = input_
... | Parses a DMARC aggregate or forensic file at the given path, a
file-like object. or bytes
Args:
input_: A path to a file, a file like object, or bytes
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
dns_timeout (float):... |
352,246 | def podcasts_iter(self, *, device_id=None, page_size=250):
if device_id is None:
device_id = self.device_id
start_token = None
prev_items = None
while True:
response = self._call(
mc_calls.PodcastSeries,
device_id,
max_results=page_size,
start_token=start_token
)
items = respon... | Get a paged iterator of subscribed podcast series.
Parameters:
device_id (str, Optional): A mobile device ID.
Default: Use ``device_id`` of the :class:`MobileClient` instance.
page_size (int, Optional): The maximum number of results per returned page.
Max allowed is ``49995``.
Default: ``250``
Y... |
352,247 | def decompose_select(selectx):
"return [(parent,setter) for scalar_subquery], wherex_including_on, NameIndexer. helper for run_select"
nix = NameIndexer.ctor_fromlist(selectx.tables)
where = []
for fromx in selectx.tables:
if isinstance(fromx,sqparse2.JoinX) and fromx.on_stmt is not None:
where... | return [(parent,setter) for scalar_subquery], wherex_including_on, NameIndexer. helper for run_select |
352,248 | def get_pages(url):
while True:
yield url
doc = html.parse(url).find("body")
links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next ")]
if not links:
break
url = urljoin(url, links[0].get()) | Return the 'pages' from the starting url
Technically, look for the 'next 50' link, yield and download it, repeat |
352,249 | def edit_dedicated_fwl_rules(self, firewall_id, rules):
mask = (
)
svc = self.client[]
fwl = svc.getObject(id=firewall_id, mask=mask)
network_vlan = fwl[]
for fwl1 in network_vlan[]:
if fwl1[] == :
continue
for c... | Edit the rules for dedicated firewall.
:param integer firewall_id: the instance ID of the dedicated firewall
:param list rules: the rules to be pushed on the firewall as defined by
SoftLayer_Network_Firewall_Update_Request_Rule |
352,250 | def goes_requires(self, regs):
if len(self) and self.mem[-1].inst == and self.mem[-1].condition_flag is None:
for block in self.calls:
if block.is_used(regs, 0):
return True
d = block.destroys()
if not len([x for x in reg... | Returns whether any of the goes_to block requires any of
the given registers. |
352,251 | def initialize(self, params, repetition):
super(TinyCIFARExperiment, self).initialize(params, repetition)
self.network_type = params.get("network_type", "sparse") | Initialize experiment parameters and default values from configuration file.
Called at the beginning of each experiment and each repetition. |
352,252 | def request(mods=None,
**kwargs):
***
kwargs[] = True
ret = apply_(mods, **kwargs)
notify_path = os.path.join(__opts__[], )
serial = salt.payload.Serial(__opts__)
req = check_request()
req.update({kwargs.get(, ): {
: ret,
: mods,
: kwargs
... | .. versionadded:: 2017.7.3
Request that the local admin execute a state run via
`salt-call state.run_request`
All arguments match state.apply
CLI Example:
.. code-block:: bash
salt '*' state.request
salt '*' state.request test
salt '*' state.request test,pkgs |
352,253 | def validate_widget(widget):
if not has_valid_id(widget):
raise InvalidWidget("%s must contain a valid attribute" % widget.__name__)
if not has_valid_name(widget):
raise InvalidWidget("%s must contain a valid attribute" % widget.__name__)
if not has_valid_template(widget):
... | Checks that the given widget contains the required fields |
352,254 | def _run_opf(self, P, q, AA, ll, uu, xmin, xmax, x0, opt):
AAcvx = tocvx(AA)
nx = x0.shape[0]
eyex = spmatrix(1.0, range(nx), range(nx))
A = sparse([eyex, AAcvx])
l = matrix([-xmin, ll])
u = matrix([ xmax, uu])
Ae, be, Ai, bi = split_linear_con... | Solves the either quadratic or linear program. |
352,255 | def _populate_common_request(self, request):
url_record = self._item_session.url_record
if url_record.parent_url and not request.fields.get():
self._add_referrer(request, url_record)
if self._fetch_rule.http_login:
request.username, request.password = ... | Populate the Request with common fields. |
352,256 | def create(self, device, setup=None, protocols=None, control_server=None):
device_builder = self._reg.device_builder(device, self._rv)
device = device_builder.create_device(setup)
adapters = []
if protocols is not None:
for protocol, options in protocols.items():
... | Creates a :class:`Simulation` according to the supplied parameters.
:param device: Name of device.
:param setup: Name of the setup for device creation.
:param protocols: Dictionary where each key is assigned a dictionary with options for the
corresponding :class:`~lewi... |
352,257 | def register(self, subscriber):
assert isinstance(subscriber, RequestHandler)
logger.debug()
self.subscribers.add(subscriber) | Register a new subscriber. This method should be invoked by
listeners to start receiving messages. |
352,258 | def stop(vm_):
*
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, , vm_)
if vm_uuid is False:
return False
try:
xapi.VM.hard_shutdown(vm_uuid)
return True
except Exception:
return False | Hard power down the virtual machine, this is equivalent to pulling the
power
CLI Example:
.. code-block:: bash
salt '*' virt.stop <vm name> |
352,259 | def create(cls, cluster_info):
conn = Qubole.agent(version="v2")
return conn.post(cls.rest_entity_path, data=cluster_info) | Create a new cluster using information provided in `cluster_info`. |
352,260 | def img2img_transformer_b3():
hparams = img2img_transformer_base()
hparams.batch_size = 2
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.block_length = 128
hparams.sampling_temp = 0.9
return hparams | Current best hparams for local 1d. |
352,261 | def regions(self):
json = self.request(, method=)
status = json.get()
if status == :
regions_json = json.get(, [])
regions = [Region.from_json(region) for region in regions_json]
return regions
else:
message = json.get()
... | This method will return all the available regions within the
DigitalOcean cloud. |
352,262 | def __file_hash_and_stat(self, load):
if in load:
load.pop()
if not in load or not in load:
return , None
if not isinstance(load[], six.string_types):
load[] = six.text_type(load[])
fnd = self.find_file(salt.utils.stringutils... | Common code for hashing and stating files |
352,263 | def should_skip_middleware(self, middleware, matching, rest) -> bool:
return bool(not matching) or bool(rest) | Returns True (i.e. should skip) if request does not match the
entire middleware path.
This is a simple check if 'rest' is truthy or not. |
352,264 | def _parse_quota(mount, opts):
cmd = .format(opts, mount)
out = __salt__[](cmd, python_shell=False).splitlines()
mode =
if in opts:
quotatype =
elif in opts:
quotatype =
ret = {quotatype: {}}
for line in out:
if not line:
continue
comps... | Parse the output from repquota. Requires that -u -g are passed in |
352,265 | def last_exception():
exc_type, exc_value, exc_traceback = sys.exc_info()
return "".join(traceback.format_exception(exc_type, exc_value, exc_traceback)) | Returns last exception as a string, or use in logging. |
352,266 | def _asStr(self):
styleDict = self._styleDict
if styleDict:
return .join([name + + value for name, value in styleDict.items()])
return | _asStr - Get the string representation of this style
@return <str> - A string representation of this style (semicolon separated, key: value format) |
352,267 | def set_file_service_properties(self, hour_metrics=None, minute_metrics=None,
cors=None, timeout=None):
s File service, including
Azure Storage Analytics. If an element (ex HourMetrics) is left as None, the
existing settings on the service for that functiona... | Sets the properties of a storage account's File service, including
Azure Storage Analytics. If an element (ex HourMetrics) is left as None, the
existing settings on the service for that functionality are preserved.
:param Metrics hour_metrics:
The hour metrics settings provide a su... |
352,268 | def list_subnets(self, retrieve_all=True, **_params):
return self.list(, self.subnets_path, retrieve_all,
**_params) | Fetches a list of all subnets for a project. |
352,269 | def delete_group_action(model, request):
try:
groups = model.parent.backend
uid = model.model.name
del groups[uid]
groups()
model.parent.invalidate()
except Exception as e:
return {
: False,
: str(e)
}
localizer = get_local... | Delete group from database. |
352,270 | def create_parser(self, prog_name, subcommand):
if not self.use_argparse:
self.__class__.option_list = TestCommand.option_list + self.custom_options
parser = super(Command, self).create_parser(prog_name, subcommand)
return parser | Override the base create_parser() method to add this command's custom
options in Django 1.7 and below. |
352,271 | def create_or_update(cluster_config_file, min_workers, max_workers, no_restart,
restart_only, yes, cluster_name):
if restart_only or no_restart:
assert restart_only != no_restart, "Cannot set both " \
"and at the same time!"
create_or_update_cluster(cluster_config... | Create or update a Ray cluster. |
352,272 | def attachedimages_inline_factory(lang=, max_width=, debug=False):
langenrumax_width
class _AttachedImagesInline(GenericTabularInline):
model = AttachedImage
form = attachedimage_form_factory(lang, debug)
template =
max_w = max_width
return _AttachedImagesInline | Returns InlineModelAdmin for attached images.
'lang' is the language for GearsUploader (can be 'en' and 'ru' at the
moment). 'max_width' is default resize width parameter to be set in
widget. |
352,273 | def unsubscribe(self):
if self._has_been_unsubscribed or not self.is_subscribed:
return
self._auto_renew_thread_flag.set()
headers = {
: self.sid
}
response = None
try:
... | Unsubscribe from the service's events.
Once unsubscribed, a Subscription instance should not be reused |
352,274 | def stopTrying(self):
protocol.ReconnectingClientFactory.stopTrying(self)
if not self._client_ready.called:
self._client_ready.errback(
pika.exceptions.AMQPConnectionError(
u"Could not connect, reconnection cancelled."
)
... | Stop trying to reconnect to the broker.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details. |
352,275 | def agent_url(self):
try:
if self._data_from_search:
agent = self._data_from_search.find(, {: })
links = agent.find_all()
return links[1][]
else:
return self._ad_page_content.find(, {: })[]
except Exception ... | This method returns the agent's url.
:return: |
352,276 | def __walk_chain(rel_dict, src_id):
paths_starting_with_id = []
for target_id in rel_dict[src_id]:
if target_id in rel_dict:
for tail in __walk_chain(rel_dict, target_id):
paths_starting_with_id.append([src_id] + tail)
else:
paths_starting_with_id.app... | given a dict of pointing relations and a start node, this function
will return a list of paths (each path is represented as a list of
node IDs -- from the first node of the path to the last).
Parameters
----------
rel_dict : dict
a dictionary mapping from an edge source node (node ID str)
... |
352,277 | def skip_module(*modules):
modules = (modules and isinstance(modules[0], list)) and \
modules[0] or modules
for module in modules:
if not module in SKIPPED_MODULES:
SKIPPED_MODULES.append(module)
traceback.extract_tb = _new_extract_tb | This will exclude all of the "modules" from the traceback
:param modules: list of modules to exclude
:return: None |
352,278 | def setup(self):
log.debug( , self.client_address )
try:
self.transport.load_server_moduli()
except:
log.exception( )
raise
try:
self.transport.add_server_key(self.host_key)
except:
if self.host_key i... | Setup the connection. |
352,279 | def extract_client_auth(request):
auth_header = request.META.get(, )
if re.compile().match(auth_header):
b64_user_pass = auth_header.split()[1]
try:
user_pass = b64decode(b64_user_pass).decode().split()
client_id, client_secret = tuple(user_pass)
except Exce... | Get client credentials using HTTP Basic Authentication method.
Or try getting parameters via POST.
See: http://tools.ietf.org/html/rfc6750#section-2.1
Return a tuple `(client_id, client_secret)`. |
352,280 | def map(self, func: Callable[[Tuple[Any, Log]], Tuple[Any, Log]]) -> :
a, w = self.run()
b, _w = func((a, w))
return Writer(b, _w) | Map a function func over the Writer value.
Haskell:
fmap f m = Writer $ let (a, w) = runWriter m in (f a, w)
Keyword arguments:
func -- Mapper function: |
352,281 | def register(style, func=None):
if func is not None:
_registry[style] = func
return
def decorator(func):
_registry[style] = func
@wraps(func)
def wrapper(pinyin, **kwargs):
return func(pinyin, **kwargs)
return wrapper
return decorator | 注册一个拼音风格实现
::
@register('echo')
def echo(pinyin, **kwargs):
return pinyin
# or
register('echo', echo) |
352,282 | def get_requirements(cls):
try:
with open("requirements.txt") as f:
return tuple(parse_requirements(f.readlines()))
except IOError as e:
LOG.debug("Couldn't open requirements file: %s", e)
return () | Get package requirements. |
352,283 | def render_default(path, cp):
filename = os.path.basename(path)
slug = filename.replace(, )
content = None
if path.endswith() or path.endswith():
try:
wf_file = SegFile.from_segment_xml(path)
wf_file.return_union_seglis... | This is the default function that will render a template to a string of HTML. The
string will be for a drop-down tab that contains a link to the file.
If the file extension requires information to be read, then that is passed to the
content variable (eg. a segmentlistdict). |
352,284 | def webhooks(self):
api_version = self._get_api_version()
if api_version == :
from .v2017_10_01.operations import WebhooksOperations as OperationClass
elif api_version == :
from .v2018_02_01_preview.operations import WebhooksOperations as OperationClass
e... | Instance depends on the API version:
* 2017-10-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2017_10_01.operations.WebhooksOperations>`
* 2018-02-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.WebhooksOperations>`
* 201... |
352,285 | def delete_dbinstance(self, id, skip_final_snapshot=False,
final_snapshot_id=):
params = { : id}
if skip_final_snapshot:
params[] =
else:
params[] =
params[] = final_snapshot_id
return self.get_object(, params, DBIn... | Delete an existing DBInstance.
:type id: str
:param id: Unique identifier for the new instance.
:type skip_final_snapshot: bool
:param skip_final_snapshot: This parameter determines whether a final
db snapshot is created before the instance
... |
352,286 | def loss_ratios(value):
dic = dictionary(value)
for lt, ratios in dic.items():
for ratio in ratios:
if not 0 <= ratio <= 1:
raise ValueError(
% (ratio, lt))
check_levels(ratios, lt)
return dic | :param value: input string
:returns: dictionary loss_type -> loss ratios
>>> loss_ratios('{"structural": [0.1, 0.2]}')
{'structural': [0.1, 0.2]} |
352,287 | def get_apply_status(self, apply_id):
res = self._post(
,
data={
: apply_id,
},
result_processor=lambda x: x[]
)
return res | 查询设备ID申请审核状态
详情请参考
http://mp.weixin.qq.com/wiki/15/b9e012f917e3484b7ed02771156411f3.html
:param apply_id: 批次ID,申请设备ID时所返回的批次ID
:return: 批次状态信息 |
352,288 | def squelch(self, threshold):
func = lambda x: zeros(x.shape) if max(x) < threshold else x
return self.map(func) | Set all records that do not exceed the given threhsold to 0.
Parameters
----------
threshold : scalar
Level below which to set records to zero |
352,289 | def _store_inferential_results(self,
value_array,
index_names,
attribute_name,
series_name=None,
column_names=None):
if len(valu... | Store the estimation results that relate to statistical inference, such
as parameter estimates, standard errors, p-values, etc.
Parameters
----------
value_array : 1D or 2D ndarray.
Contains the values that are to be stored on the model instance.
index_names : list o... |
352,290 | def add_skip_ci_to_commit_msg(message: str) -> str:
first_line_index = message.find()
if first_line_index == -1:
edited_message = message +
else:
edited_message = message[:first_line_index] + + message[first_line_index:]
LOGGER.debug(, edited_message)
... | Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message
:param message: commit message
:type message: str
:return: edited commit message
:rtype: str |
352,291 | def maybe_infer_dtype_type(element):
tipo = None
if hasattr(element, ):
tipo = element.dtype
elif is_list_like(element):
element = np.asarray(element)
tipo = element.dtype
return tipo | Try to infer an object's dtype, for use in arithmetic ops
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
Possibly has a `.dtype` attribute, a... |
352,292 | def boolWithSubParams(parameters, name):
param = parameters.find(".//BoolWithSubParams[@Name=]".format(name=name))
str_value = param.find().text
if str_value not in {, }:
raise ValueError(.format(str_value))
value = str_value ==
choice = if value else
return value, param.find(.fo... | single choice with sub parameters value and chosen subparameters. Returns -1 and None if no value was chosen.
:param parameters: the parameters tree.
:param name: the name of the parameter. |
352,293 | def bmpm(
word,
language_arg=0,
name_mode=,
match_mode=,
concat=False,
filter_langs=False,
):
return BeiderMorse().encode(
word, language_arg, name_mode, match_mode, concat, filter_langs
) | Return the Beider-Morse Phonetic Matching encoding(s) of a term.
This is a wrapper for :py:meth:`BeiderMorse.encode`.
Parameters
----------
word : str
The word to transform
language_arg : str
The language of the term; supported values include:
- ``any``
- `... |
352,294 | def get_secchan_offs(type_, data):
if data[0] < len(ht_secondary_offset):
return "{0} ({1})".format(ht_secondary_offset[data[0]], data[0])
return "{0}".format(data[0]) | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n927.
Positional arguments:
type_ -- corresponding `ieprinters` dictionary key for the instance.
data -- bytearray data to read. |
352,295 | def write(filename, samples, write_params=None, static_args=None):
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
simtable = lsctables.New(lsctables.SimInspiralTable)
xmldoc.childNodes[0].appendChild(simtable)
if static_args is None:
static_a... | Writes the injection samples to the given xml.
Parameters
----------
filename : str
The name of the file to write to.
samples : io.FieldArray
FieldArray of parameters.
write_params : list, optional
Only write the given parameter names. All giv... |
352,296 | def getLogs(self, CorpNum, MgtKeyType, MgtKey):
if MgtKeyType not in self.__MgtKeyTypes:
raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
if MgtKey == None or MgtKey == "":
raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")
return self._httpget( + Mg... | 세금계산서 문서이력 목록 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
문서이력 정보 목록 as List
raise
PopbillException |
352,297 | def generate(grammar=None, num=1, output=sys.stdout, max_recursion=10, seed=None):
if seed is not None:
gramfuzz.rand.seed(seed)
fuzzer = gramfuzz.GramFuzzer()
fuzzer.load_grammar(grammar)
cat_group = os.path.basename(grammar).replace(".py", "")
results = fuzzer.gen(cat_group=cat_gro... | Load and generate ``num`` number of top-level rules from the specified grammar.
:param list grammar: The grammar file to load and generate data from
:param int num: The number of times to generate data
:param output: The output destination (an open, writable stream-type object. default=``sys.stdout``)
... |
352,298 | def handle_finish(queue_name):
task_id = request.form.get(, type=str)
owner = request.form.get(, request.remote_addr, type=str)
error = request.form.get(, type=str) is not None
try:
work_queue.finish(queue_name, task_id, owner, error=error)
except work_queue.Error, e:
return uti... | Marks a task on a queue as finished. |
352,299 | def set_filesystems(
name,
device,
vfstype,
opts=,
mount=,
config=,
test=False,
match_on=,
**kwargs):
*
if isinstance(opts, list):
opts = .join(opts)
entry_args = {
: name,
: device.replace(, ),
... | .. versionadded:: 2018.3.3
Verify that this mount is represented in the filesystems, change the mount
to match the data passed, or add the mount if it is not present on AIX
Provide information if the path is mounted
:param name: The name of the mount point where the device is mounted.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.