content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_dump_secrets_bespon():
"""Should dump valid BespON."""
config = {
"SOME_VAR": "test",
}
actual = loader.dump_secrets(fmt="BespON", **config)
expected = "SOME_VAR = test\n"
assert actual == expected | 61,300 |
def downloader(url: str, resume_byte_pos: int = None, file_name: str = None):
"""Download url in ``URLS[position]`` to disk with possible resumption.
Parameters
----------
url: str
url to be downloaded.
resume_byte_pos: int
Position of byte from where to resume the download
"""... | 61,301 |
def load_publications (graph, used, frags, out_buf, known_datasets, known_journals, known_authors, known_topics, full_graph):
"""
load publications, link to datasets, link to authors, then reshape
the metadata as TTL
"""
seen = set([])
for partition, pub_iter in graph.iter_publications(path=gra... | 61,302 |
def autoencoder(x_hat, x, dim_img, dim_z, n_hidden, keep_prob):
"""Gateway"""
# encoding
mu, sigma = gaussian_MLP_encoder(x_hat, n_hidden, dim_z, keep_prob)
# sampling by re-parameterization technique
z = mu + sigma * tf.random_normal(tf.shape(mu), 0, 1, dtype=tf.float32)
# decoding
y = b... | 61,303 |
def leafelement(element, strip_cdata=False, compact=False, remove_blank_text=True):
"""
This function converts lowest level tree/etree element to dict structure.
:param element: etree leaf-level object,
:param strip_data: bool, whether to parse CDATA as pure text or CDATA text,
:param compact: bool,... | 61,304 |
def is_in_bbox(x, y, bbox):
"""
Answers True or Folse if the x, y is inside the BBOX.
"""
xMin, yMin, xMax, yMax = bbox
if xMin <= x <= xMax and yMin <= y <= yMax:
return True
return False | 61,305 |
def test_matchmaker_add_no_genes_no_features(app, user_obj, case_obj, mocker, mock_redirect):
"""Testing adding a case to matchmaker when the case has no set phenotype or candidate gene/variant"""
# GIVEN patched responses from the MME server
mocker.patch("scout.server.blueprints.cases.controllers.redirect... | 61,306 |
def test_keypoints_censure_color_image_unsupported_error():
"""Censure keypoints can be extracted from gray-scale images only."""
assert_raises(ValueError, CENSURE().detect, np.zeros((20, 20, 3))) | 61,307 |
def convert_tuple_to_8_int(tuple_date):
""" Converts a date tuple (Y,M,D) to 8-digit integer date (e.g. 20161231).
"""
return int('{0}{1:02}{2:02}'.format(*tuple_date)) | 61,308 |
def summarize_dist_params(dist, name, name_scope="dist_params"):
"""Summarize the parameters of a distribution.
Args:
dist: A Distribution object with mean and standard deviation
parameters.
name: The name of the distribution.
name_scope: The name scope of this summary.
"""
with tf.co... | 61,309 |
def edit_file_content(filepath, new_content):
"""Re-write a file and recover the original content when out of the context"""
original_content = ''
with open(filepath) as file:
original_content = file.read()
with open(filepath, 'w') as file:
file.write(new_content)
try:
yield
... | 61,310 |
def rule_Owner_default(x, world) :
"""We assume that the owner of an object is the first object which
Has some object which in some chain of containment (containment
optional). Returns None if no owner was found."""
poss_owner = world.query_relation(Has(Y, x), var=Y)
if poss_owner :
return ... | 61,311 |
def gpiod_line_is_requested(line: gpiod_line) -> bool:
"""
@brief Check if the calling user has ownership of this line.
@param line: GPIO line object.
@return True if given line was requested, false otherwise.
"""
return (
line.state == _LINE_REQUESTED_VALUES
or line.state == _... | 61,312 |
def coord_lister(geom):
"""[summary] when given a geometry pandas geoseries, returns an exterior
list of coordinates for all of the entries, given should
Args:
geom ([type]): [description]
Returns:
[type]: [description]
"""
coords = list(geom.exterior.coords)
return (coords... | 61,313 |
def set_config(
config_inst: Config,
key: str,
default: Any = None,
) -> None:
"""
Define a variable to be read from a `config.toml` or an environment variable.
Args:
config_inst (Config): The instance of the `Config` class.
key (str): The key of the variable.
default (A... | 61,314 |
def edgeCannotConnectInputAndOutputOfSameNode(
inputSocket: Socket, outputSocket: Socket
) -> bool:
"""Edge is invalid if it connects the same node"""
if inputSocket.node == outputSocket.node:
printError("Connecting the same node")
return False
return True | 61,315 |
def bcnn(pretrained=False, **kwargs):
"""Constructs a BCNN model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = BCNN(**kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['bcnn']))
return model | 61,316 |
def get_dataframe_intersection(df, comparator1, comparator2):
"""
Return a dataframe with only the columns found in a comparative dataframe.
Parameters
----------
comparator1: DataFrame
DataFrame to preform comparison on.
comparator2: DataFrame
DataFrame to compare with.
Re... | 61,317 |
def get_sanitized_endpoint(url):
"""
Sanitize an endpoint, as removing unneeded parameters
"""
# sanitize esri
sanitized_url = url.rstrip()
esri_string = '/rest/services'
if esri_string in url:
match = re.search(esri_string, sanitized_url)
sanitized_url = url[0:(match.start(0... | 61,318 |
def main():
"""Testing Deep Learning with Graph Neural Networks."""
data_helper = DataHelpers()
data_object = DataObject()
common_helper = CommonHelpers()
# load the data files in from datastore
workdir = os.getcwd() + "/dataset/"
# logger.debug
print("Using workdir: {}".format(workdir)... | 61,319 |
def get_request_raw_header(request, name) :
""" Return raw header value of request by header name """
name = name.lower()
for header in request.raw_headers :
if header[0].decode("utf-8").lower() == name:
return header[1].decode("utf-8")
return "" | 61,320 |
def readTimeStamp(fname,path):
"""reads an insight tstmp file and returns
an array of the times at which photos were
taken at relative to the begining of
aquasition"""
fname = os.path.join(os.path.abspath(path),fname)
num_lines = sum(1 for line in open(fname))
f = open(fname)
for i in ra... | 61,321 |
def sequence_loss(logits, targets, weights,
average_across_timesteps=True, average_across_batch=True,
softmax_loss_function=None, name=None):
"""Weighted cross-entropy loss for a sequence of logits, batch-collapsed.
Args:
logits: List of 2D Tensors of shape [batch_size x num... | 61,322 |
def scale_values_based_on_eich_peak(lead_list, gamma=0.5):
"""
scale values on the Y-axis
:param lead_list: list of the value
:param gamma: scaling factor
:return: rescaled list
"""
new_lead_list = []
for xy_pair in lead_list:
new_y_value = xy_pair[1] * gamma
... | 61,323 |
def sort_stalin(listy, delay=0):
"""A made up Stalin sort implementation, which is also a made up joke algorithm.
Adjusted to update DearPyGui, even though it doesn't look half as interesting.
Args:
listy ([type]): list of y values for the plot
delay (int, optional): Delay in seconds betwee... | 61,324 |
def signup():
""" Sign up as a friend, enter card info, etc. """
return jsonify(ok=True) | 61,325 |
def _must_find(cls, name):
"""Raises a NotFoundError if the given object doesn't exist in the datbase.
Otherwise returns the object
This is useful for most of the *_delete functions.
Arguments:
cls - the class of the object to query.
name - the name of the object in question.
Must be cal... | 61,326 |
def import_class(class_path):
"""Imports a class using a type string.
:param class_path: Type string of the class.
:type class_path: str
:rtype: type
"""
components = class_path.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
... | 61,327 |
def Base_select(self, param):
"""
- name: select 1st
select:
id: element1
by_index: 1
- name: select by value
select:
id: element1
by_value: value1
- name: select by visible text
select:
id: element1
by_text: "text 1"
"""
elem = s... | 61,328 |
def peg_time_interval(
twt_vol: xr.DataArray,
depth_surf: xr.DataArray,
twt_surf: xr.DataArray,
mapping_dims: Sequence[str] = ("xline", "iline"),
) -> xr.Dataset:
"""Shifts twt_vol to create such that the depth conversion of `depth_surf` with `twt_vol` matches
`twt_surf`
Args:
twt_v... | 61,329 |
def plotSeqAndFeatures(seq, X, createFiltAx=False, padBothSides=False, capYLim=1000):
"""plots the time series above the associated feature matrix"""
plt.figure(figsize=(10, 8))
if createFiltAx:
nRows = 4
nCols = 7
axSeq = plt.subplot2grid((nRows,nCols), (0,0), colspan=(nCols-1))
axSim = plt.subplot2grid((nR... | 61,330 |
def create_testfiles_fingerprint_1(timestamp:time):
"""
>>> f_time = time.time()
>>> create_testfiles_fingerprint_1(f_time)
>>> f_time == os.path.getmtime('./testfiles/file1_no_changes.txt')
True
>>> f_time == os.path.getatime('./testfiles/file1_no_changes.txt')
True
>>> f_time < os.path... | 61,331 |
def getYARNApplicationID(app_name):
"""Returns the YARN application ID."""
state = 'RUNNING,ACCEPTED,FINISHED,KILLED,FAILED'
out = subprocess.check_output(["yarn","application","-list", "-appStates",state], stderr=subprocess.DEVNULL, universal_newlines=True)
lines = [x for x in out.split("\n")]
application_id = ''... | 61,332 |
def test_get_disparity_map(data_loader: ArgoverseStereoDataLoader) -> None:
"""Test loading a disparity map."""
disparity_img_fpaths = data_loader.get_ordered_log_disparity_map_fpaths(
log_id=_LOG_ID,
disparity_name="stereo_front_left_rect_disparity",
)
disparity_map = data_loader.get_d... | 61,333 |
def reconstruction(capsule_mask, num_atoms, capsule_embedding, layer_sizes,
num_pixels, reuse, image, balance_factor):
"""Adds the reconstruction loss and calculates the reconstructed image.
Given the last capsule output layer as input of shape [batch, 10, num_atoms]
add 3 fully connected laye... | 61,334 |
def log_reddit_error(logger, praw_error, message=""):
"""Log a praw exception."""
if message:
logger.error("error while using the Reddit API: %s. Message = %s", praw_error, message)
else:
logger.error("error while using the Reddit API: %s", praw_error) | 61,335 |
def fetch_events_ppe(base_url='https://ppe.sas.upenn.edu/events'):
"""
Fetch events from Philosophy Politics & Economics (PPE)
"""
events = []
html_page = requests.get(urljoin(base_url, '/events'))
page_soup = BeautifulSoup(html_page.content, 'html.parser')
all_events = page_soup.find_all('u... | 61,336 |
def set_current_rankings():
"""Compute a ranking for each sponsor, which aggregates statistics
about their trials and then puts them in ranked order.
"""
with transaction.atomic():
for sponsor in Sponsor.objects.all():
due = Trial.objects.due().filter(
sponsor=sponso... | 61,337 |
def launch_terraform_deployment(directory, variables = {}) :
""" Launch terraform deployment
---
directory (str) : Deployment directory
variables (str) : List of variables to add to the deployment in a tfvars file
"""
result = TERRAFORM_TOOLS.init(directory)
if not resul... | 61,338 |
def convert_to_unicode(text):
"""
Converts `text` to Unicode (if it's not already), assuming utf-8 input.
Args:
text (str|bytes): Text to be converted to unicode.
Returns:
str: converted text.
"""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
... | 61,339 |
def create_system_id(os_string, architecture):
"""
Create a system-ID by joining the OS-String and the architecture with a hyphen.
Args:
os_string (str):
The Operating system string.
architecture (str):
The Architecture string.
Returns:
The System-ID str... | 61,340 |
def get_pairs(astring):
"""Takes a string and returns all pairs found in the string"""
adict = Counter()
for i in range(len(astring) - 1):
pair = str(astring[i] + astring[i + 1])
adict[pair] += 1
return adict | 61,341 |
def circular_array_rotation(a, k, queries):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/circular-array-rotation/problem
John Watson knows of an operation called a right circular rotation on an array of integers. One rotation operation
moves the last array element to the first position and ... | 61,342 |
def validate_bug_tracker(input_url):
"""
Validates that an issue tracker URI string contains one `%s` Python format
specification type (no other types are supported).
"""
try:
# Ignore escaped `%`'s
test_url = input_url.replace('%%', '')
if test_url.find('%s') == -1:
... | 61,343 |
def get_roomUsageSchedule(buildingType, roomType, input_calendar={}):
"""
時刻別のスケジュールを読み込む関数(空調、その他)
"""
if RoomUsageSchedule[buildingType][roomType]["空調運転パターン"] == None: # 非空調であれば
roomScheduleRoom = np.zeros((365,24))
roomScheduleLight = np.zeros((365,24))
roomSchedulePerson =... | 61,344 |
def load_bn_running(net, runnings):
"""
Restore running mean and variance for 2d BatchNorm layers of a network
:param net: net
:param runnings: List generated from save_runnings() - runnings[0] is the running mean, runnings[1] is the variance
:return:
"""
if runnings is None:
return... | 61,345 |
def refresh_drought(engine):
"""Refresh table drought from cumprcp and reference for the last day_index available."""
sql_year = "select max(year) from cumprcp"
max_year = engine.execute(sql_year).fetchone()[0]
logging.debug(f"max_year={max_year}")
sql_index = f"select max(day_index) from cumprcp wh... | 61,346 |
def create(path: pathlib.Path, key_size: int = DEFAULT_MASTER_KEY_SIZE) -> bytes:
"""Create a random key with the lenght key_size, and store it in path
Args:
path (pathlib.Path): Path to store the key in
key_size (int, optional): The size of the key to create in bytes.
Defaults to D... | 61,347 |
def sim_multi_suj_ephy(modality="meeg", n_subjects=10, **kwargs):
"""Simulate electrophysiological data of multiple subjects.
This function basically use :func:`sim_single_suj_ephy` under the hood to
generate the data of multiple subjects.
Parameters
----------
n_subjects : int | 10
Nu... | 61,348 |
def get_all_completed_exp_ids(user_id):
"""Returns a list with the ids of all the explorations completed by the
user.
Args:
user_id: str. The id of the user.
Returns:
list(str). A list of the ids of the explorations completed by the
learner.
"""
completed_activities... | 61,349 |
async def test_flow_usb_cannot_connect(hass: HomeAssistant):
"""Test usb flow connection error."""
with patch_config_flow_modem() as modemmock:
modemmock.side_effect = phone_modem.exceptions.SerialError
result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE:... | 61,350 |
def test_cosine_similarity_matrix_input_cloned(numba_compiled):
"""Test if score implementation clones the input correctly."""
vectors1 = np.array([[2, 2, 0, 0],
[2, 0, 2, 2]])
vectors2 = np.array([[0, 2, 2, 0],
[0, 0, 2, 2]])
if numba_compiled:
... | 61,351 |
def check_keyup_events(event, starship):
"""Реагирует на отпускание клавиш"""
if event.key == pygame.K_RIGHT:
starship.moving_right = False
elif event.key == pygame.K_LEFT:
starship.moving_left = False
elif event.key == pygame.K_UP:
starship.moving_up = False
elif event.key =... | 61,352 |
def problem015():
"""
Starting in the top left corner of a 2×2 grid, and only being able to move
to the right and down, there are exactly 6 routes to the bottom right
corner.
How many such routes are there through a 20×20 grid?
p_015.gif
This is a classic combinatorics problem. To... | 61,353 |
def _get_v(b1_height: FloatType, b1_width: FloatType, b2_height: FloatType,
b2_width: FloatType) -> tf.Tensor:
"""Get the consistency measurement of aspect ratio for ciou."""
@tf.custom_gradient
def _get_grad_v(height, width):
"""backpropogate gradient."""
arctan = tf.atan(tf.math.divide_no_na... | 61,354 |
def validation_run_pre_delete(sender, instance, using, *args, **kwargs):
"""
Fire events and cancel the associated job before deleting the run
"""
logger.info(
f"Deleting validation run {instance.pk} and canceling associated jobs"
)
instance.start_cancel(on_delete=True)
instance.canc... | 61,355 |
def demo_graph(ax: Axes, list_cai: list) -> None:
"""Plots a bar graph showing the Climate Awareness Index (CAI) of each article
scraped in the demo.
Instance Attributes:
- ax: an instance of Axes
- list_cai: a list of CAI values
"""
ax.bar(range(len(list_cai)), list_cai, color='gol... | 61,356 |
def on(page, visit_page=False, url_params={}):
"""
Creates PageObject with current instance of the selenium_browser.
Args:
page (PageObject): PageObject class name.
visit_page (boolean): Navigate to page.
url_params (dictionary): url parameter object.
Returns:
... | 61,357 |
def test_create_cdmi_content_by_name():
"""|sect| `CDMI_8.2`_ Tests valid uploading of a CDMI-encoded text file to the root collection.
:command: ``PUT /<file_name>.txt``
:tests:
* CDMI mimetype = text/plain, valuetransferencoding = base64
* No CDMI mimetype, valuetransferencoding = base64... | 61,358 |
def create_home_dir():
"""
Creates the w3af home directory, on linux: /home/user/.w3af/
:return: True if success.
"""
# Create .w3af inside home directory
home_path = get_home_dir()
if not os.path.exists(home_path):
try:
os.makedirs(home_path)
except OSError:
... | 61,359 |
def bold(s):
"""Returns the string bold.
Source: http://stackoverflow.com/a/16264094/2570866
:param s:
:type s: str
:return:
:rtype: str
"""
return r'\textbf{' + s + '}' | 61,360 |
def show_tables(*_args):
"""
Generates an HTML output from the penalty
tables and open the HTML file in the browser.
"""
path = target_dicts_to_html()
webbrowser.open(path) | 61,361 |
def constrained_smoothing(mesh, kmax=100, damping=0.5, constraints={}, algorithm='centroid'):
"""Constrained smoothing of a mesh. Constraints can be points, curves or surfaces.
Parameters
----------
mesh : Mesh
A mesh to smooth.
kmax : int
Number of iterations for smoothing. Default... | 61,362 |
def plot_lines(lines, color='#269df2', fig_size=(5,5), title=None):
"""plots lines in complelx plane."""
lines = np.array(lines)
tuple_lines = cmplx_lines_to_tuples(lines)
fig, ax = plt.subplots()
fig.set_size_inches(fig_size)
for line in tuple_lines:
x, y = zip(*line)
ax.plot... | 61,363 |
def decode(obj: typing.Any) -> typing.Any:
"""Decodes previously encoded information.
"""
if isinstance(obj, PRIMITIVES):
return obj
if isinstance(obj, tuple):
return tuple(map(decode, obj))
if isinstance(obj, list):
return list(map(decode, obj))
if isinstance(obj... | 61,364 |
def model(network:graph_class):
"""
create a, b, c matrix for the LP problem
"""
C = get_vector_C(network)
(A_ub, B_ub) = get_A_ub_and_B_ub(network)
(A_eq, B_eq) = get_A_eq_and_B_eq(network)
(lb, ub, bounds) = get_lb_and_ub(network)
# solve lp using linprog function
res... | 61,365 |
def face_distance(face_encodings, face_to_compare):
"""
计算人脸距离
"""
if len(face_encodings) == 0:
return np.empty((0))
return np.linalg.norm(face_encodings - face_to_compare, axis=1) | 61,366 |
def _hyperexpand(ip, z, ops0=[], z0=Dummy('z0'), premult=1, chainmult=1):
"""
Try to find an expression for the hypergeometric function
`ip.ap`, `ip.bq`.
The result is expressed in terms of a dummy variable z0. Then it
is multiplied by premult. Then ops0 is applied, using chainmult*t*d/dt
for t... | 61,367 |
def init_embedding(emb):
"""Weight initialization of embeddings (in place).
Best practise from fastai
Arguments:
emb {torch.nn.Embedding} -- Embedding
"""
w = emb.weight.data
sc = 2 / (w.shape[1]+1)
w.uniform_(-sc, sc) | 61,368 |
def stis_echelle_coadd(files=[], plot=True, nclip=15, file_path=os.getcwd()+'/', save_path=os.getcwd()+'/stitched_spectra/', flat='', filename='long'):
"""
main funtion, gather data then stitch, coadd, save and plot them
"""
#get all x1f or x1d files
if files == []:
if len(glob.glob(fil... | 61,369 |
def tri_less_eq(v1, v2):
"""Returns True if the tristate v1 is less than or equal to the tristate
v2, where "n", "m" and "y" are ordered from lowest to highest."""
return TRI_TO_INT[v1] <= TRI_TO_INT[v2] | 61,370 |
def write_columns(column, column_name):
"""Write a column into a file."""
with open(f'{column_name}.tex', 'w') as f:
for section in column:
f.writelines(print_section(section)) | 61,371 |
def decode_base64_urlsafe(text):
"""Reverse operation of :func:`encode_base64_urlsafe`.
**中文文档**
将base64字符串解码为原字符串。
"""
return base64.urlsafe_b64decode(text.encode("utf-8")).decode("utf-8") | 61,372 |
def init_figure(height=800):
"""Initialize a 3D figure."""
fig = go.Figure()
fig.update_layout(
height=height,
scene_camera=dict(
eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)),
scene=dict(
xaxis=dict(showbackground=False),
yaxis=dict(showb... | 61,373 |
def compute_indices(wires, n_block_wires):
"""Generate a list containing the wires for each block.
Args:
wires (Iterable): wires that the template acts on
n_block_wires (int): number of wires per block
Returns:
layers (array): array of wire labels for each block
"""
n_wire... | 61,374 |
def drop_distant(xy, r=6.0):
"""
Drops pedestrians more than r meters away from primary ped
"""
distance_2 = np.sum(np.square(xy - xy[:, 0:1]), axis=2)
mask = np.nanmin(distance_2, axis=0) < r**2
return xy[:, mask], mask | 61,375 |
def test4():
"""
Plot h and hinv.
"""
print "\nTEST 4"
## input ##
s = np.linspace(-20.,20.,2001)
kpm = np.array([-0.6,0.2])
kpm = np.sort(kpm)
s0 = 5.
## setup h
h = lambda s: hks(s, kpm, s0)
hinv = lambda s: hksinv(s, kpm, s0)
## test plot h
plt.figure()
plt.plot(s,s,'0.8')
plt.plot(s,h(s),'k-', label... | 61,376 |
def normalize_score_dict(input_dict: Dict[str, float], exponent=1) -> Dict[str, float]:
"""Takes a dictionary of scores and applies L1-normalization (dividing each value by the sum).
This is the simplest way of turning a collection of scores into a probability distribution.
The exponent can be used to mak... | 61,377 |
def allreduce_ring_single_shard(xs, devices, reduction_fn_string="SUM"):
"""Compute the reduction of all Tensors and put the result everywhere.
Performance-optimized for a ring of devices.
Args:
xs: a list of n tf.Tensors
devices: a list of strings
reduction_fn_string: "SUM" or "MAX"
Returns:
... | 61,378 |
def test_dressed_redirect(f_httpretty, webapp):
"""Test that going from naked to non-naked domain is not considered
being parked.
AKA, "dressing" the domain :)
"""
f_httpretty.register_uri(
f_httpretty.GET,
'http://example.com:80/',
status=302,
adding_headers={
... | 61,379 |
def test_write_read_sphericalvoronoi(sphericalvoronoi, tmpdir):
""" SphericalVoronoi
Make sure `read` understands the bits written by `write`
"""
filename = os.path.join(tmpdir, 'sphericalvoronoi.far')
io.write(filename, sphericalvoronoi=sphericalvoronoi)
actual = io.read(filename)['sphericalvor... | 61,380 |
def calcPrecision(data, modelName): #Update name to sensitivity
"""Calculates the prediction of the data using a single str or list of strings in the modelName argument. The modelName corresponds to
the columns to be analyzed.
Sensitivity Formula: True Predictions / All Prediction
"""
... | 61,381 |
def _tempfile_path(*args, **kwargs):
"""Generate a sure-to-be-free tempfile path.
It's hacky but it works.
"""
import tempfile
fd, tmpfile = tempfile.mkstemp()
# close and delete; we only want the path
os.close(fd)
os.remove(tmpfile)
return tmpfile | 61,382 |
def submitSolution(email_address, secret, output, partIdx):
"""Submits a solution to the server. Returns (result, string)."""
if output == '':
print ('')
print ("== Submission failed: Please correct and resubmit.")
sys.exit(1)
else:
output_64_msg = email.message.Message()
... | 61,383 |
def test_get_version_with_user_input_yes(versioner, mock_input_yes):
"""Tests get_version with user response = "y"."""
assert versioner.get_version() == "1.02"
assert versioner.get_version(file=os.path.join(test_dir_2,
"test_version.txt")) == "1.00"
as... | 61,384 |
def bitwise_not(column):
"""
Computes bitwise NOT.
"""
return _with_expr(exprs.BitwiseNot, column) | 61,385 |
def test_api_schema(case):
"""Test the API against the OpenAPI specification."""
response = case.call_wsgi()
case.validate_response(response) | 61,386 |
def next_moves_all(board, robots):
"""Generate list of next moves by moving a single robot."""
for index in range(len(robots)):
for move in next_moves_single(board, index, robots):
assert move is not None
yield move | 61,387 |
def ExecuteDownloadPins(pins, processes):
""" 并发processes个线程下载所有pins """
pool = ThreadPool(processes=processes)
data = pool.map(DownloadPinImg, pins)
pool.close()
pool.join()
return data | 61,388 |
def load_raw_lattice(raw_lattice_path="/data/rawdata/sighan/lattice/", path_head="."):
"""
for flat
dont care about para: 'path_head', only use for debugging
"""
train_source_path = path_head + raw_lattice_path + "train.src"
train_target_path = path_head + raw_lattice_path + "train.tgt"
vali... | 61,389 |
def quaternion_ffn(x, dim, name='', activation=None, reuse=None):
""" Implements quaternion feed-forward layer x is [bsz x features] tensor """
input_dim = x.get_shape().as_list()[1] // 4
with tf.compat.v1.variable_scope('Q{}'.format(name), reuse=reuse) as scope:
kernel = glorot([input_dim, dim], na... | 61,390 |
def mfacebookToBasic(url):
"""Reformat a url to load mbasic facebook instead of regular facebook, return the same string if
the url don't contains facebook"""
if "m.facebook.com" in url:
return url.replace("m.facebook.com", "mbasic.facebook.com")
elif "www.facebook.com" in url:
r... | 61,391 |
def assert_almost_equal(
actual: numpy.float64, desired: numpy.float64, err_msg: Literal["orth.chebys(3)"]
):
"""
usage.scipy: 1
"""
... | 61,392 |
async def process_websites_to_fetch(request):
"""
This function processes the POST request and create an asyncio task calling the Driver()'s produce_metrics_for_websites method
passing the provided list.
:param request:
:return: JSON
"""
try:
data = await request.json()
prod... | 61,393 |
def load_pbg_config(path=None):
"""Load PBG configuration into global setting
Parameters
----------
path: `str`, optional (default: None)
Path to the directory for pbg configuration file
If None, `.settings.pbg_params['checkpoint_path']` will be used
Returns
-------
Updates... | 61,394 |
def kernel_status():
"""
:return: {'running': {'kernel-X.Y.Z'}, 'required': <'kernel-A.B.C' or None>}
"""
running_kernel = "kernel-%s" % AgentShell.try_run(["uname", "-r"]).strip()
available_kernels = [
k for k in AgentShell.try_run(["rpm", "-q", "kernel"]).split("\n") if k
]
if Ag... | 61,395 |
def prepareDataForClassification(dataset, start_test):
"""
generates categorical output column, attach to dataframe
label the categories and split into train and test
"""
features = dataset.columns[0:-1]
X = dataset[features]
y = dataset.UpDown
X_train = X[X.index < start_test]
y_t... | 61,396 |
def monitor_dir(base_dir, x, y,
name_filter='.', age_filter=None,
xlog=False, ylog=False, slowcoordinate=None, preprocessor=lambda x: x,
selector=data_selector, plotter=basic_plot,
ref_data_dirs=[],
poll_period=3):
"""Monitor base_dir for... | 61,397 |
def get_new_skill_id():
"""Returns a new skill id.
Returns:
str. A new skill id.
"""
return skill_models.SkillModel.get_new_id('') | 61,398 |
def generate_url_to_event_index(website_url):
"""Given URL to workshop's website, generate a URL to its raw `index.html`
file in GitHub repository."""
template = ('https://raw.githubusercontent.com/{name}/{repo}'
'/gh-pages/index.html')
for regex in [Event.WEBSITE_REGEX, Event.REPO_REGE... | 61,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.