content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def ldns_resolver_fail(*args):
"""LDNS buffer."""
return _ldns.ldns_resolver_fail(*args) | 56,100 |
def filter(tracks, condition_func):
"""A workaround for a bug in pandas 0.12
Parameters
----------
tracks : DataFrame
must include column named 'particle'
condition_func : function
The function is applied to each group of data. It must
return True or False.
Returns
... | 56,101 |
def create_admin():
"""Creates the admin user."""
db.session.add(User(email='admin@admin.com', password='password', admin=True))
db.session.commit() | 56,102 |
def get_batch_jdot(selected_source, selected_target, source_data_file, target_data_file, batch_size, n_labels, training_keys_file, validation_keys_file,
data_split=0.8, overwrite_data=False, labels=None, augment=False,
augment_flip=Tr... | 56,103 |
async def _choose_existing_instances(
instance_registrar: InstanceRegistrar,
resources_required_per_job: Resources,
num_jobs: int,
) -> Dict[str, List[str]]:
"""
Chooses existing registered instances to run the specified job(s). The general
strategy is to pack instances as tightly as possible to... | 56,104 |
def save(*args, **kwargs):
"""
# Usage
"""
# Extract the configuration file from the click context
paths = args[0].obj["paths"]
# We will use the wmctrl program to save the active window positions
# $ sudo apt install wmctrl
# to capture the information we will use `$ wmctrl -Gl`
... | 56,105 |
def secret_view(request):
"""Dummy view with redirect to login."""
return {} | 56,106 |
def get_data_from_all_ezo_devices(device_list):
"""Returns a list of string output from all EZO devices."""
output = []
for device in device_list:
device.write("R")
sleep(device.long_timeout)
for device in device_list:
output.append(read_data(device))
return output | 56,107 |
def get_moves(board, castling_availability, enpassant_square):
"""List of all moves for white for the given position."""
moves = []
points = board.keys()
for start, piece in board.items():
if piece == 'P':
moves.extend(get_pawn_finish(board, start, enpassant_square))
i... | 56,108 |
def get_export_from_line(line):
"""Get export name from import statements"""
if not line.startswith("export * from"):
return None
start = line.find("\"")
if start > 0:
return line[start+1:-3] # remove ";\n
return None | 56,109 |
def all_col(G):
"""
Check if every column of G contains a nonzero entry
Parameters
----------
G : lin_op
operator to check
Returns
-------
Boolean
True if every column of G contains a nonzero entry
"""
ri, ci = G.toCSR().nonzero()
return np.all(np.in1d(np.a... | 56,110 |
def get_challenge(request, scopes=["build"]):
"""Given an unauthenticated request, return a challenge in
the Www-Authenticate header
Arguments:
==========
request (requests.Request): the Request object to inspect
repository (str) : the repository name
scopes (list) : li... | 56,111 |
def abbn_eva():
"""
Real Name: b'"Ab-bn Eva"'
Original Eqn: b'Max(0,"monthly evp ab-bn" (Time)*"area ab-bn"/1000)'
Units: b''
Limits: (None, None)
Type: component
b''
"""
return np.maximum(0, monthly_evp_abbn(time()) * area_abbn() / 1000) | 56,112 |
def construct_organisation_role_dict(organisation_roles):
"""Return a dict with 3 keys: organisations, roles, and organisation_roles.
Args:
organisation_roles: an iterable of OrganisationRoles.
"""
data = {}
# Defensive programming: make sure we have a unique set of
# organisation_rol... | 56,113 |
def validate_ruletype(t):
"""Validate fs_use_* rule types."""
if t not in ["fs_use_xattr", "fs_use_trans", "fs_use_task"]:
raise exception.InvalidFSUseType("{0} is not a valid fs_use_* type.".format(t))
return t | 56,114 |
async def is_dark_theme(monitor=None, app=None):
"""Return whether or not iTerm2 theme is dark"""
theme=None
if monitor:
theme = await monitor.async_get()
elif app:
theme = await app.async_get_variable("effectiveTheme")
else:
raise ValueError('Need a monitor or app instance t... | 56,115 |
def load_json(path):
"""Load json from file"""
json_object = json.load(open(path))
return json_object | 56,116 |
def home_url_response(url_endpoint: str) -> Response:
"""Represent response from `home` page"""
return Get(url_endpoint + _home).response() | 56,117 |
def module_path():
"""Figures out the full path of the directory containing this file.
`PACKAGE_DIR` becomes the parent of that directory, which is the root
of the solvertools package."""
return os.path.dirname(__file__) | 56,118 |
def evidence_download(filename):
"""Download an evidence file
:param filename: Filename to download
:returns t_evidence.f_data: Base64 of file contents
"""
row = db(db.t_evidence.f_evidence == filename).select(db.t_evidence.f_data).first()
if row is None:
return None
return row.f_d... | 56,119 |
def a_h(P, h, region = 0):
"""Isobaric cubic expansion coefficient [1 / K]"""
if region is 0:
region = idRegion_h(P, h)
if region is 1:
return region1.a_h(P, h)
elif region is 2:
return region2.a_h(P, h)
elif region is 4:
return region4.a_h(P, h)
else:
re... | 56,120 |
def register_data_module(name: str):
"""
New data module types can be added to OpenSpeech with the :func:`register_data_module` function decorator.
For example::
@register_data_module('ksponspeech')
class LightningKsponSpeechDataModule:
(...)
.. note:: All vocabs must imple... | 56,121 |
def chars(file):
"""turns a file like object into a character stream"""
for line in file:
for c in line:
yield c | 56,122 |
def create_compositor(img_name):
"""
This function creates a compositor for rendering.
"""
# clear default nodes
for node in tree.nodes:
tree.nodes.remove(node)
# create nodes
image_node = tree.nodes.new(type='CompositorNodeImage')
layer_node = tree.nodes.new(typ... | 56,123 |
def _bin_labels_to_segments(bin_labels: list) -> list[tuple]:
"""
Convert bin labels (time-axis list data) to segment data
>>> _bin_labels_to_segments(['female'] * 5 + ['male'] * 10 + ['noise'] * 5)
[('f', 0, 5), ('bbb', 5, 15), ('v', 15, 20)]
"""
if len(bin_labels) == 0:
return []
... | 56,124 |
def get_winners(post_link, MEDIA_LINK, bot):
"""It creates a list of winners."""
favorite_comments = get_favorite_comments(post_link, MEDIA_LINK, bot)
maybe_winners = defaultdict(list)
for user_id, username, text in favorite_comments:
usernames_from_comment = get_usernames_from_comment(text)
... | 56,125 |
def get_latest_layer_version(package="boto3", region="ap-southeast-1"):
"""
return:
layer_version (int): returns latest layer version as an integer!
"""
client = session.client("dynamodb")
pk = f"lyr#{region}.{package}"
sk = "lyrVrsn0#"
response = client.get_item(
TableName... | 56,126 |
def build_efficiencies(efficiencies, species_names, default_efficiency=1.0):
"""Creates line with list of third-body species efficiencies.
Parameters
----------
efficiencies : dict
Dictionary of species efficiencies
species_names : dict of str
List of all species names
default_e... | 56,127 |
def extract_job_edit_form(form):
"""Extract the input from the Job Edit Form and update the MySQL
database with the information.
"""
if not form.has_key("edit_form"):
return False
job_id = check_job_id(form)
if job_id is None:
return False
mysql.job_set_submit_time(job_id, ... | 56,128 |
def sudo_password_needed(session: SessionBase) -> bool:
"""
Check whether password reentry is necessary for sudo actions
"""
timestamp = int(session.get(SUDO_SESSION_KEY, '0'))
time_diff = time.time() - timestamp
return time_diff >= SUDO_TIMEOUT_SEC or time_diff < 0 | 56,129 |
def increment_1(time, seconds):
""" Pure function,不會修改引數,大多會產出結果。 """
new_time = copy.deepcopy(time)
new_time.second += seconds
modify_time(new_time)
return new_time | 56,130 |
def plot_points_regression(x,
y,
title,
xlabel,
ylabel,
prediction=None,
legend=False,
r_squared=None,
p... | 56,131 |
def generate_county_dcids(countyfips):
"""
Args:
countyfips: a county FIPS code
Returns:
the matching dcid for the FIPS code
"""
if countyfips != 59:
dcid = "dcid:geoId/" + str(countyfips).zfill(5)
else:
dcid = "dcid:country/USA"
return dcid | 56,132 |
def construct_arg(cls: Type[T], # pylint: disable=inconsistent-return-statements,too-many-return-statements
param_name: str,
annotation: Type,
default: Any,
params: Params,
**extras) -> Any:
"""
Does the work of actually c... | 56,133 |
def test_call(tmpdir):
"""Tests _call"""
import subprocess
import apyfal.client.syscall as syscall
from apyfal.exceptions import ClientRuntimeException
# Mock Popen
dummy_stdout = 'dummy_stdout'
dummy_stderr = 'dummy_stderr'
dummy_file_content = 'dummy_file'.encode()
dummy_file = t... | 56,134 |
def xy2r(x, y, data, xc, yc):
"""Convert (x, y) values to distance of a (xc, yc) position."""
r = np.hypot((x-xc), (y-yc))
return np.ravel(r), np.ravel(data) | 56,135 |
def _inverse_lookup(dictionary, value):
"""Does an inverse lookup of key from value"""
return [key for key in dictionary if dictionary[key] == value] | 56,136 |
def IsNodeViewed():
""" True if the node results are displayed.
When the node is viewed, its output is displayed in the
interface.
@type node: L{Node}
@rtype: C{bool}
"""
pass | 56,137 |
def list_delivery_models(request, network):
"""Propose to create a delivery based on a previous delivery."""
nw = m.Network.objects.get(id=network)
vars = {
'user': request.user,
'nw': nw,
'deliveries': m.Delivery.objects.filter(network=nw).order_by("-id")
}
return render_to_... | 56,138 |
def tags_score(tags, kw):
"""
checks library tags
see http://www.boost.org/doc/libs/1_35_0/more/getting_started/unix-variants.html 6.1
"""
score = 0
needed_tags = {
'threading': kw['tag_threading'],
'abi': kw['tag_abi'],
'toolset': kw['tag_toolset'],
'version': kw['tag_version'],
'python': ... | 56,139 |
def create_view_folders(out_dir, n_splits):
"""
Helper function that creates a set of 'split_0', 'split_1'..., folders
within a directory 'out_dir'. If n_splits == 1, only creates the out_dir.
"""
if not os.path.exists(out_dir):
print("Creating directory at %s" % out_dir)
os.makedirs... | 56,140 |
def test_pass_dummy_scans(algo_dummy_scans, dummy_scans, expected_out):
"""Check dummy scans passing."""
skip_vols = pass_dummy_scans(algo_dummy_scans, dummy_scans)
assert skip_vols == expected_out | 56,141 |
def access_userPosition(request):
"""
NOTE:
id from users databases
must in or equal to users position databases
"""
user_data = UsersDataSet.getUsersRawData()
position_data = UsersDataSet.getUsersPositionData()
new_data = []
# almost same, we need some params to access it
che... | 56,142 |
def column_to_image(columns, images_shape, filter_shape, stride, padding):
"""Rearrange columns into image blocks.
Parameters
----------
columns
images_shape : tuple(n_images, n_channels, height, width)
filter_shape : tuple(height, _width)
stride : tuple(height, width)
padding : tuple(h... | 56,143 |
def get_expected_returncode(filename):
"""
Reads expectrc file to determine what the expected
return code is
"""
expected_rc = 0
expected_rc_file = filename + '.expectrc'
if os.path.isfile(expected_rc_file):
with open(expected_rc_file) as f:
expected_rc = int(f.read())
... | 56,144 |
def probe(serial, udp, hash_type, filename):
"""Calculate HASH."""
# hash_type = hash_type.upper()
assert hash_type in ("SHA256", "SHA512", "RSA2048", "Ed25519")
data = open(filename, "rb").read()
# < CTAPHID_BUFFER_SIZE
# https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-aut... | 56,145 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Old way of setting up components.
Can only be called when a user accidentally mentions stadtreinigung_hamburg in the
config. In that case it will be ignored.
"""
pass | 56,146 |
def horizontal_shear(origin_img, sh = 0.5):
"""Shears an image horizontal
Parameters:
----------
origin_img
original image to shear iamge horizontally
sv: float, optional
shearing percentage
Returns:
-----
out_img
horizontally sheared image
"""
# find he... | 56,147 |
def isentropic_beta(tab, spec, *XYf):
"""Isentropic bulk modulus"""
return XYf[0]*tab.q['Cs2', spec](*XYf) | 56,148 |
def tensor_combinations_phases(matrices, repeat, phases):
"""Compute a list of tensor products for the iteration of matrices,
with additional rotation along the z-axis
"""
products = itertools.product(matrices, repeat=repeat)
tensor_products = []
for mats in products:
tensor_products.app... | 56,149 |
def urllist():
"""加载图片链接
"""
list_file = os.path.join('piclist/baidu.txt')
url_list = []
with open(list_file, 'r') as f:
url_list = [line.strip() for line in f]
return url_list[:50] | 56,150 |
def get_proxy():
"""从daxiang代理首页获取代理并从中加入列表"""
# 快代理
url = 'http://tvp.daxiangdaili.com/ip/?tid=556978916294208&num=50000&protocol=https'
data = requests.get(url)
# print data.content
ip_list = data.content
ip_list = ip_list.split()
print ip_list
a = []
# proxies = "https://... | 56,151 |
def redis_run():
"""Run the local redis server"""
#redis_cmd = 'redis-server /usr/local/etc/redis.conf'
redis_cmd = 'docker run --rm --name raven-redis -p 6379:6379 -d redis:6'
with settings(warn_only=True):
result = local(redis_cmd, capture=True)
if result.failed:
print('R... | 56,152 |
def cluster_verification_get(context, verification_id):
"""Return verification with the specified verification_id."""
return IMPL.cluster_verification_get(context, verification_id) | 56,153 |
def load_conf(filename: str) -> dict:
"""
Read toml file from the /conf folder.
:params filename: str, name of the toml with the extension, ie: model_1.toml
"""
with open(os.path.join(PKG_PATH, f"conf/{filename}")) as conf_file:
conf = toml.load(conf_file)
return conf | 56,154 |
def __sub_tree(self, root_node):
"""
Extract the sub tree rooted in the given node of the current tree.
The result is a new tree :math:`st` and a node map :math:`nm` such that:
- the node map associates each node of the sub tree :math:`st` to its corresponding node in the original tree
- the order... | 56,155 |
def irls_one_step(pdf: pd.DataFrame, alpha_value: Float, n_cov: Int) -> NDArray[Float]:
"""
Performs one step of the IRLS algorithm using the components found in pdf and a value of alpha.
Returns the resulting coefficient values. If n_cov > 0, then the first n_cov columns from the design matrix X
are a... | 56,156 |
def test_default_feature_selector():
"""Test the default feature selector."""
selector = FeatureSelector()
X_t = selector.fit_transform(X, y)
assert np.array_equal(X_t, X) | 56,157 |
def get_alns_instance(repair_operators=None, destroy_operators=None, seed=None):
"""
Test helper method.
"""
alns = ALNS(rnd.RandomState(seed))
if repair_operators is not None:
for idx, repair_operator in enumerate(repair_operators):
alns.add_repair_operator(repair_operator, nam... | 56,158 |
def create_key(holder: str) -> AuthKey:
"""Function for creating an authentication key."""
key: str = ''.join(random.choice(string.ascii_letters) for _ in range(100))
return AuthKey(value = key, holder = holder) | 56,159 |
def list_() -> None:
"""Print all available codemodders as a table."""
console = Console()
table = Table(show_header=True, header_style="bold")
# Headers
table.add_column("Codemodder")
table.add_column("Deprecated in", justify="right")
table.add_column("Removed in", justify="right")
tabl... | 56,160 |
def check_for_missing_files(dir_with_files, return_dates=False):
"""
Checks for missing files after a bulk download.
Args:
dir_with_files (path): Path to directory with files to verify.
return_dates (bool): Return list of dates if True. Otherwise return list of Paths.
Returns:
... | 56,161 |
def test_multiple_compare(
assert_errors,
parse_ast_tree,
default_options,
):
"""Ensuring than multiple useless compare returns a single violation."""
tree = parse_ast_tree('assert some == some == some')
visitor = CompareSanityVisitor(default_options, tree=tree)
visitor.run()
assert_er... | 56,162 |
def dictify(f):
"""Convert generator output to a dict"""
@functools.wraps(f)
def dictify_helper(*args, **kwargs):
output = f(*args, **kwargs)
if kwargs.get('as_generator'):
return output
elif output is not None:
return dict(output)
else:
... | 56,163 |
def get_song_id(url: str):
"""Get soundcloud id from website."""
html = session.get(url)
match = re.search(r"soundcloud://sounds:(\d+)", html.text)
if match:
return match.group(1)
else:
raise RuntimeError(f"Invalid url, {url}") | 56,164 |
def checkdeplaid(incidence):
"""
Given an incidence angle, select the appropriate deplaid method.
Parameters
----------
incidence : float
incidence angle extracted from the campt results.
"""
if incidence >= 95 and incidence <= 180:
return 'night'
elif incidence... | 56,165 |
def update_messages():
"""
Mesaj listesini update eder.
:return: None
"""
run = True
msgs = []
while run:
time.sleep(0.1) # her 1 salisede update eder
new_messages = c1.get_messages() # client'tan yeni mesajı tutar
msgs.extend(new_mess... | 56,166 |
def error_test(true, predict):
"""
Function for classifcation of errors.
"""
if true == predict:
return 1
else:
return 0 | 56,167 |
def determine_high_cor_pair(correlation_row, sorted_correlation_pairs):
"""Select highest correlated variable given a correlation row with columns:
["pair_a", "pair_b", "correlation"]. For use in a pandas.apply().
Parameters
----------
correlation_row : pandas.core.series.series
Pandas seri... | 56,168 |
def sgd_optim(config = None, global_step = None):
"""
Performs vanilla stochastic gradient descent.
config format:
lr_base: Scalar learning rate.
"""
learning_rate = config["learning_rate"]
train_step = tf.train.GradientDescentOptimizer(learning_rate)
#train_step = tf.train.Gradi... | 56,169 |
def customise_pr_person_controller(**attr):
"""
Customise pr_person controller
"""
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
... | 56,170 |
def get_file_content(file_name):
"""获取文件的内容"""
try:
f = open(file_name, 'rb')
file_content = f.read()
f.close()
except Exception as e:
print("打开文件异常")
else:
return file_content | 56,171 |
def create_task_a_model():
"""
Initializes the mode. Edit the code below if you would like to change the model.
"""
model = nn.Sequential(
nn.Flatten(), # Flattens the image from shape (batch_size, C, Height, width) to (batch_size, C*height*width)
nn.Linear(28*28*1, 10)
# No... | 56,172 |
def find_module(modulename, filename=None):
"""Finds a python module or package on the standard path.
If a filename is specified, add its containing folder
to the system path.
Returns a string of the full path to the module/package."""
import imp
import sys
import os
full_path... | 56,173 |
def add_user_authors(self):
"""Set author user."""
# 80% chance one user, otherwise multiple
if random.randint(1, 5) == 1:
self.author_users.add(*random.sample(
list(User.objects.all()),
random.randint(2, min(User.objects.count(), 4))
))
else:
self.author_... | 56,174 |
def Run_pCenter(p):
""" Example of simple p-Center program with the Gurobi Python API"""
m = Model()
start_time = time.time()
distMatrix = computeDistanceMatrix()
#print distMatrix
# p = 1 is a trivial solution min(max(dist))
# use this as an upper bound for z_p
# all... | 56,175 |
def deploy():
"""
update production environment
:return:
"""
with cd('/opt'):
sudo('git clone https://github.com/stikks/Feature-Request.git')
with cd('Feature-Request'):
sudo('bash setup.sh')
sudo('cat conf/gunicorn.conf >> /etc/init/gunicorn.conf')
... | 56,176 |
def title_case(sentence):
"""
Convert a string to title case.
Parameters
----------
sentence: string
String to be converted to title case
Returns
----------
ret : string
String converted to title case.
Example
----------
>>> title_case('ThIS iS a StrInG to ... | 56,177 |
def init_and_load_latest_model(hparams, model_dir, logger=None, by_name=True):
"""
Initializes a model according to hparams. Then finds the latest model in
model_dir and loads it (see mpunet.utils.get_latest_model).
Args:
hparams: A YAMLHparams object of hyperparameters
model_dir: A... | 56,178 |
def collate_columns(data, column, reset_index=True):
"""Collate specified column from different DataFrames
:param data: dict, of pd.DataFrames spread by {ZoneID: {ScenarioID: result_dataframe}}
TODO: {ZoneID: {Climate Scenario: {ScenarioID: result_dataframe}}}
:param column: str, name of co... | 56,179 |
def data_loader(name, path):
"""
Data loader for all datasets used.
:param name: Name of the file (str, without .txt)
:param path: Path to where it is
:return:
"""
if name == "dblp":
dict_snapshots, dict_weights = load_dblp(name, path)
else:
dict_snapshots, dict_weights, ... | 56,180 |
def download_archive(archive_url, unpack_dir, archive_name='dataset.zip'):
"""Download the archive at the given URL and unpack it in the specified
directory."""
res = requests.get(archive_url, stream=True)
print(res)
# We could use tempfiles if these intermediate files take too much space.
# How... | 56,181 |
def preprocess_img(img):
"""
Images are converted from RGB to grayscale and downsampled by a factor of
2. Deepmind actually used a final 84x84 image by cropping since their GPU
wanted a square input for convolutions. We do not preprocess, rather we
store as uint8 for the sake of memory.
:param i... | 56,182 |
def logits_fn(features, feature_columns, params):
"""Calculate logits."""
input_layer = {col.name: tf.keras.layers.DenseFeatures(col)(features)
for col in feature_columns}
input_layer_mf_user, input_layer_mlp_user = tf.split(
input_layer["user_id_embedding"], [params["mf_dim"], params["mlp... | 56,183 |
def stats_view(player):
"""
Display a list of the items the player's stats.
Arguments
---------
player : Player
The player.
Returns
-------
None
"""
for value_name in COMBAT_ENTITY_DATA["entity_values"]:
_print_line(player, value_name)
interface.pr... | 56,184 |
def reorder_line(bidi_types_list, text_length=None, line_offset=0,
base_direction=None, with_max_levels=False):
"""
Return visual reordered of a line of logical string
"""
# TODO
"""
This function reorders the characters in a line of text from logical to
final visual o... | 56,185 |
def processoutgoing(raw, format):
"""Process outgoing data"""
process = mapping.get(format)
if not process:
return None
return process.outgoing(raw) | 56,186 |
def create_nonlocal_gateway_cluster_name(namespace: str) -> str:
"""Create the cluster name for the non-local namespace that uses a gateway."""
return "remote-{0}-gateway".format(namespace) | 56,187 |
def add_position_network_count_entries_for_one_organization(voter_id, organization_we_vote_id,
google_civic_election_id=0):
"""
This is called when a voter follows an organization.
:param voter_id:
:param organization_we_vote_id:
:param goo... | 56,188 |
def GetDefaultExecutor():
"""Creates a new instance of the configured executor if none exists and returns it"""
global DEFAULT_EXECUTOR
if DEFAULT_EXECUTOR is not None:
return DEFAULT_EXECUTOR
executor_name = configuration.conf.get('core', 'EXECUTOR')
DEFAULT_EXECUTOR = _get_executor(exec... | 56,189 |
def get_v_info_by_path(session, line_string_path):
"""This query returns pickled stop_times information from a swuare area defined by 2 points.
:param session: the current db session.
:type session: Session.
:param line_string_2pt: line string defined by 2 points.
:type line_string_2pt: str.
:re... | 56,190 |
def change_user_team(uid, team_tid, code):
"""Provide an interface for changing a user's team"""
team = models.Team.query.get_or_404(team_tid)
user = models.User.query.get_or_404(uid)
old_team = user.team
if code.lower() != team.code.lower():
raise errors.ValidationError('Invalid team sele... | 56,191 |
async def get_normalized_node_handler(curie: List[str] = Query(['MESH:D014867', 'NCIT:C34373'])):
"""
Get value(s) for key(s) using redis MGET
"""
normalized_nodes = await get_normalized_nodes(app, curie)
if not normalized_nodes:
raise HTTPException(detail='No matches found for the specifie... | 56,192 |
async def test_info_none(event_loop, aresponses):
"""Test info data is None when communication has occured."""
# Handle to run asserts on request in
aresponses.add(
"example.com:8081",
"/zeroconf/info",
"POST",
aresponses.Response(
status=500,
headers=... | 56,193 |
def parse_coords(ifile, ctype=_ctype):
"""Parses a list of coordinate pairs."""
points = [tuple(map(ctype, pair.split(", "))) for pair in ifile if pair]
points = [Point(*pair) for pair in points]
return points | 56,194 |
def top_three_words_v_1(list_of_strings):
"""Prints top three words from a list of strings"""
full_string = connect_strings(list_of_strings)
dictionary_of_words = create_dictionary_of_words(full_string)
a = 0
for word in sorted(dictionary_of_words, key=dictionary_of_words.get, reverse=True):
... | 56,195 |
def bytecode_from_blockchain(creation_tx_hash, ipc, rpc_host='127.0.0.1', rpc_port=8545, rpc_tls=False):
"""Load bytecode from a local node via
creation_tx_hash = ID of transaction that created the contract.
"""
if ipc:
eth = EthIpc()
else:
eth = EthJsonRpc(rpc_host, rpc_port, rpc_t... | 56,196 |
def geometric_estimation(algo='ml', data=None, **kwargs):
"""
"""
return _estimation(algo,
data,
dict(ml = GeometricDistributionMLEstimation.Estimator),
**kwargs) | 56,197 |
def test_invalid_lightcurve():
"""Invalid FlareLightCurves should not be allowed."""
err_string = ("Input arrays have different lengths."
" len(time)=5, len(flux)=4")
time = np.array([1, 2, 3, 4, 5])
flux = np.array([1, 2, 3, 4])
with pytest.raises(ValueError) as err:
Flare... | 56,198 |
def get_go2parents_isa(go2obj):
"""Get set of immediate parents GO IDs"""
go2parents = {}
for goid_main, goterm in go2obj.items():
parents_goids = set(o.id for o in goterm.parents)
if parents_goids:
go2parents[goid_main] = parents_goids
return go2parents | 56,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.