content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def add_arrays(arr1, arr2):
"""
Function to adds two arrays element-wise
Returns the a new array with the result
"""
if len(arr1) == len(arr2):
return [arr1[i] + arr2[i] for i in range(len(arr1))]
return None | d16adfb33fb0c1a30277f7250485cddea60b1fe9 | 691,048 |
def strip_commands(commands):
""" Strips a sequence of commands.
Strips down the sequence of commands by removing comments and
surrounding whitespace around each individual command and then
removing blank commands.
Parameters
----------
commands : iterable of strings
Iterable of commands to strip.
Returns
-------
stripped_commands : list of str
The stripped commands with blank ones removed.
"""
# Go through each command one by one, stripping it and adding it to
# a growing list if it is not blank. Each command needs to be
# converted to an str if it is a bytes.
stripped_commands = []
for v in commands:
if isinstance(v, bytes):
v = v.decode(errors='replace')
v = v.split(';')[0].strip()
if len(v) != 0:
stripped_commands.append(v)
return stripped_commands | d2260c157de8b791af59fadaba380bbc06c6a30d | 691,049 |
def __merge2sorted__(arr1, arr2):
"""
Takes two sorted subarrays and returns a sorted array
"""
m, n = len(arr1), len(arr2)
aux_arr = [None] * (m + n)
p1 = 0
p2 = 0
c = 0
while p1 < m and p2 < n:
if arr1[p1] < arr2[p2]:
aux_arr[c] = arr1[p1]
p1 += 1
else:
aux_arr[c] = arr2[p2]
p2 += 1
c += 1
if p1 == m: # arr1 exhausted
while p2 < n:
aux_arr[c] = arr2[p2]
p2 += 1
c += 1
elif p2 == n: # arr2 exhausted
while p1 < m:
aux_arr[c] = arr1[p1]
p1 += 1
c += 1
return aux_arr | 292521702ba5b9f9237ca988c1e3f6091b0f142e | 691,051 |
def args_idx(x):
"""Get the idx of "?" in the string"""
return x.rfind('?') if '?' in x else None | 65a59f63ccad4e755731814850870f914968a060 | 691,052 |
from typing import Dict
from typing import Any
def userinfo_token(
token_subject: str,
token_idp: str,
token_ssn: str,
) -> Dict[str, Any]:
"""
Mocked userinfo-token from Identity Provider (unencoded).
"""
return {
'iss': 'https://pp.netseidbroker.dk/op',
'nbf': 1632389572,
'iat': 1632389572,
'exp': 1632389872,
'amr': ['code_app'],
'mitid.uuid': '7ddb51e7-5a04-41f8-9f3c-eec1d9444979',
'mitid.age': '55',
'mitid.identity_name': 'Anker Andersen',
'mitid.date_of_birth': '1966-02-03',
'loa': 'https://data.gov.dk/concept/core/nsis/Substantial',
'acr': 'https://data.gov.dk/concept/core/nsis/Substantial',
'identity_type': 'private',
'idp': token_idp,
'dk.cpr': token_ssn,
'auth_time': '1632387312',
'sub': token_subject,
'aud': '0a775a87-878c-4b83-abe3-ee29c720c3e7',
'transaction_id': 'a805f253-e8ea-4457-9996-c67bf704ab4a',
} | 976cadad107d5a167f169405e62d56e64b3f865e | 691,055 |
def homo_line(a, b):
"""
Return the homogenous equation of a line passing through a and b,
i.e. [ax, ay, 1] cross [bx, by, 1]
"""
return (a[1] - b[1], b[0] - a[0], a[0] * b[1] - a[1] * b[0]) | 44888650c16d2a48b2a60adaf9e9bd89e0a0de67 | 691,056 |
from unittest.mock import call
def get_local_jitter(sound, min_time=0., max_time=0., pitch_floor=75., pitch_ceiling=600.,
period_floor=0.0001, period_ceiling=0.02, max_period_factor=1.3):
"""
Function to calculate (local) jitter from a periodic PointProcess.
:param (parselmouth.Sound) sound: sound waveform
:param (float) min_time: minimum time value considered for time range (t1, t2) (default: 0.)
:param (float) max_time: maximum time value considered for time range (t1, t2) (default: 0.)
NOTE: If max_time <= min_time, the entire time domain is considered
:param (float) pitch_floor: minimum pitch (default: 75.)
:param (float) pitch_ceiling: maximum pitch (default: 600.)
:param (float) period_floor: the shortest possible interval that will be used in the computation
of jitter, in seconds (default: 0.0001)
:param (float) period_ceiling: the longest possible interval that will be used in the
computation of jitter, in seconds (default: 0.02)
:param (float) max_period_factor: the largest possible difference between consecutive intervals
that will be used in the computation of jitter (default: 1.3)
:return: value of (local) jitter
"""
# Create a PointProcess object
point_process = call(sound, 'To PointProcess (periodic, cc)',
pitch_floor, pitch_ceiling)
local_jitter = call(point_process, 'Get jitter (local)',
min_time, max_time,
period_floor, period_ceiling, max_period_factor)
return local_jitter | ba9302f7593f9d324193ba8be6b64982b515e878 | 691,057 |
def anchor_ctr_inside_region_flags(anchors, stride, region):
"""Get the flag indicate whether anchor centers are inside regions."""
x1, y1, x2, y2 = region
f_anchors = anchors / stride
x = (f_anchors[:, 0] + f_anchors[:, 2]) * 0.5
y = (f_anchors[:, 1] + f_anchors[:, 3]) * 0.5
flags = (x >= x1) & (x <= x2) & (y >= y1) & (y <= y2)
return flags | 5f1e3b764145a9ee8abb709cd43f7f99c8515eb7 | 691,059 |
def position_is_escaped(string, position=None):
"""
Checks whether a char at a specific position of the string is preceded by
an odd number of backslashes.
:param string: Arbitrary string
:param position: Position of character in string that should be checked
:return: True if the character is escaped, False otherwise
"""
escapes_uneven = False
# iterate backwards, starting one left of position.
# Slicing provides a sane default behaviour and prevents IndexErrors
for i in range(len(string[:position]) - 1, -1, -1):
if string[i] == '\\':
escapes_uneven = not escapes_uneven
else:
break
return escapes_uneven | 8fbaa26a6fb56f56819e5937a921efa3a6882627 | 691,062 |
def select_column_values(df, col_name="totale_casi", groupby=["data"], group_by_criterion="sum"):
"""
:param df: pandas dataFrame
:param col_name: column of interest
:param groupby: column to group by (optional) data.
:param group_by_criterion: how to merge the values of grouped elements in col_name.
Only sum supported.
:return: a list of of values
"""
if groupby is not None:
if group_by_criterion == "sum":
return df.groupby(by=groupby)[col_name].sum().reset_index()[col_name].values
else:
return RuntimeWarning
else:
return list(df[col_name]) | cb0d63fa3c29447353163ae8336eb42f6f454ced | 691,063 |
def normalize_min_max(x, x_min, x_max):
"""Normalized data using it's maximum and minimum values
# Arguments
x: array
x_min: minimum value of x
x_max: maximum value of x
# Returns
min-max normalized data
"""
return (x - x_min) / (x_max - x_min) | e31028c84603d0fc6d1ad00b768fb6373aee975c | 691,069 |
def get_orientation_from(pose):
""" Extract and convert the pose's orientation into a list.
Args:
pose (PoseStamped): the pose to extract the position from
Returns:
the orientation quaternion list [x, y, z, w]
"""
return [pose.pose.orientation.x,
pose.pose.orientation.y,
pose.pose.orientation.z,
pose.pose.orientation.w] | 2c3116c4070779511df54f0aafd488d22bc1c94b | 691,072 |
import string
def index_to_column(index):
"""
0ベース序数をカラムを示すアルファベットに変換する。
Params:
index(int): 0ベース座標
Returns:
str: A, B, C, ... Z, AA, AB, ...
"""
m = index + 1 # 1ベースにする
k = 26
digits = []
while True:
q = (m-1) // k
d = m - q * k
digit = string.ascii_uppercase[d-1]
digits.append(digit)
if m <= k:
break
m = q
return "".join(reversed(digits)) | 2d1b1018e91e3408aee7e8adbe51ea2e9867bd45 | 691,073 |
def _listen_count(opp):
"""Return number of event listeners."""
return sum(opp.bus.async_listeners().values()) | b342b040292ab846206d46210f834fef042af3b4 | 691,076 |
import math
def distance(point1, point2):
""" Calculates distance between two points.
:param point1: tuple (x, y) with coordinates of the first point
:param point2: tuple (x, y) with coordinates of the second point
:return: distance between two points in pixels
"""
return math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2)) | e38be3e5cc3418ab8c5edefb560e95e583dede21 | 691,082 |
from typing import List
from typing import Set
def scan_polarimeter_names(group_names: List[str]) -> Set[str]:
"""Scan a list of group names and return the set of polarimeters in it.
Example::
>>> group_names(["BOARD_G", "COMMANDS", "LOG", "POL_G0", "POL_G6"])
set("G0", "G6")
"""
result = set() # type: Set[str]
for curname in group_names:
if (len(curname) == 6) and (curname[0:4] == "POL_"):
result.add(curname[4:6].upper())
return result | d4ae998041401beb40df7746ec0afc2b98c9d6b1 | 691,084 |
def get_project_folders(window):
"""Get project folder."""
data = window.project_data()
if data is None:
data = {'folders': [{'path': f} for f in window.folders()]}
return data.get('folders', []) | d3bc83067e4acdf0df1a29891cebcb60422fe5e6 | 691,088 |
import textwrap
def dedented_lines(description):
"""
Each line of the provided string with leading whitespace stripped.
"""
if not description:
return []
return textwrap.dedent(description).split('\n') | 8a398b0afe6aa1f9cdf5f4ae386ecebef06bdd2b | 691,090 |
def behavior_get_required_inputs(self):
"""Return all required Parameters of type input for this Behavior
Note: assumes that type is all either in or out
Returns
-------
Iterator over Parameters
"""
return (p for p in self.get_inputs() if p.property_value.lower_value.value > 0) | 13063f7708d518928aed7556ca9da7a851de6622 | 691,091 |
def _AddNGrad(op, grad):
"""Copies the gradient to all inputs."""
# Not broadcasting.
return [grad] * len(op.inputs) | 9cbeee4a863b44e45475b4161fdc7b94f576005a | 691,097 |
def oneof(*args):
"""Returns true iff one of the parameters is true.
Args:
*args: arguments to check
Returns:
bool: true iff one of the parameters is true.
"""
return len([x for x in args if x]) == 1 | 14731b54f19658d25ca3e62af439d7d2000c1872 | 691,100 |
import warnings
from typing import Optional
from typing import Union
from typing import Type
from typing import cast
def _is_unexpected_warning(
actual_warning: warnings.WarningMessage,
expected_warning: Optional[Union[Type[Warning], bool]],
) -> bool:
"""Check if the actual warning issued is unexpected."""
if actual_warning and not expected_warning:
return True
expected_warning = cast(Type[Warning], expected_warning)
return bool(not issubclass(actual_warning.category, expected_warning)) | 7b4be666af4f963ef94758d5061224e2806b60ca | 691,101 |
import torch
def get_pose_loss(gt_pose, pred_pose, vis, loss_type):
"""
gt_pose: [B, J*2]
pred_pose: [B, J*2]
vis: [B, J]
Loss: L2 (MSE), or L1
"""
vis = torch.repeat_interleave(vis, 2, dim=-1) # [B, 1122...JJ]
if loss_type == "L2":
loss = torch.sum((gt_pose - pred_pose) ** 2 * vis, dim=-1) / torch.sum(vis, dim=-1) # [B]
elif loss_type == "L1":
loss = torch.sum(torch.abs(gt_pose - pred_pose) * vis, dim=-1) / torch.sum(vis, dim=-1) # [B]
else:
assert False, "Unknown loss type"
return loss | 2cedc132ec5e6fc9870ba3439b756d7b421486d6 | 691,102 |
def wrap_cdata(s: str) -> str:
"""Wraps a string into CDATA sections"""
s = str(s).replace("]]>", "]]]]><![CDATA[>")
return "<![CDATA[" + s + "]]>" | 861d086e77b02c354815da11278fc0c3b6297a68 | 691,103 |
def get_spacing_groups(font):
"""
Return a dictionary containing the ``left`` and ``right`` spacing groups in the font.
"""
_groups = {}
_groups['left'] = {}
_groups['right'] = {}
for _group in list(font.groups.keys()):
if _group[:1] == '_':
if _group[1:5] == 'left':
_groups['left'][_group] = font.groups[_group]
if _group[1:6] == 'right':
_groups['right'][_group] = font.groups[_group]
return _groups | 778a27b49ce9d869d7867774df8dfe22a3cd6140 | 691,106 |
def _get_gate_span(qregs, instruction):
"""Get the list of qubits drawing this gate would cover"""
min_index = len(qregs)
max_index = 0
for qreg in instruction.qargs:
index = qregs.index(qreg)
if index < min_index:
min_index = index
if index > max_index:
max_index = index
if instruction.cargs:
return qregs[min_index:]
return qregs[min_index:max_index + 1] | b85b1a0e5dd6691e9b460dea90cb205ce46227e9 | 691,107 |
def get_AP_parameters(exp):
"""
This function is connect with'Advanced Parameter' button.
Parameters
------
exp: the Ui_Experiment object
Return
------
AP_parameters: list contains all the advanced parameters
"""
conv_fact = float(exp.experiment_conversion_factor.text())
set_gain = float(exp.experiment_setpoint_gain.text())
set_offset = float(exp.experiment_setpoint_offset.text())
sr = float(exp.experiment_shunt_resistor.text())
ts = float(exp.experiment_time_step.text())
avg_num = int(exp.experiment_averag_number.text())
AP_parameters = [conv_fact, set_gain, set_offset, sr, ts,avg_num]
return AP_parameters | 079759600626e3c7cbb4fee882d1b9623a1f4a43 | 691,109 |
import requests
def read_data_json(typename, api, body):
"""
read_data_json directly accesses the C3.ai COVID-19 Data Lake APIs using the requests library,
and returns the response as a JSON, raising an error if the call fails for any reason.
------
typename: The type you want to access, i.e. 'OutbreakLocation', 'LineListRecord', 'BiblioEntry', etc.
api: The API you want to access, either 'fetch' or 'evalmetrics'.
body: The spec you want to pass. For examples, see the API documentation.
"""
response = requests.post(
"https://api.c3.ai/covid/api/1/" + typename + "/" + api,
json=body,
headers={
'Accept': 'application/json',
'Content-Type': 'application/json'
}
)
# if request failed, show exception
if response.status_code != 200:
raise Exception(response.json()["message"])
return response.json() | b0aed423512408efa97e0f5cf406bb442b876a3d | 691,110 |
def matrix_from_vectors(op, v):
"""
Given vector v, build matrix
[[op(v1, v1), ..., op(v1, vn)],
...
[op(v2, v1), ..., op(vn, vn)]].
Note that if op is commutative, this is redundant: the matrix will be equal to its transpose.
The matrix is represented as a list of lists.
"""
return [[op(vi, vj) for vj in v] for vi in v] | cfefaf9e66db33e993044b2cc609f25f89e103ea | 691,114 |
def create_user(connection, body, username, fields=None):
"""Create a new user. The response includes the user ID, which other
endpoints use as a request parameter to specify the user to perform an
action on.
Args:
connection(object): MicroStrategy connection object returned by
`connection.Connection()`.
body: JSON formatted user data;
{
"username": "string",
"fullName": "string",
"description": "string",
"password": "string",
"enabled": true,
"passwordModifiable": true,
"passwordExpirationDate": "2020-06-15T13:26:09.616Z",
"requireNewPassword": true,
"standardAuth": true,
"ldapdn": "string",
"trustId": "string",
"memberships": [
"string"
]
}
username(str): username of a user, used in error message
fields(list, optional): Comma separated top-level field whitelist. This
allows client to selectively retrieve part of the response model.
Returns:
HTTP response object returned by the MicroStrategy REST server.
"""
return connection.session.post(
url=f'{connection.base_url}/api/users',
params={'fields': fields},
json=body,
) | c4f11b3b39ba2a84417ca667ab1d66e978d33bd3 | 691,120 |
def plus_all(tem, sum):
"""
:param tem:int, the temperature user entered.
:param sum:int, the sum of temperatures user entered.
This function plus all temperatures user entered.
"""
return sum+tem | 187d81f2bbebc2a21e6a23a297c56550216141fa | 691,122 |
def check_input(saved_input):
"""Checks for yes and no awnsers from the user."""
if saved_input.lower() == "!yes":
return True
if saved_input.lower() == "!no":
return False | 8e0cb2613434a2e7dc00a758dd0df03cb8b06d36 | 691,124 |
def _get_fk_relations_helper(unvisited_tables, visited_tables,
fk_relations_map):
"""Returns a ForeignKeyRelation connecting to an unvisited table, or None."""
for table_to_visit in unvisited_tables:
for table in visited_tables:
if (table, table_to_visit) in fk_relations_map:
fk_relation = fk_relations_map[(table, table_to_visit)]
unvisited_tables.remove(table_to_visit)
visited_tables.append(table_to_visit)
return fk_relation
return None | fb2458437d16d94341f037ddf65347dc6d6169e4 | 691,127 |
import math
def phaseNearTargetPhase(phase,phase_trgt):
"""
Adds or subtracts 2*math.pi to get the phase near the target phase.
"""
pi2 = 2*math.pi
delta = pi2*int((phase_trgt - phase)/(pi2))
phase += delta
if(phase_trgt - phase > math.pi):
phase += pi2
return phase
if(phase_trgt - phase < -math.pi):
phase -= pi2
return phase | dbd1a7c291b47703fa64756c986815d2cf706677 | 691,132 |
def coding_problem_28(word_list, max_line_length):
"""
Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of
strings which represents each line, fully justified. More specifically, you should have as many words as possible
in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each
line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any,
distributed starting from the left. If you can only fit one word on a line, then you should pad the right-hand side
with spaces. Each word is guaranteed not to be longer than k.
Example:
>>> coding_problem_28(["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"], 16)
['the quick brown', 'fox jumps over', 'the lazy dog']
"""
lines = []
while word_list:
if len(word_list) == 1: # right-align ending word
lines.append('{:>{mll}}'.format(word_list[0], mll=max_line_length))
break
words = []
while len(' '.join(words + word_list[:1])) <= max_line_length and word_list:
words += word_list[:1]
word_list = word_list[1:]
total_spaces = max_line_length - sum(map(len, words))
gaps = len(words) - 1
gap_len = total_spaces // gaps
first_gap_add = total_spaces - gap_len * gaps
lines.append(words[0] + ' ' * (gap_len + first_gap_add) + (' ' * gap_len).join(words[1:]))
return lines | 59beff7b181730ab094f7f797128de9bfc83ef8b | 691,135 |
def truncate(value):
"""
Takes a float and truncates it to two decimal points.
"""
return float('{0:.2f}'.format(value)) | b47412443fa55e0fd9158879b3c0d85c5ecc7aad | 691,137 |
def open_file(filename, mode='r'):
"""
常用文件操作,可在python2和python3间切换.
mode: 'r' or 'w' for read or write
"""
return open(filename, mode, encoding='utf-8', errors='ignore') | 100179e22f140c4e8d25a1ccab94f9ca3831b5f3 | 691,138 |
def get_pubmed_ids_from_csv(ids_txt_filepath):
"""
Function retrieves PubMed ids from a csv file
:param ids_txt_filepath: String - Full file path including file name to txt file containing PubMed IDs
:return lines: List of PubMed article IDs
"""
with open(ids_txt_filepath, 'r') as file:
lines = file.read().split('\n')
return lines | 4f6f53eee0d14bb3beae27ac6f15f7c14b33dbe5 | 691,139 |
from typing import Dict
def parse_wspecifier(wspecifier: str) -> Dict[str, str]:
"""Parse wspecifier to dict
Examples:
>>> parse_wspecifier('ark,scp:out.ark,out.scp')
{'ark': 'out.ark', 'scp': 'out.scp'}
"""
ark_scp, filepath = wspecifier.split(":", maxsplit=1)
if ark_scp not in ["ark", "scp,ark", "ark,scp"]:
raise ValueError("{} is not allowed: {}".format(ark_scp, wspecifier))
ark_scps = ark_scp.split(",")
filepaths = filepath.split(",")
if len(ark_scps) != len(filepaths):
raise ValueError("Mismatch: {} and {}".format(ark_scp, filepath))
spec_dict = dict(zip(ark_scps, filepaths))
return spec_dict | cdd28f17387c43d475abdcf463dcd58bee2ede5c | 691,144 |
def get_nodes(graph, metanode):
"""
Return a list of nodes for a given metanode, in sorted order.
"""
metanode = graph.metagraph.get_metanode(metanode)
metanode_to_nodes = graph.get_metanode_to_nodes()
nodes = sorted(metanode_to_nodes[metanode])
return nodes | 1decea0c15425bdba58d8ab2a8735aaff8d44b98 | 691,145 |
def create_state_action_dictionary(env, policy: dict) -> dict:
"""
return initial Q (state-action) matrix storing 0 as reward for each action in each state
:param env:
:param policy: 2D dictionary of {state_index: {action_index: action_probability}}
:return: Q matrix dictionary of {state_index: {action_index: reward}}
"""
# Note: We use optimal action-value function instead of value function
# to cache the one-step-ahead searches (trade off space for time)
# initialize Q matrix
Q = {}
# traverse states in a policy
for key in policy.keys():
# for each state, assign each action 0 as reward
Q[key] = {a: 0.0 for a in range(0, env.action_space.n)}
return Q | cfa546add31b8668ba065a4635c041679bbe319a | 691,146 |
async def check_win(ctx, player_id, game):
"""Checks if the player has won the game"""
player = game.players[player_id]
if len(player.hand) == 0:
await ctx.send(f"Game over! {player.player_name} has won!")
return True
return False | cb3fb54f499f9127ebecbbed5cbfb0be518697cf | 691,147 |
def price_to_profit(lst):
"""
Given a list of stock prices like the one above,
return a list of of the change in value each day.
The list of the profit returned from this function will be our input in max_profit.
>>> price_to_profit([100, 105, 97, 200, 150])
[0, 5, -8, 103, -50]
>>> price_to_profit([205, 199, 188, 220, 235, 280, 301])
[0, -6, -11, 32, 15, 45, 21]
"""
profit = [lst[i+1] - lst[i] for i in range(len(lst) - 1)]
profit.insert(0, 0)
return profit | 5539c7c22f10c06199855e8c495221b111f67377 | 691,148 |
def upgrade(request):
"""Specify if upgrade test is to be executed."""
return request.config.getoption('--upgrade') | e52e3cd3af930f6867e6807bd7fa1402e1993b8c | 691,149 |
def _inlining_threshold(optlevel, sizelevel=0):
"""
Compute the inlining threshold for the desired optimisation level
Refer to http://llvm.org/docs/doxygen/html/InlineSimple_8cpp_source.html
"""
if optlevel > 2:
return 275
# -Os
if sizelevel == 1:
return 75
# -Oz
if sizelevel == 2:
return 25
return 225 | dd4a2ac54fc9dea53bf667095e41ca6d768a4627 | 691,151 |
def get_resampling_period(target_dts, cmip_dt):
"""Return 30-year time bounds of the resampling period.
This is the period for which the target model delta T
matches the cmip delta T for a specific year.
Uses a 30-year rolling window to get the best match.
"""
target_dts = target_dts.rolling(time=30, center=True,
min_periods=30).mean()
time_idx = abs(target_dts - cmip_dt).argmin(dim='time').values
year = target_dts.isel(time=time_idx).year.values.astype(int)
target_dt = target_dts.isel(time=time_idx).values.astype(float)
return [year - 14, year + 15], target_dt | d335fe1300703bc11ac3210d5ffce4b8c0ffd0f7 | 691,154 |
import struct
def read_data(file, endian, num=1):
"""
Read a given number of 32-bits unsigned integers from the given file
with the given endianness.
"""
res = struct.unpack(endian + "L" * num, file.read(num * 4))
if len(res) == 1:
return res[0]
return res | 74b58ea11d3818ce6bdd56ba04ee1d1d34e9913a | 691,156 |
def raw_values(y_true, y):
"""
Returns input value y. Used for numerical diagnostics.
"""
return y | 5ca341e6ed14899df6a51564ee2d8f8b90dae04b | 691,159 |
def default_filter(src,dst):
"""The default progress/filter callback; returns True for all files"""
return dst | 8b76498b6c740ec0a3c882fd42cdabbc6608ac25 | 691,161 |
def retrieve_channel(Client, UseNameOrId, Identifier):
"""Returns a channel object based or either name or Id.
"""
text_channel_object = None
for channel in Client.get_all_channels():
if UseNameOrId == 'id':
if channel.id == Identifier:
text_channel_object = channel
break
else:
if channel.name == Identifier:
text_channel_object = channel
break
return text_channel_object | 0a70268583f87dc088f3a3154d43b70830bb2680 | 691,162 |
def with_subfolder(location: str, subfolder: str):
"""
Wrapper to appends a subfolder to a location.
:param location:
:param subfolder:
:return:
"""
if subfolder:
location += subfolder + '/'
return location | 9c5c50e08ff6e2b250ac25bc317df834c359a1f3 | 691,163 |
from typing import Callable
def pow_util(gamma: float) -> Callable[[float], float]:
"""
べき乗関数的な効用関数を返します。
Parameters
----------
gamma: float
実指数
Returns
-------
Callable[[float], float]
x >= 0 について、u(x) = x^{1 - gamma} / (1 - gamma) を満たす効用関数u
"""
def u(x: float) -> float:
return x ** (1 - gamma) / (1 - gamma)
return u | 39a1e134f5fc22c406c823387a7b51e8370b79b4 | 691,169 |
def get_ports(svc_group, db):
"""Gets the ports and protocols defined in a service group.
Args:
svc_group: a list of strings for each service group
db: network and service definitions
Returns:
results: a list of tuples for each service defined, in the format:
(service name, "<port>/<protocol>")
"""
results = []
for svc in svc_group:
port = db.GetService(svc)
results.append((svc, port))
return results | 04502215d32742465a9b22c8630997f00016b236 | 691,171 |
def run(capsys, mocker):
"""CLI run method fixture
To use:
run(meth, *args, input_side_effect=['first', 'second', 'last'])
run(meth, *args, input_return_value='42')
This would run the method `meth` with arguments `*args`.
In the first every time `builtins.input()` is called by `meth`, the next
element of input_side_effect will be returned
In the second every invokation of 'buitins.input()' returns '42'.
Both return a tuple of three items, mocked-input, stdout, and stderr.
"""
def _do_run(method, *args, **kwargs):
mocked_input = mocker.patch('builtins.input')
if 'input_side_effect' in kwargs:
mocked_input.side_effect = kwargs['input_side_effect']
del kwargs['input_side_effect']
if 'input_return_value' in kwargs:
mocked_input.return_value = kwargs['input_return_value']
del kwargs['input_return_value']
method(*args, **kwargs)
captured = capsys.readouterr()
return captured.out, captured.err, mocked_input
return _do_run | f82905e8a8cca0fedbb64c896efd52e3a8c0add3 | 691,174 |
def add_spaces(x):
"""Add four spaces to every line in x
This is needed to make html raw blocks in rst format correctly
"""
y = ''
if isinstance(x, str):
x = x.split('\n')
for q in x:
y += ' ' + q
return y | 8443f4d019022b1e4705abbeca5bbd54bc94699d | 691,179 |
def tsorted(a):
"""Sort a tuple"""
return tuple(sorted(a)) | 8b2f4946453759447258fb3c437a9babd2c3e92a | 691,180 |
def ignores_leakcheck(func):
"""
Ignore the given object during leakchecks.
Can be applied to a method, in which case the method will run, but
will not be subject to leak checks.
If applied to a class, the entire class will be skipped during leakchecks. This
is intended to be used for classes that are very slow and cause problems such as
test timeouts; typically it will be used for classes that are subclasses of a base
class and specify variants of behaviour (such as pool sizes).
"""
func.ignore_leakcheck = True
return func | 7947a760db8f065fcf6a6d980db57cb1aa5fd2d2 | 691,183 |
def or_condition(field, op, seq):
""" Return an 'or' condition of the format:
((field, ('op seq[0]', 'op seq[1]'...), )
Example
-------
>>> or_condition('tag', 'has', ('Web', 'Case Study', 'Testing'))
>>> ('tag', ('has Web', 'has Case Study', 'has Testing'),
"""
return ((field, tuple(["{} {}".format(op, tag) for tag in seq])),) | dac40cec3ddac98d59676a6b713be59ea7ca1af7 | 691,184 |
def generate_projwfc_node(generate_calc_job_node, fixture_localhost, tmpdir):
"""Fixture to constructure a ``projwfc.x`` calcjob node for a specified test."""
def _generate_projwfc_node(test_name):
"""Generate a mock ``ProjwfcCalculation`` node for testing the parsing.
:param test_name: The name of the test folder that contains the output files.
"""
entry_point_calc_job = 'quantumespresso.projwfc'
retrieve_temporary_list = ['data-file-schema.xml']
attributes = {'retrieve_temporary_list': retrieve_temporary_list}
node = generate_calc_job_node(
entry_point_name=entry_point_calc_job,
computer=fixture_localhost,
test_name=test_name,
attributes=attributes,
retrieve_temporary=(tmpdir, retrieve_temporary_list)
)
return node
return _generate_projwfc_node | 9e167013a320e6b69d0121a820ea62efc9fc9f92 | 691,185 |
def to_fixed_point(val: float, precision: int) -> int:
"""
Converts the given value to fixed point representation with the provided precision.
"""
return int(val * (1 << precision)) | 182cd3b94679dab3c0247c2478029750f1fd6753 | 691,186 |
from typing import Any
from typing import Optional
def try_int(value: Any) -> Optional[int]:
"""Convert a value to an int, if possible, otherwise ``None``"""
return int(str(value)) if str(value).isnumeric() else None | ced219e25a66286df327dd41a85f328c5bc28ec4 | 691,187 |
def pre_process_tags(paragraph_element):
"""
Convert initial italics-tagged text to markdown bold
and convert the rest of a paragraph's I tags to markdown italics.
"""
first_tag = paragraph_element.find("I")
if first_tag:
bold_content = first_tag.text
first_tag.replaceWith("**{}**".format(bold_content))
for element in paragraph_element.find_all("I"):
i_content = element.text
element.replaceWith("*{}*".format(i_content))
return paragraph_element | 2db70456626a50111c664959a5c6591770567bd2 | 691,189 |
def limit_versions(language, limit, operator):
"""
Limits given languages with the given operator:
:param language:
A `Language` instance.
:param limit:
A number to limit the versions.
:param operator:
The operator to use for the limiting.
:return:
A new `Language` instance with limited versions.
:raises ValueError:
If no version is left anymore.
"""
if isinstance(limit, int):
versions = [version for version in language.versions
if operator(int(version), limit)]
else:
versions = [version for version in language.versions
if operator(version, limit)]
if not versions:
raise ValueError('No versions left')
return type(language)(*versions) | 77a7780ca5b6b9e706ebb39c1b39239fae8269be | 691,190 |
import threading
def threaded_fn(func):
"""
A decorator for any function that needs to be run on a separate thread
"""
def wrapper(*args, **kwargs):
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.start()
return thread
return wrapper | de72cc698cbbb2404e853930fcf848f2b05bff20 | 691,196 |
import re
def replace_links(text, link_patterns):
"""
A little function that will replace string patterns in text with
supplied hyperlinks. 'text' is just a string, most often a field
in a django or flask model. link_pattern is a list of two element
dictionaries. Each dicationary must have keys 'pattern' and
'url'. 'pattern' is the regular expression to apply to the text
while url is the text to be used as its replacement. Regular
expression call backs are supported. See the python documentation
for re.sub for more details.
Note: The function does not make any attempt to validate the link or
the regex pattern.
"""
for pattern in link_patterns:
regex = re.compile(pattern.get("pattern"), re.IGNORECASE)
if "project:" in pattern.get("pattern"):
# mark down replace _ with ems - replace them first:
text = re.sub(r"</?em>", "_", text)
prj_codes = regex.findall(text)
for x in prj_codes:
link = pattern["url"]
href = link.format(x.lower(), x.upper())
text = text.replace(x, href)
else:
text = re.sub(regex, pattern["url"], text)
return text | 087bfc736d2c859fdd6828255993de52af935e45 | 691,199 |
def input_action(i, _):
"""Returns the input that matched the transition"""
return i | fff447c9d049f335e485f35ab4925879b72ee585 | 691,200 |
def byteToHex( byteStr ):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
# Uses list comprehension which is a fractionally faster implementation than
# the alternative, more readable, implementation below
#
# hex = []
# for aChar in byteStr:
# hex.append( "%02X " % ord( aChar ) )
#
# return ''.join( hex ).strip()
return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip() | b599eb3e24495c8f2dc76c4b83c1d71c0919c599 | 691,201 |
def split(p):
"""Split a pathname. Returns tuple "(head, tail)" where "tail" is
everything after the final slash. Either part may be empty."""
i = p.rfind('/') + 1
head, tail = p[:i], p[i:]
if head and head != '/'*len(head):
head = head.rstrip('/')
return head, tail | ae48332005fe4fe490702bd0f514190dbf856c93 | 691,203 |
def isvalid(ctx, a):
""" Test if an identifier is known.
Returns a string '1' if valid, '0' otherwise.
"""
plotid = a.plotid()
return "%d" % (1 if ctx.isvalid(plotid) else 0) | c2b433bd4f0a4e4d0ce9443d55e659b1dc96321a | 691,214 |
def listbox_identify(listbox, y):
"""Returns the index of the listbox item at the supplied (relative) y
coordinate"""
item = listbox.nearest(y)
if item != -1 and listbox.bbox(item)[1] + listbox.bbox(item)[3] > y:
return item
return None | a378f792b9274a03895e4a646a9418e594e5537f | 691,218 |
def _s_(n: int) -> str:
"""Return spaces."""
return " " * n | 028098a8971f690b55dd60ffb8e235a8b4244c63 | 691,223 |
import math
def taylor_exp(x, accuracy=20):
"""
A function to get e^x.
It uses the taylor expansion of e^x.
## https://en.wikipedia.org/wiki/Exponential_function ##
Be aware that this loses accuracy fairly quickly.
Accuracy can be somewhat increased, but there is a limit
to how large integers can be turned to floats.
e^x = 1 + x + x^2/2! + x^3/3! + x^4/4!...
"""
result = 0
for i in range(0, accuracy, 1):
result += math.pow(x, i) / math.factorial(i)
return result | 68db3f3164fee700c76fafcd312eae0bd4012744 | 691,226 |
def get_true_graph(env):
"""Given an environment, unwrap it until there is an attribute .true_graph."""
if hasattr(env, 'true_graph'):
g = env.true_graph
assert hasattr(g, 'As')
return g
elif hasattr(env, 'env'):
return get_true_graph(env.env)
else:
return None | efbd530f2aa460af1d649d286678ac2dce7954e2 | 691,229 |
def register(dmm, typecls):
"""Used as decorator to simplify datamodel registration.
Returns the object being decorated so that chaining is possible.
"""
def wraps(fn):
dmm.register(typecls, fn)
return fn
return wraps | c8ee7372ee4f651015f26bc67e93d529c6a580c0 | 691,230 |
def build_source_url(username, repository):
"""
Create valid GitHub url for a user's repository.
:param str username: username of the repository owner
:param str repository: name of the target repository
"""
base_url = 'https://github.com/{username}/{repository}'
return base_url.format(username=username, repository=repository) | 511a29a9bf7625e3b580880d264df78f80bef8c6 | 691,232 |
def _type_name(obj: object) -> str:
"""Get type name."""
return type(obj).__qualname__ | 0ced2627eaf459c09daaa4e92d4686a58188b5a3 | 691,233 |
def log_function(func):
"""
A decorator to log arguments of function
"""
fname = func.__code__.co_name
arg_names = func.__code__.co_varnames
def echo_func(*args, **kwargs):
"""
Echoes the function arguments
"""
print("[!]", fname + ": ", ", ".join("%s=%r" % entry for entry in zip(arg_names, args)))
return func(*args, **kwargs)
return echo_func | 5fb1657209f5fe105a315ecd08b909b157eef1db | 691,239 |
def clamp(minValue, maxValue, value):
"""Make sure value is between minValue and maxValue"""
if value < minValue:
return minValue
if value > maxValue:
return maxValue
return value | 17a7d58f441143ec77c965b1c8cd9eb5a70f1372 | 691,240 |
def reconstruct_pod(coeffs, R):
"""
Reconstruct grid from POD coefficients and transormation matrix R.
Args:
coeffs (np.array): POD coefficients
R (np.array): Transformation matrix R
Returns:
np.array: Reconstructed grid
"""
return R @ coeffs | d13dd1aca6f7ffee6a805d50e94883d6ec58b0bc | 691,244 |
def cube_to_axial(c):
"""
Converts a cube coord to an axial coord.
:param c: A cube coord x, z, y.
:return: An axial coord q, r.
"""
x, z, _ = c
return x, z | 39c614c072b4e886e3ae3f6a2c8ecd40918cff8d | 691,245 |
from typing import Dict
from typing import Union
def _are_agent_locations_equal(
ap0: Dict[str, Union[float, int, bool]],
ap1: Dict[str, Union[float, int, bool]],
ignore_standing: bool,
tol=1e-2,
ignore_y: bool = True,
):
"""Determines if two agent locations are equal up to some tolerance."""
def rot_dist(r0: float, r1: float):
diff = abs(r0 - r1) % 360
return min(diff, 360 - diff)
return (
all(
abs(ap0[k] - ap1[k]) <= tol
for k in (["x", "z"] if ignore_y else ["x", "y", "z"])
)
and rot_dist(ap0["rotation"], ap1["rotation"]) <= tol
and rot_dist(ap0["horizon"], ap1["horizon"]) <= tol
and (ignore_standing or (ap0["standing"] == ap1["standing"]))
) | 0bcdf03a128a6df1f3be653c74355c00c0097692 | 691,246 |
import time
def retry_function(function, action_name, err_msg,
max_retries=4, retry_delay=60):
"""Common utility to retry calling a function with exponential backoff.
:param function: The function to call.
:type function: function
:param action_name: The name of the action being performed.
:type action_name: str
:param err_msg: The error message to display if the function fails.
:type err_msg: str
:param max_retries: The maximum number of retries.
:type max_retries: int
:param retry_delay: The delay between retries.
:type retry_delay: int
:return: The result of the function call. May be None if function
does not return a result.
:rtype: object
"""
for i in range(max_retries):
try:
print("{0} attempt {1} of {2}".format(
action_name, i + 1, max_retries))
result = function()
break
except Exception as e:
print("{0} attempt failed with exception:".format(action_name))
print(e)
if i + 1 != max_retries:
print("Will retry after {0} seconds".format(retry_delay))
time.sleep(retry_delay)
retry_delay = retry_delay * 2
else:
raise RuntimeError(err_msg)
return result | b9c628f4940e204187771996e676975f90f782e7 | 691,250 |
import json
from io import StringIO
def generate_validation_error_report(e, json_object, lines_before=7, lines_after=7):
"""
Generate a detailed report of a schema validation error.
'e' is a jsonschema.ValidationError exception that errored on
'json_object'.
Steps to discover the location of the validation error:
1. Traverse the json object using the 'path' in the validation exception
and replace the offending value with a special marker.
2. Pretty-print the json object indendented json text.
3. Search for the special marker in the json text to find the actual
line number of the error.
4. Make a report by showing the error line with a context of
'lines_before' and 'lines_after' number of lines on each side.
"""
if json_object is None:
return "'json_object' cannot be None."
if not e.path:
if e.schema_path and e.validator_value:
return "Toplevel:\n\t{}".format(e.message)
else:
return str(e)
marker = "3fb539deef7c4e2991f265c0a982f5ea"
# Find the object that is erroring, and replace it with the marker.
ob_tmp = json_object
for entry in list(e.path)[:-1]:
ob_tmp = ob_tmp[entry]
orig, ob_tmp[e.path[-1]] = ob_tmp[e.path[-1]], marker
# Pretty print the object and search for the marker.
json_error = json.dumps(json_object, indent=4)
io = StringIO(json_error)
errline = None
for lineno, text in enumerate(io):
if marker in text:
errline = lineno
break
if errline is not None:
# Re-create report.
report = []
ob_tmp[e.path[-1]] = orig
json_error = json.dumps(json_object, indent=4)
io = StringIO(json_error)
for lineno, text in enumerate(io):
if lineno == errline:
line_text = "{:4}: >>>".format(lineno + 1)
else:
line_text = "{:4}: ".format(lineno + 1)
report.append(line_text + text.rstrip("\n"))
report = report[max(0, errline - lines_before):errline + 1 + lines_after]
s = "Error in line {}:\n".format(errline + 1)
s += "\n".join(report)
s += "\n\n" + str(e).replace("u'", "'")
else:
s = str(e)
return s | ccba131c6e524ee0a990bdd6dc440248d3684ac2 | 691,253 |
def set_first_line(img, pixels):
"""Set the first line of an image with the given pixel values."""
for index, pixel in enumerate(pixels):
img.set_pixel(index, 0, pixel)
return img | c87f5cf42591443c06b6b352c9f65cb898cfccf2 | 691,254 |
def istype(obj, allowed_types):
"""isinstance() without subclasses"""
if isinstance(allowed_types, (tuple, list, set)):
return type(obj) in allowed_types
return type(obj) is allowed_types | 5c441a69030be82e4d11c54ea366ee3463d388c8 | 691,257 |
def scale3D(v,scale):
"""Returns a scaled 3D vector"""
return (v[0] * scale, v[1] * scale, v[2] * scale) | 61ce41b706d1f9aadb9241c87ebd6c0757def159 | 691,259 |
def tokenize(chars):
"""Convert a string of characters into a list of tokens."""
# Idea from http://norvig.com/lispy.html
line = chars.replace(
'[', ' [ ').replace(']', ' ] ').replace(',', ' ').split()
for i, v in enumerate(line):
if v != '[' and v != ']':
line[i] = int(v)
return(line) | 742b3594ca94cc8ea163a5879074a686f3bc7769 | 691,262 |
from typing import Tuple
def clean_version(package) -> Tuple[str, str, str]:
""" Splits the module from requirments to the tuple: (pkg, cmp_op, ver) """
separators = ["==", ">=", "<=", "!="]
for s in separators:
if s in package:
return package.partition(s)
return (package, "", "") | 4606a5b976ca2bfe6eca9e54e40564f42e451b1e | 691,264 |
def get_gate_info(gate):
"""
gate: str, string gate. ie H(0), or "cx(1, 0)".
returns: tuple, (gate_name (str), gate_args (tuple)).
"""
gate = gate.strip().lower().replace("cnot", "cx")
i = gate.index("(")
gate_name, gate_args = gate[:i], eval(gate[i:])
try: len(gate_args)
except TypeError: gate_args = gate_args,
return gate_name, gate_args | 48f75c184c441d8884ae691db2af3a90684d574c | 691,266 |
import random
def PickFromPool(n, pool, a_as_set):
"""Returns n items from the pool which do not appear in a_as_set.
Args:
n: number of items to return.
pool: an sequence of elements to choose from.
a_as_set: a set of elements which should not appear in the result.
Returns:
List of n items from the pool which do not appear in a_as_set.
"""
assert isinstance(a_as_set, set)
# Remove the ones that are in A.
filtered_pool = list(filter(lambda x: x not in a_as_set, pool))
# Pick N random numbers out of the pool.
return random.sample(filtered_pool, k=n) | e856772b02232fefe84366d0399900e79fd07adb | 691,267 |
def query_for_message_ids(service, search_query):
"""searching for an e-mail (Supports the same query format as the Gmail search box.
For example, "from:someuser@example.com rfc822msgid:<somemsgid@example.com>
is:unread")
"""
result = service.messages().list(userId='me', q=search_query).execute()
results = result.get('messages')
if results:
msg_ids = [r['id'] for r in results]
else:
msg_ids = []
return msg_ids | a973708e211feb5f77a3b8dfcf65df43535a9f44 | 691,268 |
def trim(s):
"""Trim string to fit on terminal (assuming 80-column display)"""
return s if len(s) <= 80 else s[:77] + "..." | b3c2236b902bf20e0f2e4e7c97cfb57487ec1031 | 691,271 |
def euler(Tn, dTndt, tStep):
"""
Performs Euler integration to obtain T_{n+1}.
Arguments:
Tn: Array-like representing Temperature at time t_n.
dTndt: Array-like representing dT/dt at time t_n.
tStep: Float determining the time to step over.
Returns T_{n+1} as an array-like.
"""
return Tn + dTndt * tStep | 12a89ba6c777880ab20cfe04ecd13a6ab2ecc601 | 691,273 |
def get_opts(options):
"""
Args:
options: options object.
Returns:
args (tuple): positional options.
kwargs (map): keyword arguments.
"""
if isinstance(options, tuple):
if len(options) == 2 and isinstance(options[-1], dict):
args, kwargs = options
else:
args = options
kwargs = {}
elif isinstance(options, dict):
args, kwargs = (), options
else:
raise ValueError("Options object expected to be either pair of (args, kwargs) or only args/kwargs")
return args, kwargs | 3bc8f06e66b9c3d8b8b7cbc3e67087bcfe9fd7da | 691,278 |
from pathlib import Path
def count_files(path, glob=None) -> int:
"""Return the number of files in a given directory."""
path = Path(path)
files = path.glob(glob) if glob else path.iterdir()
return sum(1 for file in files if file.is_file()) | 39d10368c8e6a073a0dca290b74520a177244a2b | 691,279 |
def arkToInfo(ark):
"""
Turn an ark id into an info: uri
"""
parts = ark.split("ark:", 1)
if len(parts) != 2:
return ark
return "info:ark%s" % parts[1] | 38295232ea4bc649d28e6bd35e9ff4eee1dc4045 | 691,280 |
import torch
def create_rectified_fundamental_matrix(batch_size):
"""Creates a batch of rectified fundamental matrices of shape Bx3x3"""
F_rect = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)
F_repeat = F_rect.repeat(batch_size, 1, 1)
return F_repeat | f641d914a6d0cf91e7e07ffc619b70dc1e4381a0 | 691,284 |
def get_midpoint(origin, destination):
""" Return the midpoint between two points on cartesian plane.
:param origin: (x, y)
:param destination: (x, y)
:return: (x, y)
"""
x_dist = destination[0] + origin[0]
y_dist = destination[1] + origin[1]
return x_dist / 2.0, y_dist / 2.0 | d1a0f2a476efe66688d2a686febc0a3d0a94caaa | 691,287 |
def _ReplaceNameByUuidProcessLine(
node_name, _key, line_identifier, line_key, found, node_uuid=None):
"""Replaces a node's name with its UUID on a matching line in the key file.
This is an auxiliary function for C{_ManipulatePublicKeyFile} which processes
a line of the ganeti public key file. If the line in question matches the
node's name, the name will be replaced by the node's UUID.
@type node_name: string
@param node_name: name of the node to be replaced by the UUID
@type _key: string
@param _key: SSH key of the node (not used)
@type line_identifier: string
@param line_identifier: an identifier of a node in a line of the public key
file. This can be either a node name or a node UUID, depending on if it
got replaced already or not.
@type line_key: string
@param line_key: SSH key of the node whose line is processed
@type found: boolean
@param found: whether or not the line matches the node's name
@type node_uuid: string
@param node_uuid: the node's UUID which will replace the node name
@rtype: (boolean, string)
@return: a tuple indicating whether the target line was found and the
processed line
"""
if node_name == line_identifier:
return (True, "%s %s\n" % (node_uuid, line_key))
else:
return (found, "%s %s\n" % (line_identifier, line_key)) | eb4bc4d320cbbde7d0d56032f0c071629cdb81c3 | 691,291 |
def quality_index(dat, colname):
"""Return the index for `colname` in `dat`"""
colname = colname.split(':')[0]
return list(dat.dtype.names).index(colname) | d13f89bd6da6ea09637433d2ed7c6378a738a6cf | 691,293 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.