content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def predict_entity_entailment(ent_ent, gold):
"""
Creates a new structure which is identical to the gold standard
except for the entailment graph, in which edges represent rules above threshold
:param ent_ent: the entity entailment finder
:param gold: the gold standard graph
:return: a new struc... | c690b7238284f432e148b200c1e819707ec4ff62 | 674,773 |
def convertcl(text: str) -> str:
"""
CL tag format conversion.
Convert cl tags that appear only before chapter one to
the form that appears after each chapter marker.
"""
lines = text.split("\n")
# count number of cl tags in text
clcount = len([_ for _ in lines if _.startswith(r"\cl "... | f3cc9c27a19dabae1be0f0fbff70aa6559107889 | 674,774 |
import math
import random
def optimizar(dominio, temperatura = 10e32, tasa_enfriamiento = 0.95):
"""Algoritmo de optimización estocástica simulated annealing.
Entradas:
dominio (Dominio)
Un objeto que modela el dominio del problema que se quiere aproximar.
temperatura (float/int)
Tem... | 0ccb5bde943bc7c60127da0007e3adbd6af2c0a6 | 674,776 |
def convert_to_dict(list, startIndex, EndIndex):
"""Convert List to Dictionary and create any index to 0 index"""
startIndex += 1
dict = {}
for i, value in enumerate(list):
dict[str(startIndex + i)] = str(value)
return dict | 4840c1e184b86fcb0485610502667b60007ef9f8 | 674,777 |
import torch
def collate_fn(samples):
"""
collate_fn for SequentialMNIST.
Args:
samples: a list of samples. Each item is a (imgs, nums) pair. Where
- imgs: shape (T, 1, C, H, W)
- nums: shape (T, 1)
And len(samples) is the batch size.
... | 29a8b44a261d9db1de0b91c4f5eace64ee21d5fb | 674,778 |
def utf8_encode(s: str) -> bytes:
"""Encodes a string with utf-8 and returns its byte sequence.
Invalid surrogates will be replaced with U+FFFD.
Args:
s: A string to encode with utf-8.
Returns:
A utf-8 encoded byte sequence.
"""
s = s.encode("utf-16", "surrogatepass").decode("... | 762588f0904eef539fa5f1648e060897e899f618 | 674,779 |
def _get_md_relative_link(id_: str, title: str) -> str:
"""Returns a representation of a zettel that is a relative Markdown link.
Asterix at the beginning is a Markdown syntax for an unordered list, as links to
zettels are usually just used in references section of a zettel.
"""
return f"* [{id_}](... | 59d5877ebb099c138cff22ffe2668d86901f25bb | 674,780 |
def subdirs(folderpath, pattern="*"):
"""
returns all sub folders in a given folder matching a pattern
"""
return [f for f in folderpath.glob(pattern) if f.is_dir()] | 8fe701c0620dc28c24d448eae3a71632bf0817d6 | 674,781 |
def extract_keywords(lst_dict, kw):
"""Extract the value associated to a specific keyword in a list of
dictionaries. Returns the list of values extracted from the keywords.
Parameters
----------
lst_dict : python list of dictionaries
list to extract keywords from
kw : string
keywo... | 28b97459dca558e245fa552a18711d5f5ce7a802 | 674,782 |
def flatten_dict(input_dict):
"""Returns flattened dictionary given an input dictionary with maximum depth
of 2
Args:
input_dict (dict): `str → number` key-value pairs, where value can be a
number or a dictionary with `str → number` key-value paris.
Returns:
dict: F... | 171fcc9f45743ade1e2a624862c8bf93cc0da775 | 674,783 |
def landscapize(image):
"""
Coloca totes les imatges en apaisat (cantó mes llarg en horitzontal),
per simplificar l'algorisme d'escollir mida standard
"""
if image.size[1] > image.size[0]:
return image.rotate(90, expand=True)
else:
return image | cf4cab7b1a0cbef1ee45a04a680774303261a95a | 674,785 |
import re
def remove_vowels(string=''):
"""
Removes the vowels from the given string.
According to the rules the letters A, E, I, O, U are considered vowels.
:param string: The input to remove vowels from
:return: The given string without vowels
"""
return re.sub('a|e|i|o|u|y', '', string,... | 965a2d2939da3b6b0cc97e1390bf17c71bf3182e | 674,786 |
def unique(scope, source):
"""
Returns a copy of the given list in which all duplicates are removed
such that one of each item remains in the list.
:type source: string
:param source: A list of strings.
:rtype: string
:return: The cleaned up list of strings.
"""
return list(dict([... | ddb671e4fc5e8ef9bdeb0cb0263d8bc2cb744628 | 674,787 |
import os
def CountsByDirname(dict_of_list):
"""Given a list of files, returns a dict of dirname to counts in that dir."""
r = {}
for path in dict_of_list:
dirname = os.path.dirname(path)
r.setdefault(dirname, 0)
r[dirname] += 1
return r | 173d388b8d6bad860dec54841eaaee72f6987322 | 674,788 |
async def async_setup(hass, config):
"""Set up renault integrations."""
return True | 2ee3dc64cdd1fcea13fa8d8ee39bb9977f3b421a | 674,789 |
def header_check(file):
"""Checks whether the file has a header or not.
Parameters
----------
file : str
Filename or filepath of file to check
Returns
-------
int
1 if header is present 0 if not
"""
with open(file, "r", encoding="utf-8") as to_check:
result ... | 6213799704ff9a1a07fac072b0bd78d1d132675f | 674,791 |
import random
def random_birthday():
"""
Generate random birthdays using random.randint. Birthdays are returned as
string objects in the format '(m)m-(d)d'.
"""
days_31 = [1, 3, 5, 7, 8, 10, 12]
days_30 = [4, 6, 9, 11]
m = random.randint(1, 12)
if m in days_31:
d = random.randi... | 8167aac5e87dd6d4ad32ecf22e650f054ac83e7f | 674,792 |
def build_parms(args):
"""Helper function to parse command line arguments into dictionary
input: ArgumentParser class object
output: dictionary of expected parameters
"""
readDir=args.dir
outdir=args.outdir
parms = {"readDir":readDir,
"outdir":outdir}
return(p... | 4f731e89b2392dbb8ce13b78c57a3772486eca64 | 674,793 |
def _make_param_bounds_nd(probe_counts, step_size=0.001):
"""Calculate bounds on parameter values in n dimensions.
For each dataset d, this calculates bounds on the values of each
parameter based only on the min/max of what has been computed
(i.e., is in probe_counts). Note that a point that satisfies ... | b862589b90f760cf5d56490fbb06e76e8126e08f | 674,795 |
import re
def strip_config_header(config):
"""Normalize items that should not show up in IOS-XR compare_config."""
config = re.sub(r"^Building config.*\n!! IOS.*", "", config, flags=re.M)
config = config.strip()
config = re.sub(r"^!!.*", "", config)
config = re.sub(r"end$", "", config)
return ... | 93f733960a5b4231628aff1b26e1e2f9cdd63ec2 | 674,796 |
def get_item_relative_limit(page, per_page):
"""Get the maximum possible number of items on one page."""
return per_page | f6e9af997fbd36ca44229d974482451f79ab99b2 | 674,797 |
def p1(range_max, factor_list):
"""Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
range_min = 0
sum_multiples = 0
for num in range(... | eaa2937ff877e5f29c85b7dc3f27b188a9035635 | 674,799 |
import re
def regex_search_list(data, regex):
"""
Allows you to search across a list with regex returns True if any match in the list.
:param data: The element to search
:param regex: The regex search string
:return: True if any elements match, false if none match
"""
# Create the data int... | affa406083c0fdcc02df76783777d20676347622 | 674,800 |
from typing import Union
def convert_strike(strike: Union[int, float]) -> Union[int, float]:
"""
Convert the type of the strike to an integer if it is an integer or float to 2 points if it is a float
Note
----
This is only a type conversion
"""
if (strike - int(strike)) == 0:
retur... | 37082340550ef9b69e4770800d3186d58e991f2a | 674,802 |
def string_is_equal_case_insensitive(subject: str, value: str) -> bool:
"""Case insensitive string is equal"""
return subject.strip().lower() == value.strip().lower() | 29de3ee6d78e6fb0abf2199ee3a1b690efb15401 | 674,803 |
from pathlib import Path
import typing
def GetImageFileName(readDir: Path) -> Path:
"""
指定されたディレクトリからpngまたはsvgのファイルを1つ
返す。複数あっても返すのは一つだけ。
最初にpngを探し、なかったらsvgを探す。
png,svgファイルを発見できない場合は、例外を上げる。
"""
pngl: typing.List[Path] = list(readDir.glob("*.png"))
if len(pngl) != 0:
# png ファイル... | 7821fe97e83e21d7f98df31ce8408142d8cf5f39 | 674,804 |
def find_odd_occurred_number_sol2(nums):
"""
You are given an array of repeating numbers. All numbers repeat in even way, except for
one. Find the odd occurring number.
- This solution takes less space.
- More details: https://youtu.be/bMF2fG9eY0A
- Time: O(len(nums))
- Space: worst: O(len... | 48bd4dba827606a01d092dc321bfed0d949e2386 | 674,805 |
import os
def generate_fixture_data_folder(message_type):
"""Generates the fixture data folder for the given message type
Keyword arguments:
message_type -- the message type in use (kafka_main, kafka_equalities, kafka_audit, corporate_data)
"""
if message_type.lower() == "kafka_main":
ret... | 7063b180c2bb6b87537e1cabe75a46532f6d5934 | 674,806 |
def check_for_all_permissions(user, permissions):
"""
Check to see if the passed user has all of the permissions
that are listed in the passed permissions.
If the user does not have all of them, false is returned.
If the passed permission list is empty, the method returns false.
Even though emp... | aa0771567448eef2fe5b079c2cf4af76ccc8c15c | 674,807 |
import os
import sys
def GENER_adder(input_dictionary):
""""It takes all the GENER section created depending on the type of run production or natural defined on the input dictionary
Parameters
----------
input_dictionary : dictionary
Dictionary specficing the type of run
Returns
-------
str
string : st... | 777929f04f51d193ca92cc8756f4dc18ed00d276 | 674,808 |
from typing import List
def route_ranks(scores: List[float]) -> List[int]:
"""
Compute the rank of route scores. Rank starts at 1
:param scores: the route scores
:return: a list of ranks for each route
"""
ranks = [1]
for idx in range(1, len(scores)):
if abs(scores[idx] - scores[i... | 06828f144d3cca13b01dde9bad104a648dbe71c5 | 674,809 |
def E_kin_cart(positionD):
"""Compute penalty for kinetic energy of cart"""
return positionD ** 2 | bbbef6c28a881a106feb552b1a2d1b50d2515e8b | 674,810 |
def transformer(y, func=None):
"""Transforms target variable and prediction"""
if func is None:
return y
else:
return func(y) | 9d90473b5aba83364902bd138cbe746fa3a3f409 | 674,811 |
def list_to_tree(data_list, parent_id=0) -> list:
"""
递归获取树形结构数据
:param data_list: 数据列表
:param parent_id: 父级id
:return:
"""
tree = []
for data in data_list:
if data['parent_id'] == parent_id:
tree.append(data)
data['children'] = list_to_tree(data_list, da... | da816712a7232d75169a2ace857279650df63922 | 674,812 |
def clip_padding(t, orig_shape):
""" return tensor with clipped padding """
co = orig_shape[0]
inners = 1
for s in orig_shape[1:]:
inners *= s
t_clipped = t.view(co, -1)[:, :inners]
return t_clipped | 3df872cd862cedf4cb260c7b1eeb848743648b5d | 674,813 |
from typing import Counter
def valencies(graph):
"""Gets the valency of each vertex in the graph."""
return Counter((v for edge in graph for v in edge)) | fb9716cac87590f90b52b457ce07e31299262eee | 674,814 |
import torch
def split_stack(x, split_sizes, split_dim, stack_dim):
"""Split x along dimension split_dim and stack again at dimension stack_dim"""
t = torch.stack(torch.split(x, split_sizes, dim=split_dim), dim=stack_dim)
return t | 63f0fdc7588baa392bf14e7b53f6881bbd16386e | 674,815 |
import math
def Griewank(x, lb=-600., ub=600.):
"""
Description:
-----------
Dimensions: d
The Griewank function has many widespread local minima, which are regularly
distributed. The complexity is shown in the zoomed-in plots.
Input Domain:
------------
The function is usually ev... | aca1ab6aa3c65839f5a492844d01a89bb8fd2c2b | 674,816 |
def dice_loss(inputs, targets, smooth=1.0):
"""
Params:
inputs: arbitrary size of Tensor
targets: arbitrary size of Tensor
smooth: smoothing factor
Returns:
loss: Tensor[]
"""
inputs = inputs.view(-1)
targets = targets.view(-1)
# Squred denominator version of... | bad787be814852e4cb0dd851a823518895f0e12e | 674,817 |
def eps_compare(f1, f2, eps):
"""Return true if |f1-f2| <= eps."""
res = f1 - f2
if abs(res) <= eps: # '<=',so eps == 0 works as expected
return 0
elif res < 0:
return -1
return 1 | ed819a0ab1ba373aad33e41c1261ce918e3efec9 | 674,818 |
import re
def parse_int_sprintf_pattern(patt):
"""Parses the integer sprintf pattern and returns a function that can
detect whether a string matches the pattern.
Args:
patt: a sprintf pattern like "%05d", "%4d", or "%d"
Returns:
a function that returns True/False whether a given stri... | c271df911ad8607f8bbd371c5acdd3ba8618959d | 674,819 |
import re
def getSender(email):
"""
Returns the best-guess sender of an email.
Arguments:
email -- the email whose sender is desired
Returns:
Sender of the email.
"""
sender = email['From']
m = re.match(r'(.*)\s<.*>', sender)
if m:
return m.group(1... | 7fabda5eef256fb2256aa1af3bc23912e76472ab | 674,821 |
def pod_list_without_instances_fixture():
"""Marathon pod without an "instances" field.
:rtype: {}
"""
return {
"id": "/pod-without-instances",
"spec": {
"id": "/pod-without-instances",
"containers": [
{
"name": "no-instances"... | d6b43474c23b83c3e7ae19fd982aad23a201e405 | 674,822 |
def parse_fish_life_stages(stages):
""" cleans up life stage strings such as 'egg,juvenile'"""
split_list = [item.split(',') for item in stages]
flat_list = [item for sublist in split_list for item in sublist]
return list(set(flat_list)) | f5d239a5f3606553bd0a8eb2de0ec79a070e8d8b | 674,823 |
import argparse
def init_argparse():
""" Returns a parser that processes the arguments from the command line. """
parser = argparse.ArgumentParser(
usage="%(prog)s [FILE1.tsv] [FILE2.tsv] [...]",
description=""" Joins tsv files for TRACER that still have a placeholder in the first colu... | 5a61f88e3c0151641024c5efd50b6b6f072a1fc7 | 674,824 |
def GetJulianEphemerisDay(julian_day, delta_seconds = 66.0):
"""delta_seconds is the value referred to by astronomers as Delta-T, defined as the difference between
Dynamical Time (TD) and Universal Time (UT). In 2007, it's around 65 seconds.
A list of values for Delta-T can be found here: ftp://maia.usno.na... | 21c60073eeed52f2b2b82722a152a8d015d2e103 | 674,825 |
import os
def setup(i):
"""
Input: {
cfg - meta of this soft entry
self_cfg - meta of module soft
ck_kernel - import CK kernel module (to reuse functions)
host_os_uoa - host OS UOA
host_os_uid - host ... | b08efc31678d342f0d0bb33838c96fabd512e9c0 | 674,827 |
def signed2unsigned(value, width=32):
""" convert a signed value to it's 2 complement unsigned
encoding """
if value >= 0:
return int(value)
else:
return int(value + 2**(width) ) | 5d51a99445decc8ddf7a06ee73d54daa6502b85f | 674,828 |
import struct
def read_binary(fileObj, byteType='uint8', size=1):
"""A helper function to readin values from a binary file
Parameters:
-----------
fileObj : object
a binary file object
byteType : string, optional, default 'uint8'
the type of readin values
size : int, option... | 68607ba14d21da017a01d1e7fb26e2b4d35491cc | 674,829 |
def erb_1990(f: float) -> float:
"""
f: in hertz, the center of bandwidth
returns: the size of bandwidth
"""
f = f/1000.0
return 24.7 * (4.37 * f +1.0) | ed8f9db362b4afca06b6adfab39c676967341725 | 674,832 |
def test_y0(adv, thresh=(5e-6, 5e-3)):
"""Test whether the advective tendency resulting from fluxes in y-direction is,
on average, much smaller than the one resulting from fluxes in x-direction. This
should be the case if the budget is averaged over y. The average absolute ratio is
compared to the given... | dd4e6cf3800763417c83e71c427532f22ef8f438 | 674,833 |
def get_rank(workers, scores):
"""
spam score -> rank
"""
a = zip(scores, workers)
b = sorted(a)
dic = {}
i = 0
for s, w in b:
dic[w] = i
i+= 1
return dic | 22520870fae2a5ec64d2224409e69eedd56a6392 | 674,834 |
def is_external_plugin(module_path):
"""
Returns true when the given module is an external plugin.
Implementation note: does a simple check on the name to see if it's
not prefixed with "kolibri.". If so, we know it's not an internal plugin.
"""
return not module_path.startswith("kolibri.") | b3058bf76882ce7f52518c993e9350d7b4fa9b24 | 674,835 |
def intersect(lst1, lst2):
"""intersection of two lists
"""
lst3 = [value for value in lst1 if value in lst2]
return lst3 | 4f579dd6eea95871ffa544852b76feb2df25d036 | 674,836 |
from typing import Dict
def prettify_data_filtering_rule(rule: Dict) -> Dict:
"""
Prettify the data filtering rule to be compatible to our standard.
Args:
rule: The profile rule to prettify
Returns: rule dictionary compatible to our standards.
"""
pretty_rule = {
'Name': rule... | a4cbd2ea0a7ae2caca6e7dbe3d7665f9abd7094f | 674,837 |
import subprocess
def register_image_file_with_dataset_id(file_path, dataset_id, usr, pwd, host, port=4064):
"""
This function imports an image file to an omero server using the OMERO.cli (using Bio-formats)
This function assumes the OMERO.cli is installed
Example:
register_image_file("data/te... | 1ef9d56fa615741443f9bab7db6ab2b6483fb8c9 | 674,838 |
def format_cal(cal: str) -> str:
"""Function used to format and make the calendar look better.
Args:
`cal`(str): a calendar in HTML format.
Returns:
`str`: the calendar formatted.
"""
html = cal.replace(
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"month\">",... | 7368c8f53cbe0371d24e6ed4affa84b500323f63 | 674,839 |
import random
def execute_event_type_queries(event_id, cursor, db):
"""Executes event type queries to insert the event types into the linking table"""
try:
cursor.execute("SELECT event_id from event_type WHERE event_id = '{}'".format(event_id))
db.commit()
id = cursor.fetchone()
... | 5393bcbf0ff1160b9963651555b3db5937a04808 | 674,840 |
import pkg_resources
def get_version():
"""
Returns current version of the package if it's installed
"""
pkg = pkg_resources.require("cwl_airflow")
return pkg[0].version if pkg else "unknown version" | 5534134debe8674940d91589a7e2fa1c03baa14a | 674,842 |
def get_base_frame_type(frame_name, is_frame_like, example=None):
"""Handles type check for input example for DataFrame/Series/Index initialization.
Returns the base type of streaming objects if type checks pass."""
if example is None:
raise TypeError("Missing required argument:'example'")
if... | 307fa784eadf874acfe1b343b236d723379168b7 | 674,844 |
def kr_wksa_school_gangwon():
"""Sample Korea school, formatted as the 설 | 경기 | 강원 schools"""
# pylint: disable=line-too-long
return {
'country_name': 'KOREA', 'country_code': 'KR', 'region': 'Seoul | Gyeonggi | Gangwon',
'city': 'Boknam Myuong', 'website': '',
'address': '1111 3Ban ... | dc7f5b6c15338e61fd77ef7589ff1841a369b7c5 | 674,845 |
def identity(x):
"""Identity activation function. Input equals output.
Args:
x (ndarray): weighted sum of inputs.
"""
return x | 86f6b926244b517023d34b76dbef10b4ae5dcfce | 674,846 |
import torch
def toy4():
""" 1D regression. """
X_train = torch.tensor([-3.5, -2, 2, 3.5]).unsqueeze(dim=1)
Y_train = torch.tensor([-1, 0.25, 3.5, 4.5]).unsqueeze(dim=1)
X_train_min = [-4.0]
X_train_max = [4.0]
return {"dataset_name": "toy4", "X_train": X_train, "Y_train": Y_train, "X_train_min": X_train_min, ... | af686dc69e55fac666065648224e6dfc0bf45e6c | 674,847 |
def _recipe_name(raw_configuration):
"""
Given a raw repository configuration, returns its recipe name.
:param raw_configuration: configuration as returned by the SCRIPT_NAME_GET
groovy script.
:type raw_configuration: dict
:return: name of the recipe ("format")
"""
name = raw_confi... | c030082623b157744bf057272f530583cb426561 | 674,848 |
from warnings import warn
def insert_metadata(df, obj, name=None, inplace=True, overwrite=False):
"""Insert/update metadata for a dataframe."""
if not inplace:
new = df.copy(deep=True)
insert_metadata(new, obj, name=name, inplace=True)
return new
if name is None:
name = t... | af55899be2a4541462f5aaddf7609a8202a714d3 | 674,849 |
def subdict_except(d, *keys):
"""Get dict, which contains all keys from argument dict, except given."""
return {k: v for k, v in d.items() if k not in keys} | 2ec45e206be2e9198fed9bd3efd6aa1376a74e36 | 674,850 |
import hashlib
def ComputeHash256Array(buf: bytes) -> bytes:
"""ComputeHash256Array Compute a cryptographically strong 256 bit hash of the input byte slice."""
m = hashlib.sha256()
m.update(buf)
return m.digest() | f690d3b9329bd9786775de925b8da69cf5032f45 | 674,852 |
import itertools
def color_repeats(n=1):
"""Set up a cycle through default Plotly colors, repeating each n times"""
color_list = (
["#1f77b4"] * n # muted blue
+ ["#ff7f0e"] * n # safety orange
+ ["#2ca02c"] * n # cooked asparagus green
+ ["#d62728"] * n # brick red
... | c4c7d68bce476b9c4c6763323057594ea19a435c | 674,853 |
def pybb_editable_by(post, user):
"""
Check if the post could be edited by the user.
"""
return post.is_editable_by(user) | 16605a5176b824ae982b17943f2fba477ad9b661 | 674,854 |
import time
import random
def generate_random_128bit_string() -> str:
"""Returns a 128 bit UTF-8 encoded string. Follows the same conventions
as generate_random_64bit_string().
The upper 32 bits are the current time in epoch seconds, and the
lower 96 bits are random. This allows for AWS X-Ray `intero... | 40117b4f137a5dda9f89f42551b962f29a736266 | 674,855 |
def lengthOfLongestSubstring2(s):
"""
:type s: str
:rtype: int
"""
cmax = gmax = [s[0]] if s else []
for i in range(1, len(s)):
cmax = cmax + [s[i]] if s[i] not in cmax else cmax[cmax.index(s[i]) + 1:] + [s[i]]
if len(cmax) > len(gmax): gmax = cmax... | 1bc9c985fb912fc7b3b8c9ed012b79fe1ae0b73f | 674,856 |
import os
def checkForType(repository):
""" Check For Type
This function will check to see if the repository is a git repository. It
will not check to see if it is valid, just that the path passed in points
to something that could be a git repository.
This check SPECIFICALLY does not validate a submodule, ... | 05048b1f2098bc51f4a244d55e7acab1bf89f26e | 674,857 |
import subprocess
import struct
def is_running_rosetta():
"""Returns whether Python is being translated by Rosetta.
Returns:
True if the Python interpreter is being run as an x86_64 binary on an arm64
macOS machine. False if it is running as an arm64 binary, or if it is
running on an Intel machine.
... | 204734210240d53be5272ba253b68f128c8ceff3 | 674,858 |
def mean_squared_error_loss(inputs, targets):
""" 平方差损失
Examples:
>>> i = torch.randn(3, 5)
>>> t = torch.randn(3, 5)
# 与官方结果比较
>>> my_ret = mean_squared_error_loss(i, t)
>>> official_ret = F.mse_loss(i, t, reduction='none')
>>> assert torch.allclose(my_ret, off... | c424cbcffeb71ed34d5473704e788921385ac891 | 674,859 |
def _get_cost (route, solution, dists):
"""
This method is used to calculate the total distance
associated to a route, once the sequence of its nodes
has been changed using the 2-OPT algorithm.
:param route: The interested route.
:param solution: The nodesin the order in which they are visited.... | 37ccdecec3fc517346bacaac0a762b68f86d4cc5 | 674,860 |
def no_data_extractor(node, user):
"""Dummy function that collects no data for the NodeDataRegistry."""
return [] | 180b076859e21c05c4b39adb1de6c8896119f74b | 674,861 |
def camel_case_from_underscores(string):
"""generate a CamelCase string from an underscore_string."""
components = string.split('_')
string = ''
for component in components:
string += component[0].upper() + component[1:]
return string | 10e86e5079641d45e614c5e38da4e73032299fda | 674,862 |
def easy_helloname(a):
"""Takes in a string representing a name and returns a new string saying hello in a very specific format, e.g., if the name is 'Dave', it should return 'Hello, Dave!'"""
return 'Hello, {}!'.format(a) | 37ac6517f700b148c712e94bc14ffe2d1c21a03c | 674,863 |
def PossibleChains(equivalences, fixed_names, chain_name):
"""Searches for all the identical chains to chain_name that are already included in the complex.
Arguments:
equivalences -- dictionary with chain IDs as keys and the equivalent IDs as values
fixed_names -- list of chains IDs that are already included in ... | f32e4ed612d8653fe049db181533fbf7e5076df1 | 674,864 |
import mimetypes
def _GuessMimeType(magic_obj, file_name):
"""Guess a file's mimetype base on its extension and content.
File extension is favored over file content to reduce noise.
Args:
magic_obj: A loaded magic instance.
file_name: A path to the file.
Returns:
A mime type of |file_name|.
"... | 8b127a463e9659080cec2873a96e296f03dbd447 | 674,865 |
def convert_headers_to_environ(headers):
"""
Converts HTTP headers into WSGI environ variables.
"""
return {
'HTTP_' + key.replace('-', '_').upper(): value.strip()
for key, value in headers.items()
} | 7fa0db7e2971d1318259e14ae269dc339e54d5b8 | 674,866 |
from pathlib import Path
def assert_generated(workdir: Path, output: Path, version="3.14") -> Path:
""" helper to check some files after running the generator
"""
assert (workdir / "language-server-protocol").exists()
assert (workdir / "vscode-languageserver-node").exists()
schema = output / f"lsp... | e4df3046502ae8c9cd1a8bb2a94ac3813b5197bb | 674,868 |
import re
def findPasswordInString(s):
"""
Try to find password in a string/HTML response based on regex (32 char long string)
return
- Booelan
- string ("X" or password found)
"""
passFound = False
password = "X"
# if s is a multi line string :
if "\n" in s:
HTMLlist=s.split("\n")
for line in H... | ce0011efae8e5c05a599a4941e58fd73f170b2ab | 674,870 |
def expand_iterable(choices):
"""
Expands an iterable into a list. We use this to expand generators/etc.
"""
return [i for i in choices] if hasattr(choices, "__iter__") else None | 4afef36052c818bce135294907207b65798a0a07 | 674,871 |
import numpy
def _rectOverlapROIs(top, bottom, pos):
"""
top is a rectangle (w,h)
bottom is a rectangle (w,h)
pos is the top left corner of the top rectangle with respect to the bottom rectangle's top left corner
method returns none if the two rectangles do not overlap. Otherwise returns the top r... | 9295de848f61f0b69762388a781ccc9b9410d43f | 674,872 |
def int2list(num,listlen=0,base=2):
"""Return a list of the digits of num, zero padding to produce a list of length at least listlen, to the given base (default binary)"""
digits = []; temp = num
while temp>0:
digits.append(temp % base)
temp = temp // base
digits.extend((listlen-len(digits))*[0]... | 9f10135736aaaea2bf655774ea0a5453766e633f | 674,873 |
def rate(e0, e1, n0, n1, nr, p):
"""
This equation is solved for p to determine the convergence rate when the
reference solution is used to measure the error.
y(p) = 0 determines the convergence rate.
e0, n0 : Error and grid number for grid "0"
e1, n1 : Error and grid number for grid "1"
n... | 1661abd1f867f65fe536bebd3ea319f002d2956a | 674,874 |
import os
import subprocess
def _sh_eval(pred_fn, ref_fn):
"""
Runs measure_scores.py script and processes the output
:param pred_fn:
:param ref_fn:
:return:
"""
this_dir = os.path.dirname(os.path.abspath(__file__))
script_fname = os.path.join(this_dir, 'eval_scripts/run_eval.sh')
... | 39567c483e105c63e52a5a99c139709a9cdc0570 | 674,875 |
from typing import Iterable
from typing import Hashable
from typing import Counter
def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]:
"""
For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g... | 5a4705f1c6fc401ac1629239c2929cdc0b67e28d | 674,876 |
def lunar_long_asc_node(t):
"""
longitude of the mean ascending node of the lunar orbit on the ecliptic
This is used to calculate nutation.
@param t : Julian centuries
@type t : float
@return: float
"""
return 125.04-1934.136*t | a73b020b0ee96d07a6dd8176e83f013ffc64baa4 | 674,877 |
def get_embedded(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the embedded object for link_relation. The returned object can be
treated as a result object in its own right.
'result_object' a JSON object returned by a previous API call.
The ... | a41bb87a1c8a55c7e0be966032fbf959d69bda6e | 674,878 |
import string
def numeric_to_alpha(value):
"""
This function maps from numeric values in {0, 1, 2, ...}
to the Roman alphabet, {A, B, ..., Z, AA, BB, ...}.
This function is for labeling the .dot file associated
with an epsilon-transducer.
Parameters
----------
value : int
A numeric value in {0, 1, 2, ..... | 471cd1f98be928f963b0b2c4f287405364f95bbf | 674,879 |
def make_album(artist, title, tracks=0):
"""Build a dictionary containing information about an album."""
album_dict = {
'artist': artist.title(),
'title': title.title(),
}
if tracks:
album_dict['tracks'] = tracks
return album_dict | f94850ee837b0667f1eca61b5c7d8d49d6ca8491 | 674,880 |
import string
def pos(letter):
"""Return the position of a letter in the alphabet (0-25)"""
if letter in string.ascii_lowercase:
return ord(letter) - ord('a')
elif letter in string.ascii_uppercase:
return ord(letter) - ord('A')
else:
raise ValueError('pos requires input of {} ... | 963d4f48ebb99789af7fb38e9a4ece949557c49b | 674,881 |
from random import choice
def get_description():
"""Return random weather, just like the pros"""
possibilities = ['rain', 'snow', 'sleet', 'fog', 'sun', 'no else']
return choice(possibilities) | 2fccc055d940d418e59bcabf54401bcb8a344af4 | 674,882 |
import re
def is_number_regex(s):
""" Returns True is string is a number. """
if re.match("^\d+?\.\d+?$", s) is None:
return s.isdigit()
return True | fe1084bfcfc78594755f188d3033f92ca4ce5eae | 674,883 |
def list_all_tables(conn, table_type=None):
"""Return a list with names of all tables in the database."""
if table_type is not None:
sql_query = (
"show full tables where TABLE_TYPE = '{}';"
.format(table_type))
else:
sql_query = 'show full tables;'
cursor = conn.... | 4d9ddba2e0f72c158415035a948c3f60b054b8cd | 674,884 |
def plot_rectangular_image_on_main_image(background_image, rect_image, pixel_xy):
""" This utility can be used when the icon with rectangular dimension and have
even pixel. This is used to overlay icon on the background image. This handles
the cases of the corners where the size of the icon goes out of the ... | 004bf39f4f1cecdcd49eaa537c45d91b02e08bc8 | 674,885 |
def process_edition(edition):
"""
Turns a string with an edition in it into a processed string.
Turns '1' into '1st', '2017' into '2017', and 'International'
into 'International'. So it doesn't do a whole lot, but what it
does do, it does well.
Arguments:
edition: The edition string.
... | 9dbd5db0e4b59ed73a66fc64b0962ff90fd71489 | 674,886 |
import numpy
def read_mat_bin(fname):
"""
Reads a .bin file containing floating-point values (real) saved by Koala
Parameters
----------
fname : string
Path to the file
Returns
-------
buffer : ndarray
An array containing the floating-point values read from the file
... | 2c42b93a0a0c94c8b7233d96cae985b5e5783fc2 | 674,887 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.