text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def json_compat_obj_decode_helper(self, data_type, obj):
"""
See json_compat_obj_decode() for argument descriptions.
"""
if isinstance(data_type, bv.StructTree):
return self.decode_struct_tree(data_type, obj)
elif isinstance(data_type, bv.Struct):
return s... | 0.001587 |
def move_dir(
src_fs, # type: Union[Text, FS]
src_path, # type: Text
dst_fs, # type: Union[Text, FS]
dst_path, # type: Text
workers=0, # type: int
):
# type: (...) -> None
"""Move a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (... | 0.001929 |
def process_request(self, request):
"""
Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function
Returns the result of resolved view function, called with provided args and kwargs
Since the view function is called directly, it isn't ran through middle... | 0.005071 |
def warning (self, msg, pos=None):
"""Logs a warning message pertaining to the given SeqAtom."""
self.log(msg, 'warning: ' + self.location(pos)) | 0.013158 |
def add_route(self, target_id, stream):
"""
Arrange for messages whose `dst_id` is `target_id` to be forwarded on
the directly connected stream for `via_id`. This method is called
automatically in response to :data:`mitogen.core.ADD_ROUTE` messages,
but remains public while the d... | 0.002717 |
def _reset(self):
""" Resets class properties.
"""
self._name = None
self._start_time = None
self._owner = os.getuid()
self._paths['task_dir'] = None
self._paths['task_config'] = None
self._loaded = False | 0.007326 |
def downgrade():
"""Downgrade database."""
op.drop_constraint(op.f('fk_access_actionsusers_user_id_accounts_user'),
'access_actionsusers', type_='foreignkey')
op.drop_index(op.f('ix_access_actionsusers_user_id'),
table_name='access_actionsusers')
op.create_foreig... | 0.001078 |
def _callback(self, *dummy):
"""
This gets called on any attempt to change the value
"""
# retrieve the value from the Entry
value = self._variable.get()
# run the validation. Returns None if no good
newvalue = self.validate(value)
if newvalue is None:
... | 0.003215 |
def load_file_as_string(self, file_string, filename=''):
'''
Load file as a string.
'''
load_data.load_file_as_string(self, file_string, filename=filename) | 0.005848 |
def get_PSL(self,min_intron_size=68):
"""Get a PSL object representation of the alignment.
:returns: PSL representation
:rtype: PSL
"""
from seqtools.format.psl import PSL
matches = sum([x[0].length for x in self.alignment_ranges]) # 1. Matches - Number of matching bases that aren't repeats
... | 0.03143 |
def setup(level: Union[str, int], structured: bool, config_path: str = None):
"""
Make stdout and stderr unicode friendly in case of misconfigured \
environments, initializes the logging, structured logging and \
enables colored logs if it is appropriate.
:param level: The global logging level.
... | 0.002565 |
def spawn(cls, argv, cwd=None, env=None, dimensions=(24, 80)):
"""Start the given command in a child process in a pseudo terminal.
This does all the setting up the pty, and returns an instance of
PtyProcess.
Dimensions of the psuedoterminal used for the subprocess can be
specif... | 0.000986 |
def r_squared(model, fit_result, data):
"""
Calculates the coefficient of determination, R^2, for the fit.
(Is not defined properly for vector valued functions.)
:param model: Model instance
:param fit_result: FitResults instance
:param data: data with which the fit was performed.
"""
... | 0.004678 |
def security_group_update(secgroup=None, auth=None, **kwargs):
'''
Update a security group
secgroup
Name, ID or Raw Object of the security group to update
name
New name for the security group
description
New description for the security group
CLI Example:
.. code... | 0.001266 |
def load_gmt(self, gene_list, gmt):
"""load gene set dict"""
if isinstance(gmt, dict):
genesets_dict = gmt
elif isinstance(gmt, str):
genesets_dict = self.parse_gmt(gmt)
else:
raise Exception("Error parsing gmt parameter for gene sets")
... | 0.008602 |
def lru_append(kc, lru, kckey, maxsize):
"""Delete old data from ``kc``, then add the new ``kckey``.
:param kc: a three-layer keycache
:param lru: an :class:`OrderedDict` with a key for each triple that should fill out ``kc``'s three layers
:param kckey: a triple that indexes into ``kc``, which will be... | 0.003289 |
def add_transcript(self, transcript):
"""Add the information transcript
This adds a transcript dict to variant['transcripts']
Args:
transcript (dict): A transcript dictionary
"""
logger.debug("Adding transcript {0} to variant {1}".format(
tra... | 0.005051 |
def dumps(self, param):
'''
Checks the parameters generating new proxy instances to avoid
query concurrences from shared proxies and creating proxies for
actors from another host.
'''
if isinstance(param, Proxy):
module_name = param.actor.klass.__module__
... | 0.002188 |
def find_usbserial(vendor, product):
"""Find the tty device for a given usbserial devices identifiers.
Args:
vendor: (int) something like 0x0000
product: (int) something like 0x0000
Returns:
String, like /dev/ttyACM0 or /dev/tty.usb...
"""
if platform.system() == 'Linux':
vendor, product ... | 0.007949 |
def reload(self):
"""Make the daemon reload itself."""
pid = self._read_pidfile()
if pid is None or pid != os.getpid():
raise DaemonError(
'Daemon.reload() should only be called by the daemon process '
'itself')
# Copy the current environment
... | 0.002941 |
def check_trytes_codec(encoding):
"""
Determines which codec to use for the specified encoding.
References:
- https://docs.python.org/3/library/codecs.html#codecs.register
"""
if encoding == AsciiTrytesCodec.name:
return AsciiTrytesCodec.get_codec_info()
elif encoding == AsciiTryt... | 0.001433 |
def next_valid_batch(self, batch_size):
"""
Return the next batch of examples from validiation data set
:param batch_size: int, size of image batch returned
:return train_labels: list, of labels
:return images: list, of images
"""
start = self.index_in_valid_epoch... | 0.00487 |
def orbit_y(self, angle):
'''Orbit around the point ``Camera.pivot`` by the angle
*angle* expressed in radians. The axis of rotation is the
camera "right" vector, ``Camera.a``.
In practice, we move around a point like if we were on a Ferris
wheel.
'''
#... | 0.009887 |
def glymurrc_fname():
"""Return the path to the configuration file.
Search order:
1) current working directory
2) environ var XDG_CONFIG_HOME
3) $HOME/.config/glymur/glymurrc
"""
# Current directory.
fname = os.path.join(os.getcwd(), 'glymurrc')
if os.path.exists(fname)... | 0.001764 |
def eeg_create_mne_events(onsets, conditions=None):
"""
Create MNE compatible events.
Parameters
----------
onsets : list or array
Events onsets.
conditions : list
A list of equal length containing the stimuli types/conditions.
Returns
----------
(events, event_id)... | 0.003051 |
def get_labs(format):
"""Gets Repair Cafe data from repairecafe.org."""
data = data_from_repaircafe_org()
repaircafes = {}
# Load all the Repair Cafes
for i in data:
# Create a lab
current_lab = RepairCafe()
# Add existing data from first scraping
current_lab.name ... | 0.000551 |
def scatter3d_and_projections(data_list,
channels=[0,1,2],
xscale='logicle',
yscale='logicle',
zscale='logicle',
xlabel=None,
ylabel=None,
... | 0.000601 |
def query( self ):
"""
Returns the query this widget is representing from the tree widget.
:return <Query> || <QueryCompound> || None
"""
# build a query if not searching all
q = Q()
operator = 'and'
for i in range(se... | 0.016925 |
def get_names(self):
"""
Returns a dict where key is the language and value is the name in that language.
Example:
{'it':"Sofocle"}
"""
names = [id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name']]
self.names = []
for n... | 0.010571 |
def right_outer(self):
"""
Performs Right Outer Join
:return right_outer: dict
"""
self.get_collections_data()
right_outer_join = self.merge_join_docs(
set(self.collections_data['right'].keys()))
return right_outer_join | 0.00678 |
def plugin(tree, file_tokens):
"""Walk the tree and detect invalid escape sequences."""
for token in file_tokens:
if token[0] != STRING: # token[0] == token.type
continue
# token[1] == token.string # python 3
invalid_sequence_match = invalid_escape_sequence_match(token[1])
... | 0.001618 |
def _zlib_compress(data, algorithm):
'''GZIP compress'''
if algorithm['subtype'] == 'deflate':
encoder = zlib.compressobj(algorithm['level'], zlib.DEFLATED, -15)
compressed = encoder.compress(data)
compressed += encoder.flush()
return compressed
... | 0.004494 |
def value(self, cell):
"""
Extract the value of ``cell``, ready to be rendered.
If this Column was instantiated with a ``value`` attribute, it
is called here to provide the value. (For example, to provide a
calculated value.) Otherwise, ``cell.value`` is returned.
"""
... | 0.004587 |
def print_err(*args, end='\n'):
"""Similar to print, but prints to stderr.
"""
print(*args, end=end, file=sys.stderr)
sys.stderr.flush() | 0.006579 |
def hagen_poiseuille(target,
pore_area='pore.area',
throat_area='throat.area',
pore_viscosity='pore.viscosity',
throat_viscosity='throat.viscosity',
conduit_lengths='throat.conduit_lengths',
con... | 0.000436 |
def get_instance(self, payload):
"""
Build an instance of AssetInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.asset.AssetInstance
:rtype: twilio.rest.serverless.v1.service.asset.AssetInstance
"""
return As... | 0.0075 |
def _Load(self,cached=True):
"""Performs a full load of all PublicIP metadata."""
if not self.data or not cached:
self.data = clc.v2.API.Call('GET','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id),
session=self.session)
# build ports
self.data['_po... | 0.037904 |
def convert_conelp(c, G, h, dims, A = None, b = None, **kwargs):
"""
Applies the clique conversion method of Fukuda et al. to the positive semidefinite blocks of a cone LP.
:param c: :py:class:`matrix`
:param G: :py:class:`spmatrix`
:param h: :py:clas... | 0.014257 |
def stitch_pdfs(pdf_list):
''' Merges a series of single page pdfs into one multi-page doc '''
pdf_merger = PdfFileMerger()
for pdf in pdf_list:
pdf_merger.append(pdf)
with NamedTemporaryFile(prefix='pyglass', suffix='.pdf', delete=False) as tempfileobj:
dest_path = tempfileobj.name
pdf_merger.write... | 0.024259 |
def _get_file_index_str(self):
"""Create a string out of the current file_index"""
file_index = str(self.file_index)
if self.n_digits is not None:
file_index = file_index.zfill(self.n_digits)
return file_index | 0.007905 |
def password_dialog(self, title="Enter password", message="Enter password", **kwargs):
"""
Show a password input dialog
Usage: C{dialog.password_dialog(title="Enter password", message="Enter password")}
@param title: window title for the dialog
@param message: m... | 0.014245 |
def invalid_config_error_message(action, key, val):
"""Returns a better error message when invalid configuration option
is provided."""
if action in ('store_true', 'store_false'):
return ("{0} is not a valid value for {1} option, "
"please specify a boolean value like yes/no, "
... | 0.00188 |
def autocorrelation(signal):
"""
The `correlation <https://en.wikipedia.org/wiki/Autocorrelation#Estimation>`_ of a signal with a delayed copy of itself.
:param signal: A 1-dimensional array or list (the signal).
:type signal: array
:return: The autocorrelated signal.
:rtyp... | 0.011706 |
def get_routing_attributes(obj, modify_doc=False, keys=None):
"""
Loops through the provided object (using the dir() function) and
finds any callables which match the name signature (e.g.
get_foo()) AND has a docstring beginning with a path-like char
string.
This does process things in alphabeti... | 0.000938 |
def get_dataset(self, key, info):
"""Load a dataset."""
# Read bands
data = self.read_band(key, info)
# Convert to xarray
xdata = xr.DataArray(data, dims=['y', 'x'])
return xdata | 0.008772 |
def brunt_vaisala_frequency(heights, potential_temperature, axis=0):
r"""Calculate the Brunt-Vaisala frequency.
This function will calculate the Brunt-Vaisala frequency as follows:
.. math:: N = \left( \frac{g}{\theta} \frac{d\theta}{dz} \right)^\frac{1}{2}
This formula based off of Equations 3.75 an... | 0.004847 |
def get_url_map():
"""
Loads custom/pypi/map.txt and builds a dict where map[package_name] = url
:return: dict, urls
"""
map = {}
path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), # current working dir ../
"custom", # ../custom/
"pypi", # ../custom/pypi... | 0.001887 |
def examples(self):
"""Return example functions in the space.
Example functions include:
Zero
One
Heaviside function
Hypercube characteristic function
Hypersphere characteristic function
Gaussian
Linear gradients
"""
# TODO: adapt... | 0.000838 |
def _addAccountRights(sidObject, user_right):
'''
helper function to add an account right to a user
'''
try:
if sidObject:
_polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS)
user_rights_list = [user_right]
_ret = win32security.LsaA... | 0.006745 |
async def generate_refresh_token(self, request, user):
"""
Generate a refresh token for a given user.
"""
refresh_token = await utils.call(self.config.generate_refresh_token())
user_id = await self._get_user_id(user)
await utils.call(
self.store_refresh_token,... | 0.004367 |
def __getX(self):
'''
Gets the View X coordinate
'''
if DEBUG_COORDS:
print >>sys.stderr, "getX(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId())
x = 0
if self.useUiAutomator:
x = self.map['bounds'][0][0]
else:
... | 0.010949 |
def snow_partitioning(im, dt=None, r_max=4, sigma=0.4, return_all=False,
mask=True, randomize=True):
r"""
Partitions the void space into pore regions using a marker-based watershed
algorithm, with specially filtered peaks as markers.
The SNOW network extraction algorithm (Sub-Netw... | 0.000229 |
def _convert_option(self):
'''
Determines how to convert CDF byte ordering to the system
byte ordering.
'''
if sys.byteorder == 'little' and self._endian() == 'big-endian':
# big->little
order = '>'
elif sys.byteorder == 'big' and self._endian() =... | 0.004211 |
def _n(v):
"""
convert string to utf8 in Py2 or unicode in Py3
:param v:
:return:
"""
if v is None:
return ""
if isinstance(v, (dict, list)):
try:
v = json.dumps(v)
except Exception:
pass
... | 0.003752 |
def fast_relpath(path, start):
"""A prefix-based relpath, with no normalization or support for returning `..`."""
relpath = fast_relpath_optional(path, start)
if relpath is None:
raise ValueError('{} is not a directory containing {}'.format(start, path))
return relpath | 0.021352 |
def show(self, ticket):
"""
通过ticket换取二维码
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
:param ticket: 二维码 ticket 。可以通过 :func:`create` 获取到
:return: 返回的 Request 对象
使用示例::
from wechatpy import WeChatClient
client... | 0.003012 |
def create_index(self, table, field, unique=False, ascending=True):
"""Creates a table index.
Creates an index on the given table,
on the given field with unique values enforced or not,
in ascending or descending order.
"""
if unique: u... | 0.019064 |
def export(rv, code=None, headers=None):
"""
Create a suitable response
Args:
rv: return value of action
code: status code
headers: response headers
Returns:
flask.Response
"""
if isinstance(rv, ResponseBase):
return make_response(rv, code, headers)
e... | 0.001845 |
def rename(self, names, inplace=False):
"""
Returns an SFrame with columns renamed. ``names`` is expected to be a
dict specifying the old and new names. This changes the names of the
columns given as the keys and replaces them with the names given as the
values.
If inpla... | 0.001508 |
def get_new_messages(self, domain):
"""
Returns new valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'new' not in... | 0.004662 |
def _get_aria_autocomplete(self, field):
"""
Returns the appropriate value for attribute aria-autocomplete of field.
:param field: The field.
:type field: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: The ARIA value of field.
:rtype: str
"""
... | 0.000957 |
def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
return rfc2425encode("adr",u';'.join(quote_semicolon(val) for val in
(self.pobox,self.extadr,self.street,self.locality,
self.r... | 0.027848 |
def parse(self, text):
"""Do the parsing."""
text = tounicode(text, encoding="utf-8")
result, i = self._parse(text, 0)
if text[i:].strip():
self._fail("Unexpected trailing content", text, i)
return result | 0.007782 |
def poke(self, context):
"""
Check for message on subscribed queue and write to xcom the message with key ``messages``
:param context: the context object
:type context: dict
:return: ``True`` if message is available or ``False``
"""
sqs_hook = SQSHook(aws_conn_i... | 0.005506 |
def flanger(self, delay=0, depth=2, regen=0, width=71, speed=0.5,
shape='sine', phase=25, interp='linear'):
'''Apply a flanging effect to the audio.
Parameters
----------
delay : float, default=0
Base delay (in miliseconds) between 0 and 30.
depth : f... | 0.001146 |
def parameter(self):
"""Return the current best value of a parameter"""
D = {}
for source in PARAM_SOURCE_ORDER:
D.update(self.params[source])
return D | 0.010256 |
def supports_mime_type(self, mime_type):
""" Return whether surface supports :obj:`mime_type`.
:param mime_type: The MIME type of the image data.
:type mime_type: ASCII string
*New in cairo 1.12.*
"""
mime_type = ffi.new('char[]', mime_type.encode('utf8'))
retu... | 0.004926 |
def laplace(affinity_matrix, shi_malik_type=False):
""" Converts affinity matrix into normalised graph Laplacian,
for spectral clustering.
(At least) two forms exist:
L = (D^-0.5).A.(D^-0.5) - default
L = (D^-1).A - `Shi-Malik` type, from Shi Malik paper"""
diagonal = affinity_matrix.sum(axis... | 0.001431 |
def seq_minibatches(inputs, targets, batch_size, seq_length, stride=1):
"""Generate a generator that return a batch of sequence inputs and targets.
If `batch_size=100` and `seq_length=5`, one return will have 500 rows (examples).
Parameters
----------
inputs : numpy.array
The input features... | 0.004521 |
def score_pairs(self, pairs):
"""Returns the learned Mahalanobis distance between pairs.
This distance is defined as: :math:`d_M(x, x') = \sqrt{(x-x')^T M (x-x')}`
where ``M`` is the learned Mahalanobis matrix, for every pair of points
``x`` and ``x'``. This corresponds to the euclidean distance betwee... | 0.001642 |
def _openapi_json(self):
"""Serve JSON spec file"""
# We don't use Flask.jsonify here as it would sort the keys
# alphabetically while we want to preserve the order.
from pprint import pprint
pprint(self.to_dict())
return current_app.response_class(json.dumps(self.to_dict... | 0.004938 |
def _store_object(self, obj_name, content, etag=None, chunked=False,
chunk_size=None, headers=None):
"""
Handles the low-level creation of a storage object and the uploading of
the contents of that object.
"""
head_etag = headers.pop("ETag", "")
if chunked:
... | 0.004988 |
def _get_entry_scores(self):
"""Takes entries from self._entries and returns a list of scores (or
output scores, if based on grades)"""
if self.get_gradebook_column().get_grade_system().is_based_on_grades():
return [e.get_grade().get_output_score() for e in self._entries if e.is_grad... | 0.007246 |
def create_starttls_connection(
loop,
protocol_factory,
host=None,
port=None,
*,
sock=None,
ssl_context_factory=None,
use_starttls=False,
local_addr=None,
**kwargs):
"""
Create a connection which can later be upgraded to use TLS.
... | 0.000206 |
def _read_json(self, path, name):
"""
Load a json into a dictionary from a file.
:param path: path to file
:param name: name of file
:return: dict
"""
with open(os.path.join(path, name), 'r') as fil:
output = json.load(fil)
self.logger.inf... | 0.005222 |
def run_websocket_server(self, host='localhost', port=9090, debug=False):
"""
Runs websocket server
"""
from .server import MeaseWebSocketServerFactory
websocket_factory = MeaseWebSocketServerFactory(
mease=self, host=host, port=port, debug=debug)
websocket_f... | 0.0059 |
def get_geoms_for_bounds(self, bounds):
"""
Helper method to get geometries within a certain bounds (as WKT).
Returns GeoJSON (loaded as a list of python dictionaries).
"""
params = {'service' : 'WFS',
'request' : 'GetFeature',
'typ... | 0.011827 |
def brightness(stations, nodes, lags, stream, threshold, thresh_type,
template_length, template_saveloc, coherence_thresh,
coherence_stations=['all'], coherence_clip=False,
gap=2.0, clip_level=100, instance=0, pre_pick=0.2,
plotvar=False, plotsave=True, cores=... | 0.000069 |
def phrases_reduce(key, values):
"""Phrases demo reduce function."""
if len(values) < 10:
return
counts = {}
for filename in values:
counts[filename] = counts.get(filename, 0) + 1
words = re.sub(r":", " ", key)
threshold = len(values) / 2
for filename, count in counts.items():
if count > thre... | 0.024457 |
def run(analysis, path=None, name=None, info=None, **kwargs):
"""Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
... | 0.001773 |
def plot_classifier_errors(predictions, absolute=True, max_relative_size=50, absolute_size=50, title=None,
outfile=None, wait=True):
"""
Plots the classifers for the given list of predictions.
TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html
... | 0.001572 |
def get_game_high_scores(user_id,
chat_id=None, message_id=None, inline_message_id=None,
**kwargs):
"""
Use this method to get data for high score tables. Will return the score of the specified user and several of his
neighbors in a game. On success, returns... | 0.005945 |
def load_joke(service_num=1):
"""Pulls the joke from the service based on the argument.
It is expected that all services used will return a string
when successful or None otherwise.
"""
result = {
1 : ronswanson.get_joke(),
2 : chucknorris.get_joke(),
3 : catfacts.get_joke(),
... | 0.015306 |
def daytime(date: datetime.date,
daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),
nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
-> "Interval":
"""
Returns an :class:`Interval` representing daytime on the date given.
"""
... | 0.008677 |
def json_success(self, json):
"""
Check the JSON response object for the success flag
Parameters
----------
json : dict
A dictionary representing a JSON object from lendingclub.com
"""
if type(json) is dict and 'result' in json and json['result'] == '... | 0.008021 |
def close(self):
"""
Close the connection.
:param purge: If True (the default), the receive buffer will
be purged.
"""
# Close the underlying socket
if self._sock:
with utils.ignore_except():
self._sock.close()
... | 0.004556 |
def get_tc_arguments(parser):
"""
Append test case arguments to parser.
:param parser: ArgumentParser
:return: ArgumentParser
"""
group2 = parser.add_argument_group('Test case arguments')
group2.add_argument('--log',
default=os.path.abspath("./log"),
... | 0.00179 |
def _load_point(big_endian, type_bytes, data_bytes):
"""
Convert byte data for a Point to a GeoJSON `dict`.
:param bool big_endian:
If `True`, interpret the ``data_bytes`` in big endian order, else
little endian.
:param str type_bytes:
4-byte integer (as a binary string) indicat... | 0.000583 |
def get_lldp_neighbors_request(last_ifindex, rbridge_id):
""" Creates a new Netconf request based on the last received or if
rbridge_id is specifed
ifindex when the hasMore flag is true
"""
request_lldp = ET.Element(
'get-lldp-neighbor-detail',
xmlns="urn... | 0.002677 |
def validate_context(self):
"""
Make sure there are no duplicate context objects
or we might end up with switched data
Converting the tuple to a set gets rid of the
eventual duplicate objects, comparing the length
of the original tuple and set tells us if we
have... | 0.003484 |
def _generate_constructor(cls, names):
"""Get a hopefully cache constructor"""
cache = cls._constructors
if names in cache:
return cache[names]
elif len(cache) > 3:
cache.clear()
func = generate_constructor(cls, names)
cache[names] = func
... | 0.006024 |
def get_context(self, parent_context, data):
"""
Wrap the context data in a :class:`~django.template.Context` object.
:param parent_context: The context of the parent template.
:type parent_context: :class:`~django.template.Context`
:param data: The result from :func:`get_contex... | 0.001807 |
def parse(self, fo):
"""
Convert MotifSampler output to motifs
Parameters
----------
fo : file-like
File object containing MotifSampler output.
Returns
-------
motifs : list
List of Motif instances.
"""
mot... | 0.005123 |
def _init_seqarray(self, quiet=False):
"""
Fills the seqarr with the full data set, and creates a bootsarr copy
with the following modifications:
1) converts "-" into "N"s, since they are similarly treated as missing.
2) randomly resolve ambiguities (RSKWYM)
3) convert... | 0.007463 |
def info(self):
"""Retrieve information about the SD interface.
Args::
no argument
Returns::
2-element tuple holding:
number of datasets inside the file
number of file attributes
C library equivalent : SDfileinfo
... | 0.003945 |
def _git_enable_branch(desired_branch):
"""Enable desired branch name."""
preserved_branch = _git_get_current_branch()
try:
if preserved_branch != desired_branch:
_tool_run('git checkout ' + desired_branch)
yield
finally:
if preserved_branch and preserved_branch != de... | 0.002558 |
def build(args):
"""
Invoke the scons build system from the current directory, exactly as if
the scons tool had been invoked.
"""
# Do some sleuthing work to find scons if it's not installed into an importable
# place, as it is usually not.
scons_path = "Error"
try:
scons_path =... | 0.004785 |
def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional para... | 0.006346 |
def send_quick_reply(recipient):
"""
shortcuts are supported
page.send(recipient, "What's your favorite movie genre?",
quick_replies=[{'title': 'Action', 'payload': 'PICK_ACTION'},
{'title': 'Comedy', 'payload': 'PICK_COMEDY'}, ],
metadata="DEVE... | 0.004777 |
def setcoef(self, Z):
"""Set coefficient array."""
self.Z = np.asarray(Z, dtype=self.dtype)
self.SZT = self.S.dot(Z.T)
# Factorise dictionary for efficient solves
self.lu, self.piv = sl.lu_factor(Z, self.rho)
self.lu = np.asarray(self.lu, dtype=self.dtype) | 0.006557 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.