content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def email_manage(request, email_pk, action):
"""Set the requested email address as the primary. Can only be
requested by the owner of the email address."""
email_address = get_object_or_404(EmailAddress, pk=email_pk)
if not email_address.user == request.user and not request.user.is_staff:
messag... | 5,345,700 |
def get_container_service_api_version():
"""Get zun-api-version with format: 'container X.Y'"""
return 'container ' + CONTAINER_SERVICE_MICROVERSION | 5,345,701 |
def prepare_config(config_path=None,
schema_path=None,
config=None,
schema=None,
base_path=None) -> Munch:
"""
Takes in paths to config and schema files.
Validates the config against the schema, normalizes the config, parses gin and... | 5,345,702 |
def setup_tab_complete() -> None:
"""Set up the readline library to hook into our command completer"""
readline.set_completer_delims("")
if sys.platform != "win32":
readline.set_completion_display_matches_hook(completer.match_command_hook)
readline.set_completer(completer.CommandComplet... | 5,345,703 |
def invalidate_view_cache(view_name, args=[], namespace=None, key_prefix=None):
"""
This function allows you to invalidate any view-level cache.
view_name: view function you wish to invalidate or it's named url pattern
args: any arguments passed to the view function
namepace: if an appl... | 5,345,704 |
def compute_ray_features_segm_2d(seg_binary, position, angle_step=5., smooth_coef=0, edge='up'):
""" compute ray features vector , shift them to be starting from larges
and smooth_coef them by gauss filter
(from given point the close distance to boundary)
:param ndarray seg_binary: np.array<height, wid... | 5,345,705 |
def test_bind_physical_segment_without_hpb_conflict(
f5_mech_driver, context, agent_hpb_bridge_mappings, vlan_segment):
"""Test the proper behaviour when a HPB segment physical name is configured
The HPB configuration item is in the agent config but the physical network
name is different from any o... | 5,345,706 |
def visualize_bbox(img, bbox, class_name, color=(255, 0, 0) , thickness=2):
"""Visualizes a single bounding box on the image"""
BOX_COLOR = (255, 0, 0) # Red
TEXT_COLOR = (255, 255, 255) # White
x_min, y_min, x_max, y_max = bbox
cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color=color, thick... | 5,345,707 |
def mock_light():
"""Mock UniFi Protect Camera device."""
data = json.loads(load_fixture("sample_light.json", integration=DOMAIN))
return Light.from_unifi_dict(**data) | 5,345,708 |
def randomize_bulge_i(N, M, bp='G', target='none', ligand='theo'):
"""
Replace the upper stem with the aptamer and randomize the bulge to connect
it to the lower stem.
This is a variant of the rb library with two small differences. First, the
nucleotides flanking the aptamer are not randomized a... | 5,345,709 |
def JSparser(contents: str) -> str:
"""
Is supposed to replace URLs in JS.
Arguments:
contents: JS string
Returns:
Input JS string
"""
# TODO: URL replacement
return contents | 5,345,710 |
def refolder(data_folder, targ_folder, train_fraction=0.8, val_fraction=0.2, test_fraction=0.0,
remove_original=False):
"""
Rearranging files under source folder (data_folder) with class subfolders
into train/val/test folders under target fold (targ_folder)
Arguments:
"""
... | 5,345,711 |
def parse_identifier(db, identifier):
"""Parse the identifier and return an Identifier object representing it.
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param identifier: String containing the identifier
:type identifier: str
:return: Identifier object
:rtype: ... | 5,345,712 |
def wrap_name(dirname, figsize):
"""Wrap name to fit in subfig."""
fontsize = plt.rcParams["font.size"]
# 1/120 = inches/(fontsize*character)
num_chars = int(figsize / fontsize * 72)
return textwrap.fill(dirname, num_chars) | 5,345,713 |
def resolve_shape(tensor, rank=None, scope=None):
"""Fully resolves the shape of a Tensor.
Use as much as possible the shape components already known during graph
creation and resolve the remaining ones during runtime.
Args:
tensor: Input tensor whose shape we query.
rank: The rank of the tensor, provi... | 5,345,714 |
def gradient_clip(gradients, max_gradient_norm):
"""Clipping gradients of a model."""
clipped_gradients, gradient_norm = tf.clip_by_global_norm(
gradients, max_gradient_norm)
gradient_norm_summary = [tf.summary.scalar("grad_norm", gradient_norm)]
gradient_norm_summary.append(
tf.summary.scalar("clip... | 5,345,715 |
def get_sha_from_ref(repo_url, reference):
""" Returns the sha corresponding to the reference for a repo
:param repo_url: location of the git repository
:param reference: reference of the branch
:returns: utf-8 encoded string of the SHA found by the git command
"""
# Using subprocess instead of ... | 5,345,716 |
def test_cross_entropy():
"""
Test cross_entropy.
"""
cross_entropy = CrossEntropy()
loc = Tensor([1.0], dtype=dtype.float32)
scale = Tensor([1.0], dtype=dtype.float32)
diff = cross_entropy(loc, scale)
tol = 1e-6
assert (np.abs(diff.asnumpy() - np.zeros(diff.shape)) < tol).all() | 5,345,717 |
def list_species(category_id):
"""
List all the species for the specified category
:return: A list of Species instances
"""
with Session.begin() as session:
species = session.query(Species)\
.filter(Species.categoryId == category_id)\
.order_by(db.asc(Species.name))\... | 5,345,718 |
def shut_down_thread_pool():
"""Shuts down the thread pool."""
logger.info('Shutting down thread pool...')
_executor.shutdown() | 5,345,719 |
def test_state_is_immutable(subject: StateStore) -> None:
"""It should treat the state as immutable."""
result_1 = subject.state
subject.handle_action(PlayAction())
result_2 = subject.state
assert result_1 is not result_2 | 5,345,720 |
def get_motif_proteins(meme_db_file):
""" Hash motif_id's to protein names using the MEME DB file """
motif_protein = {}
for line in open(meme_db_file):
a = line.split()
if len(a) > 0 and a[0] == 'MOTIF':
if a[2][0] == '(':
motif_protein[a[1]] = a[2][1:a[2].find(')')]
else:
mot... | 5,345,721 |
def get_files(search_glob):
""" Returns all files matching |search_glob|. """
recursive_glob = '**' + os.path.sep
if recursive_glob in search_glob:
if sys.version_info >= (3, 5):
result = iglob(search_glob, recursive=True)
else:
# Polyfill for recursive glob pattern matching added in Python 3.... | 5,345,722 |
def test_cloud(credential, Cloud): # noqa: N803
"""
Test cloud.
Test cloud
"""
assert(credential.username == 'test@example.com')
assert(credential.password == 'test_password')
cloud = Cloud(credential.username, credential.password)
assert(cloud) | 5,345,723 |
def main(): # pragma: no cover
"""
A wrapper for the program entrypoint that formats uncaught exceptions in a
crash report template.
"""
if IS_DEBUG:
# allow exceptions to raised when debugging
run()
else:
# wrap exceptions in crash report under normal operation
... | 5,345,724 |
def pixellate_bboxes(im, bboxes, cell_size=(5,6), expand_per=0.0):
"""Pixellates ROI using Nearest Neighbor inerpolation
:param im: (numpy.ndarray) image BGR
:param bbox: (BBox)
:param cell_size: (int, int) pixellated cell size
:returns (numpy.ndarray) BGR image
"""
if not bboxes:
return im
elif not... | 5,345,725 |
def clear_cache(raw_keys: list, user_id: int = None) -> None:
""" Remove cache records relevant to handled keys.
Parameters
----------
raw_keys:
Cache keys.
user_id:
User id.
"""
for key in raw_keys:
remove_cache_record(key, user_id) | 5,345,726 |
def rename_windows_service_display(install_id: str) -> None:
"""Changes the name of the service displayed in services.msc."""
print(f'sc config GlassFish_{install_id} DisplayName = "GlassFish ID_{install_id}"')
subprocess.call(f'sc config GlassFish_{install_id} DisplayName= "GlassFish_ID_{install_id}"', she... | 5,345,727 |
def run_local(ctx, limit: float, **kwargs):
"""Runs benchmarks locally."""
run(ctx, machine_producer.LocalMachineProducer(limit=limit), **kwargs) | 5,345,728 |
def in_ipython() -> bool:
"""try to detect whether we are in an ipython shell, e.g., a jupyter notebook"""
ipy_module = sys.modules.get("IPython")
if ipy_module:
return bool(ipy_module.get_ipython())
else:
return False | 5,345,729 |
def StepToGeom_MakeHyperbola2d_Convert(*args):
"""
:param SC:
:type SC: Handle_StepGeom_Hyperbola &
:param CC:
:type CC: Handle_Geom2d_Hyperbola &
:rtype: bool
"""
return _StepToGeom.StepToGeom_MakeHyperbola2d_Convert(*args) | 5,345,730 |
def create_dict(local=None, field=None, **kwargs):
"""
以字典的形式从局部变量locals()中获取指定的变量
:param local: dict
:param field: str[] 指定需要从local中读取的变量名称
:param kwargs: 需要将变量指定额外名称时使用
:return: dict
"""
if field is None or local is None:
return {}
result = {k: v for k, v in local.items() ... | 5,345,731 |
def sum_list_for_datalist(list):
"""
DB에 저장할 때, 기준일로부터 과거 데이터가 존재하지 않을 경우에는
0을 return 한다.
:param list:
:return: float or int
"""
mysum = 0
for i in range(0, len(list)):
if list[i] == 0:
return 0
mysum = mysum + list[i]
return mysum | 5,345,732 |
def elu(x, alpha=1.):
"""Exponential linear unit.
Arguments:
x {tensor} -- Input float tensor to perform activation.
alpha {float} -- A scalar, slope of negative section.
Returns:
tensor -- Output of exponential linear activation
"""
return x * (x > 0) + alpha * (tf... | 5,345,733 |
def coalesce(*args):
"""
Compute the first non-null value(s) from the passed arguments in
left-to-right order. This is also known as "combine_first" in pandas.
Parameters
----------
*args : variable-length value list
Examples
--------
>>> import ibis
>>> expr1 = None
>>> ex... | 5,345,734 |
def get_analysis(poem, operations, rhyme_analysis=False, alternative_output=False):
"""
View for /analysis that perform an analysis of poem running the different
operations on it.
:param poem: A UTF-8 encoded byte string with the text of the poem
:param operations: List of strings with the operation... | 5,345,735 |
def export(
ctx,
cli_obj,
db,
photos_library,
keyword,
person,
album,
folder,
uuid,
uuid_from_file,
title,
no_title,
description,
no_description,
uti,
ignore_case,
edited,
external_edit,
favorite,
not_favorite,
hidden,
not_hidden,
... | 5,345,736 |
def main():
"""Main method to run with GUI"""
global projectpath
gui = GUI()
gui.mainloop()
projectpath = "" | 5,345,737 |
def UpdateRC(bash_completion, path_update, rc_path, bin_path, sdk_root):
"""Update the system path to include bin_path.
Args:
bash_completion: bool, Whether or not to do bash completion. If None, ask.
path_update: bool, Whether or not to do bash completion. If None, ask.
rc_path: str, The path to the r... | 5,345,738 |
def get_detail_root():
"""
Get the detail storage path in the git project
"""
return get_root() / '.detail' | 5,345,739 |
def sample_data(_,
val,
sampling_strategy=spec.SamplingStrategy.UNDERSAMPLE,
side=0):
"""Function called in a Beam pipeline that performs sampling using Python's
random module on an input key:value pair, where the key is the class label
and the values are the data p... | 5,345,740 |
def solve(strs, m, n):
"""
2D 0-1 knapsack
"""
def count(s):
m, n = 0, 0
for c in s:
if c == "0":
m += 1
elif c == "1":
n += 1
return m, n
dp = []
for _ in range(m + 1):
dp.append([0] * (n + 1))
for s ... | 5,345,741 |
def bk_category_chosen_category():
"""Returns chosen category for creating bk_category object."""
return "Bread" | 5,345,742 |
def apply_weights(
events,
total_num=1214165.85244438, # for chips_1200
nuel_frac=0.00003202064566, # for chips_1200
anuel_frac=0.00000208200747, # for chips_1200
numu_frac=0.00276174709613, # for chips_1200
anumu_frac=0.00006042213136, # for chips_1200
cosmic_frac=0.99714372811940, # ... | 5,345,743 |
def on_collections_deleted(event):
"""Some collections were deleted, delete records."""
storage = event.request.registry.storage
permission = event.request.registry.permission
for change in event.impacted_objects:
collection = change["old"]
bucket_id = event.payload["bucket_id"]
... | 5,345,744 |
def search_google(search_term):
"""This function will open google.com on firefox,
then search for anything on google"""
with webdriver.Firefox() as driver:
driver.get("https://www.google.com")
assert "Google" in driver.title
# if the window loaded title is Google then continue below... | 5,345,745 |
def _pipe_line_with_colons(colwidths, colaligns):
"""Return a horizontal line with optional colons to indicate column's
alignment (as in `pipe` output format)."""
segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)]
return "|" + "|".join(segments) + "|" | 5,345,746 |
def evaluarcalc():
"""Evalua a través de un AFD una expresión numérica a ingresar
"""
if setanalizador() == False:
return
analizador.CadenaSigma = input("Ingrese la expresión a evaluar: ")
analizador.resetattributes()
ansyntax = Evaluador(analizador)
if ansyntax.inieval():
... | 5,345,747 |
def print_stats(hw_name: str = '', task_name: str = ''):
"""Prints user's progress on completing the course tasks.
Parameters
----------
hw_name : str, optional
A course homework about which the statistics was requested.
task_name : str, optional
A homework task about which the stat... | 5,345,748 |
def convert_to_dates(start, end):
"""
CTD - Convert two strings to datetimes in format 'xx:xx'
param start: String - First string to convert
param end: String - Second string to convert
return: datetime - Two datetimes
"""
start = datetime.strptime(start, "%H:%M")
end = datetime.strptime... | 5,345,749 |
def flipud(m):
"""
Flips the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
Args:
m (Tensor): Input array.
Returns:
Tensor.
Raises:
TypeError: If the input is not a tensor.
Supported Platforms:
... | 5,345,750 |
def get_book_url(tool_name, category):
"""Get the link to the help documentation of the tool.
Args:
tool_name (str): The name of the tool.
category (str): The category of the tool.
Returns:
str: The URL to help documentation.
"""
prefix = "https://jblindsay.github.io/wbt_bo... | 5,345,751 |
def demo_long_lived_cluster():
"""
Shows how to create a long-lived cluster that waits after all steps are run so
that more steps can be run. At the end of the demo, the cluster is optionally
terminated.
"""
print('-'*88)
print(f"Welcome to the Amazon EMR long-lived cluster demo.")
print... | 5,345,752 |
def save_xyz_filehandle(X, symbols, handle, text="", format_str="% .11E"):
"""
Write coordinates and symbols to given file handle.
Args:
X: coordinates (can also append velocities or whatever)
symbols: atomic symbols
handle: file handle to write to
text: Helper text in secon... | 5,345,753 |
def read_csv(file_name='data.csv'):
"""Returns a list of dicts from a csv file."""
# Your code goes here
pass | 5,345,754 |
def test_records(db, test_data):
"""Load test records."""
result = []
for r in test_data:
result.append(create_record(r))
db.session.commit()
yield result | 5,345,755 |
def game_hash(s):
"""Generate hash-based identifier for a game account based on the
text of the game.
"""
def int_to_base(n):
alphabet = "BCDFGHJKLMNPQRSTVWXYZ"
base = len(alphabet)
if n < base:
return alphabet[n]
return int_to_base(n // base) + alphabet[n % b... | 5,345,756 |
def thumbnail_url(bbox, layers, qgis_project, style=None, internal=True):
"""Internal function to generate the URL for the thumbnail.
:param bbox: The bounding box to use in the format [left,bottom,right,top].
:type bbox: list
:param layers: Name of the layer to use.
:type layers: basestring
... | 5,345,757 |
def evaluate_prediction_power(df, num_days=1):
""""
Applies a shift to the model for the number of days given, default to 1, and feed the data to
a linear regression model. Evaluate the results using score and print it.
"""
scores = {}
print "Num days: {}".format(range(num_days))
for... | 5,345,758 |
def get_select_file_dialog_dir():
""""
Return the directory that should be displayed by default
in file dialogs.
"""
directory = CONF.get('main', 'select_file_dialog_dir', get_home_dir())
directory = directory if osp.exists(directory) else get_home_dir()
return directory | 5,345,759 |
def exercise9():
"""
Write a Python program to display the examination schedule. (extract the date from exam_st_date).
exam_st_date = (11, 12, 2014)
Sample Output : The examination will start from : 11 / 12 / 2014
"""
exam_st_date = (11, 12, 2014)
string_date = datetime.da... | 5,345,760 |
def get_photo_filesystem_path(photos_basedir, album_name, filename):
"""
Gets location of photo on filesystem, e.g.:
/some/dir/album/photo.jpg
:param album_name:
:param filename:
:return:
"""
return os.path.join(photos_basedir, get_photo_filesystem_relpath(album_name, filename)) | 5,345,761 |
def _validate_detect_criteria(
ext_detect_criteria: Mapping[str, _DetectQueryMapping],
ext_communication_types: Collection[Type[Any]],
package_name: str) -> None:
"""Validates the extension detection criteria.
Args:
ext_detect_criteria: Detection criteria to validate, where mapping keys are
c... | 5,345,762 |
def test_prepare_source(source):
"""Test the ``PseudoPotentialData.prepare_source`` method for valid input."""
assert isinstance(PseudoPotentialData.prepare_source(source), io.BytesIO)
if isinstance(source, io.BytesIO):
# If we pass a bytestream, we should get the exact same back
assert Pse... | 5,345,763 |
def getAdminData(self):
"""
Deliver admin content of module alarms (ajax)
:return: rendered template as string or json dict
"""
if request.args.get('action') == 'upload':
if request.files:
ufile = request.files['uploadfile']
fname = os.path.join(current_app.config.ge... | 5,345,764 |
def join_collections(sql_query: sql.SQLQuery) -> QueryExpression:
"""Join together multiple collections to return their documents in the response.
Params:
-------
sql_query: SQLQuery object with information about the query params.
Returns:
--------
An FQL query expression for joined and fi... | 5,345,765 |
def querylist(query, encoding='utf-8', errors='replace'):
"""Split the query component into individual `name=value` pairs and
return a list of `(name, value)` tuples.
"""
if query:
qsl = [query]
else:
return []
if isinstance(query, bytes):
QUERYSEP = (b';', b'&')
... | 5,345,766 |
def plot_timeseries(ax, id_ax, data, xticks, xlabel='', ylabel='',
label='', logx=False, logy=False, zorder=10,
linespecs=None):
"""Plots timeseries data with error bars."""
if logx:
ax[id_ax].set_xscale('log')
if logy:
ax[id_ax].set_yscale('log')
if linespecs:
... | 5,345,767 |
def rotate_space_123(angles):
"""Returns the direction cosine matrix relating a reference frame B
rotated relative to reference frame A through the x, y, then z axes of
reference frame A (spaced fixed rotations).
Parameters
----------
angles : numpy.array or list or tuple, shape(3,)
Thr... | 5,345,768 |
def parse_arguments():
"""Parse and return the command line argument dictionary object
"""
parser = ArgumentParser("CIFAR-10/100 Training")
_verbosity = "INFO"
parser.add_argument(
"-v",
"--verbosity",
type=str.upper,
choices=logging._nameToLevel.keys(),
defau... | 5,345,769 |
def iree_lit_test_suite(
name,
cfg = "//iree:lit.cfg.py",
tools = None,
env = None,
**kwargs):
"""A thin wrapper around lit_test_suite with some opinionated settings.
See the base lit_test for more details on argument meanings.
Args:
name: name for the test su... | 5,345,770 |
def get_tac_resource(url):
"""
Get the requested resource or update resource using Tacoma account
:returns: http response with content in xml
"""
response = None
response = TrumbaTac.getURL(url, {"Accept": "application/xml"})
_log_xml_resp("Tacoma", url, response)
return response | 5,345,771 |
def cosweightlat(darray, lat1, lat2):
"""Calculate the weighted average for an [:,lat] array over the region
lat1 to lat2
"""
# flip latitudes if they are decreasing
if (darray.lat[0] > darray.lat[darray.lat.size -1]):
print("flipping latitudes")
darray = darray.sortby('lat')
r... | 5,345,772 |
def _GetSoftMaxResponse(goal_embedding, scene_spatial):
"""Max response of an embeddings across a spatial feature map.
The goal_embedding is multiplied across the spatial dimensions of the
scene_spatial to generate a heatmap. Then the spatial softmax-pooled value of
this heatmap is returned. If the goal_embedd... | 5,345,773 |
async def reddit_imgscrape(ctx, url):
"""
Randomly selects an image from a subreddit corresponding to a json url and sends it to the channel.
Checks for permissions, NSFW-mode.
Params:
(commands.Context): context
(str): json url
"""
current_channel = ctx.message.channel... | 5,345,774 |
def summarize_star(star):
"""return one line summary of star"""
if star.find('name').text[-2] == ' ':
name = star.find('name').text[-1]
else:
name = ' '
mass = format_star_mass_str(star)
radius = format_star_radius_str(star)
temp = format_body_temp_str(star)
metallicity = for... | 5,345,775 |
def call_cnvs(input_file, mapping_quality, bam_file, output_directory, fasta_reference):
"""
Call CNVS questions
"""
cnv_output_script = os.path.join(output_directory, input_file.samples_name)
cnv_analysis_script = "samtools view -q {0} -S {1} | " + SPLITREADBEDTOPE + " -i stdin | grep -v telo ... | 5,345,776 |
def to_unicode(text, encoding='utf8', errors='strict'):
"""Convert a string (bytestring in `encoding` or unicode), to unicode."""
if isinstance(text, unicode):
return text
return unicode(text, encoding, errors=errors) | 5,345,777 |
def shipping_hide_if_one(sender, form=None, **kwargs):
"""Makes the widget for shipping hidden if there is only one choice."""
choices = form.fields['shipping'].choices
if len(choices) == 1:
form.fields['shipping'] = forms.CharField(max_length=30, initial=choices[0][0],
widget=forms.Hi... | 5,345,778 |
def parse_pipfile():
"""Reads package requirements from Pipfile."""
cfg = ConfigParser()
cfg.read("Pipfile")
dev_packages = [p.strip('"') for p in cfg["dev-packages"]]
relevant_packages = [
p.strip('"') for p in cfg["packages"] if "nested-dataclasses" not in p
]
return relevant_packa... | 5,345,779 |
def print_dist(d, height=12, pch="o", show_number=False,
title=None):
""" Printing a figure of given distribution
Parameters
----------
d: dict, list
a dictionary or a list, contains pairs of: "key" -> "count_value"
height: int
number of maximum lines for the graph
pch : str
... | 5,345,780 |
def test_payload_with_address_invalid_length(api_server_test_instance):
""" Encoded addresses must have the right length. """
invalid_address = "0x61c808d82a3ac53231750dadc13c777b59310b" # g at the end is invalid
channel_data_obj = {
"partner_address": invalid_address,
"token_address": "0xE... | 5,345,781 |
def Per_sequence_quality_scores (file_path,output_dire, module):
""" Read Per sequence quality scores contents from a fastqc file and parses to output file.
Returns a list of data used to plot quality graph.
Data and genereted graphs are saved to output directory as png image file and plain te... | 5,345,782 |
def make_lfd_settings_package(lfd_settings_name):
""" Makes the lfd_settings package.
Makes the lfd_settings package with settings.py files with the same
subpackage and module structure as the lfd package. Only makes subpackages
and modules for which the corresponding one in the lfd package has a
... | 5,345,783 |
def import_manager(inputs=None, import_type=None, **kwargs):
"""
This module manages import of the device(s)
:param inputs: (dict) A dictionary of user provided inputs
:param import_type: (str) device import type "single" or "bulk"
:param kwargs: (kwargs) Key value pair
:returns: (str) import s... | 5,345,784 |
def count_primes(num):
"""
Write a function that returns the number
of prime numbers that exist up to and including a given number
:param num: int
:return: int
"""
count = 0
lower = int(input())
upper = int(input())
for num in range(lower, upper + 1):
if num > 1:
... | 5,345,785 |
def get_redis() -> Iterator[Redis]:
"""获取redis操作对象
每一个请求处理完毕后会关闭当前连接,不同的请求使用不同的连接
"""
# 检查间隔(health_check_interval)的含义:
# 当连接在health_check_interval秒内没有使用下次使用时需要进行健康检查。
# 在内部是通过发送ping命令来实现
r = Redis(connection_pool=_redis_pool, health_check_interval=30)
try:
yield r
finally:
... | 5,345,786 |
def run_experiment(config):
"""
Run the experiment.
Args:
config: The configuration dictionary.
Returns:
The experiment result.
"""
return None | 5,345,787 |
def read_notification(notification_id):
"""Marks a notification as read."""
notification = Notification.query.get_or_404(notification_id)
if notification.recipient_email != current_user.email:
abort(401)
notification.is_read = True
db.session.add(notification)
db.session.commit()
ret... | 5,345,788 |
def grayscale_blur(image):
"""
Convert image to gray and blur it.
"""
image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
image_gray = cv.blur(image_gray, (3, 3))
return image_gray | 5,345,789 |
def calculate_stream_hmac(stream, hmac_key):
"""Calculate a stream's HMAC code with the given key."""
stream.seek(0)
hash_hmac = hmac.new(bytearray(hmac_key, "utf-8"), digestmod=HASH_FUNCTION)
while True:
buf = stream.read(4096)
if not buf:
break
hash_hmac.update(buf)... | 5,345,790 |
def find(name, dir_path="." , p="r"):
"""
find(name: string, dirpath="." , p="r")
name: the name to find
dirpath: find in this directory
p = r recursive find sub dirs
"""
files = ls(dir_path, p)
ans = []
for fn in files:
head, tail = os.path.split(fn)
... | 5,345,791 |
def test_bad_file():
"""Dies on bad file"""
bad = random_string()
rv, out = getstatusoutput(f'{prg} -f {bad}')
assert rv != 0
assert re.search(f"No such file or directory: '{bad}'", out) | 5,345,792 |
def convert_tac(ThreeAddressCode):
"""Reads three adress code generated from parser and converts to TAC for codegen;
generates the three_addr_code along with leaders;
populates generate symbol table as per three_addr_code"""
for i in range(ThreeAddressCode.length()):
three_addr_instr = ThreeAdd... | 5,345,793 |
def is_english_score(bigrams, word):
"""Calculate the score of a word."""
prob = 1
for w1, w2 in zip("!" + word, word + "!"):
bigram = f"{w1}{w2}"
if bigram in bigrams:
prob *= bigrams[bigram] # / float(bigrams['total'] + 1)
else:
print("%s not found" % bigra... | 5,345,794 |
def modify_logistic_circuit():
"""
Preprocess new format to remove v_tree id
"""
with open('../benchmarks/mnist.circuit_985', 'r') as f:
lines= f.readlines()
lines_m=[]
for idx, i in enumerate(lines):
if i[0] == 'T' or i[0] == 'F' or i[0] == 'D':
i= i.split(' ')
del i[2]
... | 5,345,795 |
def cat(fname, fallback=_DEFAULT, binary=True):
"""Return file content.
fallback: the value returned in case the file does not exist or
cannot be read
binary: whether to open the file in binary or text mode.
"""
try:
with open_binary(fname) if binary else open_text(fname) as f:... | 5,345,796 |
def _get_from_url(url):
"""
Note: url is in format like this(following OQMD RESTful API) and the result format should be set to json:
http://oqmd.org/oqmdapi/formationenergy?fields=name,entry_id,delta_e&filter=stability=0&format=json
Namely url should be in the form supported by OQMD RESTful A... | 5,345,797 |
def createStringObject(string):
"""
Given a string (either a ``str`` or ``unicode``), create a
:class:`ByteStringObject<ByteStringObject>` or a
:class:`TextStringObject<TextStringObject>` to represent the string.
"""
if isinstance(string, string_type):
return TextStringObject(string)
... | 5,345,798 |
def _get_windows_network_adapters():
"""Get the list of windows network adapters."""
import win32com.client
wbem_locator = win32com.client.Dispatch('WbemScripting.SWbemLocator')
wbem_service = wbem_locator.ConnectServer('.', 'root\cimv2')
wbem_network_adapters = wbem_service.InstancesOf('Win32_Netwo... | 5,345,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.