text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_belbio_conf_files():
"""Get belbio configuration from files
"""
home = os.path.expanduser("~")
cwd = os.getcwd()
belbio_conf_fp, belbio_secrets_fp = "", ""
env_conf_dir = os.getenv("BELBIO_CONF", "").rstrip("/")
conf_paths = [
f"{cwd}/belbio_conf.yaml",
f"{cwd}/be... | 0.001778 |
def post_create_app(cls, app, **settings):
"""Register the errorhandler for the AppException to the passed in
App.
Args:
app (fleaker.base.BaseApplication): A Flask application that
extends the Fleaker Base Application, such that the hooks are
impleme... | 0.002162 |
def env(self):
"""Env vars for kernels"""
# Add our PYTHONPATH to the kernel
pathlist = CONF.get('main', 'spyder_pythonpath', default=[])
default_interpreter = CONF.get('main_interpreter', 'default')
pypath = add_pathlist_to_PYTHONPATH([], pathlist, ipyconsole=True,
... | 0.001128 |
def absent(name, auth=None):
'''
Ensure service does not exist
name
Name of the service
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
service = __salt__['keystoneng.service_get'](n... | 0.001418 |
def trace_grid_stack_to_next_plane(self):
"""Trace this plane's grid_stacks to the next plane, using its deflection angles."""
def minus(grid, deflections):
return grid - deflections
return self.grid_stack.map_function(minus, self.deflection_stack) | 0.01049 |
async def get_metrics(self):
"""Get metrics for the unit.
:return: Dictionary of metrics for this unit.
"""
metrics = await self.model.get_metrics(self.tag)
return metrics[self.name] | 0.008929 |
def create_lti_session(self, user_id, roles, realname, email, course_id, task_id, consumer_key, outcome_service_url,
outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label):
""" Creates an LTI cookieless session. Returns the new session id"""
self._de... | 0.005372 |
def domains(self):
"""The domains for this app."""
return self._h._get_resources(
resource=('apps', self.name, 'domains'),
obj=Domain, app=self
) | 0.010363 |
def normalize_encoding(encoding, default=DEFAULT_ENCODING):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
return default
try:
codecs.lookup(encoding)
ret... | 0.002639 |
def __split_name_unit(self, line):
"""
Split a string that has value and unit as one.
:param str line:
:return str str:
"""
vals = []
unit = ''
if line != '' or line != ' ':
# If there are parenthesis, remove them
line = line.replac... | 0.001643 |
async def starter_bus_async(loop = None, **kwargs) :
"returns a Connection object for the D-Bus starter bus."
return \
Connection \
(
await dbus.Connection.bus_get_async(DBUS.BUS_STARTER, private = False, loop = loop)
) \
.register_additional_standard(**kwargs) | 0.0347 |
def str_lsnode(self, astr_path=""):
"""
Print/return the set of nodes branching from current node as string
"""
self.sCore.reset()
str_cwd = self.cwd()
if len(astr_path): self.cdnode(astr_path)
for node in self.snode_current.d_nod... | 0.01006 |
def pick_q_v1(self):
"""Assign the actual value of the inlet sequence to the upper joint
of the subreach upstream."""
inl = self.sequences.inlets.fastaccess
new = self.sequences.states.fastaccess_new
new.qjoints[0] = 0.
for idx in range(inl.len_q):
new.qjoints[0] += inl.q[idx][0] | 0.003205 |
def _send(self, message):
"""
A helper method that does the actual sending
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool
"""
params = {
'from': message.from_phone,
'to': "... | 0.007599 |
def push_location(
self,
element_path, # type: Text
array_index=None # type: Optional[int]
):
# type: (...) -> None
"""Push an item onto the state's stack of locations."""
location = ProcessorLocation(element_path=element_path, array_index=array_index)
... | 0.013928 |
def Scanner(function, *args, **kw):
"""
Public interface factory function for creating different types
of Scanners based on the different types of "functions" that may
be supplied.
TODO: Deprecate this some day. We've moved the functionality
inside the Base class and really don't need this fa... | 0.001555 |
def proximal_gradient(x, f, g, gamma, niter, callback=None, **kwargs):
r"""(Accelerated) proximal gradient algorithm for convex optimization.
Also known as "Iterative Soft-Thresholding Algorithm" (ISTA).
See `[Beck2009]`_ for more information.
This solver solves the convex optimization problem::
... | 0.000326 |
def _parse_tree(self, node):
""" Parse a <image> object """
if 'type' in node.attrib:
self.kind = node.attrib['type']
if 'width' in node.attrib:
self.width = int(node.attrib['width'])
if 'height' in node.attrib:
self.height = int(node.attrib['height'])... | 0.005731 |
def save(self, filename, binary=True):
"""
Writes a structured grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
... | 0.001334 |
def setVehicleClass(self, vehID, clazz):
"""setVehicleClass(string, string) -> None
Sets the vehicle class for this vehicle.
"""
self._connection._sendStringCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_VEHICLECLASS, vehID, clazz) | 0.007407 |
def _update_weights(self, margins, parameters = {}):
"""
Run calmar, stores new weights and returns adjusted margins
"""
data = self._build_calmar_data()
assert self.initial_weight_name is not None
parameters['initial_weight'] = self.initial_weight_name
val_po... | 0.008621 |
def open_connection(self, connection_id, info=None):
"""Opens a new connection.
:param connection_id:
ID of the connection to open.
"""
request = requests_pb2.OpenConnectionRequest()
request.connection_id = connection_id
if info is not None:
# Inf... | 0.0033 |
def _update_tasks_redundancy(config, task_id, redundancy, limit=300, offset=0):
"""Update tasks redundancy from a project."""
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
... | 0.002537 |
def translate(self, table):
"""
S.translate(table) -> str
Return a copy of the string S, where all characters have been mapped
through the given translation table, which must be a mapping of
Unicode ordinals to Unicode ordinals, strings, or None.
Unmapped characters are ... | 0.003871 |
def get_feature_by_query(self, **kwargs):
"""
Retrieve an enumerated sequence feature
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>... | 0.002459 |
def as_representer(resource, content_type):
"""
Adapts the given resource and content type to a representer.
:param resource: resource to adapt.
:param str content_type: content (MIME) type to obtain a representer for.
"""
reg = get_current_registry()
rpr_reg = reg.queryUtility(IRepresenter... | 0.002597 |
def create_vehicle_icon(self, name, colour, follow=False, vehicle_type=None):
'''add a vehicle to the map'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if vehicle_type is None:
vehicle_type = self.vehicle_type_name
if name in self.have_vehicle and self.have_vehicle[... | 0.010448 |
def add_simple_rnn(self,name, W_h, W_x, b, hidden_size, input_size, activation, input_names, output_names, output_all = False, reverse_input = False):
"""
Add a simple recurrent layer to the model.
Parameters
----------
name: str
The name of this layer.
W_h: ... | 0.006731 |
def make_inference_summary_table(workflow, inference_file, output_dir,
variable_args=None, name="inference_table",
analysis_seg=None, tags=None):
""" Sets up the corner plot of the posteriors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflo... | 0.002773 |
def uninstall(self):
"""
Remove agent's files from remote host
"""
if self.session:
logger.info('Waiting monitoring data...')
self.session.terminate()
self.session.wait()
self.session = None
log_filename = "agent_{host}.log".format(... | 0.002139 |
def set(self, address, host_name):
"""
Assign one or more PTR record to a single IP Address
:type address: str
:type host_name: list[str]
:param address: (str) The IP address to configure
:param host_name: (list[str]) The list of strings representing PTR records
:... | 0.006969 |
def main():
"""Main function.
Mostly parsing the command line arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--backend', choices=['gatttool', 'bluepy', 'pygatt'], default='gatttool')
parser.add_argument('-v', '--verbose', action='store_const', const=True)
subparsers ... | 0.00297 |
def mks(val):
"""
make sure the value is a string, paying mind to python3 vs 2
"""
if sys.version_info > (3, 0, 0):
if isinstance(val, bytes):
sval = str(val, 'utf-8')
else:
sval = str(val)
else:
sval = str(val)
return sval | 0.003378 |
def _PrintAnalysisStatusUpdateWindow(self, processing_status):
"""Prints an analysis status update in window mode.
Args:
processing_status (ProcessingStatus): processing status.
"""
if self._stdout_output_writer:
self._ClearScreen()
output_text = 'plaso - {0:s} version {1:s}\n\n'.forma... | 0.004874 |
def run_delete_sm(self, tenant_id, fw_dict, is_fw_virt):
"""Runs the delete State Machine.
Goes through every state function until the end or when one state
returns failure.
"""
# Read the current state from the DB
ret = True
serv_obj = self.get_service_obj(tenan... | 0.001391 |
def render(self, painter, node=None):
"""
Draws this node based on its style information
:param painter | <QPainter>
"""
policy = self.visibilityPolicy()
if policy == XNodeHotspot.VisibilityPolicy.Never:
return
elif pol... | 0.00762 |
def FilterItems(self, filterFn):
"""Filter items in a ReservoirBucket, using a filtering function.
Filtering items from the reservoir bucket must update the
internal state variable self._num_items_seen, which is used for determining
the rate of replacement in reservoir sampling. Ideally, self._num_item... | 0.006907 |
def add_project(self, project_id=None, name=None, **kwargs):
"""
Creates a project or returns an existing project
:param project_id: Project ID
:param name: Project name
:param kwargs: See the documentation of Project
"""
if project_id not in self._projects:
... | 0.005326 |
def get_json_results(self, response):
'''
Parses the request result and returns the JSON object. Handles all errors.
'''
try:
# return the proper JSON object, or error code if request didn't go through.
self.most_recent_json = response.json()
json_resu... | 0.012827 |
def send_multi_value(self, channel: int, values: Union[List[int], bytearray]) -> int:
"""
Send multiple consecutive bytes to the uDMX
:param channel: The starting DMX channel number, 1-512
:param values: any sequence of integer values that can be converted
to a bytearray (e.g a l... | 0.005571 |
def make_ref(self, branch):
""" Make a branch on github
:param branch: Name of the branch to create
:return: Sha of the branch or self.ProxyError
"""
master_sha = self.get_ref(self.master_upstream)
if not isinstance(master_sha, str):
return self.ProxyError(
... | 0.00239 |
def get_verify_code(self, file_path):
"""
获取登录验证码并存储
:param file_path: 将验证码图片保存的文件路径
"""
url = 'https://mp.weixin.qq.com/cgi-bin/verifycode'
payload = {
'username': self.__username,
'r': int(random.random() * 10000000000000),
}
head... | 0.002793 |
def pre_release(version):
"""Generates new docs, release announcements and creates a local tag."""
create_branch(version)
changelog(version, write_out=True)
check_call(["git", "commit", "-a", "-m", f"Preparing release {version}"])
print()
print(f"{Fore.GREEN}Please push your branch to your for... | 0.002959 |
def _deprecated_register_to_python(self, cd, name, converter=None):
"""Register a conversion from OpenMath to Python
This function has two forms. A three-arguments one:
:param cd: A content dictionary name
:type cd: str
:param name: A symbol name
:type name: str
... | 0.003741 |
def find_events(symbols, d_data, market_sym='$SPX', trigger=drop_below, trigger_kwargs={}):
'''Return dataframe of 1's (event happened) and NaNs (no event), 1 column for each symbol'''
df_close = d_data['actual_close']
ts_market = df_close[market_sym]
print "Finding `{0}` events with kwargs={1} for {2... | 0.004266 |
def _symbol_in(self, symbol, name):
"""Checks whether the specified symbol is part of the name for completion."""
lsymbol = symbol.lower()
lname = name.lower()
return lsymbol == lname[:len(symbol)] or "_" + lsymbol in lname | 0.011765 |
def replace_local_hyperlinks(
text, base_url="https://github.com/project-rig/rig/blob/master/"):
"""Replace local hyperlinks in RST with absolute addresses using the given
base URL.
This is used to make links in the long description function correctly
outside of the repository (e.g. when publis... | 0.001895 |
def getdata(self, tree, location, force_string=False):
"""Gets XML data from a specific element and handles types."""
found = tree.xpath('%s/text()' % location)
if not found:
return None
else:
data = found[0]
if force_string:
return data
... | 0.002954 |
def phonemes(self,set=None):
"""Generator yielding all phonemes (in a particular set if specified). For retrieving one specific morpheme by index, use morpheme() instead"""
for layer in self.select(PhonologyLayer):
for p in layer.select(Phoneme, set):
yield p | 0.013201 |
def exception_handler(exceptionObj):
"""Function that takes exception Object(<Byte>,<str>) as a parameter and returns the error message<str>"""
try:
if isinstance(exceptionObj, Exception) and hasattr(exceptionObj, 'args'):
if not (hasattr(exceptionObj, 'message' or hasattr(exceptionObj, 'msg... | 0.004985 |
def attach(self, to_linode, config=None):
"""
Attaches this Volume to the given Linode
"""
result = self._client.post('{}/attach'.format(Volume.api_endpoint), model=self,
data={
"linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_lin... | 0.012678 |
def set_random_state(state):
"""Force-set the state of factory.fuzzy's random generator."""
randgen.state_set = True
randgen.setstate(state)
faker.generator.random.setstate(state) | 0.005102 |
def request(self, method, url, access_token=None, **kwargs):
"""
向微信服务器发送请求
:param method: 请求方法
:param url: 请求地址
:param access_token: access token 值, 如果初始化时传入 conf 会自动获取, 如果没有传入则请提供此值
:param kwargs: 附加数据
:return: 微信服务器响应的 JSON 数据
"""
access_token =... | 0.002285 |
def p_param_arg_exp(self, p):
'param_arg : DOT ID LPAREN expression RPAREN'
p[0] = ParamArg(p[2], p[4], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | 0.011364 |
def _get_data_by_field(self, field_number):
"""Return a data field by field number.
This is a useful method to get the values for fields that Ladybug
currently doesn't import by default. You can find list of fields by typing
EPWFields.fields
Args:
field_number: a va... | 0.006916 |
def count(self, conn, filters):
'''
Returns the count of the items that match the provided filters.
For the meaning of what the ``filters`` argument means, see the
``.search()`` method docs.
'''
pipe, intersect, temp_id = self._prepare(conn, filters)
pipe.zcard(t... | 0.005128 |
def _normalize_coerce_to_format_with_lookup(self, v):
""" Replace a format with a default """
try:
return self.format_lookup.get(v, v)
except TypeError:
# v is something we can't lookup (like a list)
return v | 0.007463 |
def normalise_correlation_coefficient(image_tile_dict, transformed_array, template, normed_tolerance=1):
"""As above, but for when the correlation coefficient matching method is used
"""
template_mean = np.mean(template)
template_minus_mean = template - template_mean
template_norm = np.linalg.norm(t... | 0.015213 |
def path_shift(self, count=1):
''' Shift some levels of PATH_INFO into SCRIPT_NAME and return the
moved part. count defaults to 1'''
#/a/b/ /c/d --> 'a','b' 'c','d'
if count == 0: return ''
pathlist = self.path.strip('/').split('/')
scriptlist = self.environ.get('S... | 0.008197 |
def create_argument_parser(self):
"""
Create a parser for the command-line options.
May be overwritten for adding more configuration options.
@return: an argparse.ArgumentParser instance
"""
parser = argparse.ArgumentParser(
fromfile_prefix_chars='@',
... | 0.009909 |
def ecc_correct_intra(ecc_manager_intra, ecc_params_intra, field, ecc, enable_erasures=False, erasures_char="\x00", only_erasures=False):
""" Correct an intra-field with its corresponding intra-ecc if necessary """
fentry_fields = {"ecc_field": ecc}
field_correct = [] # will store each block of the correcte... | 0.009259 |
def render_cvmfs_pvc(cvmfs_volume):
"""Render REANA_CVMFS_PVC_TEMPLATE."""
name = CVMFS_REPOSITORIES[cvmfs_volume]
rendered_template = dict(REANA_CVMFS_PVC_TEMPLATE)
rendered_template['metadata']['name'] = 'csi-cvmfs-{}-pvc'.format(name)
rendered_template['spec']['storageClassName'] = "csi-cvmfs-{}"... | 0.002762 |
def mobile_template(template):
"""
Mark a function as mobile-ready and pass a mobile template if MOBILE.
For example::
@mobile_template('a/{mobile/}b.html')
def view(template=None):
...
if ``request.MOBILE=True`` the template will be `a/mobile/b.html`.
if ``request.MO... | 0.000987 |
def authenticate(cls, client_id, secret):
"""
Authenticate a client using it's secret
:param client_id: the client / service ID
:param secret: the client secret
:returns: a Service instance
"""
result = yield views.oauth_client.get(key=[secret, client_id])
... | 0.004454 |
def translate_path(self, dep_file, dep_rule):
"""Translate dep_file from dep_rule into this rule's output path."""
dst_base = dep_file.split(os.path.join(dep_rule.address.repo,
dep_rule.address.path), 1)[-1]
if self.params['strip_prefix']:
... | 0.003552 |
def new(filename: str, *, file_attrs: Optional[Dict[str, str]] = None) -> LoomConnection:
"""
Create an empty Loom file, and return it as a context manager.
"""
if filename.startswith("~/"):
filename = os.path.expanduser(filename)
if file_attrs is None:
file_attrs = {}
# Create the file (empty).
# Yes, this... | 0.030963 |
def assert_keys_have_values(self, caller, *keys):
"""Check that keys list are all in context and all have values.
Args:
*keys: Will check each of these keys in context
caller: string. Calling function name - just used for informational
messages
Raise... | 0.003509 |
def libvlc_video_get_aspect_ratio(p_mi):
'''Get current video aspect ratio.
@param p_mi: the media player.
@return: the video aspect ratio or NULL if unspecified (the result must be released with free() or L{libvlc_free}()).
'''
f = _Cfunctions.get('libvlc_video_get_aspect_ratio', None) or \
... | 0.006565 |
def load_verify_locations(self, cafile, capath=None):
"""
Let SSL know where we can find trusted certificates for the certificate
chain. Note that the certificates have to be in PEM format.
If capath is passed, it must be a directory prepared using the
``c_rehash`` tool include... | 0.001873 |
def check_infile_and_wp(curinf, curwp):
"""Check the existence of the given file and directory path.
1. Raise Runtime exception of both not existed.
2. If the ``curwp`` is None, the set the base folder of ``curinf`` to it.
"""
if not os.path.exists(curinf):
if c... | 0.004711 |
def rerun(version="3.7.0"):
"""
Rerun last example code block with specified version of python.
"""
from commandlib import Command
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state")).r... | 0.003086 |
def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
"""Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a ... | 0.001957 |
def destroy(self):
""" Destroy the client
"""
if self.client:
#: Stop listening
self.client.setWebView(self.widget, None)
del self.client
super(AndroidWebView, self).destroy() | 0.008197 |
def subset(args):
"""
%prog subset pairsfile ksfile1 ksfile2 ... -o pairs.ks
Subset some pre-calculated ks ka values (in ksfile) according to pairs
in tab delimited pairsfile/anchorfile.
"""
p = OptionParser(subset.__doc__)
p.add_option("--noheader", action="store_true",
he... | 0.001572 |
def normalize_data_values(type_string, data_value):
"""Decodes utf-8 bytes to strings for abi string values.
eth-abi v1 returns utf-8 bytes for string values.
This can be removed once eth-abi v2 is required.
"""
_type = parse_type_string(type_string)
if _type.base == "string":
if _type.... | 0.001992 |
def has_change_permission(self):
"""
Returns a boolean if the current user has permission to change the current object being
viewed/edited.
"""
has_permission = False
if self.user is not None:
# We check for the object level permission here, even though by de... | 0.007722 |
def getvalue(self, v):
"""
Return a list of quantities making up the measures' value.
:param v: a measure
"""
if not is_measure(v):
raise TypeError('Incorrect input type for getvalue()')
import re
rx = re.compile("m\d+")
out = []
keys ... | 0.006211 |
def append_arrays(many, single):
"""Append an array to another padding with NaNs for constant length.
Parameters
----------
many : array_like of rank (j, k)
values appended to a copy of this array. This may be a 1-D or 2-D
array.
single : array_like of rank l
values to appen... | 0.001062 |
def get_most_recent_bike() -> Optional['Bike']:
"""
Gets the most recently cached bike from the database.
:return: The bike that was cached most recently.
"""
try:
return Bike.select().order_by(Bike.cached_date.desc()).get()
except pw.DoesNotExist:
... | 0.006024 |
def show_busy(self):
"""Hide the question group box and enable the busy cursor."""
self.progress_bar.show()
self.question_group.setEnabled(False)
self.question_group.setVisible(False)
enable_busy_cursor()
self.repaint()
qApp.processEvents()
self.busy = Tru... | 0.006231 |
def check_sub_path_create(sub_path):
"""
检查当前路径下的某个子路径是否存在, 不存在则创建;
:param:
* sub_path: (string) 下一级的某路径名称
:return:
* 返回类型 (tuple),有两个值
* True: 路径存在,False: 不需要创建
* False: 路径不存在,True: 创建成功
举例如下::
print('--- check_sub_path_create demo ---')
#... | 0.003756 |
def unreduce_array(array, shape, axis, keepdims):
"""Reverse summing over a dimension, NumPy implementation.
Args:
array: The array that was reduced.
shape: The original shape of the array before reduction.
axis: The axis or axes that were summed.
keepdims: Whether these axes were kept as singleton... | 0.011598 |
def smoothed_hazards_(self, bandwidth=1):
"""
Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth
"""
timeline = self._index.values
return pd.DataFrame(
np.dot(epanechnikov_kernel(timeline[:, None], timeline, bandwidth), self.hazards_.va... | 0.009828 |
def set_wrapped(self, wrapped):
"""This will decide what wrapped is and set .wrapped_func or .wrapped_class
accordingly
:param wrapped: either a function or class
"""
self.wrapped = wrapped
functools.update_wrapper(self, self.wrapped, updated=())
self.wrapped_fun... | 0.005769 |
def reconstruct_url(environ, port):
"""Reconstruct the remote url from the given WSGI ``environ`` dictionary.
:param environ: the WSGI environment
:type environ: :class:`collections.MutableMapping`
:returns: the remote url to proxy
:rtype: :class:`basestring`
"""
# From WSGI spec, PEP 333
... | 0.000971 |
def host(self, host):
"""
Return the configuration of a specific host as a dictionary.
Dictionary always contains lowercase versions of the attribute names.
Parameters
----------
host : the host to return values for.
Returns
-------
dict of key ... | 0.005063 |
def start_record():
"""
Install an httplib wrapper that records but does not modify calls.
"""
global record, playback, current
if record:
raise StateError("Already recording.")
if playback:
raise StateError("Currently playing back.")
record = True
current = ReplayData()
... | 0.002618 |
def get_provider_info(self, user_descriptor):
"""GetProviderInfo.
[Preview API]
:param str user_descriptor:
:rtype: :class:`<GraphProviderInfo> <azure.devops.v5_0.graph.models.GraphProviderInfo>`
"""
route_values = {}
if user_descriptor is not None:
ro... | 0.006944 |
def _filter_seqs(fn):
"""Convert names of sequences to unique ids"""
out_file = op.splitext(fn)[0] + "_unique.fa"
idx = 0
if not file_exists(out_file):
with open(out_file, 'w') as out_handle:
with open(fn) as in_handle:
for line in in_handle:
if li... | 0.001052 |
def parse(self, fo, width, seed=None):
"""
Convert Posmo output to motifs
Parameters
----------
fo : file-like
File object containing Posmo output.
Returns
-------
motifs : list
List of Motif instances.
"""
... | 0.007512 |
def _lu_solve_assertions(lower_upper, perm, rhs, validate_args):
"""Returns list of assertions related to `lu_solve` assumptions."""
assertions = _lu_reconstruct_assertions(lower_upper, perm, validate_args)
message = 'Input `rhs` must have at least 2 dimensions.'
if rhs.shape.ndims is not None:
if rhs.shap... | 0.013361 |
def get_candidates(self, docs=None, split=0, sort=False):
"""Return a list of lists of the candidates associated with this extractor.
Each list of the return will contain the candidates for one of the
candidate classes associated with the CandidateExtractor.
:param docs: If provided, r... | 0.002042 |
def universe(self):
"""
Data universe available at the current time.
Universe contains the data passed in when creating a Backtest.
Use this data to determine strategy logic.
"""
# avoid windowing every time
# if calling and on same date return
# cached va... | 0.003676 |
def get_admin_urls_for_registration(self):
"""
Utilised by Wagtail's 'register_admin_urls' hook to register urls for
our the views that class offers.
"""
urls = super(OrderModelAdmin, self).get_admin_urls_for_registration()
urls = urls + (
url(self.url_helper.... | 0.004115 |
def get_tunnel_info_input_filter_type_filter_by_cfg_src_config_src(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_tunnel_info = ET.Element("get_tunnel_info")
config = get_tunnel_info
input = ET.SubElement(get_tunnel_info, "input")
fi... | 0.004594 |
def daily_txns_with_bar_data(transactions, market_data):
"""
Sums the absolute value of shares traded in each name on each day.
Adds columns containing the closing price and total daily volume for
each day-ticker combination.
Parameters
----------
transactions : pd.DataFrame
Prices ... | 0.000831 |
def files(self):
""" Get a generator that yields all files in the directory. """
filelist_p = new_gp_object("CameraList")
lib.gp_camera_folder_list_files(self._cam._cam, self.path.encode(),
filelist_p, self._cam._ctx)
for idx in range(lib.gp_list_c... | 0.003891 |
def required_attributes(element, *attributes):
"""Check element for required attributes. Raise ``NotValidXmlException`` on error.
:param element: ElementTree element
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing
"""
if not reduce(... | 0.008081 |
def safe_makedir(dname):
"""Make a directory if it doesn't exist, handling concurrent race conditions.
"""
if not dname:
return dname
num_tries = 0
max_tries = 5
while not os.path.exists(dname):
# we could get an error here if multiple processes are creating
# the directo... | 0.003597 |
def get_assessment_taken_form(self, *args, **kwargs):
"""Pass through to provider AssessmentTakenAdminSession.get_assessment_taken_form_for_update"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.get_resource_form_for_update
# This method might be a bit s... | 0.0067 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.