text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def normalize_boolop(expr):
"""
Normalize a boolop by folding together nested And/Or exprs.
"""
optype = expr.op
newvalues = []
for subexpr in expr.values:
if not isinstance(subexpr, ast.BoolOp):
newvalues.append(subexpr)
elif type(subexpr.op) != type(optype):
... | 0.001667 |
def check_restructuredtext(self):
"""
Checks if the long string fields are reST-compliant.
"""
# Warn that this command is deprecated
# Don't use self.warn() because it will cause the check to fail.
Command.warn(
self,
"This command has been deprec... | 0.001183 |
def connect(self):
"""Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host.
... | 0.001357 |
def command(self, verb, args=None):
"""Call a command on the server.
If the user has not authenticated then authentication will be done
as part of calling the command on the server.
For commands that don't return a status message the status message
will default to an empty stri... | 0.001862 |
def _gen_headers(self, bearer, url):
'''
Generate headders, adding in Oauth2 bearer token if present
'''
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " +
... | 0.002418 |
def python_dependencies(context: Context, common_path=None):
"""
Updates python dependencies
"""
context.pip_command('install', '-r', context.requirements_file)
if common_path:
context.pip_command('uninstall', '--yes', 'money-to-prisoners-common')
context.pip_command('install', '--fo... | 0.002439 |
def print_stats(self):
""" Compute some basic stats on the next block of data """
header, data = self.read_next_data_block()
data = data.view('float32')
print("AVG: %2.3f" % data.mean())
print("STD: %2.3f" % data.std())
print("MAX: %2.3f" % data.max())
print("MI... | 0.005376 |
def hash(self):
"""Return an hash string computed on the PSF data."""
hash_list = []
for key, value in sorted(self.__dict__.items()):
if not callable(value):
if isinstance(value, np.ndarray):
hash_list.append(value.tostring())
else:... | 0.004608 |
def rotate_bitmaps_to_roots(bitmaps, roots):
"""Circularly shift a relative bitmaps to asbolute pitch classes.
See :func:`rotate_bitmap_to_root` for more information.
Parameters
----------
bitmap : np.ndarray, shape=(N, 12)
Bitmap of active notes, relative to the given root.
root : np.... | 0.001479 |
async def connect(self, conn_id, connection_string):
"""Connect to a device.
See :meth:`AbstractDeviceAdapter.connect`.
"""
self._ensure_connection(conn_id, False)
msg = dict(connection_string=connection_string)
await self._send_command(OPERATIONS.CONNECT, msg, COMMAND... | 0.007538 |
def port_add_nio_binding(self, port_number, nio):
"""
Adds a port NIO binding.
:param port_number: port number
:param nio: NIO instance to add to the slot/port
"""
if not self._ethernet_adapter.port_exists(port_number):
raise VPCSError("Port {port_number} do... | 0.008 |
def count_multi(self, strands, permutation=None, pseudo=False):
'''Enumerates the total number of secondary structures over the
structural ensemble Ω(π) with an ordered permutation of strands. Runs
the \'count\' command.
:param strands: List of strands to use as inputs to count -multi.
... | 0.001035 |
def pathcase(string):
"""Convert string into path case.
Join punctuation with slash.
Args:
string: String to convert.
Returns:
string: Path cased string.
"""
string = snakecase(string)
if not string:
return string
return re.sub(r"_", "/", string) | 0.003279 |
def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"):
"""Return values at the given quantile over requested axis,
a la numpy.percentile.
Args:
q (float): 0 <= q <= 1, the quantile(s) to compute
axis (int): 0 or 'index' for row-wise,
... | 0.001821 |
def evaluate(self, dataset, metric='auto', missing_value_action='auto'):
"""
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include colum... | 0.002832 |
def print_coords(rows, prefix=''):
"""Print coordinates within a sequence.
This is only used for debugging. Printed in a form that can be
pasted into Python for visualization."""
lat = [row['lat'] for row in rows]
lon = [row['lon'] for row in rows]
print('COORDS'+'-' * 5)
print("%slat, %sl... | 0.002639 |
def plane(strike, dip, segments=100, center=(0, 0)):
"""
Calculates the longitude and latitude of `segments` points along the
stereonet projection of each plane with a given `strike` and `dip` in
degrees. Returns points for one hemisphere only.
Parameters
----------
strike : number or sequ... | 0.001967 |
def configure(self, options, conf):
"""Configure plugin. Plugin is enabled by default.
"""
self.conf = conf
if not options.capture:
self.enabled = False | 0.010204 |
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
if salt.utils.platform.is_proxy():
gfn = os.path.join(
__opts__['conf_file'],
'proxy.d... | 0.000746 |
def insert(self,*args,**kw):
"""Insert a record in the database
Parameters can be positional or keyword arguments. If positional
they must be in the same order as in the create() method
If some of the fields are missing the value is set to None
Returns the record identifier
... | 0.015896 |
def _get_final_set(self, sets, pk, sort_options):
"""
Add intersects fo sets and call parent's _get_final_set.
If we have to sort by sorted score, and we have a slice, we have to
convert the whole sorted set to keys now.
"""
if self._lazy_collection['intersects']:
... | 0.002726 |
def load(self , filename=None, data=None):
"""Load a PEiD signature file.
Invoking this method on different files combines the signatures.
"""
self.__load(filename=filename, data=data) | 0.013761 |
def list_snapshots(name, snap_name=None, tree=False, names=False, runas=None):
'''
List the snapshots
:param str name:
Name/ID of VM whose snapshots will be listed
:param str snap_id:
Name/ID of snapshot to display information about. If ``tree=True`` is
also specified, display... | 0.001063 |
async def prover_close_credentials_search(search_handle: int) -> None:
"""
Close credentials search (make search handle invalid)
:param search_handle: Search handle (created by prover_open_credentials_search)
:return: None
"""
logger = logging.getLogger(__name__)
logger.debug("prover_close... | 0.003264 |
def tostype(self, stype):
"""Return a copy of the array with chosen storage type.
Returns
-------
NDArray or RowSparseNDArray
A copy of the array with the chosen storage stype
"""
# pylint: disable= no-member, protected-access
if stype == 'csr':
... | 0.006682 |
def _kind(d):
""" Return the VSCode type """
MAP = {
'none': lsp.CompletionItemKind.Value,
'type': lsp.CompletionItemKind.Class,
'tuple': lsp.CompletionItemKind.Class,
'dict': lsp.CompletionItemKind.Class,
'dictionary': lsp.CompletionItemKind.Class,
'function': ls... | 0.000627 |
def AdvancedJsonify(data, status_code):
""" Advanced Jsonify Response Maker
:param data: Data
:param status_code: Status_code
:return: Response
"""
response = jsonify(data)
response.status_code = status_code
return response | 0.006944 |
def env_unset(context):
"""Unset $ENVs.
Context is a dictionary or dictionary-like. context is mandatory.
context['env']['unset'] must exist. It's a list.
List items are the names of the $ENV values to unset.
For example, say input context is:
key1: value1
key2: value2
key... | 0.00081 |
def render(file):
"""Pretty print the XML file for rendering."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
file_content = fp.read().decode(encoding)
parsed_xml = xml.dom.minidom.parseString(file_content)
return parsed_xml.toprettyxml(indent=' ', new... | 0.003077 |
def CreateStorageWriter(cls, storage_format, session, path):
"""Creates a storage writer.
Args:
session (Session): session the storage changes are part of.
path (str): path to the storage file.
storage_format (str): storage format.
Returns:
StorageWriter: a storage writer or None i... | 0.003597 |
def wrsamp(record_name, fs, units, sig_name, p_signal=None, d_signal=None,
fmt=None, adc_gain=None, baseline=None, comments=None,
base_time=None, base_date=None, write_dir=''):
"""
Write a single segment WFDB record, creating a WFDB header file and any
associated dat files.
Parame... | 0.00177 |
def extendMarkdown(self, md, md_globals):
"""Modifies inline patterns."""
md.inlinePatterns.add('del', SimpleTagPattern(DEL_RE, 'del'), '<not_strong')
md.inlinePatterns.add('ins', SimpleTagPattern(INS_RE, 'ins'), '<not_strong')
md.inlinePatterns.add('mark', SimpleTagPattern(MARK_RE, 'mar... | 0.014749 |
def check_file_age(filename, days):
"""
Check if the target file has an older creation date than X amount of time.
i.e. One day: 60*60*24
:param str filename: Target filename
:param int days: Limit in number of days
:return bool: True - older than X time, False - not older than X time
"""
... | 0.001691 |
def log_data_send(self, id, ofs, count, data, force_mavlink1=False):
'''
Reply to LOG_REQUEST_DATA
id : Log id (from LOG_ENTRY reply) (uint16_t)
ofs : Offset into the log (uint32_t)
count ... | 0.008696 |
def encrypt_report(self, device_id, root, data, **kwargs):
"""Encrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (... | 0.005319 |
def reverse(view, *args, **kwargs):
'''
User-friendly reverse. Pass arguments and keyword arguments to Django's `reverse`
as `args` and `kwargs` arguments, respectively.
The special optional keyword argument `query` is a dictionary of query (or GET) parameters
that can be appended to the `reverse`d URL.
Example... | 0.036 |
def create(cls, name, members=None, comment=None):
"""
Create the TCP Service group
:param str name: name of tcp service group
:param list element: tcp services by element or href
:type element: list(str,Element)
:raises CreateElementFailed: element creation failed with ... | 0.003221 |
def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied \
arguments with the message.
"""
if isinstance(self.msg, numpy.ndarray):
msg = self.array2string(self.msg)
else:
... | 0.003992 |
def _warmup(self, num_updates):
"""
Returns linearly increasing fraction of base_lr.
"""
assert self.base_lr is not None
if not self.warmup:
return self.base_lr
fraction = (num_updates + 1) * self.base_lr / (self.warmup + 1)
if num_updates > self.last_... | 0.007421 |
def _git(*command_parts, **kwargs):
""" Convenience function for running git commands. Automatically deals with exceptions and unicode. """
# Special arguments passed to sh: http://amoffat.github.io/sh/special_arguments.html
git_kwargs = {'_tty_out': False}
git_kwargs.update(kwargs)
try:
res... | 0.007519 |
def crispness(alpha, T, right_eigenvectors, square_map, pi):
"""Return the crispness PCCA+ objective function.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
T : csr sparse matrix
Transition matrix
right_eigenvectors : ndarray
T... | 0.000899 |
def _lim_moment(self, u, order=1):
"""
This method calculates the kth order limiting moment of
the distribution. It is given by -
E(u) = Integral (-inf to u) [ (x^k)*pdf(x) dx ] + (u^k)(1-cdf(u))
where, pdf is the probability density function and cdf is the
cumulative d... | 0.002073 |
def registration(fixed,
moving,
type_of_transform='SyN',
initial_transform=None,
outprefix='',
mask=None,
grad_step=0.2,
flow_sigma=3,
total_sigma=0,
aff_metric='matte... | 0.006106 |
def render_include_tree(self):
"""
Return a text representation, suitable for displaying to the
user, of the include tree for the sources of this node.
"""
if self.is_derived():
env = self.get_build_env()
if env:
for s in self.sources:
... | 0.003866 |
def get_chatlist(chatfile):
"""Try reading ids of saved chats from file.
If we fail, return empty set"""
if not chatfile:
return set()
try:
with open(chatfile) as file_contents:
return set(int(chat) for chat in file_contents)
except (OSError, IOError) as exc:
LOGG... | 0.002571 |
def clean_boundary_shapefile(shapefile_path):
"""
Cleans the boundary shapefile to that there is only one main polygon.
:param shapefile_path:
:return:
"""
wfg = gpd.read_file(shapefile_path)
first_shape = wfg.iloc[0].geometry
if hasattr(first_shape, 'geo... | 0.001982 |
def check_encoding(proof_req: dict, proof: dict) -> bool:
"""
Return whether the proof's raw values correspond to their encodings
as cross-referenced against proof request.
:param proof request: proof request
:param proof: corresponding proof to check
:return: True if OK... | 0.005565 |
def parse_view(query):
""" Parses asql query to view object.
Args:
query (str): asql query
Returns:
View instance: parsed view.
"""
try:
idx = query.lower().index('where')
query = query[:idx]
except ValueError:
pass
if not query.endswith(';'):
... | 0.002299 |
def _get_version_info():
"""
Returns the currently-installed awslimitchecker version, and a best-effort
attempt at finding the origin URL and commit/tag if installed from an
editable git clone.
:returns: awslimitchecker version
:rtype: str
"""
if os.environ.get('VERSIONCHECK_DEBUG', '')... | 0.001511 |
def add_healthcheck_expect(self, id_ambiente, expect_string, match_list):
"""Insere um novo healthckeck_expect e retorna o seu identificador.
:param expect_string: expect_string.
:param id_ambiente: Identificador do ambiente lógico.
:param match_list: match list.
:return: Dicio... | 0.005133 |
def makeServoMaxLimitPacket(ID, angle):
"""
Sets the maximum servo angle (in the CCW direction)
"""
angle = int(angle/300.0*1023)
pkt = makeWritePacket(ID, xl320.XL320_CCW_ANGLE_LIMIT, le(angle))
return pkt | 0.033019 |
def make_fasta_dna_url(
ensembl_release,
species,
contig,
server=ENSEMBL_FTP_SERVER):
"""
Construct URL to FASTA file with full sequence of a particular chromosome.
Returns server_url/subdir and filename as tuple result.
"""
ensembl_release, species, _ = \
nor... | 0.001261 |
def get_dividendhistory(self, symbol, startDate, endDate, items=None):
"""Retrieves divident history
"""
startDate, endDate = self.__get_time_range(startDate, endDate)
response = self.select('yahoo.finance.dividendhistory', items).where(['symbol', '=', symbol], ['startDate', '=', startDa... | 0.008 |
def xpath(self, xpath_str):
"""
Override of ``lxml`` _Element.xpath() method to provide standard Open
XML namespace mapping (``nsmap``) in centralized location.
"""
return super(BaseOxmlElement, self).xpath(
xpath_str, namespaces=nsmap
) | 0.006734 |
def potinflayers(self, x, y, layers, aq=None):
'''Returns array of size (len(layers),nparam)
only used in building equations'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
pot = self.potinf(x, y, aq) # nparam rows, naq cols
rv = np.sum(pot[:,np.newaxis,:] * aq.eigv... | 0.016627 |
def get_object_data(self, ref):
""" As get_object_header, but returns object data as well
:return: (hexsha, type_string, size_as_int,data_string)
:note: not threadsafe"""
hexsha, typename, size, stream = self.stream_object_data(ref)
data = stream.read(size)
del(stream)
... | 0.00551 |
def _compute_resized_shape(from_shape, to_shape):
"""
Computes the intended new shape of an image-like array after resizing.
Parameters
----------
from_shape : tuple or ndarray
Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or
alternativel... | 0.004277 |
def get_info(self):
'''Return ResourceInfo instances.'''
if self._min_disk:
for path in self._resource_paths:
usage = psutil.disk_usage(path)
yield ResourceInfo(path, usage.free, self._min_disk)
if self._min_memory:
usage = psutil.virtual... | 0.004975 |
def create_environment_vip(self):
"""Get an instance of environment_vip services facade."""
return EnvironmentVIP(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | 0.008299 |
def averageSweep(self,sweepFirst=0,sweepLast=None):
"""
Return a sweep which is the average of multiple sweeps.
For now, standard deviation is lost.
"""
if sweepLast is None:
sweepLast=self.sweeps-1
nSweeps=sweepLast-sweepFirst+1
runningSum=np.zeros(le... | 0.019017 |
def create_field(self, work_item_field, project=None):
"""CreateField.
[Preview API] Create a new field.
:param :class:`<WorkItemField> <azure.devops.v5_1.work_item_tracking.models.WorkItemField>` work_item_field: New field definition
:param str project: Project ID or project name
... | 0.006042 |
def initiate(self, aspect=None, view=None, parent=None, officer=None):
"""Do not keep any reference to its parent,
this way it can be garbage-collected."""
def got_view(view):
if view is None:
return None
return init(view)
def init(view):
... | 0.001548 |
def catch(self, exceptions): # pylint: disable=redefined-outer-name
"""Check if this node handles any of the given exceptions.
If ``exceptions`` is empty, this will default to ``True``.
:param exceptions: The name of the exceptions to check for.
:type exceptions: list(str)
"""... | 0.003745 |
def is_ordered(self):
"""
True if site is an ordered site, i.e., with a single species with
occupancy 1.
"""
totaloccu = self.species.num_atoms
return totaloccu == 1 and len(self.species) == 1 | 0.008333 |
def _read_response(self):
"""
Internal response reader.
:return: CliResponse or None
"""
try:
line = self.readline()
except RuntimeError:
Dut._logger.warning("Failed to read PIPE", extra={'type': '!<-'})
return -1
if line:
... | 0.00272 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document') and self.document is not None:
_dict['document'] = self.document._to_dict()
if hasattr(self, 'model_id') and self.model_id is not None:
_dict['model... | 0.003195 |
async def wait_until_ready(
self, timeout: Optional[float] = None, no_raise: bool = False
) -> bool:
"""
Waits for the underlying node to become ready.
If no_raise is set, returns false when a timeout occurs instead of propogating TimeoutError.
A timeout of None means to wai... | 0.006431 |
def handle(self, *args, **options):
"""
Parses/validates, and breaks off into actions.
"""
if len(args) < 1:
raise CommandError("Please specify an action. See --help.")
action = args[0]
email = None
if action not in self.valid_actions:
me... | 0.002237 |
def convert_multiPointSource(self, node):
"""
Convert the given node into a MultiPointSource object.
:param node: a node with tag multiPointGeometry
:returns: a :class:`openquake.hazardlib.source.MultiPointSource`
"""
geom = node.multiPointGeometry
lons, lats = z... | 0.001854 |
def destroy_multiprocessing(parallel_data, queue=None):
'''
This function will be called from another process when running a map in
parallel mode. The result from the destroy is always a json object.
'''
salt.utils.crypt.reinit_crypto()
parallel_data['opts']['output'] = 'json'
clouds = salt... | 0.000951 |
def refine (self, requirements):
""" Refines this set's properties using the requirements passed as an argument.
"""
assert isinstance(requirements, PropertySet)
if requirements not in self.refined_:
r = property.refine(self.all_, requirements.all_)
self.refined_... | 0.010256 |
def names(self):
"""Set of the variable in this list"""
ret = set()
for arr in self:
if isinstance(arr, InteractiveList):
ret.update(arr.names)
else:
ret.add(arr.name)
return ret | 0.007519 |
def unregister(self, name: str):
'''Unregister hook.'''
del self._callbacks[name]
if self._event_dispatcher is not None:
self._event_dispatcher.unregister(name) | 0.010152 |
def start(self, **kwargs):
"""
Start the commands of this organizer
Parameters
----------
``**kwargs``
Any keyword from the :attr:`commands` or :attr:`parser_commands`
attribute
Returns
-------
argparse.Namespace
The n... | 0.00107 |
def get_week_start_end_day():
"""
Get the week start date and end date
"""
t = date.today()
wd = t.weekday()
return (t - timedelta(wd), t + timedelta(6 - wd)) | 0.005495 |
def cluster_sites(mol, tol, give_only_index=False):
"""
Cluster sites based on distance and species type.
Args:
mol (Molecule): Molecule **with origin at center of mass**.
tol (float): Tolerance to use.
Returns:
(origin_site, clustered_sites): origin_site is a site at the cente... | 0.000677 |
def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]:
"""
This method should return one epoch worth of batches.
"""
raise NotImplementedError | 0.014218 |
def _remove_identical_contigs(self, containing_contigs, contig_lengths):
'''Input is dictionary of containing contigs made by self._expand_containing_using_transitivity().
Removes redundant identical contigs, leaving one representative (the longest) of
each set of identical contigs.
... | 0.003606 |
def get_parent_parser():
"""Create instances of a parser containing common arguments shared among
all the commands.
When overwritting `-q` or `-v`, you need to instantiate a new object
in order to prevent some weird behavior.
"""
parent_parser = argparse.ArgumentParser(add_help=False)
log_... | 0.001477 |
def import_from_pypower_ppc(network, ppc, overwrite_zero_s_nom=None):
"""
Import network from PYPOWER PPC dictionary format version 2.
Converts all baseMVA to base power of 1 MVA.
For the meaning of the pypower indices, see also pypower/idx_*.
Parameters
----------
ppc : PYPOWER PPC dict
... | 0.01674 |
def highlight_info(ctx, style):
"""Outputs the CSS which can be customized for highlighted code"""
click.secho("The following styles are available to choose from:", fg="green")
click.echo(list(pygments.styles.get_all_styles()))
click.echo()
click.secho(
f'The following CSS for the "{style}" ... | 0.006772 |
def _stopHeartbeatWithReason(self, reason=DISCONNECT.GO_AWAY):
'''We lost our connection - stop our heartbeat. This runs when the
protocol wants a disconnection.
This redundant output ensures that the heartbeater stops
immediately after the connection is lost. Twisted will call
... | 0.00316 |
def convert_attribute_name_to_tag(value):
"""
A utility function that converts an attribute name string into the
corresponding attribute tag.
For example: 'State' -> enums.Tags.STATE
Args:
value (string): The string name of the attribute.
Returns:
enum: The Tags enumeration va... | 0.001233 |
def load_checkpoints(self, checkpointDirs):
"""Load checkpoints from the checkpoint files into a dictionary.
The results are used to pre-populate the memoizer's lookup_table
Kwargs:
- checkpointDirs (list) : List of run folder to use as checkpoints
Eg. ['runinfo/001... | 0.002865 |
def get_broks(self, broker_name):
"""Send a HTTP request to the satellite (GET /_broks)
Get broks from the satellite.
Un-serialize data received.
:param broker_name: the concerned broker link
:type broker_name: BrokerLink
:return: Broks list on success, [] on failure
... | 0.003788 |
def flowspec_prefix_add(self, flowspec_family, rules, route_dist=None,
actions=None):
""" This method adds a new Flow Specification prefix to be advertised.
``flowspec_family`` specifies one of the flowspec family name.
This parameter must be one of the following.
... | 0.002623 |
def check_configuration(config):
'''Check if configuration object is not malformed.
:param config: configuration
:type config: dict
:return: is configuration correct?
:rtype: bool
'''
sections = ('commands', 'parameters', 'pipelines')
# Check all sections are there and contain dicts
... | 0.00052 |
def _prune_subdirs(dir_: str) -> None:
"""
Delete all subdirs in training log dirs.
:param dir_: dir with training log dirs
"""
for logdir in [path.join(dir_, f) for f in listdir(dir_) if is_train_dir(path.join(dir_, f))]:
for subdir in [path.join(logdir, f) for f in listdir(logdir) if path... | 0.007833 |
def get_parameter_value(self):
"""Get parameter of the tab.
:returns: Dictionary of parameters by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
"""
parameters = self.parameter_container.get_parameters(True)
field_parameters = {}
valu... | 0.002625 |
def replace_u_start_day(day):
"""Find the earliest legitimate day."""
day = day.lstrip('-')
if day == 'uu' or day == '0u':
return '01'
if day == 'u0':
return '10'
return day.replace('u', '0') | 0.004405 |
def unselect(self):
"""
Select a Null bitmasp into this wxDC instance
"""
if sys.platform=='win32':
self.dc.SelectObject(wx.NullBitmap)
self.IsSelected = False | 0.013953 |
def handleTickSize(self, msg):
"""
holds latest tick bid/ask/last size
"""
if msg.size < 0:
return
df2use = self.marketData
if self.contracts[msg.tickerId].m_secType in ("OPT", "FOP"):
df2use = self.optionsData
# create tick holder for t... | 0.000939 |
def _to_vcard(self, entry):
"""Return a vCard of the Abook entry"""
card = vCard()
card.add('uid').value = Abook._gen_uid(entry)
card.add('fn').value = entry['name']
card.add('n').value = Abook._gen_name(entry['name'])
if 'email' in entry:
for email in entry... | 0.002105 |
def register_unused_addresses(wallet_obj, subchain_index, num_addrs=1):
'''
Hit /derive to register new unused_addresses on a subchain_index and verify them client-side
Returns a list of dicts of the following form:
[
{'address': '1abc123...', 'path': 'm/0/9', 'public': '0123456...'},
... | 0.001892 |
def varchar(anon, obj, field, val):
"""
Returns random data for a varchar field.
"""
return anon.faker.varchar(field=field) | 0.007194 |
def sleep(dt):
"""Public function to sleep some time.
Example:
yield tasklets.sleep(0.5) # Sleep for half a sec.
"""
fut = Future('sleep(%.3f)' % dt)
eventloop.queue_call(dt, fut.set_result, None)
return fut | 0.022222 |
def _get_stddevs(self, C, stddev_types, stddev_shape):
"""
Returns the standard deviations given in Table 2
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOT... | 0.003008 |
def format_data(x, vectorizer='CountVectorizer',
semantic='LatentDirichletAllocation', corpus='wiki', ppca=True, text_align='hyper'):
"""
Formats data into a list of numpy arrays
This function is useful to identify rows of your array that contain missing
data or nans. The returned indi... | 0.004667 |
def evaluate_tokens(tokens):
"""Evaluate the given tokens in the computation graph."""
if isinstance(tokens, str):
return tokens
elif isinstance(tokens, ParseResults):
# evaluate the list portion of the ParseResults
toklist, name, asList, modal = tokens.__getnewargs__()
new_t... | 0.00325 |
def delete_file(self, sass_filename, sass_fileurl):
"""
Delete a *.css file, but only if it has been generated through a SASS/SCSS file.
"""
if self.use_static_root:
destpath = os.path.join(self.static_root, os.path.splitext(sass_fileurl)[0] + '.css')
else:
... | 0.006612 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.