content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getHRLanguages(fname, hrthreshold=0):
"""
:param fname: the name of the file containing filesizes. Created using wc -l in the wikidata folder
:param hrthreshold: how big a set of transliteration pairs needs to be considered high resource
:return: a list of language names (in ISO 639-3 format?)
"... | 33,000 |
def test_model_with_single_repo_is_valid():
"""
Model may have only one OS repository and be valid
"""
repos = [AutoinstallMachineModel.OsRepository(
'os-repo', 'http://example.com/os', '/kernel', '/initrd', None,
'os', 'Default OS repo')]
model = AutoinstallMachineModel(DEFAULT_OS,... | 33,001 |
def test_preorder():
"""PreOrderIter."""
f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)
d = Node("d", parent=b)
c = Node("c", parent=d)
e = Node("e", parent=d)
g = Node("g", parent=f)
i = Node("i", parent=g)
h = Node("h", parent=i)
eq_(list(PreOrderIter(f)), [... | 33,002 |
def _wrap(func, *args, **kwargs):
"""To do."""
def _convert(func_, obj):
try:
return func_(obj)
except BaseException:
return obj
# First, decode each arguments
args_ = [_convert(decode, x) for x in args]
kwargs_ = {k: _convert(decode, v) for k, v in kwargs.i... | 33,003 |
def make_id_graph(xml):
"""
Make an undirected graph with CPHD identifiers as nodes and edges from correspondence and hierarchy.
Nodes are named as {xml_path}<{id}, e.g. /Data/Channel/Identifier<Ch1
There is a single "Data" node formed from the Data branch root that signifies data that can be read from... | 33,004 |
def LOG_INFO(msg):
"""
print information with green color
"""
print('\033[32m' + msg + '\033[0m') | 33,005 |
def aes_base64_encrypt(data, key):
"""
@summary:
1. pkcs7padding
2. aes encrypt
3. base64 encrypt
@return:
string
"""
cipher = AES.new(key)
return base64.b64encode(cipher.encrypt(_pkcs7padding(data))) | 33,006 |
def write_results(prediction, confidence, num_classes, nms_thresh = 0.4):
"""
@prediction salida de la red neural
@confidence objectness
@nms_conf non maximum supression confidence
@description En base a la confianza de la prediccion y las clases se devuelve
la prediccion final de la red, luego... | 33,007 |
def es_indexing(builder) -> int:
"""indexing all examples in lsc4 dict
TODO: 性能很差,indexing动作应该放在解析mdx文件的时候
:param builder dict builder
"""
# create index
if not create_index():
return 0
print("es is connected and index created succeed, starting indexing the examples...")
conn = s... | 33,008 |
def test_quote_arg(unquote_home_dir):
"""should correctly quote arguments passed to the shell"""
quoted_arg = swb.quote_arg('a/b c/d')
nose.assert_equal(quoted_arg, '\'a/b c/d\'')
unquote_home_dir.assert_called_once_with('\'a/b c/d\'') | 33,009 |
def import_data(users, agencies, filename):
"""Import data from CSV file."""
if users:
Users.populate(csv_name=filename)
elif agencies:
Agencies.populate(csv_name=filename) | 33,010 |
def mast_query_darks(instrument, aperture, start_date, end_date):
"""Use ``astroquery`` to search MAST for dark current data
Parameters
----------
instrument : str
Instrument name (e.g. ``nircam``)
aperture : str
Detector aperture to search for (e.g. ``NRCA1_FULL``)
start_date... | 33,011 |
def randomNumGen(choice):
"""Get a random number to simulate a d6, d10, or d100 roll."""
if choice == 1: #d6 roll
die = random.randint(1, 6)
elif choice == 2: #d10 roll
die = random.randint(1, 10)
elif choice == 3: #d100 roll
die = random.randint(1, 100)
elif choice == 4: ... | 33,012 |
def schedule_job_with_distance_matrix(request):
"""
:param request: HTTP request with following fields:
- distance_matrix: dictionary where keys correspond to node ids and values to coordinates.
- first_node: integer - id of the first node
:return:
"""
request_dict = json.loads(request.read... | 33,013 |
def download_all():
"""Download all files in the DATA_HUB."""
for name in DATA_HUB:
download(name) | 33,014 |
def is_distinct(coll, key=EMPTY):
"""Checks if all elements in the collection are different."""
if key is EMPTY:
return len(coll) == len(set(coll))
else:
return len(coll) == len(set(xmap(key, coll))) | 33,015 |
def split_data(df_data, config, test_frac=0.2):
"""
split df_data to train and test.
"""
df_train, df_test = train_test_split(df_data, test_size=test_frac)
df_train.reset_index(inplace=True, drop=True)
df_test.reset_index(inplace=True, drop=True)
df_train.to_csv(config.path_train_data, index... | 33,016 |
def query(params, lang='en'):
"""
Simple Mediawiki API wrapper
"""
url = 'https://%s.wikipedia.org/w/api.php' % lang
finalparams = {
'action': 'query',
'format': 'json',
}
finalparams.update(params)
resp = requests.get(url, params=finalparams)
if not resp.ok:
... | 33,017 |
def reporting_window(year, month):
"""
Returns the range of time when people are supposed to report
"""
last_of_last_month = datetime(year, month, 1) - timedelta(days=1)
last_bd_of_last_month = datetime.combine(
get_business_day_of_month(last_of_last_month.year, last_of_last_month.month, -1)... | 33,018 |
def df_destroyer(df):
"""destroys a df"""
# TODO - implement a destroyer
pass | 33,019 |
def load_json(path: str) -> Dict[str, Any]:
"""Loads a `.json` file from `path`.
Args:
path (str): Path to file.
Returns:
Dict[str, Any]: Returns the loaded json.
Example:
>>> # Load a json file
>>> load_json('mlnext.json')
{'name': 'mlnext'}
"""
if no... | 33,020 |
def test_newcollection(runner, input_dir):
"""Test newcoll command."""
result = runner.invoke(
main,
[
"--url",
"mock://example.com/",
"--email",
"test@test.mock",
"--password",
"1234",
"newcollection",
... | 33,021 |
def _ensure_accepted_tags(builds: List[Dict], brew_session: koji.ClientSession, tag_pv_map: Dict[str, str], raise_exception: bool = True):
"""
Build dicts returned by koji.listTagged API have their tag names, however other APIs don't set that field.
Tag names are required because they are associated with Er... | 33,022 |
def fit_cluster_13():
"""Fit a GMM to resolve objects in cluster 13 into C, Q, O.
Returns
-------
sklearn.mixture.GaussianMixture
The mixture model trained on the latent scores.
list
The classes represented in order by the model components.
"""
data = classy.data.load()
... | 33,023 |
def sidebar_left(request):
"""
Return the left sidebar values in context
"""
if request.user.is_authenticated():
moderation_obj = {
'is_visible': False,
'count_notifs': 0,
}
if request.user.is_staff:
moderation_obj['is_visible'] = True
... | 33,024 |
async def test_init_entry(hass, generic_data):
"""Test setting up config entry."""
await setup_ozw(hass, fixture=generic_data)
# Verify integration + platform loaded.
assert "ozw" in hass.config.components
for platform in PLATFORMS:
assert platform in hass.config.components, platform
... | 33,025 |
def addAttribute(p, value, run, data):
""" add a particular attribute to the run object. p is a string with the type
value is a string that contains the value to add, run is the run object, data
is the data object and badValue is a function that takes the run name, the
bad value's string name, the value, and th... | 33,026 |
def get_edge_lengths(vertices, edge_points):
"""
get edge squared length using edge_points from get_edge_points(mesh) or edge_vertex_indices(faces)
:params
vertices (N,3)
edge_points (E,4)
"""
N, D = vertices.shape
E = edge_points.shape[0]
# E,2,D (OK to do this ki... | 33,027 |
def compute_pca(nparray):
"""
:param nparray: nxd array, d is the dimension
:return: evs eigenvalues, axmat dxn array, each column is an eigenvector
author: weiwei
date: 20200701osaka
"""
ca = np.cov(nparray, y=None, rowvar=False, bias=True) # rowvar row=point, bias biased covariance
pc... | 33,028 |
def fac(num):
"""求阶乘"""
assert num >= 0
if num in (0, 1):
return 1
return num * fac(num - 1) | 33,029 |
def test_doc_example():
"""Text examples given in documentation"""
assert color('my string', fg='blue') == \
'\x1b[34mmy string\x1b[0m'
assert color('some text', fg='red', bg='yellow', style='underline') == \
'\x1b[31;43;4msome text\x1b[0m' | 33,030 |
def create_rep_avg_plot(plot_data, title, xlab, ylab, xlims, figname, add_line=False):
"""Create plot with replicates on same y-value with line showing average.
Inputs: plot_data - list of tuples in form (entry name, entry value)
title - title of plot
xlab - x-a... | 33,031 |
def entropy(logp, p):
"""Compute the entropy of `p` - probability density function approximation.
We need this in order to compute the entropy-bonus.
"""
H = -(logp * p).sum(dim=1).mean()
return H | 33,032 |
def main():
"""
Method main, set output dir and call a specific function, as given in the options
:param argv:
:return: None
"""
config2 = ConfigParser()
stream = resource_stream('drf_gen','config.ini')
cg = stream.read().decode()
#config2.read(resource_stream('drf_gen', 'config.ini'... | 33,033 |
def find(query):
"""Retrieve *exactly* matching tracks."""
args = _parse_query(query)
return mpctracks('find', args) | 33,034 |
def permuteregulations(graph):
"""Randomly change which regulations are repressions, maintaining activation and repression counts and directions."""
edges = list(graph.edges)
copy = graph.copy()
repressions = 0
for edge in edges:
edge_data = copy.edges[edge]
if edge_data['repress']:
... | 33,035 |
def handle_tokennetwork_new2(raiden, event, current_block_number):
""" Handles a `TokenNetworkCreated` event. """
data = event.event_data
token_network_address = data['token_network_address']
token_network_registry_address = event.originating_contract
token_network_registry_proxy = raiden.chain.tok... | 33,036 |
def editor_command(command):
"""
Is this an external editor command?
:param command: string
"""
# It is possible to have `\e filename` or `SELECT * FROM \e`. So we check
# for both conditions.
return command.strip().endswith('\\e') or command.strip().startswith('\\e ') | 33,037 |
def blrObjFunction(initialWeights, *args):
"""
blrObjFunction computes 2-class Logistic Regression error function and
its gradient.
Input:
initialWeights: the weight vector (w_k) of size (D + 1) x 1
train_data: the data matrix of size N x D
labeli: the label vector (y_k... | 33,038 |
def edit_battle(battle_id):
"""
Edit battle form.
:param battle_id:
:return:
"""
battle = Battle.query.get(battle_id) or abort(404)
if battle.clan != g.player.clan and g.player.name not in config.ADMINS:
abort(403)
all_players = Player.query.filter_by(clan=g.player.clan, loc... | 33,039 |
def write_config(yamlpath: PathType) -> None:
"""Read CONFIG in YAML format."""
config_str = omegaconf.OmegaConf.to_yaml(CONFIG)
yamlpath = pathlib.Path(yamlpath)
yamlpath.write_text(config_str) | 33,040 |
def construct_epsilon_heli(epsilon_diag,
pitch,
divisions,
thickness,
handness="left"):
"""
construct the dielectric matrices of all layers
return a N*3*3 array where N is the number of layers
We ... | 33,041 |
def list_fm_tsv(f_tsv: os.path.abspath, col=0) -> List[int]:
""" 2cols (pred, out_label_id) -> List[pred:int] """
return [int(line.split()[col]) for line in open(f_tsv, 'r')] | 33,042 |
def image_overlay(im_1, im_2, color=True, normalize=True):
"""Overlay two images with the same size.
Args:
im_1 (np.ndarray): image arrary
im_2 (np.ndarray): image arrary
color (bool): Whether convert intensity image to color image.
normalize (bool): If both color and nor... | 33,043 |
def ansible_hostsfile_filepath(opts):
"""returns the filepath where the ansible hostsfile will be created"""
# if the location was specified on the cmdline, return that
if "hosts_output_file" in opts and bool(opts["hosts_output_file"]):
return opts["hosts_output_file"]
# otherwise return the d... | 33,044 |
def get_next_seg(ea):
"""
Get next segment
@param ea: linear address
@return: start of the next segment
BADADDR - no next segment
"""
nextseg = ida_segment.get_next_seg(ea)
if not nextseg:
return BADADDR
else:
return nextseg.start_ea | 33,045 |
def validate_item_pid(item_pid):
"""Validate item or raise and return an obj to easily distinguish them."""
from invenio_app_ils.items.api import ITEM_PID_TYPE
if item_pid["type"] not in [BORROWING_REQUEST_PID_TYPE, ITEM_PID_TYPE]:
raise UnknownItemPidTypeError(pid_type=item_pid["type"])
# inl... | 33,046 |
async def async_setup(hass, config):
"""Setup pool pump services."""
hass.data[DOMAIN] = {}
# Copy configuration values for later use.
hass.data[DOMAIN][ATTR_SWITCH_ENTITY_ID] = config[DOMAIN][ATTR_SWITCH_ENTITY_ID]
hass.data[DOMAIN][ATTR_POOL_PUMP_MODE_ENTITY_ID] = config[DOMAIN][ATTR_POOL_PUM... | 33,047 |
def save_as_png(prs: pptx.presentation.Presentation, save_folder: str, overwrite: bool = False) -> bool:
"""
Save presentation as PDF.
Requires to save a temporary *.pptx first.
Needs module comtypes (windows only).
Needs installed PowerPoint.
Note: you have to give full path for save_folder, or... | 33,048 |
def http_post(request):
"""HTTP Cloud Function.
Args:
request (flask.Request): The request object.
<https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
Returns:
The response text, or any set of values that can be turned into a
Response object using `... | 33,049 |
def _get_add_noise(stddev, seed: Optional[int] = None):
"""Utility function to decide which `add_noise` to use according to tf version."""
if distutils.version.LooseVersion(
tf.__version__) < distutils.version.LooseVersion('2.0.0'):
# The seed should be only used for testing purpose.
if seed is not N... | 33,050 |
def create_incident_field_context(incident):
"""Parses the 'incident_fields' entry of the incident and returns it
Args:
incident (dict): The incident to parse
Returns:
list. The parsed incident fields list
"""
incident_field_values = dict()
for incident_field in incident.get('i... | 33,051 |
def create_profile(body, user_id): # noqa: E501
"""Create a user profile
# noqa: E501
:param body:
:type body: dict | bytes
:param user_id: The id of the user to update
:type user_id: int
:rtype: None
"""
if connexion.request.is_json:
json = connexion.request.get_json()
... | 33,052 |
def get_server_info(context):
"""Get the server info."""
context.server_info = context.get("server")
print(context.server_info) | 33,053 |
def load_global_recovered() -> pd.DataFrame:
"""Loads time series data for global COVID-19 recovered cases
Returns:
pd.DataFrame: A pandas dataframe with time series data for global COVID-19 recovered cases
"""
return load_csv(global_recovered_cases_location) | 33,054 |
def build_url(self, endpoint):
"""
Builds a URL given an endpoint
Args:
endpoint (Endpoint: str): The endpoint to build the URL for
Returns:
str: The URL to access the given API endpoint
"""
return urllib.parse.urljoin(self.base_url, endpoint) | 33,055 |
def neighbors(i, diag = True,inc_self=False):
"""
determine the neighbors, returns a set with neighboring tuples {(0,1)}
if inc_self: returns self in results
if diag: return diagonal moves as well
"""
r = [1,0,-1]
c = [1,-1,0]
if diag:
if inc_self:
return {(i[0]+d... | 33,056 |
def test_create_product_price_min_10():
"""capsys -- object created by pytest to
capture stdout and stderr"""
# pip the input
os.chdir(working_dir)
output = subprocess.run(
['python', '-m', 'qbay'],
stdin=expected_in14,
capture_output=True, text=True
).stdout
produc... | 33,057 |
def readPLY(name):
"""Read a PLY mesh file."""
try:
reader = vtk.vtkPLYReader()
reader.SetFileName(name)
reader.Update()
print("Input mesh:", name)
mesh = reader.GetOutput()
del reader
# reader = None
return mesh
except BaseException:
pr... | 33,058 |
def gumbel_softmax(logits, tau=1, hard=False, eps=1e-10):
"""
NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3
Sample from the Gumbel-Softmax distribution and optionally discretize.
Args:
logits: [batch_size, n_class] unnormalized log-... | 33,059 |
def decompose_f_string(f_string: str) -> (List[str], List[str]):
"""
Decompose an f-string into the list of variable names and the separators between them.
An f-string is any string that contains enclosed curly brackets around text.
A variable is defined as the text expression within the enclosed curly... | 33,060 |
def process(register, instructions):
"""Process instructions on copy of register."""
cur_register = register.copy()
cur_index = 0
while cur_index < len(instructions):
cur_instruction = instructions[cur_index]
cur_index += process_instruction(cur_register, cur_instruction)
return cur_... | 33,061 |
def bearing_radians(lat1, lon1, lat2, lon2):
"""Initial bearing"""
dlon = lon2 - lon1
y = sin(dlon) * cos(lat2)
x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)
return atan2(y, x) | 33,062 |
def RunSimulatedStreaming(vm):
"""Spawn fio to simulate streaming and gather the results.
Args:
vm: The vm that synthetic_storage_workloads_benchmark will be run upon.
Returns:
A list of sample.Sample objects
"""
test_size = min(vm.total_memory_kb / 10, 1000000)
iodepth_list = FLAGS.iodepth_list or... | 33,063 |
def create_warning_path(paths_=None):
"""It Creates the files names for both files ( strangers and spoofing )"""
if not paths_:
if not os.path.isdir('/opt/arp_warnings/'):
os.system('mkdir /opt/arp_guard/arp_warnings')
paths_ = ['/opt/arp_guard/arp_warnings/'] # default warning dir... | 33,064 |
def write_conll(fstream, data):
"""
Writes to an output stream @fstream (e.g. output of `open(fname, 'r')`) in CoNLL file format.
@data a list of examples [(tokens), (labels), (predictions)]. @tokens, @labels, @predictions are lists of string.
"""
for cols in data:
for row in zip(*cols):
... | 33,065 |
def get_all_tutorial_info():
"""
Tutorial route to get tutorials with steps
Parameters
----------
None
Returns
-------
Tutorials with steps
"""
sql_query = "SELECT * FROM diyup.tutorials"
cur = mysql.connection.cursor()
cur.execute(sql_query)
tutorials = cur.fetcha... | 33,066 |
def parse_date(datestring, default_timezone=UTC):
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified in default_timezone is used.... | 33,067 |
def fworker(fworker_file, name):
"""
Configure the basic settings of a fireworker.
Although the information can be put in manually when using the command without
options, it's probably easiest to first set up the fireworker file and then use
the '-f option to configure the fireworker based on this ... | 33,068 |
def BigSpectrum_to_H2COdict(sp, vrange=None):
"""
A rather complicated way to make the spdicts above given a spectrum...
"""
spdict = {}
for linename,freq in pyspeckit.spectrum.models.formaldehyde.central_freq_dict.iteritems():
if vrange is not None:
freq_test_low = freq - freq... | 33,069 |
def get_thickness_model(model):
"""
Return a function calculating an adsorbate thickness.
The ``model`` parameter is a string which names the thickness equation which
should be used. Alternatively, a user can implement their own thickness model, either
as an experimental isotherm or a function whic... | 33,070 |
def http(session: aiohttp.ClientSession) -> Handler:
"""`aiohttp` based request handler.
:param session:
"""
async def handler(request: Request) -> Response:
async with session.request(
request.method,
request.url,
params=request.params or None,
d... | 33,071 |
def remove_package_repo_and_wait(repo_name, wait_for_package):
""" Remove a repository from the list of package sources, then wait for the removal to complete
:param repo_name: name of the repository to remove
:type repo_name: str
:param wait_for_package: the package whose version should ch... | 33,072 |
def lyndon_of_word(word : str, comp: Callable[[List[str]],str] = min ) -> str:
"""
Returns the Lyndon representative among set of circular shifts,
that is the minimum for th lexicographic order 'L'<'R'
:code:`lyndon_of_word('RLR')`.
Args:
`word` (str): a word (supposedly binary L&R)
... | 33,073 |
def setColor(poiID, color):
"""setColor(string, (integer, integer, integer, integer)) -> None
Sets the rgba color of the poi.
"""
traci._beginMessage(tc.CMD_SET_POI_VARIABLE, tc.VAR_COLOR, poiID, 1+1+1+1+1)
traci._message.string += struct.pack("!BBBBB", tc.TYPE_COLOR, int(color[0]), int(color[1... | 33,074 |
def num_of_visited_nodes(driver_matrix):
""" Calculate the total number of visited nodes for multiple paths.
Args:
driver_matrix (list of lists): A list whose members are lists that
contain paths that are represented by consecutively visited nodes.
Returns:
int: Number of visited no... | 33,075 |
def gen_custom_item_windows_file(description, info, value_type, value_data,
regex, expect):
"""Generates a custom item stanza for windows file contents audit
Args:
description: string, a description of the audit
info: string, info about the audit
value_type: string, "POLICY_TEXT" -- include... | 33,076 |
def create_signature(args=None, kwargs=None):
"""Create a inspect.Signature object based on args and kwargs.
Args:
args (list or None): The names of positional or keyword arguments.
kwargs (list or None): The keyword only arguments.
Returns:
inspect.Signature
"""
args = []... | 33,077 |
def execute_message_call(
laser_evm, callee_address: BitVec, func_hashes: List[List[int]] = None
) -> None:
"""Executes a message call transaction from all open states.
:param laser_evm:
:param callee_address:
"""
# TODO: Resolve circular import between .transaction and ..svm to import LaserEVM... | 33,078 |
def select(type, name, optional):
"""Select data from data.json file"""
with open('data.json', 'r') as f:
data = json.load(f)
for i in data[type]:
if i == data[name]:
return data[optional] | 33,079 |
def test_xlseventform_month_out_of_range(
stocking_event_dict, xls_choices, cache, year, month, day
):
"""If the stocking event data contains month that is >12 or less than 1,
the form will not be valid and an error will be thrown.
This test is parameterized to accept a list of day, month, year
com... | 33,080 |
def perform_step(polymer: str, rules: dict) -> str:
"""
Performs a single step of polymerization by performing all applicable insertions; returns new polymer template string
"""
new = [polymer[i] + rules[polymer[i:i+2]] for i in range(len(polymer)-1)]
new.append(polymer[-1])
return "".join(... | 33,081 |
def load_datasets(json_file):
"""load dataset described in JSON file"""
datasets = {}
with open(json_file, 'r') as fd:
config = json.load(fd)
all_set_path = config["Path"]
for name, value in config["Dataset"].items():
assert isinstance(value, dict)
datasets[n... | 33,082 |
def group(batch):
""" batch: contains
[
(name, [list of data], [list of others]),
(name, [list of data], [list of others]),
(name, [list of data], [list of others]),
...
]
Note
----
We assume the shape[0] (or length) of all "data" and "othe... | 33,083 |
def instantiate_descriptor(**field_data):
"""
Instantiate descriptor with most properties.
"""
system = get_test_descriptor_system()
course_key = CourseLocator('org', 'course', 'run')
usage_key = course_key.make_usage_key('html', 'SampleHtml')
return system.construct_xblock_from_class(
... | 33,084 |
def simple_switch(M_in, P_in, slack=1, animate=True, cont=False, gen_pos=None, verbose=True):
"""
A simple switch algorithm. When encountering a change in sequence, compare the value
of the switch to the value of the current state, switch if it's more. The default value
function sum(exp(length(adjoint sequence... | 33,085 |
def drop_duplicates_by_type_or_node(n_df, n1, n2, typ):
"""
Drop the duplicates in the network, by type or by node.
For each set of "duplicate" edges, only the edge with the maximum weight
will be kept.
By type, the duplicates are where nd1, nd2, and typ are identical; by node,
the duplicates ... | 33,086 |
def voting(labels):
""" Majority voting. """
return sitk.LabelVoting(labels, 0) | 33,087 |
def user_city_country(obj):
"""Get the location (city, country) of the user
Args:
obj (object): The user profile
Returns:
str: The city and country of user (if exist)
"""
location = list()
if obj.city:
location.append(obj.city)
if obj.country:
... | 33,088 |
def test_get_midi_download_name():
"""This test checks the functionality of our midi download name maker.
We expect:
- Any text going into our function comes back prefixed
with '-melodie.mid'
- Returns a string.
"""
for file_name in range(20):
assert get_midi_downloa... | 33,089 |
def test_encrypted_parquet_write_kms_error(tempdir, data_table,
basic_encryption_config):
"""Write an encrypted parquet, but raise KeyError in KmsClient."""
path = tempdir / 'encrypted_table_kms_error.in_mem.parquet'
encryption_config = basic_encryption_config
... | 33,090 |
async def putStorBytes(app, key, data, filter_ops=None, bucket=None):
""" Store byte string as S3 object with given key
"""
client = _getStorageClient(app)
if not bucket:
bucket = app['bucket_name']
if key[0] == '/':
key = key[1:] # no leading slash
shuffle = -1 # auto-shuffle... | 33,091 |
def fetch_block(folder, ind, full_output=False):
"""
A more generic function to fetch block number "ind" from a trajectory in a folder
This function is useful both if you want to load both "old style" trajectories (block1.dat),
and "new style" trajectories ("blocks_1-50.h5")
It will ... | 33,092 |
def unique_boxes(boxes, scale=1.0):
"""Return indices of unique boxes."""
assert boxes.shape[1] == 4, 'Func doesnot support tubes yet'
v = np.array([1, 1e3, 1e6, 1e9])
hashes = np.round(boxes * scale).dot(v)
_, index = np.unique(hashes, return_index=True)
return np.sort(index) | 33,093 |
def export_all_courses(exported_courses_folder):
"""
Export all courses into specified folder
Args:
exported_courses_folder (str): The path of folder to export courses to.
"""
try:
course_list = subprocess.Popen(
['/edx/bin/python.edxapp',
'/edx/app/edxapp/ed... | 33,094 |
def dataloader(loader, mode):
"""Sets batchsize and repeat for the train, valid, and test iterators.
Args:
loader: tfds.load instance, a train, valid, or test iterator.
mode: string, set to 'train' for use during training;
set to anything else for use during validation/test
Returns:
An itera... | 33,095 |
def sub_inplace(X, varX, Y, varY):
"""In-place subtraction with error propagation"""
# Z = X - Y
# varZ = varX + varY
X -= Y
varX += varY
return X, varX | 33,096 |
def gitlab_mngr_fixture(mock_config_file):
"""A pytest fixture that returns a GitLabRepositoryManager instance"""
yield GitLabManager("https://test.repo.gigantum.com/",
"https://test.gigantum.com/api/v1/", "fakeaccesstoken", "fakeidtoken") | 33,097 |
def inv_logtransform(plog):
""" Transform the power spectrum for the log field to the power spectrum of delta.
Inputs
------
plog - power spectrum of log field computed at points on a Fourier grid
Outputs
-------
p - power spectrum of the delta field
"""
xi_log = np.fft.ifftn(plo... | 33,098 |
def ipv6_b85decode(encoded,
_base85_ords=RFC1924_ORDS):
"""Decodes an RFC1924 Base-85 encoded string to its 128-bit unsigned integral
representation. Used to base85-decode IPv6 addresses or 128-bit chunks.
Whitespace is ignored. Raises an ``OverflowError`` if stray characters
are found.
:... | 33,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.