Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
351,200 | def isSane(self):
if self.host == :
return True
host_parts = self.host.split()
if self.wildcard:
assert host_parts[0] == , host_parts
del host_parts[0]
return len(host_parts) > 2
... | This method checks the to see if a trust root represents a
reasonable (sane) set of URLs. 'http://*.com/', for example
is not a reasonable pattern, as it cannot meaningfully specify
the site claiming it. This function attempts to find many
related examples, but it can only work via heu... |
351,201 | def capture(self):
url = str.replace(CONST.CAMS_ID_CAPTURE_URL,
, self.device_id)
try:
response = self._abode.send_request("put", url)
_LOGGER.debug("Capture image response: %s", response.text)
return True
except AbodeExce... | Request a new camera image. |
351,202 | def add_table(self, rows, cols, left, top, width, height):
graphicFrame = self._add_graphicFrame_containing_table(
rows, cols, left, top, width, height
)
graphic_frame = self._shape_factory(graphicFrame)
return graphic_frame | Add a |GraphicFrame| object containing a table with the specified
number of *rows* and *cols* and the specified position and size.
*width* is evenly distributed between the columns of the new table.
Likewise, *height* is evenly distributed between the rows. Note that
the ``.table`` prope... |
351,203 | def metric_ids(self):
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Metric)
]) | Return the Metrics on this shelf in the order in which
they were used. |
351,204 | def load_manual_sequence(self, seq, ident=None, write_fasta_file=False, outdir=None,
set_as_representative=False, force_rewrite=False):
if write_fasta_file:
if not outdir:
outdir = self.sequence_dir
if not outdir:
... | Load a manual sequence given as a string and optionally set it as the representative sequence.
Also store it in the sequences attribute.
Args:
seq (str, Seq, SeqRecord): Sequence string, Biopython Seq or SeqRecord object
ident (str): Optional identifier for the sequence, require... |
351,205 | def write(self, char):
char = str(char).lower()
self.segments.write(self.font[char]) | Display a single character on the display
:type char: str or int
:param char: Character to display |
351,206 | def create_schema(self, check_if_exists=False, sync_schema=True,
verbosity=1):
connection = connections[get_tenant_database_alias()]
_check_schema_name(self.schema_name)
cursor = connection.cursor()
if check_if_exists and schema_exists(self.schem... | Creates the schema 'schema_name' for this tenant. Optionally checks if
the schema already exists before creating it. Returns true if the
schema was created, false otherwise. |
351,207 | def fit_to_window(self):
state = self.state
self.dragpos = wx.Point(0, 0)
client_area = state.frame.GetClientSize()
self.zoom = min(float(client_area.x) / self.img.GetWidth(),
float(client_area.y) / self.img.GetHeight())
self.need_redraw = True | fit image to window |
351,208 | def _validate_targets(self, targets):
if targets is None:
return self.ids
if isinstance(targets, (int,str,unicode)):
targets = [targets]
_targets = []
for t in targets:
if isinstance(t, (str,unicode)):
... | turn any valid targets argument into a list of integer ids |
351,209 | def encode(self, boundary):
if self.value is None:
value = self.fileobj.read()
else:
value = self.value
if re.search("^--%s$" % re.escape(boundary), value, re.M):
raise ValueError("boundary found in encoded string")
return "%s%s\r\n" % (self... | Returns the string encoding of this parameter |
351,210 | def v_type_if_feature(ctx, stmt, no_error_report=False):
stmt.i_feature = None
expr = syntax.parse_if_feature_expr(stmt.arg)
if stmt.i_module.i_version == :
if type(expr) != type():
err_add(ctx.errors, stmt.pos,
, (stmt.arg, ))
return
... | verify that the referenced feature exists. |
351,211 | def paragraph(self, paragraph, prefix=""):
content = []
for text in paragraph.content:
content.append(self.text(text))
content = u"".join(content).encode("utf-8")
for line in content.split("\n"):
self.target.write(" " * self.indent)
self.tar... | process a pyth paragraph into the target |
351,212 | def _document_root(self, fully_qualified=True):
nsmap = {"xsi": utils.NAMESPACES["xsi"], "xlink": utils.NAMESPACES["xlink"]}
if fully_qualified:
nsmap["mets"] = utils.NAMESPACES["mets"]
else:
nsmap[None] = utils.NAMESPACES["mets"]
attrib = {
"... | Return the mets Element for the document root. |
351,213 | def is_adjacency_matrix_symmetric(adjacency_matrix):
num_columns = len(adjacency_matrix)
for column in adjacency_matrix:
if len(column) != num_columns:
return False
max_i = 0
for j in range(num_columns):
for i in range(max_i):
... | Determines if an adjacency matrix is symmetric.
Ref: http://mathworld.wolfram.com/SymmetricMatrix.html |
351,214 | def wait_for(text, finish=None, io=None):
if finish:
finish.set()
time.sleep(0.1)
if not io:
io = sys.stdout
finish = threading.Event()
io.write(text)
def _wait():
while not finish.is_set():
io.write()
io.flush()
finish.wait(t... | Displays dots until returned event is set |
351,215 | def pp_tuple(self, tup):
last_line = self.f.getvalue().split("\n")[-1]
l = len(last_line)+1
indent = * l
self.write()
sep =
for item in tup:
self.write(sep)
l += len(sep)
s = repr(item)
l += len(s)
sel... | Pretty print a tuple |
351,216 | def get_currency(self, code):
missing = True
for currency in self.currencies[0]:
try:
if code != currency.find().text:
continue
except AttributeError:
continue
missing = False
yield currency
... | Returns an iterable of currency elements matching the code:
<CtryNm>UNITED STATES MINOR OUTLYING ISLANDS (THE)</CtryNm>
<CcyNm>US Dollar</CcyNm>
<Ccy>USD</Ccy>
<CcyNbr>840</CcyNbr>
<CcyMnrUnts>2</CcyMnrUnts>
NOTE: the currency is repeated for each country name |
351,217 | def get_temperature(self, format=, sensor=0):
results = self.get_temperatures(sensors=[sensor,])
if format == :
return results[sensor][]
elif format == :
return results[sensor][]
elif format == :
return results[sensor][]
else:
... | Get device temperature reading. |
351,218 | def read(pin):
f = _open[pin].value
out = int(_read(f))
log.debug("Read {0}: {1}".format(pin, out))
return out | read the pin value
Returns:
bool: 0 or 1 |
351,219 | def main():
args = get_arguments()
setup_logging(args)
version_path = os.path.abspath(os.path.join(
os.path.dirname(__file__),
,
,
))
try:
version_text = open(version_path).read().strip()
except Exception:
print()
sys.exit(1)
t... | Main method.
This method holds what you want to execute when
the script is run on command line. |
351,220 | def _execute_callback(self, *args):
"Executes the callback with the appropriate args and kwargs"
self._validate_key(args)
with dynamicmap_memoization(self.callback, self.streams):
retval = self.callback(*args, **kwargs)
return self._style(retval) | Executes the callback with the appropriate args and kwargs |
351,221 | async def update_firmware(
self,
firmware_file: str,
loop: asyncio.AbstractEventLoop = None,
explicit_modeset: bool = True) -> str:
if None is loop:
checked_loop = self._loop
else:
checked_loop = loop
return await s... | Update the firmware on the Smoothie board.
:param firmware_file: The path to the firmware file.
:param explicit_modeset: `True` to force the smoothie into programming
mode; `False` to assume it is already in
programming mode.
:pa... |
351,222 | def get_local_dist_packages_dir():
import utool as ut
if not ut.in_virtual_env():
return get_site_packages_dir()
else:
candidates = []
if ut.LINUX:
candidates += [
,
]
else:
raise NotImplementedError()
... | Attempts to work around virtualenvs and find the system dist_pacakges.
Essentially this is implmenented as a lookuptable |
351,223 | def write_log(log_directory, log_filename, header, logline, debug,
require_latest, latest_directory, latest_filename):
create_new_file = False
if not os.path.exists(log_directory):
os.makedirs(log_directory)
full_path_log = os.path.join(log_directory, log_filename)
... | This function logs a line of data to both a 'log' file, and a 'latest'
file The 'latest' file is optional, and is sent to this function as a
boolean value via the variable 'require_latest'.
So the 2 log directories and filenames are:
a. (REQUIRED): log_directory + log_filename
b. (OP... |
351,224 | def get(self, block=True, timeout=None):
_, node_id = self.inner.get(block=block, timeout=timeout)
with self.lock:
self._mark_in_progress(node_id)
return self.get_node(node_id) | Get a node off the inner priority queue. By default, this blocks.
This takes the lock, but only for part of it.
:param bool block: If True, block until the inner queue has data
:param Optional[float] timeout: If set, block for timeout seconds
waiting for data.
:return Parse... |
351,225 | def device(self):
splitted_path = self.path.split("/")
return Device(self.db,
splitted_path[0] + "/" + splitted_path[1]) | returns the device which owns the given stream |
351,226 | def _get_head_types(pat):
if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
if isinstance(pat, pytree.WildcardPattern):
r = set()
for p in pat.content:
for x in p:
r.update(_get_head_types(x))
return r
raise E... | Accepts a pytree Pattern Node and returns a set
of the pattern types which will match first. |
351,227 | def run_compare_gold_standard(in_prefix, in_type, out_prefix, base_dir,
options):
os.mkdir(out_prefix)
required_type = "bfile"
check_input_files(in_prefix, in_type, required_type)
script_prefix = os.path.join(out_prefix, "compare_with_gold")
o... | Compares with a gold standard data set (compare_gold_standard.
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options needed.
:type in_prefix: str
... |
351,228 | def dict_to_paths(dict_):
metrics = {}
for k, v in dict_.iteritems():
if isinstance(v, dict):
submetrics = dict_to_paths(v)
for subk, subv in submetrics.iteritems():
metrics[.join([str(k), str(subk)])] = subv
else:
metrics[k] = v
retur... | Convert a dict to metric paths.
>>> dict_to_paths({'foo': {'bar': 1}, 'baz': 2})
{
'foo.bar': 1,
'baz': 2,
} |
351,229 | def reset_to_default(self):
scheme = self.current_scheme
names = self.get_option()
if scheme in names:
for key in syntaxhighlighters.COLOR_SCHEME_KEYS:
option = "{0}/{1}".format(scheme, key)
value = CONF.get_default(self.CONF_SECTION,... | Restore initial values for default color schemes. |
351,230 | def check_config(data):
is_right = True
if "title" not in data:
logging.error("No in _config.yml")
is_right = False
return is_right | Check if metadata is right
TODO(crow): check more |
351,231 | def index(self, doc_type, sources, **kwargs):
try:
actions = []
for source in sources:
self._check_mappings(doc_type, source)
id_ = source[] if in source else None
log.debug("indexing %s object with id %s", doc_type, id_)
... | Implements call to add documents to the ES index
Note the call to _check_mappings which will setup fields with the desired mappings |
351,232 | def wpeak(self, wavelengths=None):
x = self._validate_wavelengths(wavelengths)
return x[self(x) == self.tpeak(wavelengths=wavelengths)][0] | Calculate
:ref:`wavelength at peak throughput <synphot-formula-tpeak>`.
If there are multiple data points with peak throughput
value, only the first match is returned.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
... |
351,233 | def _python_to_lua(pval):
import lua
if pval is None:
return lua.eval("")
if isinstance(pval, (list, tuple, set)):
lua_list = lua.eval("{}")
lua_table = lua.eval("table")
for... | Convert Python object(s) into Lua object(s), as at times Python object(s)
are not compatible with Lua functions |
351,234 | def create_main_frame(self):
self.resize(800, 600)
self.main_frame = QWidget()
self.dpi = 128
self.save_button = QPushButton()
self.save_button.clicked.connect(self.saveResult)
self.qapf_button = QPushButton()
self.qapf_button.clicked.connect(self.QAPF)
... | self.tableView = CustomQTableView(self.main_frame)
self.tableView.setObjectName('tableView')
self.tableView.setSortingEnabled(True) |
351,235 | def _palette(self):
self.palette_idx += 1
try:
self.loop.screen.register_palette(self.palettes[self.palette_names[self.palette_idx]])
except IndexError:
self.loop.screen.register_palette(self.palettes[self.palette_names[0]])
self.palette_idx ... | p |
351,236 | def all_high_level_calls(self):
if self._all_high_level_calls is None:
self._all_high_level_calls = self._explore_functions(lambda x: x.high_level_calls)
return self._all_high_level_calls | recursive version of high_level calls |
351,237 | def _dir_additions(self):
rv = set()
for accessor in self._accessors:
try:
getattr(self, accessor)
rv.add(accessor)
except AttributeError:
pass
return rv | Add additional __dir__ for this object. |
351,238 | def get_output_data_port_m(self, data_port_id):
for data_port_m in self.output_data_ports:
if data_port_m.data_port.data_port_id == data_port_id:
return data_port_m
return None | Returns the output data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id |
351,239 | def do_add_all_link(self, args):
linkcode = 1
group = 0
addr = None
params = args.split()
if params:
try:
linkcode = int(params[0])
except IndexError:
linkcode = 1
except ValueError:
link... | Add an All-Link record to the IM and a device.
Usage:
add_all_link [linkcode] [group] [address]
Arguments:
linkcode: 0 - PLM is responder
1 - PLM is controller
3 - PLM is controller or responder
Default 1
... |
351,240 | def _independent_lattice(self, shape, lattice=None):
I, J = shape
if lattice is not None:
end_I = min(I, max(lattice[..., 3])) - 1
end_J = min(J, max(lattice[..., 4])) - 1
unvisited_nodes = deque([(i, j, s)
for i in range... | Helper to construct the list of nodes and edges. |
351,241 | def print_meter_record(file_path, rows=5):
m = nr.read_nem_file(file_path)
print(, m.header)
print(, m.transactions)
for nmi in m.readings:
for channel in m.readings[nmi]:
print(nmi, , channel)
for reading in m.readings[nmi][channel][-rows:]:
print(, ... | Output readings for specified number of rows to console |
351,242 | def posixpath_normpath(pathname):
backslash =
pathname2 = os.path.normpath(pathname) or "."
if backslash in pathname2:
pathname2 = pathname2.replace(backslash, )
return pathname2 | Convert path into POSIX path:
* Normalize path
* Replace backslash with slash
:param pathname: Pathname (as string)
:return: Normalized POSIX path. |
351,243 | async def set_endpoint_for_did(wallet_handle: int,
did: str,
address: str,
transport_key: str) -> None:
logger = logging.getLogger(__name__)
logger.debug("set_endpoint_for_did: >>> wallet_handle: %r, did: %r, addr... | Set/replaces endpoint information for the given DID.
:param wallet_handle: Wallet handle (created by open_wallet).
:param did: The DID to resolve endpoint.
:param address: The DIDs endpoint address.
:param transport_key: The DIDs transport key (ver key, key id).
:return: Error code |
351,244 | def get_message_encoded_size(self):
if not self._message:
raise ValueError("No message data to encode.")
cloned_data = self._message.clone()
self._populate_message_attributes(cloned_data)
encoded_data = []
return c_uamqp.get_encoded_message_size(cloned_data, ... | Pre-emptively get the size of the message once it has been encoded
to go over the wire so we can raise an error if the message will be
rejected for being to large.
This method is not available for messages that have been received.
:rtype: int |
351,245 | def image(self, image):
if image.mode != :
raise ValueError()
imwidth, imheight = image.size
if imwidth != self.width or imheight != self.height:
raise ValueError( \
.format(self.width, self.height))
print("bitmap display: image")
... | Set buffer to value of Python Imaging Library image. The image should
be in 1 bit mode and a size equal to the display size. |
351,246 | def get_followers(self, auth_secret):
result = {pytwis_constants.ERROR_KEY: None}
loggedin, userid = self._is_loggedin(auth_secret)
if not loggedin:
result[pytwis_constants.ERROR_KEY] = pytwis_constants.ERROR_NOT_LOGGED_IN
return (False, result)
... | Get the follower list of a logged-in user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the follower list is successfully obtained, False otherwise.
result
... |
351,247 | def fowlkes_mallows(self, reference_clusters):
return fowlkes_mallows_score(self.get_labels(self), self.get_labels(reference_clusters)) | Calculates the Fowlkes-Mallows index (FMI) w.r.t. the reference clusters (explicit evaluation)
:param reference_clusters: Clusters that are to be used as reference
:return: The resulting Fowlkes-Mallows score. |
351,248 | def get(self, id):
info = self._get_droplet_info(id)
return DropletActions(self.api, self, **info) | Retrieve a droplet by id
Parameters
----------
id: int
droplet id
Returns
-------
droplet: DropletActions |
351,249 | def _append_action(self, option, opt_unused, value_unused, parser):
parser.values.actions.append(option.action_code) | Callback for an option that adds to the `actions` list. |
351,250 | def normalize_vector(x, y, z):
mag = np.sqrt(x**2 + y**2 + z**2)
x = x/mag
y = y/mag
z = z/mag
return x, y, z | Normalizes vector to produce a unit vector.
Parameters
----------
x : float or array-like
X component of vector
y : float or array-like
Y component of vector
z : float or array-like
Z component of vector
Returns
-------
x, y, z
Unit vector x,... |
351,251 | def bake(self):
self._sh_command = getattr(sh, self.command)
self._sh_command = self._sh_command.bake(
self.options,
,
_env=self.env,
_out=LOG.out,
_err=LOG.error) | Bake a ``gilt`` command so it's ready to execute and returns None.
:return: None |
351,252 | def load(filename):
json_obj = Seed.load(filename)
return SeedInteger(json_obj["seed_value"], json_obj["seed_id"], json_obj["date"]) | Load seed from a file.
:param filename: Source file name
:return: SeedInteger |
351,253 | def arg_parser(self, passed_args=None):
parser, subpar, remaining_argv = self._setup_parser()
if not isinstance(passed_args, list):
passed_args = list()
if remaining_argv:
passed_args.extend(remaining_argv)
optional_args = self.arguments.get()
... | Setup argument Parsing.
If preset args are to be specified use the ``passed_args`` tuple.
:param passed_args: ``list``
:return: ``dict`` |
351,254 | def _default_key_normalizer(key_class, request_context):
context = request_context.copy()
context[] = context[].lower()
context[] = context[].lower()
for key in (, , ):
if key in context and context[key] is not None:
context[key] = frozenset(context[key].items())
... | Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to change this behaviour, provide
alternate callables to ``key_fn_by_s... |
351,255 | def easyopen(fname, idd=None, epw=None):
if idd:
eppy.modeleditor.IDF.setiddname(idd)
idf = eppy.modeleditor.IDF(fname, epw=epw)
return idf
if isinstance(fname, (IOBase, StringIO)):
fhandle = fname
else:
fhandle = io.open(fname, , encoding=)
txt =... | automatically set idd and open idf file. Uses version from idf to set correct idd
It will work under the following circumstances:
- the IDF file should have the VERSION object.
- Needs the version of EnergyPlus installed that matches the IDF version.
- Energyplus should be installed in the default... |
351,256 | def add_object(self, request):
try:
data = json.loads(request.body if hasattr(request, ) else request.raw_post_data)
except ValueError:
return HttpResponseBadRequest(_())
form = self.get_form_instance(request, data=data)
if form... | Adds an object. |
351,257 | async def send_video_note(self, chat_id: typing.Union[base.Integer, base.String],
video_note: typing.Union[base.InputFile, base.String],
duration: typing.Union[base.Integer, None] = None,
length: typing.Union[base.Integer, None] =... | As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long.
Use this method to send video messages.
Source: https://core.telegram.org/bots/api#sendvideonote
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id... |
351,258 | def clean_var(text):
text = re_invalid_var.sub(, text)
text = re_invalid_start.sub(, text)
return text | Turn text into a valid python classname or variable |
351,259 | def required(cls):
columns = []
for column in cls.__table__.columns:
is_autoincrement = in str(column.type).lower() and column.autoincrement
if (not column.nullable and not column.primary_key) or (column.primary_key and not is_autoincrement):
columns.a... | Return a list of all columns required by the database to create the
resource.
:param cls: The Model class to gather attributes from
:rtype: list |
351,260 | def _parse(self, parsable, parser_name):
calc, error = None, None
try:
for calc in self.Parsers[parser_name].iparse(parsable):
yield calc, None
return
except RuntimeError as e:
error = "routine %s parser error in %s: %s" % ( parser_nam... | Low-level parsing
NB: this is the PRIVATE method
@returns tilde_obj, error |
351,261 | def make_serviceitem_description(description, condition=, negate=False, preserve_case=False):
document =
search =
content_type =
content = description
ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content,
n... | Create a node for ServiceItem/description
:return: A IndicatorItem represented as an Element node |
351,262 | def set_right_table(self, table):
self.right_table = table
if self.left_table is None:
return
if type(self.left_table) is ModelTable and type(self.right_table) is ModelTable:
for field in self.get_all_related_objects(self.left... | Sets the right table for this join clause and try to automatically set the condition
if one isn't specified |
351,263 | def cmd_tool(args=None):
from argparse import ArgumentParser
parser = ArgumentParser(description="Command line utility for reading and plotting blimpy files.")
parser.add_argument(, type=str,
help=)
parser.add_argument(, action=, default=, dest=, type=str,
... | Command line tool for plotting and viewing info on blimpy files |
351,264 | def is_in(bim, geno_range):
r
Ichrom = bim.chrom == geno_range[0]
Ipos1 = bim.pos >= geno_range[1]
Ipos2 = bim.pos < geno_range[2]
return Ichrom & Ipos1 & Ipos2 | r"""
Parameters
----------
bim : pandas.DataFrame
Variant annotation
geno_range : tuple
(chrom, pos_start, pos_end)
Returns
-------
Isnp : bool array
Variant filter |
351,265 | def unproject(self, xy):
(x, y) = xy
lng = x/EARTH_RADIUS * RAD_TO_DEG
lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG
return (lng, lat) | Returns the coordinates from position in meters |
351,266 | def group_required(group,
login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME,
skip_superuser=True):
def decorator(view_func):
@login_required(redirect_field_name=redirect_field_name,
login_url=login_url)
... | View decorator for requiring a user group. |
351,267 | def getS(self, add_intercept=False):
S = self.S
if add_intercept is True:
zeros = np.zeros_like(S[:1, :])
S = np.vstack([zeros, S])
zeros = np.zeros_like(S[:, :1])
S = np.hstack([zeros, S])
return S | Get the penalty matrix S
Returns
np.array, of shape (n_bases + add_intercept, n_bases + add_intercept) |
351,268 | def init_hierarchy(cls, model_admin):
hierarchy = getattr(model_admin, )
if hierarchy:
if not isinstance(hierarchy, Hierarchy):
hierarchy = AdjacencyList()
else:
hierarchy = NoHierarchy()
model_admin.hierarchy = hierarchy | Initializes model admin with hierarchy data. |
351,269 | def parseLines(self):
inAst = parse(.join(self.lines), self.inFilename)
self.visit(inAst) | Form an AST for the code and produce a new version of the source. |
351,270 | def pyxb_to_dict(node_list_pyxb):
f_dict = {}
for f_pyxb in sorted(node_list_pyxb.node, key=lambda x: x.identifier.value()):
f_dict[f_pyxb.identifier.value()] = {
: f_pyxb.name,
: f_pyxb.description,
: f_pyxb.baseURL,
: f_pyxb.ping,
: f_py... | Returns:
dict : Representation of ``node_list_pyxb``, keyed on the Node identifier
(``urn:node:*``).
Example::
{
u'urn:node:ARCTIC': {
'base_url': u'https://arcticdata.io/metacat/d1/mn',
'description': u'The US National Science Foundation...',
'name': u'Arctic Data Center... |
351,271 | def Run(self):
count = 0
for count, input_data in enumerate(self.GetInput()):
if count % 2000 == 0:
logging.debug("%d processed.", count)
args = (input_data, self.out_queue, self.token)
self.thread_pool.AddTask(
target=self.IterFunction, args=args, name=self.THREAD_POOL_... | Run the iteration. |
351,272 | def uri_path(self):
value = []
for option in self.options:
if option.number == defines.OptionRegistry.URI_PATH.number:
value.append(str(option.value) + )
value = "".join(value)
value = value[:-1]
return value | Return the Uri-Path of a request
:rtype : String
:return: the Uri-Path |
351,273 | def morph_cost(self) -> Optional["Cost"]:
if self.tech_alias is None or self.tech_alias[0] in {UnitTypeId.TECHLAB, UnitTypeId.REACTOR}:
return None
tech_alias_cost_minerals = max([self._game_data.units[tech_alias.value].cost.minerals for tech_alias in self.tech_ali... | This returns 150 minerals for OrbitalCommand instead of 550 |
351,274 | def enqueue_in(self, time_delta, func, *args, **kwargs):
timeout = kwargs.pop(, None)
job_id = kwargs.pop(, None)
job_ttl = kwargs.pop(, None)
job_result_ttl = kwargs.pop(, None)
job_description = kwargs.pop(, None)
meta = kwargs.pop(, None)
job = self._... | Similar to ``enqueue_at``, but accepts a timedelta instead of datetime object.
The job's scheduled execution time will be calculated by adding the timedelta
to datetime.utcnow(). |
351,275 | def _separate_bitstring(bitstring, creg_sizes):
substrings = []
running_index = 0
for _, size in reversed(creg_sizes):
substrings.append(bitstring[running_index: running_index + size])
running_index += size
return .join(substrings) | Separate a bitstring according to the registers defined in the result header. |
351,276 | def get_path_info(environ, charset=, errors=):
path = wsgi_get_bytes(environ.get(, ))
return to_unicode(path, charset, errors, allow_none_charset=True) | Returns the `PATH_INFO` from the WSGI environment and properly
decodes it. This also takes care about the WSGI decoding dance
on Python 3 environments. if the `charset` is set to `None` a
bytestring is returned.
.. versionadded:: 0.9
:param environ: the WSGI environment object to get the path fr... |
351,277 | def detect_event(self, model, ms_per_input, transition_matrix, model_stats, event_length_s,
start_as_yes=False, prob_raw_yes=0.5):
if ms_per_input < 0 or ms_per_input / MS_PER_S > self.duration_seconds:
raise ValueError("ms_per_input cannot be negative and cannot be lon... | A list of tuples of the form [('n', AudioSegment), ('y', AudioSegment), etc.] is returned, where tuples
of the form ('n', AudioSegment) are the segments of sound where the event was not detected,
while ('y', AudioSegment) tuples were the segments of sound where the event was detected.
.. code-b... |
351,278 | def filter_content_types(self, content_type_qs):
valid_ct_ids = []
for ct in content_type_qs:
model = ct.model_class()
if model and issubclass(model, EventBase):
valid_ct_ids.append(ct.id)
return content_type_qs.filter(pk__in=valid_ct_ids) | Filter the content types selectable to only event subclasses |
351,279 | def rmtree(path, use_shutil=True, followlinks=False, retries=10):
if use_shutil and not followlinks:
try:
shutil.rmtree(path)
return
except Exception, exc:
logger.info(, path)
logger.debug(, traceback.format_exc(exc))
if not os.path.isdir(pat... | remove all files and directories below path, including path
itself; works even when shutil.rmtree fails because of read-only
files in NFS and Windows. Follows symlinks.
`use_shutil` defaults to True; useful for testing
`followlinks` defaults to False; if set to True, shutil.rmtree is
not used. |
351,280 | def _create_dataset(
self, group, chunk_size, compression, compression_opts):
if chunk_size == :
chunks = True
else:
per_chunk = (
nb_per_chunk(20, 1, chunk_size) if self.dtype == np.dtype()
else nb_per_chunk(
... | Create an empty dataset in a group. |
351,281 | def assertDateTimesLagLess(self, sequence, lag, msg=None):
<
if not isinstance(sequence, collections.Iterable):
raise TypeError()
if not isinstance(lag, timedelta):
raise TypeError()
if isinstance(max(sequence), datetime):
target = d... | Fail if max element in ``sequence`` is separated from
the present by ``lag`` or more as determined by the '<'
operator.
If the max element is a datetime, "present" is defined as
``datetime.now()``; if the max element is a date, "present"
is defined as ``date.today()``.
... |
351,282 | def remove(self, toRemove):
list.remove(self, toRemove)
self.uids.remove(toRemove.uid) | remove - Remove an item from this tag collection
@param toRemove - an AdvancedTag |
351,283 | def SetQualifier(self, *args, **kwargs):
qual = args[0] if args else kwargs[]
try:
self.qualifiers[self.default_namespace][qual.name] = qual
except KeyError:
self.qualifiers[self.default_namespace] = \
NocaseDict({qual.name: qual}) | Create or modify a qualifier type in the local repository of this
class.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.SetQualifier`. |
351,284 | def _ParsePerformanceOptions(self, options):
self._buffer_size = getattr(options, , 0)
if self._buffer_size:
try:
if self._buffer_size[-1].lower() == :
self._buffer_size = int(self._buffer_size[:-1], 10)
self._buffer_size *= self._BYTES_IN_A_MIB
... | Parses the performance options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. |
351,285 | def borrow_or_take(self, now, can_borrow):
with self._lock:
return self._borrow_or_take(now, can_borrow) | Decide whether to borrow or take one quota from
the reservoir. Return ``False`` if it can neither
borrow nor take. This method is thread-safe. |
351,286 | def move_to_position(
self,
resource_id,
to_position,
new_parent_id=noop,
db_session=None,
*args,
**kwargs
):
return self.service.move_to_position(
resource_id=resource_id,
to_position=to_position,
new_paren... | Moves node to new location in the tree
:param resource_id: resource to move
:param to_position: new position
:param new_parent_id: new parent id
:param db_session:
:return: |
351,287 | async def serialize_archive(self, ar, version=None):
await ar.message(self, TransactionPrefix)
if self.version == 1:
await ar.tag()
await ar.begin_array()
await ar.prepare_container(len(self.vin), eref(self, ), elem_type=SignatureArray)
... | Serialize the transaction
:param ar:
:type ar: x.Archive
:return: |
351,288 | def deleteLogicalInterface(self, logicalInterfaceId):
req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId)
resp = requests.delete(req, auth=self.credentials, verify=self.verify)
if resp.status_code == 204:
self.logger.debug("logical interface de... | Deletes a logical interface.
Parameters: logicalInterfaceId (string).
Throws APIException on failure. |
351,289 | def accumulate_metric(cls, name, value):
metrics_cache = cls._get_metrics_cache()
metrics_cache.setdefault(name, 0)
metrics_cache.set(name, value) | Accumulate a custom metric (name and value) in the metrics cache. |
351,290 | def get_absorbing_atom_symbol_index(absorbing_atom, structure):
if isinstance(absorbing_atom, str):
return absorbing_atom, structure.indices_from_symbol(absorbing_atom)[0]
elif isinstance(absorbing_atom, int):
return str(structure[absorbing_atom].specie), absorbing_atom
else:
ra... | Return the absorbing atom symboll and site index in the given structure.
Args:
absorbing_atom (str/int): symbol or site index
structure (Structure)
Returns:
str, int: symbol and site index |
351,291 | def handle_error(self, error=None):
if _debug: TCPServer._debug("handle_error %r", error)
asyncore.dispatcher.handle_error(self) | Trap for TCPServer errors, otherwise continue. |
351,292 | def plot_temporal_firing_rate(self,time_dimension=0,resolution=1.0,units=None,min_t=None,max_t=None,weight_function=None,normalize_time=False,normalize_n=False,start_units_with_0=True,cell_dimension=,**kwargs):
if bool(self):
import matplotlib.pylab as plt
H,ed = self.temporal_f... | Plots a firing rate plot.
Accepts the same keyword arguments as :func:`matplotlib.pylab.plot()` for lines (:class:`~matplotlib.lines.Line2D`), eg `color`, `linewidth` (or `lw`), `linestyle` (or `ls`).
See help for :func:`matplotlib.pylab.plot()`. |
351,293 | def create_v4flowspec_actions(actions=None):
from ryu.services.protocols.bgp.api.prefix import (
FLOWSPEC_ACTION_TRAFFIC_RATE,
FLOWSPEC_ACTION_TRAFFIC_ACTION,
FLOWSPEC_ACTION_REDIRECT,
FLOWSPEC_ACTION_TRAFFIC_MARKING,
)
action_types = {
FLOWSPEC_ACTION_TRAF... | Create list of traffic filtering actions
for Ipv4 Flow Specification and VPNv4 Flow Specification.
`` actions`` specifies Traffic Filtering Actions of
Flow Specification as a dictionary type value.
Returns a list of extended community values. |
351,294 | def is_present(self, locator):
return self.driver_wrapper.is_present(locator, search_object=self.element) | Tests to see if an element is present
@type locator: webdriverwrapper.support.locator.Locator
@param locator: locator used in search
@rtype: bool
@return: True if present, False if not present |
351,295 | def file(self, md5=None, sha1=None, sha256=None, **kwargs):
indicator_obj = File(md5, sha1, sha256, **kwargs)
return self._indicator(indicator_obj) | Add File data to Batch object.
.. note:: A least one file hash value must be specified.
Args:
md5 (str, optional): The md5 value for this Indicator.
sha1 (str, optional): The sha1 value for this Indicator.
sha256 (str, optional): The sha256 value for this Indicator.... |
351,296 | def _set_fcoe_fabric_map(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("fcoe_fabric_map_name",fcoe_fabric_map.fcoe_fabric_map, yang_name="fcoe-fabric-map", rest_name="fabric-map", parent=self, is_container=, user_ordered=False, path_hel... | Setter method for fcoe_fabric_map, mapped from YANG variable /fcoe/fcoe_fabric_map (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_fabric_map is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_f... |
351,297 | def getPrevNextUrn(self, reference):
_prev, _next = _SharedMethod.prevnext(
self.retriever.getPrevNextUrn(
urn="{}:{}".format(
str(
URN(
str(self.urn)).upTo(URN.NO_PASSAGE)
),
... | Get the previous URN of a reference of the text
:param reference: CtsReference from which to find siblings
:type reference: Union[CtsReference, str]
:return: (Previous CapitainsCtsPassage CtsReference,Next CapitainsCtsPassage CtsReference) |
351,298 | def summary(self, summary):
if summary is not None:
if summary == :
click.secho(, fg=self.colors.YELLOW)
click.echo()
elif summary == :
click.secho(, fg=self.colors.WHITE)
elif summary == :
click.secho... | Prints the ASCII Icon |
351,299 | def get_vault_connection():
def _use_local_config():
log.debug()
try:
if __opts__[][][] == :
verify = __opts__[].get(, None)
if _selftoken_expired():
log.debug()
url = .format(__opts__[][])
... | Get the connection details for calling Vault, from local configuration if
it exists, or from the master otherwise |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.