text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_subgraphs_by_citation(graph):
"""Stratify the graph based on citations.
:type graph: pybel.BELGraph
:rtype: dict[tuple[str,str],pybel.BELGraph]
"""
rv = defaultdict(graph.fresh_copy)
for u, v, key, data in graph.edges(keys=True, data=True):
if CITATION not in data:
... | 0.002 |
def optimize(self, problem, max_iterations=100, max_seconds=float('inf'),
cache_encoded=True, cache_solution=False, clear_cache=True,
logging_func=_print_fitnesses,
n_processes=0):
"""Find the optimal inputs for a given fitness function.
Args:
... | 0.002764 |
def _after_request(self, response):
"""A function to be run after each request.
See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.after_request
"""
# Do not trace if the url is blacklisted
if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
re... | 0.00289 |
def public_keys(self):
"""Return a list of SSH public keys (in textual format)."""
if not self.public_keys_cache:
conn = self.conn_factory()
self.public_keys_cache = conn.export_public_keys(self.identities)
return self.public_keys_cache | 0.007042 |
def solve_hessian_approx_uniform(X, cells, rhs):
"""As discussed above, the approximated Jacobian is
partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
To get the Hessian, we have to form its derivative. As a simplifications,
let us assume again that |tau_j| is independent of the node... | 0.002256 |
def times_csv(path, times, annotations=None, delimiter=',', fmt='%0.3f'):
r"""Save time steps as in CSV format. This can be used to store the output
of a beat-tracker or segmentation algorithm.
If only `times` are provided, the file will contain each value
of `times` on a row::
times[0]\n
... | 0.00056 |
def adj_par_names(self):
""" wrapper around pyemu.Pst.adj_par_names for list adjustable parameter
names
Returns
-------
adj_par_names : list
pyemu.Pst.adj_par_names
"""
if self.__pst is not None:
return self.pst.adj_par_names
... | 0.010899 |
def event_source_mapping_present(name, EventSourceArn, FunctionName,
StartingPosition, Enabled=True, BatchSize=100,
region=None, key=None, keyid=None,
profile=None):
'''
Ensure event source mapping exists.
na... | 0.000173 |
def add(self, dpos, dlen, ulen, flag, typcd, nm):
"""Add an entry to the table of contents.
DPOS is data position.
DLEN is data length.
ULEN is the uncompressed data len.
FLAG says if the data is compressed.
TYPCD is the "type" of the entry (used by the C ... | 0.004706 |
def semicovariance(prices, benchmark=0, frequency=252):
"""
Estimate the semicovariance matrix, i.e the covariance given that
the returns are less than the benchmark.
.. semicov = E([min(r_i - B, 0)] . [min(r_j - B, 0)])
:param prices: adjusted closing prices of the asset, each row is a date
... | 0.00199 |
async def append_entries(self, destination=None):
"""AppendEntries RPC — replicate log entries / heartbeat
Args:
destination — destination id
Request params:
term — leader’s term
leader_id — so follower can redirect clients
prev_log_index — index ... | 0.003205 |
def param_extract(args, short_form, long_form, default=None):
"""
Quick extraction of a parameter from the command line argument list.
In some cases we need to parse a few arguments before the official
arg-parser starts.
Returns parameter value, or None if not present.
"""
val = default
... | 0.001059 |
def ensure_exe(exe_name: str, *paths: str): # pragma: no cover
"""
Makes sure that an executable can be found on the system path.
Will exit the program if the executable cannot be found
Args:
exe_name: name of the executable
paths: optional path(s) to be searched; if not specified, sea... | 0.004016 |
def lstm_seq2seq_internal_attention(inputs, targets, hparams, train,
inputs_length, targets_length):
"""LSTM seq2seq model with attention, main step used for training."""
with tf.variable_scope("lstm_seq2seq_attention"):
# Flatten inputs.
inputs = common_layers.flatten4d3... | 0.003046 |
async def items(self, name=None, *, watch=None):
"""Lists the most recent events an agent has seen
Parameters:
name (str): Filter events by name.
watch (Blocking): Do a blocking query
Returns:
CollectionMeta: where value is a list of events
It return... | 0.002817 |
def remove_segments(self, segments_to_remove):
''' Remove the faces and vertices for given segments, keeping all others.
Args:
segments_to_remove: a list of segnments whose vertices will be removed
'''
v_ind = self.vertex_indices_in_segments(segments_to_remove)
self.... | 0.011086 |
def swatch(self, x, y, w=35, h=35, roundness=0):
"""
Rectangle swatch for this color.
"""
_ctx.fill(self)
_ctx.rect(x, y, w, h, roundness) | 0.011236 |
def LoadElement(href, only_etag=False):
"""
Return an instance of a element as a ElementCache dict
used as a cache.
:rtype ElementCache
"""
request = SMCRequest(href=href)
request.exception = FetchElementFailed
result = request.read()
if only_etag:
return result.etag
... | 0.005263 |
def set_color_temp(self, color_temp, *, index=0, transition_time=None):
"""Set color temp a light."""
self._value_validate(color_temp, RANGE_MIREDS, "Color temperature")
values = {
ATTR_LIGHT_MIREDS: color_temp
}
if transition_time is not None:
values[AT... | 0.004878 |
def roughcwt(data, wavelet, widths):
"""
Continuous wavelet transform.
Performs a continuous wavelet transform on `data`,
using the `wavelet` function. A CWT performs a convolution
with `data` using the `wavelet` function, which is characterized
by a width parameter and length parameter.
P... | 0.001136 |
def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
... | 0.002203 |
def get_pinned_version(ireq):
"""Get the pinned version of an InstallRequirement.
An InstallRequirement is considered pinned if:
- Is not editable
- It has exactly one specifier
- That specifier is "=="
- The version does not contain a wildcard
Examples:
django==1.8 # pinned
... | 0.00078 |
def poolRunner(target, queue, coverage_number=None, omit_patterns=[], cov_config_file=True): # pragma: no cover
"""
I am the function that pool worker processes run. I run one unit test.
coverage_config_file is a special option that is either a string specifying
the custom coverage config file or the... | 0.002946 |
def blueprint(self):
"""
blueprint support, returns a partial dictionary
"""
blueprint = dict()
blueprint['type'] = "%s.%s" % (self.__module__, self.__class__.__name__)
# Fields
fields = dict()
# inspects the attributes of a parameter set and tries to v... | 0.003971 |
def _max(self):
"""Getter for the maximum series value"""
return (
self.range[1] if (self.range and self.range[1] is not None) else
(max(self._values) if self._values else None)
) | 0.008811 |
def _read_embeddings_from_text_file(file_uri: str,
embedding_dim: int,
vocab: Vocabulary,
namespace: str = "tokens") -> torch.FloatTensor:
"""
Read pre-trained word vectors from an eventually compressed t... | 0.005809 |
def isns_isns_vrf_esi_timeout(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
isns = ET.SubElement(config, "isns", xmlns="urn:brocade.com:mgmt:brocade-isns")
isns_vrf = ET.SubElement(isns, "isns-vrf")
isns_vrf_instance_key = ET.SubElement(isns_vr... | 0.004862 |
def make_sign(api_secret, params=[]):
"""
>>> make_sign("123456",[1,'2',u'中文'])
'33C9065427EECA3490C5642C99165145'
"""
_params = [utils.safeunicode(p) for p in params if p is not None]
_params.sort()
# print 'sorted params:',_params
_params.insert(0, api_secret)
strs = ''.joi... | 0.002309 |
def plane_fit(points):
"""
This fits an n-dimensional plane to a set of points. See
http://stackoverflow.com/questions/12299540/plane-fitting-to-4-or-more-xyz-points
:parameter points:
An instance of :class:~numpy.ndarray. The number of columns must be
equal to three.
:return:
... | 0.001484 |
def initialize_pop(self):
"""Assigns indices to individuals in population."""
self.toolbox.register("individual", self.generate)
self.toolbox.register("population", tools.initRepeat,
list, self.toolbox.individual)
self.population = self.toolbox.population(n=... | 0.00224 |
def send_messages(cls, http_request, message_requests):
"""
Deduplicate any outgoing message requests, and send the remainder.
Args:
http_request: The HTTP request in whose response we want to embed the messages
message_requests: A list of undeduplicated messages in the ... | 0.006154 |
def delete(self, port, qos_policy=None):
"""Remove QoS rules from port.
:param port: port object.
:param qos_policy: the QoS policy to be removed from port.
"""
LOG.info("Deleting QoS policy %(qos_policy)s on port %(port)s",
dict(qos_policy=qos_policy, port=port... | 0.005249 |
def loadMatlabImages(self, path, name):
"""
Loads images from a .mat file.
:param path: (string) Path to .mat file
:param name: (string) Object name in the .mat file, just before .mat
Also stores image dimensions to later the original images. If there are
multiple channels, self.n... | 0.005017 |
def showPopup( self ):
"""
Displays a custom popup widget for this system if a checkable state \
is setup.
"""
if not self.isCheckable():
return super(XComboBox, self).showPopup()
if not self.isVisible():
return
# update t... | 0.008989 |
def _realize(self, master, element):
"""Builds a widget from xml element using master as parent."""
data = data_xmlnode_to_dict(element, self.translator)
cname = data['class']
uniqueid = data['id']
if cname not in CLASS_MAP:
self._import_class(cname)
if cna... | 0.002083 |
def namespace(ns_key):
'''Construct a validation schema for a given namespace.
Parameters
----------
ns_key : str
Namespace key identifier (eg, 'beat' or 'segment_tut')
Returns
-------
schema : dict
JSON schema of `namespace`
'''
if ns_key not in __NAMESPACE__:
... | 0.00157 |
def scale(self, scaled_cx, scaled_cy):
"""
Return scaled image dimensions in EMU based on the combination of
parameters supplied. If *scaled_cx* and *scaled_cy* are both |None|,
the native image size is returned. If neither *scaled_cx* nor
*scaled_cy* is |None|, their values are ... | 0.001885 |
def get_icon_url(self, icon):
"""
Replaces the "icon name" with a full usable URL.
* When the icon is an absolute URL, it is used as-is.
* When the icon contains a slash, it is relative from the ``STATIC_URL``.
* Otherwise, it's relative to the theme url folder.
"""
... | 0.004644 |
def get_request(url):
"""Return a requests response from url
Args:
url(str)
Returns:
decoded_data(str): Decoded response
"""
try:
LOG.info("Requesting %s", url)
response = urllib.request.urlopen(url)
if url.endswith('.gz'):
LOG.info("Deco... | 0.005447 |
def get(self, url, callback,
params=None, json=None, headers=None):
"""Get a URL.
Args:
callback(func): The response callback function
Keyword Args:
params(dict): Parameters for the request
json(dict): JSON body for the request
he... | 0.004808 |
def get_record(self, zone_name, record_id):
"""
Get record with given id
:param zone_name: Name of the zone
:param record_id: Id of the record
:return: Value of the record
"""
return self._client.get(
'/domain/zone/{}/record/{}'.format(zone_name, recor... | 0.006135 |
def p_type_def(self, p):
'''type_def : IDENT COLON OBJECT SEMI
| IDENT COLON LCURLY enum_list RCURLY SEMI'''
if len(p) == 5:
p[0] = (p[1], p[3])
elif len(p) == 7:
p[0] = (p[1], p[4]) | 0.008 |
def resolve_any_xref(self, env, fromdocname, builder, target,
node, contnode):
"""Similar to :py:meth:`ChapelDomain.resolve_xref`, but applies to *any* or
similar role where type is not known. This returns a list of tuples
with ("domain:role", newnode).
"""
... | 0.003687 |
def add_permission_view_menu(self, permission_name, view_menu_name):
"""
Adds a permission on a view or menu to the backend
:param permission_name:
name of the permission to add: 'can_add','can_edit' etc...
:param view_menu_name:
name of the v... | 0.001837 |
def request(self, verb, path, **params):
'''
A helper function for making generic POST requests calls. It is used by
every namespaced API method. It can be used to make any generic API
call that is automatically authenticated using your API credentials:
.. code-block:: python
... | 0.002286 |
def get_tag(self, tagname, tagidx):
"""
:returns: the tag associated to the given tagname and tag index
"""
return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx])) | 0.009709 |
def get_list(value):
"""
Wraps the given value in a list. ``None`` returns an empty list. Lists and tuples are returned as lists. Single
strings and registered types are wrapped in a list.
:param value: Value to return as a list.
:return: List with the provided value(s).
:rtype: list
"""
... | 0.005587 |
def ma(X, Q, M):
"""Moving average estimator.
This program provides an estimate of the moving average parameters
and driving noise variance for a data sequence based on a
long AR model and a least squares fit.
:param array X: The input data array
:param int Q: Desired MA model order (must be >... | 0.004701 |
def walk(self, address):
'''
Returns a stream of pairs of node addresses and data, raising
AddressNotInTree if ADDRESS is not in the tree.
First the ancestors of ADDRESS (including itself) are yielded,
earliest to latest, and then the descendants of ADDRESS are
yielded i... | 0.002364 |
def find_time_base(self, gps, first_ms_stamp):
'''work out time basis for the log - new style'''
t = self._gpsTimeToTime(gps.Week, gps.TimeMS)
self.set_timebase(t - gps.T*0.001)
self.timestamp = self.timebase + first_ms_stamp*0.001 | 0.007605 |
def by_name(self, tag_name, semantictag_URI,
autoflush=True):
'''Return the TagSemanticTag for the given tag name and semantic tag URI, or None.
:param tag_name: the name of the tag to look for
:type tag_name: string
:param tag_URI: the name of the tag to look for
:type tag_URI: string
:returns: the Ta... | 0.036671 |
def report(self):
""" Print user-friendly statistics and metrics. """
table = [["Mails", "Metric"]]
table.append(["Found", self.stats['mail_found']])
table.append(["Skipped", self.stats['mail_skipped']])
table.append(["Rejected", self.stats['mail_rejected']])
table.append... | 0.000839 |
def get_failed_job(self, id):
"""Get failed job error details
Args:
id (str): The id of the job.
See: https://auth0.com/docs/api/management/v2#!/Jobs/get_errors
"""
url = self._url('{}/errors'.format(id))
return self.client.get(url) | 0.006803 |
def update_config(updated_project):
'''
Update project in configuration
args:
updated_project (dict): Updated project configuration values
'''
home = os.path.expanduser('~')
if os.path.isfile(os.path.join(home, '.transfer', 'config.yaml')):
with open(os.path.join(home, '.trans... | 0.001927 |
def module_name(self):
"""
:return: str
"""
if self.module_type in velbus.MODULE_DIRECTORY.keys():
return velbus.MODULE_DIRECTORY[self.module_type]
return "Unknown" | 0.009259 |
def reload_sources(self, names):
"""Recompute the source map for a list of sources in the model.
"""
try:
self.like.logLike.loadSourceMaps(names, True, True)
# loadSourceMaps doesn't overwrite the header so we need
# to ignore EXPSCALE by setting check_header... | 0.005671 |
def create_lazy_user(self):
""" Create a lazy user. Returns a 2-tuple of the underlying User
object (which may be of a custom class), and the username.
"""
user_class = self.model.get_user_class()
username = self.generate_username(user_class)
user = user_class.objects.cre... | 0.004963 |
def shift(self, *args, **kwargs):
"""
shift(hours, minutes, seconds, milliseconds)
All arguments are optional and have a default value of 0.
"""
if 'ratio' in kwargs:
self *= kwargs.pop('ratio')
self += self.__class__(*args, **kwargs) | 0.00678 |
def combine_dicts(*args, **kwargs):
""" Combines all arguments (if they are dictionaries) and kwargs to a final dict
:param args: dict, any dictionaries the user wants combined
:param kwargs: dict, kwargs.
:return: dict, compiled dictionary
"""
dicts = [arg for arg in args if isinstance(arg, di... | 0.003766 |
def write_script(self, script_name, contents, mode="t", *ignored):
"""Write an executable file to the scripts directory"""
from setuptools.command.easy_install import chmod, current_umask
log.info("Installing %s script to %s", script_name, self.install_dir)
target = os.path.join(self.ins... | 0.004967 |
def _get_all_eip_addresses(addresses=None, allocation_ids=None, region=None,
key=None, keyid=None, profile=None):
'''
Get all EIP's associated with the current credentials.
addresses
(list) - Optional list of addresses. If provided, only those those in the
list w... | 0.004566 |
def create_log(self, log, scope_identifier, hub_name, plan_id):
"""CreateLog.
:param :class:`<TaskLog> <azure.devops.v5_0.task.models.TaskLog>` log:
:param str scope_identifier: The project GUID to scope the request
:param str hub_name: The name of the server hub: "build" for the Build s... | 0.005443 |
def batch_get_item(self, request_items, object_hook=None):
"""
Return a set of attributes for a multiple items in
multiple tables using their primary keys.
:type request_items: dict
:param request_items: A Python version of the RequestItems
data structure defined by ... | 0.005495 |
def ExecuteCmd(cmd, quiet=False):
""" Run a command in a shell. """
result = None
if quiet:
with open(os.devnull, "w") as fnull:
result = subprocess.call(cmd, shell=True, stdout=fnull, stderr=fnull)
else:
result = subprocess.call(cmd, shell=True)
return result | 0.024648 |
def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None:
""" Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema.
:param shex: Schema
"""
self.pfx = None
if shex is not None:
if isinstance(shex, ShExJ.Schema):
... | 0.004678 |
def iterate_fs(self):
# type: () -> Iterator[Tuple[Text, FS]]
"""Get iterator that returns (name, fs) in priority order.
"""
if self._fs_sequence is None:
self._fs_sequence = [
(name, fs)
for name, (_order, fs) in sorted(
se... | 0.006711 |
def mchirp_sampler_flat(**kwargs):
''' Draw chirp mass samples for flat in mass model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
mchirp-astro: array
The chirp mass samples ... | 0.00216 |
async def connections(
for_type: Optional[CONNECTION_TYPES] = None) -> List[Dict[str, str]]:
""" Return the list of configured connections.
This is all connections that nmcli knows about and manages.
Each connection is a dict containing some basic information - the
information retrievable from ... | 0.000813 |
def return_dat(self, chan, begsam, endsam):
"""Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last ... | 0.003165 |
def call(self, phone_number, message, message_type, **params):
"""
Send a voice call to the target phone_number.
See https://developer.telesign.com/docs/voice-api for detailed API documentation.
"""
return self.post(VOICE_RESOURCE,
phone_number=phone_num... | 0.006623 |
def historic_doslegs_parse(html, url_an=None, logfile=sys.stderr, nth_dos_in_page=0, parse_previous_works=True, parse_next_works=True):
"""
Parse an AN dosleg like http://www.assemblee-nationale.fr/13/dossiers/accord_Montenegro_mobilite_jeunes.asp
nth_dos_in_page, parse_previous_works and parse_next_works ... | 0.002559 |
def do_updatereplication(self, line):
"""updatereplication <identifier> [identifier ...] Update the Replication Policy
on one or more existing Science Data Objects."""
pids = self._split_args(line, 1, -1)
self._command_processor.update_replication_policy(pids)
self._print_info_if... | 0.008282 |
def make_dict_from_vector(in_array):
""" Converts the cluster membership array stored in a fits file back to a dictionary
Parameters
----------
in_array : `np.ndarray'
An array filled with the index of the seed of a cluster if a source belongs to a cluster,
and with -1 if it does not.
... | 0.008929 |
def thumbnail(self):
"""Read-only attribute that provides the value of the thumbnail to display.
"""
# check if there is a valid thumbnail override
if self.thumbnail_override.id is not None:
return self.thumbnail_override
# otherwise, just try to grab the first image... | 0.006757 |
def get_groups_data(self, groups):
'''
Gets aggregated data from a list of groups. Vars are collected in order so, for
any groups which define the same var twice, the last group's value will hold.
'''
data = {}
for group in groups:
data.update(self.get_group... | 0.011299 |
def _get_exchange_key_ntlm_v1(negotiate_flags, session_base_key,
server_challenge, lm_challenge_response,
lm_hash):
"""
[MS-NLMP] v28.0 2016-07-14
3.4.5.1 KXKEY
Calculates the Key Exchange Key for NTLMv1 authentication. Used for signing
an... | 0.000555 |
def _update_dPrxy(self):
"""Update `dPrxy`, accounting for dependence of `phi` on `beta`."""
super(ExpCM_empirical_phi, self)._update_dPrxy()
if 'beta' in self.freeparams:
self.dQxy_dbeta = scipy.zeros((N_CODON, N_CODON), dtype='float')
for w in range(N_NT):
... | 0.004926 |
def get(url: str, *args, **kwargs) -> tuple:
"""Send a GET request. Returns a dict or :class:`requests.Response <Response>`"""
return RequestsHelper.request(url, "get", *args, **kwargs) | 0.010363 |
def add_common_check(self, actions, table, func):
"""
emitted before query
:param actions:
:param table:
:param func:
:return:
"""
self.common_checks.append([table, actions, func])
"""def func(ability, user, action, available_columns: list):
... | 0.008746 |
def _fillVolumesAndPaths(self, paths):
""" Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]}
"""
with self.btrfs as mount:
for bv in mount.subvolumes:
if not bv.readOnly:
continue
vol = self._btrfsVol2StoreVol(... | 0.001103 |
def hash(file):
"""
Hashes file using SHA-256.
:param file: name of file to be hashed
:type file: str
:rtype: str
:raises check50.Failure: if ``file`` does not exist
"""
exists(file)
log(_("hashing {}...").format(file))
# https://stackoverflow.com/a/22058673
with open(fil... | 0.002041 |
def _set_bfd(self, v, load=False):
"""
Setter method for bfd, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/bfd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bfd is considered as a private
method. Backends looking to populate this ... | 0.005391 |
def write_contents(self, table, reader):
"""Write the contents of `table`
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write.
- `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql... | 0.009934 |
def run(self):
""" Fonctionnement du thread """
if self.debug:
print("Starting " + self.name)
# Lancement du programme du thread
if isinstance(self.function, str):
globals()[self.function](*self.args, **self.kwargs)
else:
self.function(*self.args, **self.kwargs)
if self.debug:
print("Exiting "... | 0.036036 |
def show_color_bar(viewer, tf, side='bottom'):
"""Show a color bar in the window.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
tf : bool
If True, show the color bar; else remove it if present.
side : str
... | 0.001245 |
def create_environment_dict(overrides):
"""
Create and return a copy of os.environ with the specified overrides
"""
result = os.environ.copy()
result.update(overrides or {})
return result | 0.004739 |
def slice_sequences(sequences, start, end, apply_slice=None):
"""
Performs a slice across multiple sequences.
Useful when paginating across chained collections.
:param sequences: an iterable of iterables, each nested iterable should contain
a sequence and its size
:param start: starting index... | 0.002596 |
def writefits(self, filename, clobber=True, trimzero=True,
binned=False, precision=None, hkeys=None):
"""Write the spectrum to a FITS table.
Primary header in EXT 0. ``FILENAME``, ``ORIGIN``, and any
extra keyword(s) from ``hkeys`` will also be added.
Table header an... | 0.002236 |
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]:
"""
Given an SQLAlchemy ORM base class, returns a dictionary whose keys are
table names and whose values are ORM classes.
If you begin with the proper :class`Base` class, then this should give all
tables and ORM classes in ... | 0.002208 |
async def get_reader(self, source=FFMPEG_STDOUT) -> asyncio.StreamReader:
"""Create and return streamreader."""
reader = asyncio.StreamReader(loop=self._loop)
reader_protocol = asyncio.StreamReaderProtocol(reader)
# Attach stream
if source == FFMPEG_STDOUT:
await sel... | 0.003333 |
def filter_embeddings(embeddings, vocab, dim):
"""Loads word vectors in numpy array.
Args:
embeddings (dict): a dictionary of numpy array.
vocab (dict): word_index lookup table.
Returns:
numpy array: an array of word embeddings.
"""
if not isinstance(embeddings, dict):
... | 0.001845 |
def get_api_date(self):
'''
Figure out the date to use for API requests. Assumes yesterday's date
if between midnight and 10am Eastern time. Override this function in a
subclass to change how the API date is calculated.
'''
# NOTE: If you are writing your own function to ... | 0.001635 |
def _publish_queue_wss(self):
"""
send the messages down the web socket connection as a json object
:return: None
"""
msg = []
for m in self._tx_queue:
msg.append({'id': m.id, 'body': m.body, 'zone_id': m.zone_id})
self._ws.send(json.dumps(msg), opcod... | 0.005698 |
def plot_ebands(self, **kwargs):
"""
Plot the band structure. kwargs are passed to the plot method of :class:`ElectronBands`.
Returns:
`matplotlib` figure
"""
with self.nscf_task.open_gsr() as gsr:
return gsr.ebands.plot(**kwargs) | 0.010169 |
def clear_queue(self):
"""
clear outs all messages from INPUT_QUEUE_NAME
"""
def remove_message(ch, method, properties, body):
print("Removed message: %s" % body)
self.input_channel.basic_consume(remove_message, queue=self.INPUT_QUEUE_NAME, no_ack=True)
try:
... | 0.006356 |
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
"""
Pan or rotate the view.
"""
self.view['ball'].drag(np.array([x, y]))
self.scene.camera.transform = self.view['ball'].pose | 0.008929 |
def dorun(SNR=20, njitters=20, samples=10, noise_samples=10, sweeps=20, burn=10):
"""
we want to display the errors introduced by pixelation so we plot:
* CRB, sampled error vs exposure time
a = dorun(ntimes=10, samples=5, noise_samples=5, sweeps=20, burn=8)
"""
jitters = np.logspace(-6, np... | 0.007759 |
def get_duckduckgo_links(limit, params, headers):
"""
function to fetch links equal to limit
duckduckgo pagination is not static, so there is a limit on
maximum number of links that can be scraped
"""
resp = s.get('https://duckduckgo.com/html', params = params, headers = headers)
links = scrape_links(resp.conte... | 0.044568 |
def shellPrintOverview(g, opts={'labels': False}):
"""
overview of graph invoked from command line
@todo
add pagination via something like this
# import pydoc
# pydoc.pager("SOME_VERY_LONG_TEXT")
"""
ontologies = g.all_ontologies
# get opts
try:
labels = opts['labels']... | 0.001144 |
def update(self, other):
""" Merge two Textgroup Objects.
- Original (left Object) keeps his parent.
- Added document merges with work if it already exists
:param other: Textgroup object
:type other: CtsTextgroupMetadata
:return: Textgroup Object
:rtype: CtsText... | 0.004171 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.