content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def lambda_sum_largest_canon(expr, real_args, imag_args, real2imag):
"""Canonicalize nuclear norm with Hermitian matrix input.
"""
# Divide by two because each eigenvalue is repeated twice.
real, imag = hermitian_canon(expr, real_args, imag_args, real2imag)
real.k *= 2
if imag_args[0] is not Non... | 42,100 |
def dp_palindrome_length(dp, S, i, j):
"""
Recursive function for finding the length
of the longest palindromic sequence
in a string
This is the algorithm covered in the lecture
It uses memoization to improve performance,
dp "dynamic programming" is a Python dict
containing previously computed values
... | 42,101 |
def ellip_enclose(points, color, inc=1, lw=2, nst=2):
"""
Plot the minimum ellipse around a set of points.
Based on:
https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py
"""
def eigsorted(cov):
vals, vecs = np.linalg.eigh(cov)
order = vals.argsort()[::-1... | 42,102 |
def RangeComparator(current, compare):
"""Checks if value is in between 2 ranges (compare must be a 2-value tuple/list)."""
if current < compare[0] or current > compare[1]:
msg = '{0} ({1}) is between {2} and {3}'
raise JsonPatchTestFailed(msg.format(current, type(current), compare[0], compare[1... | 42,103 |
def test_temp_sensor_critical(mock_subproc):
"""
Test Critical Warning. Changed ASIC Network Sensor to 84C. Crit is 85
See tests/smonctl_critical.txt. This stubs the smonctl -j output
"""
smonctl_out = open('tests/smonctl_critical.txt').read()
mock_subproc.return_value = smonctl_out
with ass... | 42,104 |
def imd(im):
""" Invariant Multi-scale shape descriptor
http://eeeweba.ntu.edu.sg/computervision/Research%20Papers/2016/Invariant%20Multi-Scale%20Shape%20Descriptor%20for%20Object%20Matching%20and%20Recognition.pdf
"""
pass | 42,105 |
def catalog_dictionary_per_observation(cats, obs_nums, targets, defaults):
"""Translate a dictionary of catalogs from a case of either:
1. Separate catalogs for each target name
2. Separate catalogs for each target name and instrument
into a dictionary of catalogs for each instrument and observation
... | 42,106 |
def sierpinkspi(p1, p2, p3, degree, draw, image, colors):
"""
Draw Sierpinksi Triangles.
"""
colour = colors
draw.polygon(((p1[0], p1[1]), (p2[0], p2[1]), (p3[0], p3[1])), fill=colour[degree])
if degree > 0:
sierpinkspi(p1, mid(p1, p2), mid(p1, p3), degree-1, draw, image, colors)
... | 42,107 |
def generate_depth_map(camera, Xw, shape):
"""Render pointcloud on image.
Parameters
----------
camera: Camera
Camera object with appropriately set extrinsics wrt world.
Xw: np.ndarray (N x 3)
3D point cloud (x, y, z) in the world coordinate.
shape: np.ndarray (H, W)
O... | 42,108 |
def test_perturb_features_empty():
"""Test perturb empty features"""
features = []
perturbationContext = PerturbationContext(jrandom, 0)
newFeatures = DataUtils.perturbFeatures(features, perturbationContext)
assert newFeatures is not None
assert len(features) == newFeatures.size() | 42,109 |
def zeros(shape, dtype, allocator=drv.mem_alloc):
"""
Return an array of the given shape and dtype filled with zeros.
Parameters
----------
shape : tuple
Array shape.
dtype : data-type
Data type for the array.
allocator : callable
Returns an object that represents th... | 42,110 |
def execute_script(session, file_name):
"""Execute a SQL script as one or more SQL statements in a single file."""
print('Executing SQL statements in file ' + file_name)
with open(file_name, 'r') as sql_file:
sql_command = ''
# Iterate over all lines in the sql file
for line in sql_f... | 42,111 |
def create_own_child_column(X):
"""
Replaces the column 'relationship' with a binary one called own-child
"""
new_column = X['relationship'] == 'own-child'
X_transformed = X.assign(own_child=new_column)
X_transformed = X_transformed.drop('relationship', axis=1)
return X_transformed | 42,112 |
def find_next_gate(wires, op_list):
"""Given a list of operations, finds the next operation that acts on at least one of
the same set of wires, if present.
Args:
wires (Wires): A set of wires acted on by a quantum operation.
op_list (list[Operation]): A list of operations that are implement... | 42,113 |
def FDilatedConv1d(xC, xP, nnModule):
"""1D DILATED CAUSAL CONVOLUTION"""
convC = nnModule.convC # current
convP = nnModule.convP # previous
output = F.conv1d(xC, convC.weight, convC.bias) + \
F.conv1d(xP, convP.weight, convP.bias)
return output | 42,114 |
def load_spans(file):
"""
Loads the predicted spans
"""
article_id, span_interval = ([], [])
with open(file, 'r', encoding='utf-8') as f:
for line in f.readlines():
art_id, span_begin, span_end = [int(x) for x in line.rstrip().split('\t')]
span_interval.append((span_b... | 42,115 |
def is_stupid_header_row(row):
"""returns true if we believe row is what the EPN-TAP people used
as section separators in the columns table.
That is: the text is red:-)
"""
try:
perhaps_p = row.contents[0].contents[0]
perhaps_span = perhaps_p.contents[0]
if perhaps_span.get("style")=='color: rgb(... | 42,116 |
def get_cli_parser() -> ArgumentParser:
"""Return an ArgumentParser instance."""
parser = ArgumentParser(description="CLI options for Alice and Bob key share")
parser.add_argument('-p', help='Prime p for information exchange', type=int)
parser.add_argument('-g', help='Prime g for information exchange', ... | 42,117 |
def _get_http_and_https_proxy_ip(creds):
"""
Get the http and https proxy ip.
Args:
creds (dict): Credential information according to the dut inventory
"""
return (re.findall(r'[0-9]+(?:\.[0-9]+){3}', creds.get('proxy_env', {}).get('http_proxy', ''))[0],
re.findall(r'[... | 42,118 |
def multiple_files_multiple_tracks():
"""Returns a path to a CUE file with multiple tracks per source file."""
cue_file = "Non-ISO_extended-ASCII_text_with_CRLF.cue"
return os.path.join("tests", "files", cue_file) | 42,119 |
def geometric_expval(p):
"""
Expected value of geometric distribution.
"""
return 1. / p | 42,120 |
def make_ticc_dataset(
clusters=(0, 1, 0), n_dim=3, w_size=5, break_points=None,
n_samples=200, n_dim_lat=0, sparsity_inv_matrix=0.5, T=9,
rand_seed=None, **kwargs):
"""Generate data as the TICC method.
Library implementation of `generate_synthetic_data.py`, original can be
found at... | 42,121 |
def tag_tuple(tag):
"""Simple function to decompose a tag for debugging."""
return (tag.tagClass, tag.tagNumber, tag.tagLVT, tag.tagData) | 42,122 |
def get_dustmap(sourcemap, useweb=False):
""" get the dustmap (from the dustmaps package) of the given source.
Parameters
---------
sourcemap: [string]
origin of the MW extinction information.
currently implemented: planck, sfd
useweb: [bool] -optional-
shall this ... | 42,123 |
def destroy(model_name):
"""Run all steps to cleaup after a test run.
:param model: Name of model to remove
:type bundle: str
"""
zaza.controller.destroy_model(model_name) | 42,124 |
def make_retro_pulse(x, y, z, zenith, azimuth):
"""Retro pulses originate from a DOM with an (x, y, z) coordinate and
(potentially) a zenith and azimuth orientation (though for now the latter
are ignored).
"""
pulse = I3CLSimFlasherPulse()
pulse.type = I3CLSimFlasherPulse.FlasherPulseType.retro... | 42,125 |
def shiftLeft(col, numBits):
"""Shift the given value numBits left.
>>> spark.createDataFrame([(21,)], ['a']).select(shiftLeft('a', 1).alias('r')).collect()
[Row(r=42)]
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.shiftLeft(_to_java_column(col), numBits)) | 42,126 |
def lerp(x0: float, x1: float, p: float) -> float:
"""
Interplates linearly between two values such that when p=0
the interpolated value is x0 and at p=1 it's x1
"""
return (1 - p) * x0 + p * x1 | 42,127 |
def discard_events(library, session, event_type, mechanism):
"""Discards event occurrences for specified event types and mechanisms in a session.
Corresponds to viDiscardEvents function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier t... | 42,128 |
def test_user4_gene_by_id_access(user4_token):
""""
Make sure user4 has access to open1, open2, and controlled4
"""
for id in ["open1", "open2", "controlled5"]:
response = helper_get_katsu_response(user4_token, f"{KATSU_URL}/api/genes/{id}")
assert response.status_code == 200
ass... | 42,129 |
def clean():
"""Remove all generated files (.pyc, .coverage, .egg, etc)."""
with lcd(_relative_to_fabfile()):
local('find . -name "*.pyc" -exec rm -rf {} \;')
local('find . -name ".coverage" -exec rm -rf {} \;')
local('find . -name ".DS_Store" -exec rm -rf {} \;')
local('find . -... | 42,130 |
async def test_track_point_in_time(hass):
"""Test track point in time."""
before_birthday = datetime(1985, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC)
birthday_paulus = datetime(1986, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC)
after_birthday = datetime(1987, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC)
runs = []
asyn... | 42,131 |
def getSpeed(spindle=0):
"""Gets the interpreter's speed setting for the specified spindle.
Args:
spindle (int, optional) : The number of the spindle to get the speed
of. If ``spindle`` is not specified spindle 0 is assumed.
Returns:
float: The interpreter speed setting, with a... | 42,132 |
def appointment() -> any:
"""
Defines route to appointment booking page.
:return: String of HTML template for appointment booking page or homepage if booking was successful.
"""
if request.method == 'POST':
user_input = request.form.to_dict()
try:
request_is_valid(request... | 42,133 |
def add_kms_key_id(module, template, kms_key_id):
"""
Add the kms key id to the Packer template.
"""
# 'launch_block_device_mappings' =
for builder in template['builders']:
if 'launch_block_device_mappings' in builder:
if isinstance(builder['launch_block_device_mappings'], list)... | 42,134 |
def variable_summaries(var, name):
"""Attach summaries to a Tensor."""
mean = tf.reduce_mean(var)
tf.summary.scalar('mean/' + name, mean)
stddev = tf.math.reduce_std(var)
tf.summary.scalar('sttdev/' + name, stddev)
tf.summary.scalar('max/' + name, tf.reduce_max(var))
tf.summary.scalar('min/' + name, tf.re... | 42,135 |
def getfile(basedir, manifest_value, user_argument):
"""Get name for a file that is referenced in a workflow manifest. If the
user argument is given it overrides the respective value in the manifest.
For user arguments we first assume that the path references a file on disk,
either as absolute path or a... | 42,136 |
def wait_for_task(task, actionName='job', hideResult=False):
"""
Waits and provides updates on a vSphere task
"""
while task.info.state == vim.TaskInfo.State.running:
time.sleep(2)
if task.info.state == vim.TaskInfo.State.success:
if task.info.result is not None and not hideResult:... | 42,137 |
def _get_candidate_names():
"""Common setup sequence for all user-callable interfaces."""
global _name_sequence
if _name_sequence is None:
_once_lock.acquire()
try:
if _name_sequence is None:
_name_sequence = _RandomNameSequence()
finally:
_on... | 42,138 |
def plot_uq_output(output_dir="", graphs_dir=""):
""" Plot generated output results using plot-flee-output.py. """
local("mkdir -p %s/%s/%s" % (env.local_results, output_dir, graphs_dir))
# import plot_flee_uq_output.py from env.flee_location
# when we have pip flee installation option, this part shoul... | 42,139 |
def relative_difference(x: np.array, y: np.array) -> np.array:
""" Returns the relative difference estimator for two Lagrange multipliers.
"""
maximum = np.max([x, y])
minimum = np.min([x, y])
difference = maximum-minimum
return np.abs(difference) / np.max(np.abs([x, y, difference, 1.])) | 42,140 |
def ConvertPngToYuvBarcodes(input_directory='.', output_directory='.'):
"""Converts PNG barcodes to YUV barcode images.
This function reads all the PNG files from the input directory which are in
the format frame_xxxx.png, where xxxx is the number of the frame, starting
from 0000. The frames should be consecut... | 42,141 |
def _ignore_on_copy(directory, contents): # pylint: disable=unused-argument
"""Provides list of items to be ignored.
Args:
directory (Path): The path to the current directory.
contents (list): A list of files in the current directory.
Returns:
list: A list of files to be ignored.
... | 42,142 |
def registDeptUser(request):
"""
홈택스 현금영수증 부서사용자 계정을 등록합니다.
- https://docs.popbill.com/htcashbill/python/api#RegistDeptUser
"""
try:
# 팝빌회원 사업자번호
CorpNum = settings.testCorpNum
# 홈택스 부서사용자 계정아이디
DeptUserID = "deptuserid"
# 홈택스 부서사용자 계정비밀번호
DeptUserPW... | 42,143 |
def generate_repository_path(object_id):
"""
Generate the path of a cilantro (sub)object in the repository.
This is based on the last 4/2 digits of the object_id, which should
be a zenon or atom ID.
E.g. object_id "JOURNAL-ZID1234567" is stored under
"4500/4567/JOURNAL-ZID1234567".
:param s... | 42,144 |
def write_sysctl(entry, value):
"""Write value to a sysctl entry. Return this value if successful"""
path = SYSCTL_ENDPOINT + '/' + '/'.join(entry.split('.'))
if not os.path.exists(path):
logger.debug("{} does not exist".format(entry))
return
try:
with open(path, 'w') as f:
... | 42,145 |
def tec2asiCorrelation(tec_ts, tec, asi_ts, intensity):
"""
""" | 42,146 |
async def get_rank(mode: str, num: int) -> list[dict]:
"""请求pixiv榜单的函数
Args:
mode (str): 日榜daily/周榜weekly/月榜monthly
num (int): 数量(1-50)
Returns:
list[dict]: 一个包含图片标题与id,排名,画师名称与id,原图链接以及tags的列表,请求失败的返回请求失败字符串
"""
url = "https://www.pixiv.net/ranking.php"
param = {"mode"... | 42,147 |
def generate_fake_data_loader():
"""" Generate fake-DataLoader with four batches, i.e. a list with sub-lists of samples and labels.
It has four batches with three samples each. """
samples1 = torch.tensor([[2., 2., 2., 2.], [2., 2., 0., 0.], [0., 0., 2., 2.]])
samples2 = torch.tensor([[1., 2., 3., 4.], ... | 42,148 |
def create_map(
title: Optional[str] = typer.Option(None, help="The title of the map"),
slug: Optional[str] = typer.Option(
None, help="The map slug. Currently un-used"
),
description: Optional[str] = typer.Option(
None, help="The description of the map and its purpose"
),
privac... | 42,149 |
def get_graph(node, seq):
"""Get the relaxed pose graph from the map server"""
request = GraphRelaxation.Request()
request.seq = int(seq)
request.update_graph = False # TODO not used?
request.project = True # TODO always True?
return ros_service_request(node, "relaxed_graph", GraphRelaxation, request) | 42,150 |
def test_interaction_accepts_name(fixt):
"""
Check that the interaction accepts a 'name' argument and has a 'name' attribute.
"""
K1 = 1
a = df.Constant((0, 0, 1))
anis = UniaxialAnisotropy(K1, a, name='MyAnisotropy')
assert hasattr(anis, 'name') | 42,151 |
def get_RV_K(
P_days,
mp_Mearth,
Ms_Msun,
ecc=0.0,
inc_deg=90.0,
nsamples=10000,
percs=[50, 16, 84],
return_samples=False,
plot=False,
):
"""Compute the RV semiamplitude in m/s via Monte Carlo
P_days : tuple
median and 1-sigma error
mp_Mearth : tuple
media... | 42,152 |
def arc(color, start_angle, stop_angle, width, height,
x=None, y=None, thickness=1, anchor='center', **kwargs):
"""
Function to make an arc.
:param color: color to draw arc
:type color: str or List[str]
:param start_angle: angle to start drawing arc at
:type start_angle: int
:param ... | 42,153 |
def calculate_shapley_value(g, prob_vals, maxIter=20000):
"""
This algorithm is based on page 29 of the following paper:
https://arxiv.org/ftp/arxiv/papers/1402/1402.0567.pdf
:param g: the graph
:param prob_vals: a list. it contains the weight of each node in the graph
:param maxIter: ... | 42,154 |
async def complete_multipart_upload(bucket: str, s3_key: str, parts: List, upload_id: str) -> Dict[str, Any]:
"""Complete multipart upload to s3.
Args:
bucket (str): s3 bucket
s3_key (str): s3 prefix
parts (List): all parts info
upload_id (str): multipart upload Id
Returns:... | 42,155 |
def build_mask(module='A', pixscale=0.03):
"""Create coronagraphic mask image
Return a truncated image of the full coronagraphic mask layout
for a given module.
+V3 is up, and +V2 is to the left.
"""
if module=='A':
names = ['MASK210R', 'MASK335R', 'MASK430R', 'MASKSWB', 'MASKLWB']
... | 42,156 |
def validate_auth_header_has_signature(
request_headers: Dict[str, str],
) -> None:
"""
Validate the authorization header includes a signature.
Args:
request_headers: The headers sent with the request.
Raises:
QueryOutOfBounds: The "Authorization" header has no signature.
"""
... | 42,157 |
async def update_login_me(
*,
password: str = Body(...),
new_email: tp.Optional[EmailStr] = Body(None, alias='newEmail'),
new_password: tp.Optional[str] = Body(None, alias='newPassword'),
current_user: models.User = Depends(common.get_current_user),
uow: IUnitOfWork = Depends(common.get_uow),
) ... | 42,158 |
def test_g_day_min_exclusive004_1272_g_day_min_exclusive004_1272_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : (facet=minExclusive and value=- - -01
and facet=maxInclusive and value=- - -30) and document value=- - -15
"""
assert_bindings(
schema="msData/datatypes/... | 42,159 |
def comp_sharpness(is_stationary, signal, fs, method='din', skip=0):
""" Acoustic sharpness calculation according to different methods:
Aures, Von Bismarck, DIN 45692, Fastl
Parameters:
----------
is_stationary: boolean
True if the signal is stationary, false if it is time varying
... | 42,160 |
def main(config):
"""
Start up the editor to edit the configuration file.
:param config: the configuration file wrapper object
:type config: cea.config.Configuration
:return:
"""
app = htmlPy.AppGUI(title=u"CEA Configuration File Editor", maximized=False, developer_mode=True)
app.templ... | 42,161 |
def main():
"""
This example shows the use of regular expressions to do
pattern matching.
"""
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
# let'... | 42,162 |
def load_hobbies(path='data', extract=True):
"""
Downloads the 'hobbies' dataset, saving it to the output
path specified and returns the data.
"""
# name of the dataset
name = 'hobbies'
data = _load_file_data(name, path, extract)
return data | 42,163 |
def is_viable(individual):
"""
evaluate.evaluate() will set an individual's fitness to NaN and the
attributes `is_viable` to False, and will assign any exception triggered
during the individuals evaluation to `exception`. This just checks the
individual's `is_viable`; if it doesn't have one, this a... | 42,164 |
def combine_counts(hits1,
hits2,
multipliers=None,
total_reads=0,
unmatched_1="Unknown",
unmatched_2="Unknown",
):
""" compile counts into nested dicts """
total_counted = 0
counts = {}
# ke... | 42,165 |
def spider_gui():
"""
爬虫GUI界面
:return:
"""
def init_run(s: str):
"""
运行爬虫的函数
:param s: 输入要执行的参数。选择爬全校还是爬电院
:return:
"""
# 启动子进程,并保证父进程结束时子进程跟着结束
th[s].setDaemon(True)
th[s].start()
# 消去爬虫按钮,防止用户多次点击导致程序频繁多次创建... | 42,166 |
def _bitwidth_sweep(stride_degree: int = 0):
"""Yields a standard range of bitwidth.
Increasing stride_degree increases the stride of the range (maximum
stride_degree = 3).
Args:
stride_degree: Index into BITWIDTH_STRIDE_DEGREES indicating the stride
amount.
"""
for bit_count in range(8, 71, BIT... | 42,167 |
def test_create():
"""Verify that you can create users."""
mock_request = Mock()
users = Users(fixture, mock_request)
users.create('joe', pwd='abcd', sgrp=SGRP_ADMIN)
mock_request.assert_called_with(
'post', '/axis-cgi/pwdgrp.cgi',
data={
'action': 'add',
'us... | 42,168 |
def root():
"""Serves the website home page"""
return render_template("index.html") | 42,169 |
def getCookie():
"""
This function will return a randomly generated cookie
:return: A cookie
"""
lettersAndDigits = string.ascii_lowercase + string.digits
cookie = 'JSESSIONID='
cookie += ''.join(random.choice(lettersAndDigits) for ch in range(31))
return cookie | 42,170 |
async def mute_members(bot, ctx, member: discord.Member, reason, mute_role, time=None):
"""
Mute members
"""
schema = {
'_id': member.id,
'at': utc(),
'duration': time or None,
'moderator': ctx.author.id,
'guild_id': ctx.guild.id,
'type': 'mute'
}
... | 42,171 |
def zip_data(name='data', zip_json_directory=JSON_DIR, zip_csv_directory=CSV_DIR, pwd=PWD):
"""Create a zip file from data."""
if zip_json_directory:
# build zip filename
zip_json_file_name = os.path.join(pwd, '%s_json.zip' % name)
print('Writing %s' % os.path.basename(zip_json_file_na... | 42,172 |
def setup(self, packet, field_info):
"""Sets up the variables and classes for the agent.
Arguments:
self {BaseAgent} -- The agent.
packet {GameTickPacket} -- Information about the game.
field_info {FieldInfoPacket} -- Information about the game field.
"""
# Game info
self.g... | 42,173 |
def get_authenticated_igramscraper(username: str, password: str):
"""Gets an authenticated igramscraper Instagram client instance."""
client = Instagram()
client.with_credentials(username, password)
#client.login(two_step_verificator=True)
client.login(two_step_verificator=False)
return client | 42,174 |
def read_in_nn_path(path):
"""
Read in NN from a specified path
"""
tmp = np.load(path)
w_array_0 = tmp["w_array_0"]
w_array_1 = tmp["w_array_1"]
w_array_2 = tmp["w_array_2"]
b_array_0 = tmp["b_array_0"]
b_array_1 = tmp["b_array_1"]
b_array_2 = tmp["b_array_2"]
x_min = tmp["x... | 42,175 |
def test_sx(params=''):
"""
Run all tests printing output and terminating tests at first failure
:param params: parameters to py.test
:return:
"""
docker_exec('py.test -sx /shared/tests {}'.format(params)) | 42,176 |
def crop_zeros(array, remain=0, return_bound=False):
"""
Crop the edge zero of the input array.
Parameters
----------
array : numpy.ndarray
2D numpy array.
remain : int
The number of edges of all zeros which you want to remain.
return_bound : str or bool
S... | 42,177 |
def go_info_running(data, info_name, arguments):
"""Returns "1" if go is running, otherwise "0"."""
return '1' if 'modifier' in hooks else '0' | 42,178 |
def letra_mas_comun(cadena: str) -> str:
""" Letra
Parámetros:
cadena (str): La cadena en la que se quiere saber cuál es la letra más común
Retorno:
str: La letra más común en la cadena que ingresa como parámetro, si son dos es la letra alfabéticamente
posterior.
"""
... | 42,179 |
def dwt2(image, wavelet, mode="symmetric", axes=(-2, -1)):
"""Computes single level wavelet decomposition for 2D images
"""
wavelet = ensure_wavelet_(wavelet)
image = promote_arg_dtypes(image)
dec_lo = wavelet.dec_lo
dec_hi = wavelet.dec_hi
axes = tuple(axes)
if len(axes) != 2:
r... | 42,180 |
def recommended_global_tags_v2(release, base_tags, user_tags, metadata):
"""
Determine the recommended set of global tags for the given conditions.
This function is called by b2conditionsdb-recommend and it may be called
by conditions configuration callbacks. While it is in principle not limited
to... | 42,181 |
def test_post_hls_to_edx_no_endpoints(mocker):
"""post_hls_to_edx should log an error if no endpoints are configured for some video's collection"""
patched_log_error = mocker.patch("ui.api.log.error")
video_file = VideoFileFactory.create(
encoding=EncodingNames.HLS,
video__collection__edx_co... | 42,182 |
def plot_corelation_matrix(data):
"""
Plotting the co-relation matrix on the dataset
using the numeric columns only.
"""
corr = data.select_dtypes(include=['float64', 'int64']).iloc[:, 1:].corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.... | 42,183 |
def success_message(page_event_new) -> None:
"""I should see the success message."""
p_action = EventCreateAction(_page=page_event_new)
assert p_action.has_succeeded() is True | 42,184 |
def clean_tree(root):
"""
Cleans dirty HTML from an ElementTree
"""
initial_html = ET.tostring(root)
body = root[0] # <html><body>
# If there is text directly in body, it needs wrapping in a block element.
_promote_child_text(body, 'p')
# replace 'command' divs
_remove_command_divs(... | 42,185 |
def product_by_id(product_id):
"""
Get Product description by product id
:param product_id: Id of the product
:return:
"""
host = "https://cymax.com/"
site_data = urllib.urlopen(host + str(product_id) + '--C0.htm').read()
soup = BeautifulSoup(site_data)
product = soup.fi... | 42,186 |
def overlap(X, window_size, window_step):
"""
Create an overlapped version of X
Parameters
----------
X : ndarray, shape=(n_samples,)
Input signal to window and overlap
window_size : int
Size of windows to take
window_step : int
Step size between windows
Returns
... | 42,187 |
def test_collect_rollout_ML1_train_multi_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
... | 42,188 |
def cli(ctx, **kwargs):
"""Job resource.
"""
pass | 42,189 |
def may_ozerov_depth_3_complexity(n, k, w, mem=inf, hmap=1, memory_access=0):
"""
Complexity estimate of May-Ozerov algorithm in depth 3 using Indyk-Motwani for NN search
[MayOze15] May, A. and Ozerov, I.: On computing nearest neighbors with applications to decoding of binary linear codes.
In: Annual I... | 42,190 |
def _check_options(options):
""" Check the options bitfield.
Parameters
----------
options : str
Raises
------
TypeError
if options is not a string
ValueError
either if any character in option is not a zero or a one, or if options
is not of length 8
"""
... | 42,191 |
def test_simple_inference():
"""
Tests inference on the Huang graph.
:return: None.
"""
bbn = BbnUtil.get_simple()
join_tree = InferenceController.apply(bbn)
expected = {
'a': [0.5, 0.5],
'b': [0.45, 0.55],
'c': [0.45, 0.55],
'd': [0.68, 0.32],
'e': ... | 42,192 |
def ensure_lambda_list_permissions(session):
"""
Ensures that the current AWS session has the necessary permissions to list the functions
with New Relic AWS Lambda layers.
:param session: A boto3 session
"""
needed_permissions = check_permissions(session, actions=["lambda:ListFunctions"])
i... | 42,193 |
def unpack_single_run_meta(storage, meta, molecules):
"""Transforms a metadata compute packet into an expanded
QC Schema for multiple runs.
Parameters
----------
db : DBSocket
A live connection to the current database.
meta : dict
A JSON description of the metadata involved with... | 42,194 |
def getKey(event):
"""Returns the Key Identifier of the given event.
Available Codes: https://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413/keyset.html#KeySet-Set
"""
if hasattr(event, "key"):
return event.key
elif hasattr(event, "keyIdentifier"):
if event.keyIdentifier in ["Es... | 42,195 |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = create_engine(URL)
with connectable.connect() as connection:
context.configure(
connection=connectio... | 42,196 |
def main():
"""Parses the command line arguments and calls the appropriate function."""
if not Path('contacts.db').exists():
create_database()
if len(sys.argv) < 2 or sys.argv[1].lower() not in COMMANDS:
print_instructions()
elif sys.argv[1].lower() == 'add':
add_contact()
... | 42,197 |
def handle_exception(exc_type, exc_value, exc_traceback):
""" handle all exceptions """
error_logfile = os.path.join(os.path.expanduser("~"),
'.odmltables',
'error.log')
## KeyboardInterrupt is a special case.
## We don't raise the erro... | 42,198 |
def get_long_season_name(short_name):
"""convert short season name of format 1718 to long name like 2017-18.
Past generations: sorry this doesn't work for 1999 and earlier!
Future generations: sorry this doesn't work for the 2100s onwards!
"""
return '20' + short_name[:2] + '-' + short_name[2:] | 42,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.