Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
349,200 | def api_server(connection, server_class):
return server_class(
link=xbahn.connection.link.Link(
receive=connection,
respond=connection
)
) | Establishes an API Server on the supplied connection
Arguments:
- connection (xbahn.connection.Connection)
- server_class (xbahn.api.Server)
Returns:
- server_class: server instance |
349,201 | def bcc(self, bcc):
Bcc
if isinstance(bcc, basestring):
bcc = bcc.split()
self._bcc = bcc | :param bcc: Email addresses for the 'Bcc' API field.
:type bcc: :keyword:`list` or `str` |
349,202 | def key_to_path(self, key):
return os.path.join(self.cache_dir, key[:2], key[2:4],
key[4:] + ) | Return the fullpath to the file with sha1sum key. |
349,203 | def hovering_widgets(
kmgraph,
graph_fw,
ctooltips=False,
width=400,
height=300,
top=100,
left=50,
bgcolor="rgb(240,240,240)",
y_gridcolor="white",
member_textbox_width=200,
):
fnode = kmgraph["nodes"][0]
fwc = node_hist_fig(
fnode["distributio... | Defines the widgets that display the distribution of each node on hover
and the members of each nodes
Parameters
----------
kmgraph: the kepler-mapper graph dict returned by `get_mapper_graph()``
graph_fw: the FigureWidget representing the graph
ctooltips: boolean; if True/False ... |
349,204 | def _apply_features_filter(self, station_codes):
if hasattr(self, "features") and self.features is not None:
station_codes = set(station_codes)
station_codes = list(
station_codes.intersection(set(self.features))
)
return station_cod... | If the features filter is set, this will return the intersection of
those filter items and the given station codes. |
349,205 | def _log_rate(output_f, d, message=None):
if d[2] <= 0:
if message is None:
message = d[4]
d[6].append(int(d[3] / (time() - d[1])))
rate = sum(d[6]) / len(d[6])
output_f(message + + str(rate) + + str(d[0] / 1000) + )
d[1] = time()
... | Log a message for the Nth time the method is called.
d is the object returned from init_log_rate |
349,206 | def block_username(username):
if not username:
return
if config.DISABLE_USERNAME_LOCKOUT:
return
key = get_username_blocked_cache_key(username)
if config.COOLOFF_TIME:
REDIS_SERVER.set(key, , config.COOLOFF_TIME)
else:
REDIS_SERVER.set(key, )
... | given the username block it. |
349,207 | def _hook_unmapped(self, uc, access, address, size, value, data):
try:
m = self._create_emulated_mapping(uc, address)
except MemoryException as e:
self._to_raise = e
self._should_try_again = False
return False
self._should_try_again = Tr... | We hit an unmapped region; map it into unicorn. |
349,208 | def CopyMicrosecondsToFractionOfSecond(cls, microseconds):
if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND:
raise ValueError(
.format(
microseconds))
return decimal.Decimal(microseconds) / definitions.MICROSECONDS_PER_SECOND | Copies the number of microseconds to a fraction of second value.
Args:
microseconds (int): number of microseconds.
Returns:
decimal.Decimal: fraction of second, which must be a value between 0.0 and
1.0.
Raises:
ValueError: if the number of microseconds is out of bounds. |
349,209 | def __extractSkosConcepts(self):
self.skosConcepts = []
qres = self.queryHelper.getSKOSInstances()
for candidate in qres:
test_existing_cl = self.getSkosConcept(uri=candidate[0])
if not test_existing_cl:
self.skosConcepts += [... | 2015-08-19: first draft |
349,210 | def predictions(self, image):
return np.squeeze(self.batch_predictions(image[np.newaxis]), axis=0) | Convenience method that calculates predictions for a single image.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
Returns
-------
`numpy.ndarray`
Vector of... |
349,211 | def to_dict(self, **kwargs):
d = {}
if self.query:
d["query"] = self.query.to_dict()
if self._script:
d[] = self._script
d.update(self._extra)
d.update(kwargs)
return d | Serialize the search into the dictionary that will be sent over as the
request'ubq body.
All additional keyword arguments will be included into the dictionary. |
349,212 | def _parse_host(cls, host=, port=0):
if not port and (host.find() == host.rfind()):
i = host.rfind()
if i >= 0:
host, port = host[:i], host[i + 1:]
try:
port = int(port)
except ValueError:
ra... | Parse provided hostname and extract port number
:param host: Server hostname
:type host: string
:param port: Server port
:return: Tuple of (host, port)
:rtype: tuple |
349,213 | def delete_user_rating(self, item_type, item_id):
raw_response = requests_util.run_request(,
self.API_BASE_URL + %
(item_type, item_id), headers=self.__get_header_with_auth())
return self.parse_... | Deletes from the list of rating of the current user, the rating provided for the specified element type.
:param item_type: One of: series, episode, banner.
:param item_id: The TheTVDB Id of the item.
:return: a python dictionary with either the result of the search or an error from TheTVDB. |
349,214 | def _uptime_bsd():
global __boottime
try:
libc = ctypes.CDLL()
except AttributeError:
return None
except OSError:
return None
buf = ctypes.create_string_buffer(sz.value)
libc.sysctlbyname(, buf, ctypes.byref(sz), None, 0)
sec, usec = struct.unpack(... | Returns uptime in seconds or None, on BSD (including OS X). |
349,215 | def check_valid_locations(self, locations=None):
if locations is None:
locations = self.locations
for location in locations:
if (not self.is_server(location) and
not self.is_ssh_url(location) and
not self.has_host(location)):
... | Fail if 'locations' contains bad destinations. |
349,216 | def set_up_phase(self, training_info, model, source):
self._optimizer_instance = self.optimizer_factory.instantiate(model)
self._source = source
self.special_callback = CycleCallback(
self._optimizer_instance,
max_lr=self.max_lr, min_lr=self.min_lr, cyc... | Prepare the phase for learning |
349,217 | def cmd(
name,
func=None,
arg=(),
**kwargs):
ret = {: name,
: {},
: ,
: True}
if func is None:
func = name
local_opts = {}
local_opts.update(__opts__)
local_opts[] = True
local_opts.update({
: func,
:... | Execute a runner asynchronous:
USAGE:
.. code-block:: yaml
run_cloud:
runner.cmd:
- func: cloud.create
- arg:
- my-ec2-config
- myinstance
run_cloud:
runner.cmd:
- func: cloud.create
- kwargs:... |
349,218 | def configure(self, options, conf):
super(NoseExclude, self).configure(options, conf)
self.exclude_dirs = {}
if options.exclude_dir_file:
if not options.exclude_dirs:
options.exclude_dirs = []
new_dirs = self._load_from_file(options.ex... | Configure plugin based on command line options |
349,219 | def print_images(self, *printable_images):
printable_image = reduce(lambda x, y: x.append(y), list(printable_images))
self.print_image(printable_image) | This method allows printing several images in one shot. This is useful if the client code does not want the
printer to make pause during printing |
349,220 | def remove(self):
title = % self.__class__.__name__
if not self.admin_access:
raise Exception( % title)
if self.configs[].find() > -1:
flush_url = self.configs[] + % (self.configs[], self.bucket_name)
response = requests.post... | a method to remove the entire bucket from the database
:return: string with confirmation message |
349,221 | def is_dir_url(link):
link_path = url_to_path(link.url_without_fragment)
return os.path.isdir(link_path) | Return whether a file:// Link points to a directory.
``link`` must not have any other scheme but file://. Call is_file_url()
first. |
349,222 | def prepare_everything(self):
self.prepare_network()
self.init_models()
self.load_conditions()
with hydpy.pub.options.warnmissingobsfile(False):
self.prepare_nodeseries()
self.prepare_modelseries()
self.load_inputseries() | Convenience method to make the actual |HydPy| instance runable. |
349,223 | def listMemberHelps(TargetGroup):
r
Members = []
for Member in TargetGroup.Members.values():
if Member not in Members:
Members.append(Member)
Ret = []
for Member in Members:
Config = Member.Config
Ret.append(( % (Config[], % Config[] if in Config else ), Config.get(, )))
return Ret | r"""Gets help on a group's children. |
349,224 | def collection_names(self, include_system_collections=True):
with self.__client._socket_for_reads(
ReadPreference.PRIMARY) as (sock_info, slave_okay):
wire_version = sock_info.max_wire_version
results = self._list_collections(sock_info, slave_okay)
... | Get a list of all the collection names in this database.
:Parameters:
- `include_system_collections` (optional): if ``False`` list
will not include system collections (e.g ``system.indexes``) |
349,225 | def transform(data, keysToSplit=[]):
transformed = { }
for key in data:
if key in keysToSplit:
transformed[key] = data[key][].split(SEPARATOR)
else:
transformed[key] = data[key][]
return transformed | Transform a SPARQL json result by:
1) outputing only { key : value }, removing datatype
2) for some keys, transform them into array based on SEPARATOR |
349,226 | def excel_to_bytes(wb: Workbook) -> bytes:
memfile = io.BytesIO()
wb.save(memfile)
return memfile.getvalue() | Obtain a binary version of an :class:`openpyxl.Workbook` representation of
an Excel file. |
349,227 | def GetPlatformRestrictions(campaign_feed):
platform_restrictions = None
if campaign_feed[][] == :
for argument in campaign_feed[][]:
if argument[][] == :
request_context_operand = argument[][][0]
if (request_context_operand and
request_context_operand == ):
... | Get the Platform Restrictions for a given Campaign Feed.
Args:
campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for.
Returns:
The Platform Restrictions for the given feed. |
349,228 | def _check_metaclasses(self, node):
consumed = []
for child_node in node.get_children():
if isinstance(child_node, astroid.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
for scope_locals, name in consumed:... | Update consumption analysis for metaclasses. |
349,229 | def update(self, chat_id, op_user, name=None, owner=None,
add_user_list=None, del_user_list=None):
data = optionaldict(
chatid=chat_id,
op_user=op_user,
name=name,
owner=owner,
add_user_list=add_user_list,
del_user_l... | 修改会话
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param chat_id: 会话 ID
:param op_user: 操作人 userid
:param name: 会话标题
:param owner: 管理员userid,必须是该会话userlist的成员之一
:param add_user_list: 会话新增成员列表,成员用userid来标识
:param del_user_list: 会话退出成员列表... |
349,230 | def api_run_get(run_id):
data = current_app.config["data"]
run = data.get_run_dao().get(run_id)
records_total = 1 if run is not None else 0
if records_total == 0:
return Response(
render_template(
"api/error.js",
error_code=404,
er... | Return a single run as a JSON object. |
349,231 | def delete(self, key):
dct = self
keys = key.split()
last_key = keys[-1]
for k in keys:
if k == last_key:
del dct[k]
break
if isinstance(dct, DotDict):
dct = super(Dot... | Remove a value from the `DotDict`.
The `key` parameter can either be a regular string key,
e.g. "foo", or it can be a string key with dot notation,
e.g. "foo.bar.baz", to signify a nested element.
If the key does not exist in the `DotDict`, it will continue
silently.
A... |
349,232 | def relocated_grid_stack_from_grid_stack(self, grid_stack):
border_grid = grid_stack.regular[self]
return GridStack(regular=self.relocated_grid_from_grid_jit(grid=grid_stack.regular, border_grid=border_grid),
sub=self.relocated_grid_from_grid_jit(grid=grid_stack.sub, bo... | Determine a set of relocated grid_stack from an input set of grid_stack, by relocating their pixels based on the \
borders.
The blurring-grid does not have its coordinates relocated, as it is only used for computing analytic \
light-profiles and not inversion-grid_stack.
Parameters
... |
349,233 | def _or(ctx, *logical):
for arg in logical:
if conversions.to_boolean(arg, ctx):
return True
return False | Returns TRUE if any argument is TRUE |
349,234 | def models_for_pages(*args):
from warnings import warn
warn("template tag models_for_pages is deprectaed, use "
"PageAdmin.get_content_models instead")
from yacms.pages.admin import PageAdmin
return PageAdmin.get_content_models() | Create a select list containing each of the models that subclass the
``Page`` model. |
349,235 | def load_filesystem_plugins(self):
self.logger.info()
search_path = self.__get_fs_plugin_search_path()
fs_plugins = []
PluginManagerSingleton.setBehaviour([
VersionedPluginManager,
])
plugin_manager = PluginManagerSingleton.get()
pl... | Looks for *.yapsy-plugin files, loads them and returns a list
of :class:`VersionedPluginInfo \
<yapsy.VersionedPluginManager.VersionedPluginInfo>` objects
Note:
Plugin search locations:
* $(rawdisk package location)/plugins/filesystems
... |
349,236 | def del_client(self, **kwargs):
try:
body = self.vtep_app.del_client(**kwargs)
except (BGPSpeakerNotFound, DatapathNotFound,
VniNotFound, ClientNotFound, ClientNotLocal) as e:
return Response(body=str(e), status=500)
return Response(content_type=... | Registers a new client to the specified network.
Usage:
======= ===================================
Method URI
======= ===================================
DELETE /vtep/networks/{vni}/clients/{mac}
======= ===================================
... |
349,237 | def valid_daily_mean_discharge(comp):
r
@wraps(comp)
def func(q, **kwds):
check_valid_discharge(q)
return comp(q, **kwds)
return func | r"""Decorator to check that a computation runs on valid discharge data. |
349,238 | def checkURL(cls, trust_root, url):
tr = cls.parse(trust_root)
return tr is not None and tr.validateURL(url) | quick func for validating a url against a trust root. See the
TrustRoot class if you need more control. |
349,239 | def to_affine(self):
X, Y, Z = self.x, self.y, self.inverse(self.z)
return ((X * Z ** 2) % P, (Y * Z ** 3) % P) | Converts this point to an affine representation.
Returns:
AffinePoint: The affine reprsentation. |
349,240 | def detect_output_type(args):
if not args[] and not args[]:
if len(args[]) > 1 or len(args[]) > 1:
args[] = True
else:
args[] = True | Detect whether to save to a single or multiple files. |
349,241 | def set_fold_trigger(block, val):
if block is None:
return
state = block.userState()
if state == -1:
state = 0
state &= 0x7BFFFFFF
state |= int(val) << 26
block.setUserState(state) | Set the block fold trigger flag (True means the block is a fold
trigger).
:param block: block to set
:param val: value to set |
349,242 | def merge(self,DataTypeTargetForNetworkCollection=None,\
dataTypeTargetForNetworkList=None,mergeType=None,SourceMergeColumns=None,\
SourceMergeKey=None,SourceTable=None,TargetKeyNetworkCollection=None,\
TargetMergeKey=None,TargetNetworkCollection=None,TargetNetworkList=None,\
UnassignedT... | Merge tables together joining around a designated key column. Depending
on the arguments, might merge into multiple local tables.
:param DataTypeTargetForNetworkCollection (string, optional): The collectio
n of networks where the merged table will reside
:param dataTypeTargetForNetw... |
349,243 | def check_params_types(self, method):
mn = method.__name__
annos = dict(method.__annotations__)
errors = []
msg_tuple =
msg_ptype =
msg_mod =
msg_cls =
bodies = []
for pname, anno in annos.items():
if pname == :
... | Types in argument annotations must be instances, not classes. |
349,244 | async def init():
global redis_conn
conn = await aioredis.create_connection(
.format(
SETTINGS.get(, {}).get(, {}).get(, ),
SETTINGS.get(, {}).get(, {}).get(, 56379)
),
db=int(SETTINGS.get(, {}).get(, {}).get(, 1))
)
redis_conn = aioredis.Redis(conn... | Create a connection to the Redis server. |
349,245 | def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None
print(SEPARATOR, file=sys.stderr)
... | Load filename as a python file. Import ``filename`` and return it
as a module. |
349,246 | def lock_account(self, identifier):
locked_time = int(time.time() * 1000)
self.account_store.lock_account(identifier, locked_time) | :type account: Account |
349,247 | def ffill_query_in_range(expr,
lower,
upper,
checkpoints=None,
odo_kwargs=None,
ts_field=TS_FIELD_NAME):
odo_kwargs = odo_kwargs or {}
computed_lower, materialized_checkpoints = get_... | Query a blaze expression in a given time range properly forward filling
from values that fall before the lower date.
Parameters
----------
expr : Expr
Bound blaze expression.
lower : datetime
The lower date to query for.
upper : datetime
The upper date to query for.
... |
349,248 | def is_authenticated(self):
token = self.con.token_backend.token
if not token:
token = self.con.token_backend.get_token()
return token is not None and not token.is_expired | Checks whether the library has the authentication and that is not expired
:return: True if authenticated, False otherwise |
349,249 | def Dictionary(self):
d = self.__dict__[].Dictionary().copy()
d.update(self.__dict__[])
return d | Emulates the items() method of dictionaries. |
349,250 | async def handle_adapter_event(self, adapter_id, conn_string, conn_id, name, event):
if name == :
self._track_device_seen(adapter_id, conn_string, event)
event = self._translate_device_seen(adapter_id, conn_string, event)
conn_string = self._translate_conn_string(a... | Handle an event received from an adapter. |
349,251 | def rot_rads_v2(vec_a, rads):
x = vec_a.x * math.cos(rads) - vec_a.y * math.sin(rads)
y = vec_a.x * math.sin(rads) + vec_a.y * math.cos(rads)
return Vec2(x, y) | Rotate vector by angle in radians. |
349,252 | def forward(self, x):
fwd = np.zeros((self.num_matrices, self.N, self.N), settings.float_type)
indices = np.tril_indices(self.N, 0)
z = np.zeros(len(indices[0])).astype(int)
for i in range(self.num_matrices):
fwd[(z + i,) + indices] = x[i, :]
return fwd.squee... | Transforms from the packed to unpacked representations (numpy)
:param x: packed numpy array. Must have shape `self.num_matrices x triangular_number
:return: Reconstructed numpy array y of shape self.num_matrices x N x N |
349,253 | def tipbod(ref, body, et):
ref = stypes.stringToCharP(ref)
body = ctypes.c_int(body)
et = ctypes.c_double(et)
retmatrix = stypes.emptyDoubleMatrix()
libspice.tipbod_c(ref, body, et, retmatrix)
return stypes.cMatrixToNumpy(retmatrix) | Return a 3x3 matrix that transforms positions in inertial
coordinates to positions in body-equator-and-prime-meridian
coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tipbod_c.html
:param ref: ID of inertial reference frame to transform from.
:type ref: str
:param body: ID ... |
349,254 | def _generate_alias_type(self, alias_type):
namespace = alias_type.namespace
self.emit( % (fmt_type_name(alias_type, namespace),
fmt_type_name(alias_type.data_type, namespace)))
self.emit() | Generates a TypeScript type for a stone alias. |
349,255 | def _refresh_buckets_cache_file(cache_file):
log.debug()
key, keyid, service_url, verify_ssl, kms_keyid, location, path_style, https_enable = _get_s3_key()
metadata = {}
def __get_s3_meta(bucket, key=key, keyid=keyid):
ret, marker = [],
while True:
tmp = __utils... | Retrieve the content of all buckets and cache the metadata to the buckets
cache file |
349,256 | def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
super(ApplicationSpecificInformation, self).read(
istream,
kmip_version=kmip_version
)
tstream = BytearrayStream(istream.read(self.length))
self.application_namespace.read(tstream, kmip_ve... | Read the data encoding the ApplicationSpecificInformation object and
decode it into its constituent parts.
Args:
istream (Stream): A data stream containing encoded object data,
supporting a read method; usually a BytearrayStream object.
kmip_version (KMIPVersion)... |
349,257 | def minimumLineInArray(arr, relative=False, f=0,
refinePosition=True,
max_pos=100,
return_pos_arr=False,
):
s0, s1 = arr.shape[:2]
if max_pos >= s1:
x = np.arange(s1)
els... | find closest minimum position next to middle line
relative: return position relative to middle line
f: relative decrease (0...1) - setting this value close to one will
discriminate positions further away from the center
##order: 2 for cubic refinement |
349,258 | def encode_genotype(s, mindepth=3, depth_index=2, nohet=False):
atoms = s.split(":")
if len(atoms) < 3:
return g2x[atoms[0]]
inferred = atoms[0]
depth = int(atoms[depth_index])
if depth < mindepth:
return
if inferred == :
return
if inferred == :
return... | >>> encode_genotype("1/1:128,18,0:6:18") # homozygote B
'B'
>>> encode_genotype("0/1:0,0,0:0:3") # missing data
'-'
>>> encode_genotype("0/1:128,0,26:7:22") # heterozygous A/B
'X' |
349,259 | def new(cls, **kwargs):
kwargs = cls.preprocess_kwargs_before_new(kwargs)
if cls.__mapper__.polymorphic_on is not None:
discriminator_key = cls.__mapper__.polymorphic_on.name
discriminator_val = kwargs.get(discriminator_key)
if discriminator_val is not None a... | Returns a new, unsaved instance of the model class. |
349,260 | def check(self, locator=None, allow_label_click=None, **kwargs):
self._check_with_label(
"checkbox", True, locator=locator, allow_label_click=allow_label_click, **kwargs) | Find a check box and mark it as checked. The check box can be found via name, id, or label
text. ::
page.check("German")
Args:
locator (str, optional): Which check box to check.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
... |
349,261 | def inside_softimage():
try:
import maya
return False
except ImportError:
pass
try:
from win32com.client import Dispatch as disp
disp()
return True
except:
return False | Returns a boolean indicating if the code is executed inside softimage. |
349,262 | def set_style(self, column, style):
column_idx = None
while len(self.headers) > len(self.__style_list):
self.__style_list.append(None)
if isinstance(column, six.integer_types):
column_idx = column
elif isinstance(column, six.string_types):
... | Set |Style| for a specific column.
Args:
column (|int| or |str|):
Column specifier. column index or header name correlated with the column.
style (|Style|):
Style value to be set to the column.
Raises:
ValueError: If the column specif... |
349,263 | def checkAlphabet(self, count=10):
if six.PY3:
readLetters = super().checkAlphabet(count)
else:
readLetters = Read.checkAlphabet(self, count)
if len(self) > 10 and readLetters.issubset(set()):
raise ValueError(
)
r... | A function which checks if an AA read really contains amino acids. This
additional testing is needed, because the letters in the DNA alphabet
are also in the AA alphabet.
@param count: An C{int}, indicating how many bases or amino acids at
the start of the sequence should be conside... |
349,264 | def removeRemoteByName(self, name: str) -> int:
remote = self.getRemote(name)
rid = remote.uid
self.removeRemote(remote)
return rid | Remove the remote by name.
:param name: the name of the remote to remove
:raises: RemoteNotFound |
349,265 | def cmd(send, msg, args):
if not msg:
send("kill who?")
return
if msg.lower() == args[].lower():
send( % msg)
else:
send( % msg) | Kills somebody.
Syntax: {command} <victim> |
349,266 | def offset_random_rgb(seed, amount=1):
r, g, b = seed
results = []
for _ in range(amount):
base_val = ((r + g + b) / 3) + 1
new_val = base_val + (random.random() * rgb_max_val / 5)
ratio = new_val / base_val
results.append((min(int(r*ratio), rgb_max_val), min(int(g*... | Given a seed color, generate a specified number of random colors (1 color by default) determined by a randomized
offset from the seed.
:param seed:
:param amount:
:return: |
349,267 | def fit(self, data):
self._setup_from_data(data)
self.transform_chain.fit(data)
self.__proxy__.update({"fitted" : True})
return self | Fits a transformer using the SFrame `data`.
Parameters
----------
data : SFrame
The data used to fit the transformer.
Returns
-------
self (A fitted object)
See Also
--------
transform, fit_transform |
349,268 | def sizes(args):
from jcvi.formats.base import DictFile
from jcvi.apps.align import blast
p = OptionParser(sizes.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
gapsbed, afasta, bfasta = args
pf = gapsbed.rsplit(".", 1)[0]
extbed =... | %prog sizes gaps.bed a.fasta b.fasta
Take the flanks of gaps within a.fasta, map them onto b.fasta. Compile the
results to the gap size estimates in b. The output is detailed below:
Columns are:
1. A scaffold
2. Start position
3. End position
4. Gap identifier
5. Gap size in A (= ... |
349,269 | def read_msr(address):
if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
raise NotImplementedError(
"MSR reading is only supported on i386 or amd64 processors.")
msr = win32.SYSDBG_MSR()
msr.Address = address
msr.Data = 0
wi... | Read the contents of the specified MSR (Machine Specific Register).
@type address: int
@param address: MSR to read.
@rtype: int
@return: Value of the specified MSR.
@raise WindowsError:
Raises an exception on error.
@raise NotImplementedError:
... |
349,270 | def NTU_from_P_E(P1, R1, Ntp, optimal=True):
rs rational number support
works better but is extremely slow for these complicated solutions.
Nevertheless, so long as a solution is between 1E-11 and 10, the solver is
quite robust.
Examples
--------
>>> NTU_from_P_E(P1=.58, R1=1/3., Ntp=2)
... | r'''Returns the number of transfer units of a TEMA E type heat exchanger
with a specified (for side 1) thermal effectiveness `P1`, heat capacity
ratio `R1`, the number of tube passes `Ntp`, and for the two-pass case
whether or not the inlets are arranged optimally. The supported cases are
as follows:
... |
349,271 | def observe(self, success, failure):
if isinstance(success, int) is False:
if isinstance(success, float) is False:
raise TypeError()
if isinstance(failure, int) is False:
if isinstance(failure, float) is False:
raise TypeError()
i... | Observation data.
Args:
success: The number of success.
failure: The number of failure. |
349,272 | def get_capability_definitions(profile_manager):
res_type = pbm.profile.ResourceType(
resourceType=pbm.profile.ResourceTypeEnum.STORAGE)
try:
cap_categories = profile_manager.FetchCapabilityMetadata(res_type)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise... | Returns a list of all capability definitions.
profile_manager
Reference to the profile manager. |
349,273 | def from_sequence(cls, *args):
start = None
stop = None
if len(args) == 1:
stop = args[0]
elif len(args) == 2:
start = args[0]
stop = args[1]
if stop is None and start is None:
raise TypeError("from_sequence expec... | from_sequence(start=0, stop)
Create an SArray from sequence
.. sourcecode:: python
Construct an SArray of integer values from 0 to 999
>>> tc.SArray.from_sequence(1000)
This is equivalent, but more efficient than:
>>> tc.SArray(range(1000))
... |
349,274 | def add_endpoint(self, endpoint):
if self.url_prefix:
url = .format(prefix=self.url_prefix, url=endpoint.url)
else:
url = endpoint.url
self.add_url_rule(
url,
view_func=endpoint.as_view(endpoint.get_name()),
) | Register an :class:`.Endpoint` aginst this resource.
:param endpoint: :class:`.Endpoint` API Endpoint class
Usage::
foo_resource = Resource('example', __name__)
class MyEndpoint(Endpoint):
url = '/example'
name = 'myendpoint'
foo_r... |
349,275 | def MapEncoder(field_descriptor):
message_type = field_descriptor.message_type
encode_message = MessageEncoder(field_descriptor.number, False, False)
def EncodeField(write, value):
for key in value:
entry_msg = message_type._concrete_class(key=key, value=value[key])
encode_message(write,... | Encoder for extensions of MessageSet.
Maps always have a wire format like this:
message MapEntry {
key_type key = 1;
value_type value = 2;
}
repeated MapEntry map = N; |
349,276 | def get_credentials(self):
creds_mgr = CredentialsManager(self)
creds = creds_mgr.get_credentials_from_upload_api()
return {
: creds[],
: creds[],
: creds[],
: creds[]
} | Return a set of credentials that may be used to access the Upload Area folder in the S3 bucket
:return: a dict containing AWS credentials in a format suitable for passing to Boto3
or if capitalized, used as environment variables |
349,277 | def __extract_autoWidgets(self):
if self.__autoWidgets_calculated: return
if self._builder is not None:
for wid in self._builder.get_objects():
try:
name = Gtk.Buildable.get_name(wid)
except TypeE... | Extract autoWidgets map if needed, out of the glade
specifications and gtk builder |
349,278 | def _merge_prefix(self, size):
if len(self._buf) == 1 and len(self._buf[0]) <= size:
return
prefix = []
remaining = size
while self._buf and remaining > 0:
chunk = self._buf.popleft()
if len(chunk) > remaining:
self._buf.append... | Replace the first entries in a deque of strings with a single
string of up to size bytes.
>>> d = collections.deque(['abc', 'de', 'fghi', 'j'])
>>> _merge_prefix(d, 5); print(d)
deque(['abcde', 'fghi', 'j'])
Strings will be split as necessary to reach the desired size.
... |
349,279 | def construct_difference(self, parent, excluded, name=None, fp=None):
assert parent in self.locations, "Cant find location {}".format(location)
included = set(self.data[parent]).difference(
reduce(set.union, [set(self.data[loc]) for loc in excluded])
)
geom = _union(... | Construct geometry from ``parent`` without the regions in ``excluded`` and optionally write to filepath ``fp``.
``excluded`` must be an iterable of location strings (not face ids). |
349,280 | def reduceByKeyLocally(self, func):
func = fail_on_stopiteration(func)
def reducePartition(iterator):
m = {}
for k, v in iterator:
m[k] = func(m[k], v) if k in m else v
yield m
def mergeMaps(m1, m2):
for k, v in m2.items(... | Merge the values for each key using an associative and commutative reduce function, but
return the results immediately to the master as a dictionary.
This will also perform the merging locally on each mapper before
sending results to a reducer, similarly to a "combiner" in MapReduce.
>... |
349,281 | def get_from_dicts(dict1, key, default_value, dict2, extra=):
value=default_value
if key not in dict1:
if dict2!=None:
value=dict2.get(extra+key, default_value)
else:
value=dict1[key]
del(dict1[key])
if dict2!=None:
dict2[extra+key]=value
return v... | Input: dict1 - first check in this dict (and remove if there)
key - key in dict1
default_value - default value if not found
dict2 - then check from here
Output: value |
349,282 | def mea_approximation(model, max_order, closure=, *closure_args, **closure_kwargs):
r
mea = MomentExpansionApproximation(model, max_order, closure=closure, *closure_args, **closure_kwargs)
return mea.run() | r"""
A wrapper around :class:`~means.approximation.mea.moment_expansion_approximation.MomentExpansionApproximation`.
It performs moment expansion approximation (MEA) up to a given order of moment.
See :class:`~means.approximation.mea.moment_expansion_approximation.MomentExpansionApproximation` for detail... |
349,283 | def _publish_stats(self, counter_prefix, stats):
for stat_name, stat_value in flatten_dictionary(
stats,
prefix=counter_prefix,
):
self.publish_gauge(stat_name, stat_value) | Given a stats dictionary from _get_stats_from_socket,
publish the individual values. |
349,284 | def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256):
if not isinstance(hash_hex, (str, unicode)):
raise ValueError("hash hex is not a string")
hash_hex = str(hash_hex)
pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex)
sig_r, sig_s = decode_signature(... | Given a digest, public key (as hex), and a base64 signature,
verify that the public key signed the digest.
Return True if so
Return False if not |
349,285 | def _json_safe(data):
if not hasattr(data, ):
try:
data = data.decode()
except UnicodeDecodeError:
raise ValueError(
% (data,))
return data | json.loads wants an unistr in Python3. Convert it. |
349,286 | def create_legacy_pad(scope, input_name, output_name, H_in, W_in, k_h, k_w,
s_h, s_w, p_h, p_w, padded_value, container):
pooling under IncludeLastPixel padding mode.
:param scope:
:param input_name:
:param output_name:
:param H_in: input dimension along H-axis
:param W_i... | This function adds one Pad operator into its last argument, which is a Container object. By feeding the output of
the created Pad operator into Pool operator under valid padding mode, we can achieve the same functionality of
CoreML' pooling under IncludeLastPixel padding mode.
:param scope:
:param inpu... |
349,287 | def now(self):
localtime = datetime.datetime.now()
return localtime + datetime.timedelta(hours = time.timezone/60/60 + self.TimeZone) | Display Taiwan Time now
顯示台灣此刻時間 |
349,288 | def set_passthrough(self, bus, enabled):
request = {
"command": "passthrough",
"bus": bus,
"enabled": enabled
}
return self._check_command_response_status(request) | Control the status of CAN message passthrough for a bus.
Returns True if the command was successful. |
349,289 | def read_text_file(filename, encoding="utf-8"):
try:
with open(filename, , encoding) as f:
r = f.read()
except TypeError:
with open(filename, ) as f:
r = f.read()
return r | Reads a file under python3 with encoding (default UTF-8).
Also works under python2, without encoding.
Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp)
principle. |
349,290 | def parse(self, rule: str):
if not rule:
return checks.TrueCheck()
for token, value in self._parse_tokenize(rule):
self._shift(token, value)
try:
return self.result
except ValueError:
LOG.exception(, rule)
... | Parses policy to tree.
Translate a policy written in the policy language into a tree of
Check objects. |
349,291 | def get_assessments_taken(self):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
result = collection.find(self._view_filter()).sort(, DESCENDING)
return ob... | Gets all ``AssessmentTaken`` elements.
In plenary mode, the returned list contains all known
assessments taken or an error results. Otherwise, the returned
list may contain only those assessments taken that are
accessible through this session.
return: (osid.assessment.Assessmen... |
349,292 | def make_country_matrix(self, loc):
top = loc[][]
top_count = loc[][]
two = loc[][]
two_count = loc[][]
word_vec = loc[][]
first_back = loc[][]
most_alt = loc[][]
most_pop = loc[][]
possible_labels = set([top, two, word_vec, first_back, ... | Create features for all possible country labels, return as matrix for keras.
Parameters
----------
loc: dict
one entry from the list of locations and features that come out of make_country_features
Returns
--------
keras_inputs: dict with two keys, "label" a... |
349,293 | def p_namespace(self, p):
p[0] = ast.Namespace(scope=p[2], name=p[3], lineno=p.lineno(1)) | namespace : NAMESPACE namespace_scope IDENTIFIER |
349,294 | def _offset_subplot_ids(fig, offsets):
for trace in fig.get(, None):
trace_type = trace.get(, )
subplot_types = _trace_to_subplot.get(trace_type, [])
for subplot_type in subplot_types:
subplot_prop_name = _get_subplot_prop_name(subplot_type)
s... | Apply offsets to the subplot id numbers in a figure.
Note: This function mutates the input figure dict
Note: This function assumes that the normalize_subplot_ids function has
already been run on the figure, so that all layout subplot properties in
use are explicitly present in the figure's layout.
... |
349,295 | def Zebra():
"Return an instance of the Zebra Puzzle."
Colors = .split()
Pets = .split()
Drinks = .split()
Countries = .split()
Smokes = .split()
vars = Colors + Pets + Drinks + Countries + Smokes
domains = {}
for var in vars:
domains[var] = range(1, 6)
domains[] = [1]
... | Return an instance of the Zebra Puzzle. |
349,296 | def random_string_alphanumeric(size):
return .join(random.choice(string.ascii_letters + string.digits) for x in range(size)) | Generate a random string of *size* length consisting of mixed case letters
and numbers. This function is not meant for cryptographic purposes.
:param int size: The length of the string to return.
:return: A string consisting of random characters.
:rtype: str |
349,297 | def list_group_s_users(self, group_id, include=None, search_term=None):
path = {}
data = {}
params = {}
path["group_id"] = group_id
if search_term is not None:
params["search_term"] = search_term
... | List group's users.
Returns a list of users in the group. |
349,298 | def delete_sessions(self, uid):
title = % self.__class__.__name__
input_fields = {
: uid
}
for key, value in input_fields.items():
object_title = % (title, key, str(value))
self.fields.validate(value, % key, obje... | a method to delete all session tokens associated with a user
:param uid: string with id of user in bucket
:return: integer with status code of delete operation |
349,299 | def complete(
self, config, prompt, session, context, current_arguments, current
):
with use_ipopo(context) as ipopo:
try:
for idx, completer_id in enumerate(config.completers):
if completer_id == FACTORY:
... | Returns the list of services IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.