Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
368,000 | def fit_size(min_length: int = 0, max_length: int = None,
message=None) -> Filter_T:
def validate(value):
length = len(value) if value is not None else 0
if length < min_length or \
(max_length is not None and length > max_length):
_raise_failure(messag... | Validate any sized object to ensure the size/length
is in a given range [min_length, max_length]. |
368,001 | def get_owner_asset_ids(self, address):
block_filter = self._get_event_filter(owner=address)
log_items = block_filter.get_all_entries(max_tries=5)
did_list = []
for log_i in log_items:
did_list.append(id_to_did(log_i.args[]))
return did_list | Get the list of assets owned by an address owner.
:param address: ethereum account address, hex str
:return: |
368,002 | def cancel_spot_requests(self, requests):
ec2_requests = self.retry_on_ec2_error(self.ec2.get_all_spot_instance_requests, request_ids=requests)
for req in ec2_requests:
req.cancel() | Cancel one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list |
368,003 | def get(self, key, default=None, remote=False):
if not remote:
return super(CouchDB, self).get(key, default)
db = self._DATABASE_CLASS(self, key)
if db.exists():
super(CouchDB, self).__setitem__(key, db)
return db
return default | Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally cached database object is returned.
:param str key: Database... |
368,004 | def setup_debug_logging():
logger = logging.getLogger("xbahn")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter("%(name)s: %(message)s"))
logger.addHandler(ch) | set up debug logging |
368,005 | def check_job_collection_name(self, cloud_service_id, job_collection_id):
_validate_not_none(, cloud_service_id)
_validate_not_none(, job_collection_id)
path = self._get_cloud_services_path(
cloud_service_id, "scheduler", "jobCollections")
path += "?op=checknameavai... | The Check Name Availability operation checks if a new job collection with
the given name may be created, or if it is unavailable. The result of the
operation is a Boolean true or false.
cloud_service_id:
The cloud service id
job_collection_id:
The name of the job... |
368,006 | def openid_form(parser, token):
bits = get_bits(token)
if len(bits) > 1:
return FormNode(bits[0], bits[1:])
if len(bits) == 1:
return FormNode(bits[0])
return FormNode(None) | Render OpenID form. Allows to pre set the provider::
{% openid_form "https://www.google.com/accounts/o8/id" %}
Also creates custom button URLs by concatenating all arguments
after the provider's URL
{% openid_form "https://www.google.com/accounts/o8/id" STATIC_URL "image/for/google.jpg" %} |
368,007 | def complement(self, other):
s = SimVariableSet()
s.register_variables = self.register_variables - other.register_variables
s.register_variable_offsets = self.register_variable_offsets - other.register_variable_offsets
s.memory_variables = self.memory_variables - other.memory_v... | Calculate the complement of `self` and `other`.
:param other: Another SimVariableSet instance.
:return: The complement result. |
368,008 | def get_meta(self, name, meta_key=None):
decriptionog:titleproperty
meta_key = meta_key or
for child in self.meta._children:
if isinstance(child, Html) and child.attr(meta_key) == name:
return child.attr() | Get the ``content`` attribute of a meta tag ``name``.
For example::
head.get_meta('decription')
returns the ``content`` attribute of the meta tag with attribute
``name`` equal to ``description`` or ``None``.
If a different meta key needs to be matched, it can be specified ... |
368,009 | def date_time_between_dates(
self,
datetime_start=None,
datetime_end=None,
tzinfo=None):
if datetime_start is None:
datetime_start = datetime.now(tzinfo)
if datetime_end is None:
datetime_end = datetime.now(tzinfo)
... | Takes two DateTime objects and returns a random datetime between the two
given datetimes.
Accepts DateTime objects.
:param datetime_start: DateTime
:param datetime_end: DateTime
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('1999-02-02 1... |
368,010 | def p_expr_exit(p):
if len(p) == 5:
p[0] = ast.Exit(p[3], lineno=p.lineno(1))
else:
p[0] = ast.Exit(None, lineno=p.lineno(1)) | expr : EXIT
| EXIT LPAREN RPAREN
| EXIT LPAREN expr RPAREN |
368,011 | def _list_dict(l: Iterator[str], case_insensitive: bool = False):
if case_insensitive:
raise NotImplementedError()
d = tldap.dict.CaseInsensitiveDict()
else:
d = {}
for i in l:
d[i] = None
return d | return a dictionary with all items of l being the keys of the dictionary
If argument case_insensitive is non-zero ldap.cidict.cidict will be
used for case-insensitive string keys |
368,012 | def get_attribute(self, obj, attribute):
raw_return = self.send_command_return(obj, attribute, )
if len(raw_return) > 2 and raw_return[0] == and raw_return[-1] == :
return raw_return[1:-1]
return raw_return | Returns single object attribute.
:param obj: requested object.
:param attribute: requested attribute to query.
:returns: returned value.
:rtype: str |
368,013 | def trailing_stop_loss(self, accountID, **kwargs):
return self.create(
accountID,
order=TrailingStopLossOrderRequest(**kwargs)
) | Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request |
368,014 | def population_counts(
self,
population_size,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
):
population_counts = [
slice_.population_counts(
population_size,
weighted... | Return counts scaled in proportion to overall population.
The return value is a numpy.ndarray object. Count values are scaled
proportionally to approximate their value if the entire population
had been sampled. This calculation is based on the estimated size of
the population provided a... |
368,015 | def __flush_buffer(self):
self.__flush_data(self._buffer.getvalue())
self._buffer.close()
self._buffer = StringIO() | Flush the buffer contents out to a chunk. |
368,016 | def vertex_to_entity_path(vertex_path,
graph,
entities,
vertices=None):
def edge_direction(a, b):
if a[0] == b[0]:
return -1, 1
elif a[0] == b[1]:
return -1, -1
elif a[1] == b[... | Convert a path of vertex indices to a path of entity indices.
Parameters
----------
vertex_path : (n,) int
Ordered list of vertex indices representing a path
graph : nx.Graph
Vertex connectivity
entities : (m,) list
Entity objects
vertices : (p, dimension) float
... |
368,017 | def identity(self):
if self.dataset is None:
s = object_session(self)
ds = s.query(Dataset).filter(Dataset.id_ == self.d_id).one()
else:
ds = self.dataset
d = {
: self.id,
: self.vid,
: self.name,
... | Return this partition information as a PartitionId. |
368,018 | def GET(self, courseid):
course = self.get_course(courseid)
return self.show_page(course) | GET request |
368,019 | def clean_old_jobs():
s event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
keep_jobskeep_jobsselect date_sub(now(), interval {0} hour) as stamp;keep_jobsarchive_jobsMysql returner was unable to get timestamp for purge/archive of jobs')
... | Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return: |
368,020 | def expand(self, url):
url = self.clean_url(url)
response = self._get(url)
if response.ok:
return response.url
raise ExpandingErrorException | Base expand method. Only visits the link, and return the response
url |
368,021 | def start(config, bugnumber=""):
repo = config.repo
if bugnumber:
summary, bugnumber, url = get_summary(config, bugnumber)
else:
url = None
summary = None
if summary:
summary = input(.format(summary)).strip() or summary
else:
summary = input("Summary: "... | Create a new topic branch. |
368,022 | def _set_Buffer(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=Buffer.Buffer, is_container=, presence=False, yang_name="Buffer", rest_name="Buffer", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensi... | Setter method for Buffer, mapped from YANG variable /rbridge_id/threshold_monitor/Buffer (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_Buffer is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set... |
368,023 | def selectrowindex(self, window_name, object_name, row_index):
object_handle = self._get_object_handle(window_name, object_name)
if not object_handle.AXEnabled:
raise LdtpServerException(u"Object %s state disabled" % object_name)
count = len(object_handle.AXRows)
if... | Select row index
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type object_name: stri... |
368,024 | def set_units(self, unit):
self._units = validate_type(unit, type(None), *six.string_types) | Set the unit for this data point
Unit, as with data_type, are actually associated with the stream and not
the individual data point. As such, changing this within a stream is
not encouraged. Setting the unit on the data point is useful when the
stream might be created with the write o... |
368,025 | def multi_index_insert_row(df, index_row, values_row):
row_index = pd.MultiIndex(levels=[[i] for i in index_row],
labels=[[0] for i in index_row])
row = pd.DataFrame(values_row, index=row_index, columns=df.columns)
df = pd.concat((df, row))
if df.index.lexsort_depth ==... | Return a new dataframe with a row inserted for a multi-index dataframe.
This will sort the rows according to the ordered multi-index levels. |
368,026 | def _resample(self, arrays, ji_windows):
win_dst = ji_windows[self.dst_res]
aff_dst = self._layer_meta[self._res_indices[self.dst_res][0]]["transform"]
arrays_dst = list()
for i, array in enumerate(arrays):
arr_dst = np.zeros((int(win_dst.height), int(win_ds... | Resample all arrays with potentially different resolutions to a common resolution. |
368,027 | def setup_versioneer():
try:
import versioneer
versioneer.get_version()
except ImportError:
import subprocess
try:
subprocess.check_output(["versioneer", "install"])
except OSError:
... | Generate (temporarily) versioneer.py file in project root directory
:return: |
368,028 | def matches_querytime(instance, querytime):
if not querytime.active:
return True
if not querytime.time:
return instance.version_end_date is None
return (instance.version_start_date <= querytime.time and
(instance.version_end_date is None or
... | Checks whether the given instance satisfies the given QueryTime object.
:param instance: an instance of Versionable
:param querytime: QueryTime value to check against |
368,029 | def _set_icmp(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=icmp.icmp, is_container=, presence=False, yang_name="icmp", rest_name="icmp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u... | Setter method for icmp, mapped from YANG variable /rbridge_id/interface/ve/ip/icmp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_icmp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_icmp() ... |
368,030 | def get_grouped_psf_model(template_psf_model, star_group, pars_to_set):
group_psf = None
for star in star_group:
psf_to_add = template_psf_model.copy()
for param_tab_name, param_name in pars_to_set.items():
setattr(psf_to_add, param_name, star[param_tab_name])
if grou... | Construct a joint PSF model which consists of a sum of PSF's templated on
a specific model, but whose parameters are given by a table of objects.
Parameters
----------
template_psf_model : `astropy.modeling.Fittable2DModel` instance
The model to use for *individual* objects. Must have paramete... |
368,031 | def subtree(events):
stack = 0
for obj in events:
if obj[] == ENTER:
stack += 1
elif obj[] == EXIT:
if stack == 0:
break
stack -= 1
yield obj | selects sub-tree events |
368,032 | def _generate_replacement(interface_number, segment_number):
replacements = {}
for i in range(0, 9):
replacements["port" + str(i)] = interface_number + i
replacements["segment" + str(i)] = segment_number + i
return replacements | This will generate replacement string for
{port0} => {port9}
{segment0} => {segment9} |
368,033 | def count(a, axis=None):
axes = _normalise_axis(axis, a)
if axes is None or len(axes) != 1:
msg = "This operation is currently limited to a single axis"
raise AxisSupportError(msg)
return _Aggregation(a, axes[0],
_CountStreamsHandler, _CountMaskedStreamsHandler,
... | Count the non-masked elements of the array along the given axis.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the inp... |
368,034 | def special_type(self):
try:
return self.__dict__["special_type"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute ".format(self.order_book_id)
) | [str] 特别处理状态。’Normal’ - 正常上市, ‘ST’ - ST处理, ‘StarST’ - *ST代表该股票正在接受退市警告,
‘PT’ - 代表该股票连续3年收入为负,将被暂停交易, ‘Other’ - 其他(股票专用) |
368,035 | def create_from_fits(cls, fitsfile, norm_type=):
tsmap = WcsNDMap.read(fitsfile)
tab_e = Table.read(fitsfile, )
tab_s = Table.read(fitsfile, )
tab_f = Table.read(fitsfile, )
tab_e = convert_sed_cols(tab_e)
tab_s = convert_sed_cols(tab_s)
tab_f = convert... | Build a TSCube object from a fits file created by gttscube
Parameters
----------
fitsfile : str
Path to the tscube FITS file.
norm_type : str
String specifying the quantity used for the normalization |
368,036 | def triplet_loss(anchor, positive, negative, margin, extra=False, scope="triplet_loss"):
r
with tf.name_scope(scope):
d_pos = tf.reduce_sum(tf.square(anchor - positive), 1)
d_neg = tf.reduce_sum(tf.square(anchor - negative), 1)
loss = tf.reduce_mean(tf.maximum(0., margin + d_pos - d_ne... | r"""Loss for Triplet networks as described in the paper:
`FaceNet: A Unified Embedding for Face Recognition and Clustering
<https://arxiv.org/abs/1503.03832>`_
by Schroff et al.
Learn embeddings from an anchor point and a similar input (positive) as
well as a not-similar input (negative).
Intui... |
368,037 | def healthy(self, url):
response = requests.get(url)
status_code = response.status_code
if status_code != 200:
bot.error( %(url, status_code))
return False
return True | determine if a resource is healthy based on an accepted response (200)
or redirect (301)
Parameters
==========
url: the URL to check status for, based on the status_code of HEAD |
368,038 | def date(self, date):
self._occurrence_data[] = self._utils.format_datetime(
date, date_format=
) | Set File Occurrence date. |
368,039 | def pump_reader(self):
origin, message = self.transport.read_packet()
if isinstance(origin, MessageTargetWatch):
self._handle_watch_message(message)
else:
self._broadcast_transport_message(origin, message) | Synchronously reads one message from the watch, blocking until a message is available.
All events caused by the message read will be processed before this method returns.
.. note::
You usually don't need to invoke this method manually; instead, see :meth:`run_sync` and :meth:`run_async`. |
368,040 | def fast_comp(seq1, seq2, transpositions=False):
replace, insert, delete = "r", "i", "d"
L1, L2 = len(seq1), len(seq2)
if L1 < L2:
L1, L2 = L2, L1
seq1, seq2 = seq2, seq1
ldiff = L1 - L2
if ldiff == 0:
models = (insert+delete, delete+insert, replace+replace)
elif ldiff == 1:
models = (delete+replace,... | Compute the distance between the two sequences `seq1` and `seq2` up to a
maximum of 2 included, and return it. If the edit distance between the two
sequences is higher than that, -1 is returned.
If `transpositions` is `True`, transpositions will be taken into account for
the computation of the distance. This can ... |
368,041 | def clean_cell(self, cell, cell_type):
try:
cell = cell.encode(, ).decode()
if cell_type == :
cell = datetime.strptime(cell, )
elif cell_type == :
cell = int(cell)
elif cell_type == :
cell = Dec... | Uses the type of field (from the mapping) to
determine how to clean and format the cell. |
368,042 | def send_calibrate_barometer(self):
calibration_command = self.message_factory.command_long_encode(
self._handler.target_system, 0,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION,
0,
0,
0,
1,
0,
... | Request barometer calibration. |
368,043 | def as_dict(self):
return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__, "efermi": self.efermi,
"energies": list(self.energies),
"densities": {str(spin): list(dens)
for spin, dens in self.densities.... | Json-serializable dict representation of Dos. |
368,044 | def parse_workflow_declaration(self, wf_declaration_subAST):
typevaluetypevaluetypevalue
var_map = OrderedDict()
var_name = self.parse_declaration_name(wf_declaration_subAST.attr("name"))
var_type = self.parse_declaration_type(wf_declaration_subAST.attr("type"))
var_expressn = se... | Parses a WDL declaration AST subtree into a string and a python
dictionary containing its 'type' and 'value'.
For example:
var_name = refIndex
var_map = {'type': File,
'value': bamIndex}
:param wf_declaration_subAST: An AST subtree of a workflow declaration.
... |
368,045 | def temp_db(db, name=None):
if name is None:
name = temp_name()
db.create(name)
if not db.exists(name):
raise DatabaseError()
try:
yield name
finally:
db.drop(name)
if db.exists(name):
raise DatabaseError() | A context manager that creates a temporary database.
Useful for automated tests.
Parameters
----------
db: object
a preconfigured DB object
name: str, optional
name of the database to be created. (default: globally unique name) |
368,046 | def app_update_state(app_id,state):
try:
create_at = datetime.datetime.now().strftime()
conn = get_conn()
c = conn.cursor()
c.execute("UPDATE app SET state=,change_at= WHERE id=".format(state, create_at, app_id))
conn.commit()
conn.close()
print % (app_i... | update app state |
368,047 | def pkg_resources_env(self, platform_str):
os_name =
platform_machine =
platform_release =
platform_system =
platform_version =
sys_platform =
if in platform_str:
os_name =
platform_machine = if in platform_str else
platform_system =
sys_platform =
... | Returns a dict that can be used in place of packaging.default_environment. |
368,048 | def get_data():
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
m = maps.get("Sequencer")
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=m.path, map_data=m.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create... | Retrieve static data from the game. |
368,049 | def _cfactory(attr, func, argtypes, restype, errcheck=None):
meth = getattr(attr, func)
meth.argtypes = argtypes
meth.restype = restype
if errcheck:
meth.errcheck = errcheck | Factory to create a ctypes function and automatically manage errors. |
368,050 | def traverse(self, root="ROOT", indent="", transform=None, stream=sys.stdout):
if transform is None:
transform = ViewClient.TRAVERSE_CIT
if type(root) == types.StringType and root == "ROOT":
root = self.root
return ViewCl... | Traverses the C{View} tree and prints its nodes.
The nodes are printed converting them to string but other transformations can be specified
by providing a method name as the C{transform} parameter.
@type root: L{View}
@param root: the root node from where the traverse starts
@t... |
368,051 | def coderelpath(coderoot, relpath):
from os import chdir, getcwd, path
cd = getcwd()
chdir(coderoot)
result = path.abspath(relpath)
chdir(cd)
return result | Returns the absolute path of the 'relpath' relative to the specified code directory. |
368,052 | def run_kernel(self, func, gpu_args, instance):
logging.debug(, instance.name)
logging.debug(, *instance.threads)
logging.debug(, *instance.grid)
try:
self.dev.run_kernel(func, gpu_args, instance.threads, instance.grid)
except Exception as e:
if ... | Run a compiled kernel instance on a device |
368,053 | def sync_close(self):
if self._closed:
return
while self._free:
conn = self._free.popleft()
if not conn.closed:
conn.sync_close()
for conn in self._used:
if not conn.closed:
... | 同步关闭 |
368,054 | def bin_dense(M, subsampling_factor=3):
m = min(M.shape)
n = (m // subsampling_factor) * subsampling_factor
if n == 0:
return np.array([M.sum()])
N = np.array(M[:n, :n], dtype=np.float64)
N = N.reshape(n // subsampling_factor, subsampling_factor,
n // subsampling_fa... | Sum over each block of given subsampling factor, returns a matrix whose
dimensions are this much as small (e.g. a 27x27 matrix binned with a
subsampling factor equal to 3 will return a 9x9 matrix whose each component
is the sum of the corresponding 3x3 block in the original matrix).
Remaining columns an... |
368,055 | def _compute_counts(event, time, order=None):
n_samples = event.shape[0]
if order is None:
order = numpy.argsort(time, kind="mergesort")
uniq_times = numpy.empty(n_samples, dtype=time.dtype)
uniq_events = numpy.empty(n_samples, dtype=numpy.int_)
uniq_counts = numpy.empty(n_samples, dt... | Count right censored and uncensored samples at each unique time point.
Parameters
----------
event : array
Boolean event indicator.
time : array
Survival time or time of censoring.
order : array or None
Indices to order time in ascending order.
If None, order will ... |
368,056 | def calc_effective_diffusivity(self, inlets=None, outlets=None,
domain_area=None, domain_length=None):
r
return self._calc_eff_prop(inlets=inlets, outlets=outlets,
domain_area=domain_area,
domain_len... | r"""
This calculates the effective diffusivity in this linear transport
algorithm.
Parameters
----------
inlets : array_like
The pores where the inlet composition boundary conditions were
applied. If not given an attempt is made to infer them from the
... |
368,057 | def __set_quantity(self, value):
try:
if value < 0:
raise ValueError()
self.__quantity = Decimal(str(value))
except ValueError:
raise ValueError("Quantity must be a positive number") | Sets the quantity
@param value:str |
368,058 | def remove_lvm_physical_volume(block_device):
p = Popen([, , block_device],
stdin=PIPE)
p.communicate(input=) | Remove LVM PV signatures from a given block device.
:param block_device: str: Full path of block device to scrub. |
368,059 | def _switch_tz_offset_sql(self, field_name, tzname):
field_name = self.quote_name(field_name)
if settings.USE_TZ:
if pytz is None:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("This query requires pytz, "
... | Returns the SQL that will convert field_name to UTC from tzname. |
368,060 | def __regions_russian(self, word):
r1 = ""
r2 = ""
rv = ""
vowels = ("A", "U", "E", "a", "e", "i", "o", "u", "y")
word = (word.replace("i^a", "A")
.replace("i^u", "U")
.replace("e`", "E"))
for i in range(1, len(word)):
... | Return the regions RV and R2 which are used by the Russian stemmer.
In any word, RV is the region after the first vowel,
or the end of the word if it contains no vowel.
R2 is the region after the first non-vowel following
a vowel in R1, or the end of the word if there is no such non-vo... |
368,061 | def copyto_file_object(self, query, file_object):
response = self.copyto(query)
for block in response.iter_content(DEFAULT_CHUNK_SIZE):
file_object.write(block) | Gets data from a table into a writable file object
:param query: The "COPY { table_name [(column_name[, ...])] | (query) }
TO STDOUT [WITH(option[,...])]" query to execute
:type query: str
:param file_object: A file-like object.
Normally t... |
368,062 | def solve_sweep_wavelength(
self,
structure,
wavelengths,
filename="wavelength_n_effs.dat",
plot=True,
):
n_effs = []
for w in tqdm.tqdm(wavelengths, ncols=70):
structure.change_wavelength(w)
self.solve(structure)
n... | Solve for the effective indices of a fixed structure at
different wavelengths.
Args:
structure (Slabs): The target structure to solve
for modes.
wavelengths (list): A list of wavelengths to sweep
over.
filename (str): The nominal filen... |
368,063 | def floor_func(self, addr):
try:
prev_addr = self._function_map.floor_addr(addr)
return self._function_map[prev_addr]
except KeyError:
return None | Return the function who has the greatest address that is less than or equal to `addr`.
:param int addr: The address to query.
:return: A Function instance, or None if there is no other function before `addr`.
:rtype: Function or None |
368,064 | def get(self, instance, aslist=False, **kwargs):
refs = self.get_versioned_references_for(instance)
if not self.multiValued:
if len(refs) > 1:
logger.warning("Found {} references for non-multivalued "
"reference field of {}".format(
... | Get (multi-)references |
368,065 | def bulk_export(self, ids, exclude_captures=False):
return self.service.bulk_export(self.base, ids, params={: exclude_captures}) | Bulk export a set of results.
:param ids: Int list of result IDs.
:rtype: tuple `(io.BytesIO, 'filename')` |
368,066 | def clean_regex(regex):
ret_regex = regex
escape_chars =
ret_regex = ret_regex.replace(, )
for c in escape_chars:
ret_regex = ret_regex.replace(c, + c)
ret_regex = ret_regex[:-1]
return ret_regex | Escape any regex special characters other than alternation.
:param regex: regex from datatables interface
:type regex: str
:rtype: str with regex to use with database |
368,067 | def raw(self, sql):
res = self.cursor.execute(sql)
if self.cursor.description is None:
return res
rows = self.cursor.fetchall()
columns = [d[0] for d in self.cursor.description]
structured_rows = []
for row in rows:
data = {}
... | Execute raw sql
:Parameters:
- sql: string, sql to be executed
:Return: the result of this execution
If it's a select, return a list with each element be a DataRow instance
Otherwise return raw result from the cursor (Should be insert or update or delete) |
368,068 | def splitbins(t, trace=0):
if trace:
def dump(t1, t2, shift, bytes):
print("%d+%d bins at shift %d; %d bytes" % (
len(t1), len(t2), shift, bytes), file=sys.stderr)
print("Size of original table:", len(t)*getsize(t), \
"bytes", file=sys.st... | t, trace=0 -> (t1, t2, shift). Split a table to save space.
t is a sequence of ints. This function can be useful to save space if
many of the ints are the same. t1 and t2 are lists of ints, and shift
is an int, chosen to minimize the combined size of t1 and t2 (in C
code), and where for each i in ra... |
368,069 | def connected_client(self):
future = self.get_connected_client()
cb = functools.partial(self._connected_client_release_cb, future)
return ContextManagerFuture(future, cb) | Returns a ContextManagerFuture to be yielded in a with statement.
Returns:
A ContextManagerFuture object.
Examples:
>>> with (yield pool.connected_client()) as client:
# client is a connected tornadis.Client instance
# it will be automati... |
368,070 | def _comp_method_SERIES(cls, op, special):
op_name = _get_op_name(op, special)
masker = _gen_eval_kwargs(op_name).get(, False)
def na_op(x, y):
assert not (is_categorical_dtype(y) and not is_scalar(y))
if is_object_dtype(x.dtype):
... | Wrapper function for Series arithmetic operations, to avoid
code duplication. |
368,071 | async def _request(
self,
method: str,
endpoint: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None,
ssl: bool = True) -> dict:
return await self._client_request(
method,
... | Wrap the generic request method to add access token, etc. |
368,072 | def _sentence(self, words):
db = self.database
seed = random.randint(0, db[] - 3)
seed_word, next_word = db[][seed], db[][seed + 1]
w1, w2 = seed_word, next_word
sentence = []
for i in range(0, words - 1):
sentence.append(w1)
... | Generate a sentence |
368,073 | def handleSubRectangles(self, images, subRectangles):
if isinstance(subRectangles, (tuple, list)):
xy = subRectangles
if xy is None:
xy = (0, 0)
if hasattr(xy, ):
if len(xy) == len(images):
... | handleSubRectangles(images)
Handle the sub-rectangle stuff. If the rectangles are given by the
user, the values are checked. Otherwise the subrectangles are
calculated automatically. |
368,074 | def set_object(self, obj, properties):
self._objects.add(obj)
properties = set(properties)
self._properties |= properties
pairs = self._pairs
for p in self._properties:
if p in properties:
pairs.add((obj, p))
else:
... | Add an object to the definition and set its ``properties``. |
368,075 | def edge_val_set(self, graph, orig, dest, idx, key, branch, turn, tick, value):
if (branch, turn, tick) in self._btts:
raise TimeError
self._btts.add((branch, turn, tick))
graph, orig, dest, key, value = map(self.pack, (graph, orig, dest, key, value))
self._edgevals2... | Set this key of this edge to this value. |
368,076 | def barf(msg, exit=None, f=sys.stderr):
exit = const() if exit is None else exit
shout(msg, f)
sys.exit(exit) | Exit with a log message (usually a fatal error) |
368,077 | def add_batch(self, batch_id, batch_properties=None):
if batch_properties is None:
batch_properties = {}
if not isinstance(batch_properties, dict):
raise ValueError(
+ str(type(batch_properties)))
self._data[batch_id] = batch_properties.copy()
self._data[batch_id]... | Adds batch with give ID and list of properties. |
368,078 | def schnorr_generate_nonce_pair(self, msg, raw=False,
digest=hashlib.sha256):
if not HAS_SCHNORR:
raise Exception("secp256k1_schnorr not enabled")
msg32 = _hash32(msg, raw, digest)
pubnonce = ffi.new()
privnonce = ffi.new()
... | Generate a nonce pair deterministically for use with
schnorr_partial_sign. |
368,079 | def energy(self, sample_like, dtype=np.float):
energy, = self.energies(sample_like, dtype=dtype)
return energy | The energy of the given sample.
Args:
sample_like (samples_like):
A raw sample. `sample_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`, optional):
The data type of the returned ... |
368,080 | def get_single_item(d):
assert len(d) == 1, % len(d)
return next(six.iteritems(d)) | Get an item from a dict which contains just one item. |
368,081 | def update_sig(queue):
while True:
options, sign, vers = queue.get()
info("[+] \033[92mChecking signature version:\033[0m %s" % sign)
localver = get_local_version(options.mirrordir, sign)
remotever = vers[sign]
if localver is None or (localver and int(localver) < int(rem... | update signature |
368,082 | def find(self, func: Callable[[T], bool]) -> TOption[T]:
for x in self:
if func(x):
return TOption(x)
return TOption(None) | Usage:
>>> TList([1, 2, 3, 4, 5]).find(lambda x: x > 3)
Option --> 4
>>> TList([1, 2, 3, 4, 5]).find(lambda x: x > 6)
Option --> None |
368,083 | def plot_pairwise_distance(dist, labels=None, colorbar=True, ax=None,
imshow_kwargs=None):
import matplotlib.pyplot as plt
dist_square = ensure_square(dist)
if ax is None:
x = plt.rcParams[][0]
fig, ax = plt.subplots(figsize=(x, x))
... | Plot a pairwise distance matrix.
Parameters
----------
dist : array_like
The distance matrix in condensed form.
labels : sequence of strings, optional
Sample labels for the axes.
colorbar : bool, optional
If True, add a colorbar to the current figure.
ax : axes, optional... |
368,084 | def description(filename):
with open(filename) as fp:
for lineno, line in enumerate(fp):
if lineno < 3:
continue
line = line.strip()
if len(line) > 0:
return line | Provide a short description. |
368,085 | def _unary_(self, func, inplace=False):
funcfuncinplaceself
dst = self if inplace else self.__class__(self)
dst.x = func(dst.x)
dst.y = func(dst.y)
dst.z = func(dst.z)
return dst | :func: unary function to apply to each coordinate
:inplace: optional boolean
:return: Point
Implementation private method.
All of the unary operations funnel thru this method
to reduce cut-and-paste code and enforce consistent
behavior of unary ops.
Applies 'fu... |
368,086 | def sql_dequote_string(s: str) -> str:
if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE:
raise ValueError("Not an SQL string literal")
s = s[1:-1]
return s.replace(DOUBLE_SQUOTE, SQUOTE) | Reverses :func:`sql_quote_string`. |
368,087 | def _create_flow(self, request_handler):
if self.flow is None:
redirect_uri = request_handler.request.relative_url(
self._callback_path)
self.flow = client.OAuth2WebServerFlow(
self._client_id, self._client_secret, self._scope,
r... | Create the Flow object.
The Flow is calculated lazily since we don't know where this app is
running until it receives a request, at which point redirect_uri can be
calculated and then the Flow object can be constructed.
Args:
request_handler: webapp.RequestHandler, the requ... |
368,088 | def _prune_some_if_small(self, small_size, a_or_u):
"Merge some nodes in the directory, whilst keeping others."
prev_app_size = self.app_size()
prev_use_size = self.use_size()
keep_nodes = []
prune_app_size = 0
prune_use_size = 0
for node in self._nodes:... | Merge some nodes in the directory, whilst keeping others. |
368,089 | def model_reaction_limits(model):
for reaction in sorted(model.reactions, key=lambda r: r.id):
equation = reaction.properties.get()
if equation is None:
continue
lower_default, upper_default = None, None
if model.default_flux_limit is not None:
... | Yield model reaction limits as YAML dicts. |
368,090 | def _update_triplestore(self, es_result, action_list, **kwargs):
idx_time = XsdDatetime(datetime.datetime.utcnow())
uri_keys = {}
bnode_keys = {}
for item in action_list:
try:
uri_keys[item[]] = item[]["uri"]
except KeyError:
... | updates the triplestore with success of saves and failues of indexing
Args:
-----
es_result: the elasticsearch result list
action_list: list of elasticsearch action items that were indexed |
368,091 | def remove_folder(self, tree, prefix):
while True:
child = tree
tree = tree.parent
if not child.folders and not child.files:
del self.cache[tuple(prefix)]
if tree:
del tree.folders[prefix.pop()]
if not... | Used to remove any empty folders
If this folder is empty then it is removed. If the parent is empty as a
result, then the parent is also removed, and so on. |
368,092 | def _compute_raw_image_norm(self, data):
return np.sum(self._data, dtype=np.float64) | Helper function that computes the uncorrected inverse normalization
factor of input image data. This quantity is computed as the
*sum of all pixel values*.
.. note::
This function is intended to be overriden in a subclass if one
desires to change the way the normalizatio... |
368,093 | def igetattr(self, name, context=None, class_context=True):
context = contextmod.copy_context(context)
context.lookupname = name
try:
attr = self.getattr(name, context, class_context=class_context)[0]
for inferred in bases._infer_stmts([attr], c... | Infer the possible values of the given variable.
:param name: The name of the variable to infer.
:type name: str
:returns: The inferred possible values.
:rtype: iterable(NodeNG or Uninferable) |
368,094 | def isBridgeFiltered (self):
return ((self.__value[0] == 0x01)
and (self.__value[1] == 0x80)
and (self.__value[2] == 0xC2)
and (self.__value[3] == 0x00)
and (self.__value[4] == 0x00)
and (self.__value[5] <= 0x0F)) | Checks if address is an IEEE 802.1D MAC Bridge Filtered MAC Group Address
This range is 01-80-C2-00-00-00 to 01-80-C2-00-00-0F. MAC frames that
have a destination MAC address within this range are not relayed by
bridges conforming to IEEE 802.1D |
368,095 | def copy(self):
new = self.__class__()
for dict_attr in ("symbol2number", "number2symbol", "dfas", "keywords",
"tokens", "symbol2label"):
setattr(new, dict_attr, getattr(self, dict_attr).copy())
new.labels = self.labels[:]
new.states = self.... | Copy the grammar. |
368,096 | def picard_sort(picard, align_bam, sort_order="coordinate",
out_file=None, compression_level=None, pipe=False):
base, ext = os.path.splitext(align_bam)
if out_file is None:
out_file = "%s-sort%s" % (base, ext)
if not file_exists(out_file):
with tx_tmpdir(picard._config) ... | Sort a BAM file by coordinates. |
368,097 | def distance2_to_line(pt, l0, l1):
pt = np.atleast_1d(pt)
l0 = np.atleast_1d(l0)
l1 = np.atleast_1d(l1)
reshape = pt.ndim == 1
if reshape:
pt.shape = l0.shape = l1.shape = (1, pt.shape[0])
result = (((l0[:,0] - l1[:,0]) * (l0[:,1] - pt[:,1]) -
(l0[:,0] - pt[:,0]) * (... | The perpendicular distance squared from a point to a line
pt - point in question
l0 - one point on the line
l1 - another point on the line |
368,098 | def connect_vpc(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
from boto.vpc import VPCConnection
return VPCConnection(aws_access_key_id, aws_secret_access_key, **kwargs) | :type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.vpc.VPCConnection`
:return: A connection to VPC |
368,099 | def write_xpm(matrix, version, out, scale=1, border=None, color=,
background=, name=):
row_iter = matrix_iter(matrix, version, scale, border)
width, height = get_symbol_size(version, scale=scale, border=border)
stroke_color = colors.color_to_rgb_hex(color)
bg_color = colors.color_to_r... | \
Serializes the matrix as `XPM <https://en.wikipedia.org/wiki/X_PixMap>`_ image.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write binary data.
:param scale: Indicates the size of a single module (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.