text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def disambiguate_entity(key, text):
"""Resolve ambiguity between entities with same dimensionality."""
new_ent = l.DERIVED_ENT[key][0]
if len(l.DERIVED_ENT[key]) > 1:
transformed = TFIDF_MODEL.transform([text])
scores = CLF.predict_proba(transformed).tolist()[0]
scores = sorted(zip(... | 0.001456 |
def all_filters(lc):
"""
Get a list of all your saved filters
Parameters
----------
lc : :py:class:`lendingclub.LendingClub`
An instance of the authenticated LendingClub class
Returns
-------
list
A list of lendingclub.filters.Sav... | 0.002878 |
def update_field(self, name, update):
"""https://github.com/frictionlessdata/tableschema-py#schema
"""
for field in self.__next_descriptor['fields']:
if field['name'] == name:
field.update(update)
return True
return False | 0.006734 |
def get_payload(request):
"""
Extracts the request's payload information.
This method will merge the URL parameter information
and the JSON body of the request together to generate
a dictionary of key<->value pairings.
This method assumes that the JSON body being provided
is also a key-valu... | 0.001028 |
def _getSyllableNucleus(phoneList):
'''
Given the phones in a syllable, retrieves the vowel index
'''
cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList]
vowelCount = cvList.count('V')
if vowelCount > 1:
raise TooManyVowelsInSyllable(phoneList, cvList)
... | 0.009153 |
def get_movies(self):
"""
Retrieves all the movies published by the artist
:return: List. Movies published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['movie'])[1:] | 0.012245 |
def get_named_nodes(self, *names):
"""Deprecated. Use named_nodes()."""
warnings.warn('The method get_named_nodes() is being replaced by named_nodes()',
'Returning a list of node_ids is also deprecated, named_nodes() '
'returns a list of DAGNodes ',
... | 0.007092 |
def wrap(self, message, conf_req=True, qop_req=C.GSS_C_QOP_DEFAULT):
"""
Wraps a message with a message integrity code, and if `conf_req` is True, encrypts the
message. The message can be decrypted and the MIC verified by the peer by passing the
token returned from this method to :meth:`... | 0.002914 |
def put(self, url, data=None, verify=False,
headers=None, proxies=None, timeout=60, **kwargs):
"""Sends a PUT request. Refactor from requests module
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to
sen... | 0.003032 |
def _pkg_names(pkg):
"""
Given a namespace package, yield the components of that
package.
>>> names = Installer._pkg_names('a.b.c')
>>> set(names) == set(['a', 'a.b', 'a.b.c'])
True
"""
parts = pkg.split('.')
while parts:
yield '.'.joi... | 0.005682 |
def self_inventory(self):
"""
Inventory output will only contain the server name and the session ID
when a key is provided. Provide the same format as with the full
inventory instead for consistency.
"""
if self.api_key is None:
return {}
if self._sel... | 0.002928 |
def make_config_data(*, guided):
"""
Makes the data necessary to construct a functional config file
"""
config_data = {}
config_data[INCLUDE_DIRS_KEY] = _make_include_dirs(guided=guided)
config_data[RUNTIME_DIRS_KEY] = _make_runtime_dirs(guided=guided)
config_data[RUNTIME_KEY] = _make_runtim... | 0.002882 |
def _FormatSocketUnixToken(self, token_data):
"""Formats an Unix socket token as a dictionary of values.
Args:
token_data (bsm_token_data_sockunix): AUT_SOCKUNIX token data.
Returns:
dict[str, str]: token values.
"""
protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKN... | 0.002208 |
def get_count(dataset, query=None):
"""Ask DataBC WFS how many features there are in a table/query
"""
# https://gis.stackexchange.com/questions/45101/only-return-the-numberoffeatures-in-a-wfs-query
table = validate_name(dataset)
payload = {
"service": "WFS",
"version": "2.0.0",
... | 0.001639 |
def eval_from_json(json):
""" Evaluates OBV from JSON (typically Poloniex API response)
Args:
json: List of dates where each entry is a dict of raw market data.
Returns:
Float of OBV
"""
closes = poloniex.get_attribute(json, 'close')
volumes = po... | 0.003289 |
def convert(self, normalization=None, csphase=None, lmax=None, kind=None,
check=True):
"""
Return a SHCoeffs class instance with a different normalization
convention.
Usage
-----
clm = x.convert([normalization, csphase, lmax, kind, check])
Return... | 0.000828 |
def _format_level_2(rows, list_embeds, embed_many):
"""
From the _format_level_1 function we have a list of rows. Because of using
joins, we have as many rows as join result.
For example:
[{'id' : 'id1',
'name' : 'name1,
'b' : {'id': 'id2,
'name': 'name2'}
}
{'id'... | 0.000253 |
def set_name(self, col=None, name=None):
"""
Set a new name for a column.
:param col: index or name of the column whose name is to be set; may be skipped for 1-column frames
:param name: the new name of the column
"""
assert_is_type(col, None, int, str)
assert_is... | 0.005245 |
def _assert_lt(self, cost):
"""
The method enforces an upper bound on the cost of the MaxSAT
solution. This is done by encoding the sum of all soft clause
selectors with the use the iterative totalizer encoding, i.e.
:class:`.ITotalizer`. Note that the sum is crea... | 0.003693 |
def i2c_monitor_read(self):
"""Retrieved any data fetched by the monitor.
This function has an integrated timeout mechanism. You should use
:func:`poll` to determine if there is any data available.
Returns a list of data bytes and special symbols. There are three
special symbol... | 0.004658 |
def gdaldem_mem_ds(ds, processing='hillshade', returnma=False, computeEdges=False):
"""
Wrapper for gdaldem functions
Uses gdaldem API, requires GDAL v2.1+
"""
choices = ["hillshade", "slope", "aspect", "color-relief", "TRI", "TPI", "Roughness"]
out = None
scale=1.0
if not get_ds_srs(ds... | 0.009763 |
def unban_chat_member(self, *args, **kwargs):
"""See :func:`unban_chat_member`"""
return unban_chat_member(*args, **self._merge_overrides(**kwargs)).run() | 0.017647 |
def generate_frames(self, frame_duration_ms, zero_pad=True):
"""
Yields self's data in chunks of frame_duration_ms.
This function adapted from pywebrtc's example [https://github.com/wiseman/py-webrtcvad/blob/master/example.py].
:param frame_duration_ms: The length of each frame in ms.
... | 0.005938 |
def zeros(dur=None):
"""
Zeros/zeroes stream generator.
You may sum your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "0.0" during a given time duration (if any) or
endlessl... | 0.010989 |
def generate_fetch_ivy(cls, jars, ivyxml, confs, resolve_hash_name):
"""Generates an ivy xml with all jars marked as intransitive using the all conflict manager."""
org = IvyUtils.INTERNAL_ORG_NAME
name = resolve_hash_name
extra_configurations = [conf for conf in confs if conf and conf != 'default']
... | 0.007407 |
def get_items(self, project=None, scope_path=None, recursion_level=None, include_links=None, version_descriptor=None):
"""GetItems.
Get a list of Tfvc items
:param str project: Project ID or project name
:param str scope_path: Version control path of a folder to return multiple items.
... | 0.007032 |
def getCircles(rawnodes,rawedges):
''' Example input:
rawnodes = [1,2,3,4,5,6]
rawedges = [(1,2),(1,3),(1,4),(2,4),(1,5),(5,6)]
Returns an array of Circle objects with attribute child arrays populated.
'''
circles = []
for x in rawnodes:
i = Circle(str(x))
for (p,q) in r... | 0.011792 |
def move_to(self, position):
"""Set the Coordinator to a specific endpoint or time, or load state from a token.
:param position: "trim_horizon", "latest", :class:`~datetime.datetime`, or a
:attr:`Coordinator.token <bloop.stream.coordinator.Coordinator.token>`
"""
if isinstan... | 0.008974 |
def get_harddisk_sleep():
'''
Display the amount of idle time until the hard disk sleeps.
:return: A string representing the sleep settings for the hard disk
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_harddisk_sleep
'''
ret = salt.utils.mac_utils.execute_... | 0.002353 |
def eval_model(model, test, add_eval_metrics={}):
"""Evaluate model's performance on the test-set.
# Arguments
model: Keras model
test: test-dataset. Tuple of inputs `x` and target `y` - `(x, y)`.
add_eval_metrics: Additional evaluation metrics to use. Can be a dictionary or a list of f... | 0.002508 |
def recognized_release(self):
"""
Check if this Release value is something we can parse.
:rtype: bool
"""
_, _, rest = self.get_release_parts()
# If "rest" is not a well-known value here, then this package is
# using a Release value pattern we cannot recognize.
... | 0.004785 |
def retry_over_time(fun, catch, args=[], kwargs={}, errback=None,
max_retries=None, interval_start=2, interval_step=2, interval_max=30):
"""Retry the function over and over until max retries is exceeded.
For each retry we sleep a for a while before we try again, this interval
is increased for every... | 0.00111 |
def prune_chunks(self, tsn):
"""
Prune chunks up to the given TSN.
"""
pos = -1
size = 0
for i, chunk in enumerate(self.reassembly):
if uint32_gte(tsn, chunk.tsn):
pos = i
size += len(chunk.user_data)
else:
... | 0.004938 |
def find_similar_days(training_data, now, observation_length, k, method=hamming_distance):
min_time = training_data.index[0] + timedelta(minutes=observation_length)
# Find moments in our dataset that have the same hour/minute and is_weekend() == weekend.
selector = ((training_data.index.minute == now.minute) &
... | 0.031226 |
def max_pool(x_input, pool_size):
"""max_pool downsamples a feature map by 2X."""
return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1],
strides=[1, pool_size, pool_size, 1], padding='SAME') | 0.004237 |
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](instal... | 0.001502 |
def retry_count(self):
"""
Amount of retried test cases in this list.
:return: integer
"""
retries = len([i for i, result in enumerate(self.data) if result.retries_left > 0])
return retries | 0.012605 |
def remove(self, path, recursive=True, skip_trash=True):
"""
Removes the given mockfile. skip_trash doesn't have any meaning.
"""
if recursive:
to_delete = []
for s in self.get_all_data().keys():
if s.startswith(path):
to_delete... | 0.004338 |
def focusInEvent(self, e):
"""Qt Override."""
super(ShortcutsTable, self).focusInEvent(e)
self.selectRow(self.currentIndex().row()) | 0.012658 |
def pop_record_writes(self):
"""
Stop recording trace and return a `list[(address, value)]` of all the writes
that occurred, where `value` is of type list[str]. Can be called without
intermediate `pop_record_writes()`.
For example::
mem.push_record_writes()
... | 0.005348 |
def plot_wigner2d(iradon_output, bin_centres, cmap=_cm.cubehelix_r, figsize=(6, 6)):
"""
Plots the wigner space representation as a 2D heatmap.
Parameters
----------
iradon_output : ndarray
2d array of size (histbins x histbins)
bin_centres : ndarray
positions of the bin centres... | 0.006275 |
def to_xml(self):
"""Get this batch as XML"""
assert self.connection != None
s = '<?xml version="1.0" encoding="UTF-8"?>\n'
s += '<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/%s/">\n' % self.connection.Version
for p in self.paths:
s += ' <Path>%s</... | 0.010352 |
def update_position(self, newpos):
'''update object position'''
if getattr(self, 'trail', None) is not None:
self.trail.update_position(newpos)
self.latlon = newpos.latlon
if hasattr(self, 'rotation'):
self.rotation = newpos.rotation | 0.00692 |
def to_nice_yaml(yaml_input, indentation=2):
"""
Return condensed yaml into human readable yaml.
"""
return yaml.safe_dump(yaml_input, indent=indentation,
allow_unicode=True, default_flow_style=False) | 0.004132 |
def __show_pattern(ax_handle, syncpr_output_dynamic, image_height, image_width, iteration):
"""!
@brief Draws pattern on specified ax.
@param[in] ax_handle (Axis): Axis where pattern should be drawn.
@param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr n... | 0.023203 |
def _download_file(self, fname):
"""
Download a file from the remote data storage to the local storage.
Used by :meth:`~pooch.Pooch.fetch` to do the actual downloading.
Parameters
----------
fname : str
The file name (relative to the *base_url* of the remote... | 0.00377 |
def get_name(path_name, *, ext=True, override=None, identity=None):
"""
Gets the name par of the path name given. By 'name' I mean the basename of
a filename's path, such as 'test.o' in the path: 'C:/test/test.o'
"""
if identity is None:
identity = identify(path_name, override=override)
... | 0.001912 |
def backward_smoothing_pass(self,
filtered_means,
filtered_covs,
predicted_means,
predicted_covs):
"""Run the backward pass in Kalman smoother.
The backward smoothing is using Rauch, Tung and... | 0.007289 |
def generate_phrase_detection_function(cls, min_token_count, max_phrases, exclude_ngram_filter=None):
"""
This is a factory function for generating a phrase detection function
:param cls: the class
:param min_token_count: tokens that appear less than this will be ignored in the phrase de... | 0.008094 |
def reboot(self):
"""
Reboot the device
Useful when trying to get xDSL sync
"""
token = self.get_token()
self.bbox_auth.set_access(BboxConstant.AUTHENTICATION_LEVEL_PRIVATE, BboxConstant.AUTHENTICATION_LEVEL_PRIVATE)
url_suffix = "reboot?btoken={}".format(token)
... | 0.005515 |
def cli(ctx, all, top, nostyle, nowarn, warn, project_dir):
"""Lint the verilog code."""
exit_code = SCons(project_dir).lint({
'all': all,
'top': top,
'nostyle': nostyle,
'nowarn': nowarn,
'warn': warn
})
ctx.exit(exit_code) | 0.003559 |
def dict_fun(data, function):
"""
Apply a function to all values in a dictionary, return a dictionary with
results.
Parameters
----------
data : dict
a dictionary whose values are adequate input to the second argument
of this function.
function : function
a function... | 0.003738 |
def _parse_phone(self, val):
"""
The function for parsing the vcard phone numbers.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
... | 0.004959 |
def handle_long(self, item):
"""Helper method for fetching a long value. Result is integer."""
doc = yield from self.handle_get(item)
if doc is None:
return None
return int(doc.value.u32.text) or None | 0.008163 |
def get_kpoints(self, line_density=20, coords_are_cartesian=True):
"""
Returns:
the kpoints along the paths in cartesian coordinates
together with the labels for symmetry points -Wei
"""
list_k_points = []
sym_point_labels = []
for b in self.kpath[... | 0.001432 |
def get_or_create_party(self, row):
"""
Gets or creates the Party object based on AP code of the row of
election data.
All parties that aren't Democratic or Republican are aggregable.
"""
if row["party"] in ["Dem", "GOP"]:
aggregable = False
else:
... | 0.003472 |
def copy_with_new_atts(self, **attributes):
"""Returns a new FmtStr with the same content but new formatting"""
return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes))
for bfs in self.chunks]) | 0.008547 |
def services(self, name=None, pk=None, scope=None, **kwargs):
"""
Retrieve Services.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param na... | 0.00432 |
def mapPartitionsWithIndex(self, f, preservesPartitioning=False):
"""
Return a new DStream in which each RDD is generated by applying
mapPartitionsWithIndex() to each RDDs of this DStream.
"""
return self.transform(lambda rdd: rdd.mapPartitionsWithIndex(f, preservesPartitioning)) | 0.009375 |
def rotate(image, angle, interpolation=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_REFLECT, borderValue=0):
'''
angle [deg]
'''
s0, s1 = image.shape
image_center = (s0 - 1) / 2., (s1 - 1) / 2.
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
result = cv2.warpAffine(i... | 0.002028 |
def maybe_dotted(module, throw=True):
""" If ``module`` is a dotted string pointing to the module,
imports and returns the module object.
"""
try:
return Configurator().maybe_dotted(module)
except ImportError as e:
err = '%s not found. %s' % (module, e)
if throw:
... | 0.002457 |
def parse_duration(string):
"""
Parse human readable duration.
>>> parse_duration('1m')
60
>>> parse_duration('7 days') == 7 * 24 * 60 * 60
True
"""
if string.isdigit():
return int(string)
try:
return float(string)
except ValueError:
pass
string = st... | 0.001757 |
def use_shared_vocab(args: argparse.Namespace) -> bool:
"""
True if arguments entail a shared source and target vocabulary.
:param: args: Arguments as returned by argparse.
"""
weight_tying = args.weight_tying
weight_tying_type = args.weight_tying_type
shared_vocab = args.shared_vocab
d... | 0.004556 |
def client_update(self):
"""
[NOT IMPLEMENTED]
"""
if not self.is_client:
raise ValueError("Bundle is not in client mode, cannot update")
logger.info("updating client...")
# wait briefly to pickup any missed messages, which should then fire
# the corr... | 0.004444 |
def check_args(arguments, data_frame):
"""
check arguments against a command_line_dataframe.
checks that:
all arguments are valid
all required arguments are present
default values are used where needed
"""
stripped_args = [a[0] for a in arguments]
df = data_frame.df
# first make ... | 0.004518 |
def untrace_module(module):
"""
Untraces given module members.
:param module: Module to untrace.
:type module: ModuleType
:return: Definition success.
:rtype: bool
"""
for name, function in inspect.getmembers(module, inspect.isfunction):
untrace_function(module, function)
... | 0.002217 |
def setup_data(X, y, tokenizer, proc_data_path, **kwargs):
"""Setup data
Args:
X: text data,
y: data labels,
tokenizer: A Tokenizer instance
proc_data_path: Path for the processed data
"""
# only build vocabulary once (e.g. training data)
train = ... | 0.001992 |
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
self.json = json.dumps(self.data)
self._parent.html.add_child(Element(Template("""
<div id="{{this.get_name()}}"></div>
""").render(this=self, kwargs=kwargs)), name=self.get_name())
... | 0.001108 |
def blacklist_bulk(self, blacklist):
"""
Add blacklist entries to the engine node in bulk. For blacklist to work,
you must also create a rule with action "Apply Blacklist".
First create your blacklist entries using :class:`smc.elements.other.Blacklist`
then provide the blacklist ... | 0.009217 |
def get(self, recipe_id):
'''
Retrieves an AnswerFactory Recipe by id
Args:
recipe_id The id of the recipe
Returns:
A JSON representation of the recipe
'''
self.logger.debug('Retrieving recipe by id: ' + recipe_id)
url = '%(base_url)s/rec... | 0.003929 |
def read_stat():
"""
Mocks read_stat as this is a Linux-specific operation.
"""
return [
{
"times": {
"user": random.randint(0, 999999999),
"nice": random.randint(0, 999999999),
"sys": random.randint(0, 999999999),
"idle... | 0.002299 |
def update_widget_attrs(self, bound_field, attrs):
"""
Update the dictionary of attributes used while rendering the input widget
"""
bound_field.form.update_widget_attrs(bound_field, attrs)
widget_classes = self.widget.attrs.get('class', None)
if widget_classes:
... | 0.006073 |
def _set_cfunctions(self):
"""
Set all ctypes functions and attach them to attributes.
See https://tronche.com/gui/x/xlib/function-index.html for details.
"""
def cfactory(attr=self.xlib, func=None, argtypes=None, restype=None):
# type: (Any, str, List[Any], Any) -> ... | 0.00149 |
def to_dict(self, field):
"""Export data to a {cluster: value} dictionary, for a particular
field."""
assert field in self._fields, "This field doesn't exist"
return {cluster: self.get(field, cluster)
for cluster in self._data.keys()} | 0.007092 |
def mobileclient(username=None, device_id=None, *, token=None, locale='en_US'):
"""Create and authenticate a Google Music mobile client.
>>> import google_music
>>> mc = google_music.mobileclient('username')
Parameters:
username (str, Optional): Your Google Music username.
This is used to store OAuth credent... | 0.024083 |
def _set_value(value):
'''
A function to detect if user is trying to pass a dictionary or list. parse it and return a
dictionary list or a string
'''
#don't continue if already an acceptable data-type
if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list):
retu... | 0.006707 |
def get_best_match_zone(all_zones, domain):
"""Return zone id which name is closer matched with domain name."""
# Related: https://github.com/Miserlou/Zappa/issues/459
public_zones = [zone for zone in all_zones['HostedZones'] if not zone['Config']['PrivateZone']]
zones = {zone['Name'][... | 0.008726 |
def setup_signals():
"""Set up the signal handlers.
"""
signal.signal(signal.SIGINT, shutit_util.ctrl_c_signal_handler)
signal.signal(signal.SIGQUIT, shutit_util.ctrl_quit_signal_handler) | 0.026178 |
def get_task_subtasks(client, task_id, completed=False):
''' Gets subtasks for task with given ID '''
params = {
'task_id' : int(task_id),
'completed' : completed,
}
response = client.authenticated_request(client.api.Endpoints.SUBTASKS, params=params)
return response.... | 0.01227 |
def _unify_rows(a):
"""Unify lengths of each row of a."""
lens = np.fromiter(map(len, a), np.int32)
if not (lens[0] == lens).all():
out = np.zeros((len(a), lens.max()), np.float32)
for i, row in enumerate(a):
out[i, :lens[i]] = row
else:
out = np.float32(a)
return out | 0.023649 |
def _compute_iso_color(self):
""" compute LineVisual color from level index and corresponding level
color
"""
level_color = []
colors = self._lc
for i, index in enumerate(self._li):
level_color.append(np.zeros((index, 4)) + colors[i])
self._cl = np.vst... | 0.005952 |
def _parse_redirect(self, element):
"""
Parse a redirect statement
:param element: The XML Element object
:type element: etree._Element
"""
self._log.info('Parsing response as a redirect')
self.redirect = True
return self._parse_template(element) | 0.006431 |
def set(self, ip, notation=IP_UNKNOWN):
"""Set the IP address/netmask."""
self._ip_dec = int(_convert(ip, notation=IP_DEC, inotation=notation,
_check=True, _isnm=self._isnm))
self._ip = _convert(self._ip_dec, notation=IP_DOT, inotation=IP_DEC,
... | 0.00551 |
def translate_variants(
variants_with_supporting_reads,
transcript_id_whitelist=None,
protein_sequence_length=PROTEIN_SEQUENCE_LENGTH,
min_alt_rna_reads=MIN_ALT_RNA_READS,
min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,
min_transcript_prefix_length=MIN_TRANSC... | 0.000632 |
def find_by_name(self, name):
"""
Find a resource by name (i.e. value of its 'name' resource property)
and return its Python resource object (e.g. for a CPC, a
:class:`~zhmcclient.Cpc` object is returned).
This method performs an optimized lookup that uses a name-to-URI
... | 0.001214 |
def _decrypt_and_extract(self, fname):
'''
This does the extraction (e.g., it decrypts the image and writes it to a new file on disk).
'''
with open(fname, "r") as fp_in:
encrypted_data = fp_in.read()
decrypted_data = self._hilink_decrypt(encrypted_data)
... | 0.00885 |
def solveConsGenIncProcess(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rfree,pLvlNextFunc,
BoroCnstArt,aXtraGrid,pLvlGrid,vFuncBool,CubicBool):
'''
Solves the one period problem of a consumer who experiences persistent and
transitory shocks to his income. Unlike in ConsIndS... | 0.011573 |
def mysummary(self):
"""Display a summary of the IGMPv3 object."""
if isinstance(self.underlayer, IP):
return self.underlayer.sprintf("IGMPv3: %IP.src% > %IP.dst% %IGMPv3.type% %IGMPv3.gaddr%")
else:
return self.sprintf("IGMPv3 %IGMPv3.type% %IGMPv3.gaddr%") | 0.014134 |
def enumerate_tautomers_smiles(smiles):
"""Return a set of tautomers as SMILES strings, given a SMILES string.
:param smiles: A SMILES string.
:returns: A set containing SMILES strings for every possible tautomer.
:rtype: set of strings.
"""
# Skip sanitize as standardize does this anyway
m... | 0.001873 |
def wait_until_alert_is_present(self, timeout=None):
"""
Waits for an alert to be present
@type timeout: int
@param timeout: the maximum number of seconds the driver will wait before timing out
@rtype: webdriverwrapper.WebElementWrapper
... | 0.005038 |
def serialize(self, buffer=bytearray(), index=Index(), **options):
""" Serializes the `Field` to the byte *buffer* starting at the begin
of the *buffer* or with the given *index* by packing the :attr:`value`
of the `Field` to the byte *buffer* in accordance with the encoding
*byte order*... | 0.002066 |
def _get_or_add(self, prop_name):
"""
Return element returned by 'get_or_add_' method for *prop_name*.
"""
get_or_add_method_name = 'get_or_add_%s' % prop_name
get_or_add_method = getattr(self, get_or_add_method_name)
element = get_or_add_method()
return element | 0.006289 |
def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):
"""Draw ``tree`` to the terminal
:type tree: dict
:param tree: ``tree`` should be a tree representing a hierarchy; each
key should be a string describing that hierarchy level and value
should also be ``d... | 0.001662 |
def localopt(self, forcefield='mmff94', steps=500):
"""
A wrapper to pybel's localopt method to optimize a Molecule.
Args:
forcefield: Default is mmff94. Options are 'gaff', 'ghemical',
'mmff94', 'mmff94s', and 'uff'.
steps: Default is 500.
"""
... | 0.004435 |
def var_quadratic_sum(A, C, H, beta, x0):
r"""
Computes the expected discounted quadratic sum
.. math::
q(x_0) = \mathbb{E} \Big[ \sum_{t=0}^{\infty} \beta^t x_t' H x_t \Big]
Here :math:`{x_t}` is the VAR process :math:`x_{t+1} = A x_t + C w_t`
with :math:`{x_t}` standard normal and :math... | 0.000638 |
def get_tasks(current):
"""
List task invitations of current user
.. code-block:: python
# request:
{
'view': '_zops_get_tasks',
'state': string, # one of these:
# "active", "future", "finished", "expire... | 0.004071 |
def import_file(args):
"""
Given a dataset and a local path, upload and import the file(s).
Command arguments (args):
* create_dataset
* template_id
* full_path
* vault (optional, overrides the vault in full_path)
* path (optional, overrides the path in full_path)
... | 0.000643 |
def safe_url(self):
"""
This will generate a url equivalent call without private parameters
:return: str
"""
ret = str(self.endpoint_url)
if self.params:
ret += '?' + '&'.join(
['%s=%s' % (k, [v, '[%s]' % k.upper()][
k in ['... | 0.004684 |
def strip_comments(text):
"""Comment stripper for JSON.
"""
regex = r'\s*(#|\/{2}).*$'
regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$' # noqa
lines = text.split('\n')
for index, line in enumerate(lines):
if re.search(regex, line):
i... | 0.001842 |
def helical_turbulent_Nu_Mori_Nakayama(Re, Pr, Di, Dc):
r'''Calculates Nusselt number for a fluid flowing inside a curved
pipe such as a helical coil under turbulent conditions, using the method of
Mori and Nakayama [1]_, also shown in [2]_ and [3]_.
For :math:`Pr < 1`:
.. ma... | 0.007137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.