code stringlengths 15 1.19k | docstring stringlengths 13 400 |
|---|---|
def _encode(coord, max_coord, chars):
encoding = []
coord += max_coord
for p in range(chars):
if coord >= max_coord:
coord -= max_coord
encoding.append("1")
else:
encoding.append("0")
max_coord /= 2
return encoding
| Returns a binary geohash of longitude or latitude
as an array of 0s and 1s. |
def _decode(geohash, max_coord):
coord = 0
for c in geohash:
max_coord /= 2
coord = coord - max_coord if c == "0" else coord + max_coord
return coord, max_coord * 2
| Returns a tuple with the coord and the range of the boundary
defined by the binary geohash. |
def _nbr_prev(geohash):
GH = list(geohash)
for i in range(len(GH) - 1, -1, -1):
if GH[i] == "0":
GH[i] = "1"
else:
GH[i] = "0"
break
return GH
| Helper function for computing S/W neighbors. |
def _nbr_next(geohash):
GH = list(geohash)
for i in range(len(GH) - 1, -1, -1):
if GH[i] == "1":
GH[i] = "0"
else:
GH[i] = "1"
break
return GH
| Helper function for computing N/E neighbors. |
def _directory_validation(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
| Check if the directory is present, if not create this directory |
def router_added_actions(resource, event, l3_agent, **kwargs):
router = kwargs["router"]
for device_driver in l3_agent.device_drivers:
device_driver.create_router(router)
device_driver.sync(l3_agent.context, [router.router])
| Create the router and sync for each loaded device driver. |
def router_removed_actions(resource, event, l3_agent, **kwargs):
router = kwargs["router"]
for device_driver in l3_agent.device_drivers:
device_driver.destroy_router(router.router_id)
| Remove the router from each loaded device driver. |
def router_updated_actions(resource, event, l3_agent, **kwargs):
router = kwargs["router"]
for device_driver in l3_agent.device_drivers:
device_driver.sync(l3_agent.context, [router.router])
| Perform a sync on each loaded device driver. |
def make_p(count):
a = []
for i in range(count):
a.append(1 / count)
return a
| A helper function that generates count based on the number of
actions. |
def cdf(p_vector):
cdf = []
sigma = 0
for i in range(len(p_vector)):
sigma += p_vector[i]
cdf.append(sigma)
return cdf
| get the cumulative distribution vector for a given input vector. |
def _x_per_inch(ax):
xlim = ax.get_xlim()
return (xlim[1] - xlim[0]) / ax.get_figure().get_figwidth()
| Conversion factor between the plot x variable and the figure width.
For example. |
def openapi_types():
return {
"hashed_password": (str,),
"password": (str,),
}
| This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type. |
def openapi_types():
return {
"version": (str,),
}
| This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type. |
def openapi_types():
return {
"_async": (bool,),
"crossorigin": (str,),
"id": (str,),
"integrity": (str,),
"node_type": (str,),
"nonce": (str,),
"referrerpolicy": (str,),
"src": (str,),
"type": (str,),
}
| This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type. |
def constructCssString(css):
cssString = "style='"
for k, v in css.iteritems():
cssString += k + ":" + v + ";"
cssString += "'"
return cssString
| Converts a dict of css properties into a string for HTML use |
def constructAttrsString(dict):
string = ""
for k, v in dict.iteritems():
string += k + "=" + str(v) + " "
return string
| Converts a dict of attributes into a string for HTML use |
def verify_hpo_mappings_up_to_date(hpo_file_df, hpo_table_df):
hpo_ids_df = hpo_file_df["HPO_ID"].dropna()
if set(hpo_table_df["hpo_id"].to_list()) != set(hpo_ids_df.str.lower().to_list()):
raise ValueError(
f"Please update the config/hpo_site_mappings.csv file "
f"to the latest ... | Verifies that the hpo_mappings.csv file is up to date with lookup_tables.hpo_site_id_mappings |
def check_concept_id_field(df):
df_columns = df.columns
if "concept_id" in df_columns:
return True
else:
return False
| helper function to check that 'concept_id' is included in the dataframe schema |
def convert_to_bq_string(mapping_list):
bq_insert_list = []
for hpo_rdr_item in mapping_list:
bq_insert_list.append(f'("{hpo_rdr_item[0]}", "{hpo_rdr_item[1]}")')
bq_insert_string = ", ".join(bq_insert_list)
return bq_insert_string
| Converts list of lists to bq INSERT friendly string |
def _except_hook(exc_type, exc_value, exc_traceback):
root_logger = logging.getLogger()
root_logger.critical(
"Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)
)
| Log exception info to root logger. Used as a hook for uncaught exceptions prior
to system exit. |
def mod_2_representation(mat):
return mat % 2
| returns mod 2 representation of the matrix mat |
def add_mod_2(r1, r2):
return r1 ^ r2
| adds two rows of the matrix mod 2 |
def check_user_exists_by_email(cls, email):
exists = False
if cls.query.filter_by(email=email).first():
return True
else:
return False
| Check whether the user email exists |
def does_this_relation_exists(cls, portfolioId, bookId):
exists = False
if cls.query.filter_by(portfolioId=portfolioId).filter_by(bookId=bookId).first():
return True
else:
return False
| Check whether the reltation containing a portfolioId and bookId exists in order to avoir duplicates. |
def random_colors(n, bright=True):
brightness = 1.0 if bright else 0.7
hsv = [(i / n, 1, brightness) for i in range(n)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
random.shuffle(colors)
return colors
| Generate random colors.
To get visually distinct colors, generate them in HSV space then
convert to RGB. |
def flatten_columns(columns):
return ["_".join(col).strip() for col in columns]
| Transforms hierarchical column names to concatenated single-level
columns |
def check_if_variable_used(methodNode, name):
for assignment in methodNode.find_all("assignment"):
if assignment.target.type == "name" and assignment.target.value == name:
return True
if assignment.target.type == "tuple" and assignment.target.find(
"name", value=name
... | Check if a variable with the given name is assigned in the given method |
def prepend_tab(strings):
return list(map(lambda x: "\t%s" % x, strings))
| Prepend tab to strings in list. |
def add_libvirt_options(parser):
pass
| Adds the command line options that are specific to libvirt. |
def path_from_trackid(msddir, trackid):
p = os.path.join(msddir, trackid[2])
p = os.path.join(p, trackid[3])
p = os.path.join(p, trackid[4])
p = os.path.join(p, trackid.upper() + ".h5")
return p
| Create a full path from the main MSD dir and a track id.
Does not check if the file actually exists. |
def feat_names():
res = [
"track_id",
"artist_name",
"title",
"loudness",
"tempo",
"time_signature",
"key",
"mode",
"duration",
]
for k in range(1, 13):
res.append("avg_timbre" + str(k))
for k in range(1, 13):
res.ap... | return the name of each feature return by the following function |
def color_mapping(color):
if color == "default":
return "lightgray"
if color in ["green", "black", "cyan", "blue", "brown"]:
return color
try:
return (int(color[0:2], 16), int(color[2:4], 16), int(color[4:6], 16))
except:
return color
return color
| Convert pyte color to PIL color |
def line_len(line):
last_pos = len(line)
while last_pos > 0 and line[last_pos - 1].data == " ":
last_pos -= 1
return last_pos
| Returns len of the line excluding spaces from the right |
def grad(w, X, y):
G = 0
for n in range(X.shape[0]):
numerator = 1
denominator = 1
G += numerator / denominator
return G
| Computes the gradient of the log-loss function
at w. The computation uses the data in X with
corresponding labels in y. |
def create_single_bucket(data):
bucket = {}
for k in data.keys():
if k in data["_LIST_OF_COUNTERS_"]:
bucket[k] = 0
else:
bucket[k] = data[k].copy()
return bucket
| Creates an bucket dictionary that will be used to collect data and then
packed into the the master data dictionary. |
def block_signals(method, *args, **kwargs):
obj = method.__self__
obj.blockSignals(True)
method(*args, **kwargs)
obj.blockSignals(False)
| Allow block signals emitted by an QtObject during execution of one
of its method |
def update_progress_acquired_frame(ui, idx_frame=0, progression=0):
if idx_frame is not None:
ui.sB_actual_frame_cnt.setValue(idx_frame)
ui.meas_progress_bar.setValue(progression)
| Update the progression bar and the idx of the aquired frame |
def mkListOfHex(rx_data):
list_hex = []
for rx_datum in rx_data:
tmp = hex(rx_datum).replace("0x", "")
if len(tmp) == 1:
list_hex.append(f"0{tmp.capitalize()}")
else:
list_hex.append(tmp.capitalize())
return list_hex
| Return a list of str of the Hex-representation of the list of int8 |
def convert4Bytes2Float(data_4bytes):
if len(data_4bytes) == 4:
return struct.unpack(">f", bytearray(data_4bytes))[0]
else:
raise TypeError(f"Only 4Bytes allowed: {data_4bytes} transmitted")
| Convert the represention of a single float format (a list of 4 int8 (4 Bytes)) of a number
to its float value
Parameters
list of 4 int8 representing a float value according the single float format
Returns
corresponding float
Notes
see documentation of the EIT device |
def convertFloat2Bytes(float_val):
return list(struct.pack(">f", float_val))
| Convert a float value to its single float format (a list of 4 int8 (4 Bytes))
representation
Parameters
float
Returns
list of 4 int8 representing float_val according thesingle float format
Notes
see documentation of the EIT device |
def convertInt2Bytes(int_val, n_bytes):
return list((int(int_val)).to_bytes(n_bytes, byteorder="big"))
| Convert an integer to its representaion as a list of int8 with n_bytes
Parameters
int
value to convert in list of int8
n_bytes: int
length of the output list
Returns
list of n_bytes int8
Notes
see documentation of the EIT device |
def convertBoolToByte(val):
val = 1 if val else 0
return val.to_bytes(1, byteorder="big")
| Convert a boolean in a bytes |
def build_us_details(details):
return {
"name": {
"last": details[0],
"first": details[1],
"full name": f"{details[0]} {details[1]}",
},
"terms": [
{
"party": details[2],
"type": details[3],
"stat... | Build test data for a member of Congress. |
def build_member_matrix(mbr_list):
headers = [
"Last Name",
"First Name",
"Party",
]
matrix = [
headers,
]
for mbr in mbr_list:
row = [
mbr.last_name,
mbr.first_name,
mbr.party,
]
matrix.append(row)
retur... | Return a matrix of information on the given members list. |
def build_args_list():
return [
[
"Spam",
"Eggs",
"Democrat",
],
[
"Bacon",
"Baked Beans",
"Democrat",
],
[
"Ham",
"Tomato",
"Independent",
],
]
| Build a list of arguments for generating members. |
def makedir(pathlist):
for path in pathlist:
if not os.path.isdir(path):
os.makedirs(path)
return True
| List of FULL Paths to be made if they dont exist
Output: Confirmation if the paths were made |
def prepend(files, dirpath):
return [os.path.join(dirpath, i) for i in files]
| List of files in the input directory and path to input directory Input: List of files in the input directory and path to input directory
Output: List of full paths to log files in input directory Output: List of full paths to log files in input directory |
def days_hours_minutes(td):
return td.days, td.seconds // 3600, (td.seconds / 60) % 60
| Breaks a datetime.timedelta into the days as an integer, the hours as an
integer, and the minutes as a float. |
def dp_fibonacci(num):
if num < 0:
return -1
if num == 0:
return 0
if num == 1 or num == 2:
return 1
dp = [1, 1]
for i in range(2, num):
dp.append(dp[i - 1] + dp[i - 2])
return dp[-1]
| Returns fibonacci number of a given integer
using dynamic programming for faster runtime
|
def disable_button(button):
button.attrs["style"] = ""
button.classList.add("btn-dis")
button.disabled = True
| helper function to disable a specific button and set its style to show the
disabled state |
def enable_button(button):
button.classList.remove("btn-dis")
button.disabled = False
| helper function to enable a specific button and set its style to show the
enabled state |
def cell_unhover(event):
target = event.target
target.text = ""
| event function that responds to a cell when a mouse cursor NO LONGER hovers
removes the grayed out game piece on top of the hovered cell |
def to_varname(string):
import re
return re.sub(r"\W|^(?=\d)", "_", string)
| Converts string to correct Python variable name.
Replaces unavailable symbols with _ and insert _ if string starts with digit. |
def list_to_string(l):
return ",".join(l)
| Return string of a list. |
def string2list(string):
tmp_str = string.replace(";", ",").replace("\n", ",").replace("\r", ",")
s = set()
for e in tmp_str.split(","):
e = e.strip(" ")
if not e:
continue
s.add(e)
return [x for x in s]
| Split string contacted with different separators to a list, and remove
duplicated strings. |
def is_org_context(request):
return request.cloud_mode and request.user.org is not None
| An organization context is a virtual private Seafile instance on cloud
service.
`request`. |
def _same_events(e1, e2):
if hasattr(e1, "commit") and hasattr(e2, "commit"):
if (
e1.repo_id == e2.repo_id
and e1.commit.desc == e2.commit.desc
and e1.commit.creator_name == e2.commit.creator_name
):
return True
return False
| Two events are equal should follow two rules:
1. |
def mkstemp():
fd, path = tempfile.mkstemp()
return fd, path
| Returns (fd, filepath), the same as tempfile.mkstemp, except the
filepath is encoded in UTF-8 |
def calculate_bitwise(num):
level = 0
for i in range(4):
if num & 1:
level += 1
num = num >> 1
return level
| Return different level according to the given num. |
def within_time_range(d1, d2, maxdiff_seconds):
delta = d2 - d1 if d2 > d1 else d1 - d2
diff = (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 1e6) / 1e6
return diff < maxdiff_seconds
| Return true if two datetime.datetime object differs less than the given seconds |
def __convert_list_to_tuple(*args):
return [tuple(x) for x in args]
| Converts multiple tuple/array-like objects to a list of tuples |
def __default_style_gen(depth, shape=None):
if depth <= 2:
fill = (100, 54, 15)
elif depth <= 5:
fill = (162, 96, 41)
else:
fill = (38, 196, 64)
return {"fill": fill, "outline": (0, 0, 0)}
| Default function for coloring the tree |
def _check_weights(weights):
if weights in (None, "uniform", "distance"):
return weights
elif callable(weights):
return weights
else:
raise ValueError(
"weights not recognized: should be 'uniform', "
"'distance', or a callable function"
)
| Check to make sure weights are valid |
def _tree_query_parallel_helper(tree, *args, **kwargs):
return tree.query(*args, **kwargs)
| Helper for the Parallel calls in KNeighborsMixin.kneighbors
The Cython method tree.query is not directly picklable by cloudpickle
under PyPy. |
def _tree_query_radius_parallel_helper(tree, *args, **kwargs):
return tree.query_radius(*args, **kwargs)
| Helper for the Parallel calls in RadiusNeighborsMixin.radius_neighbors
The Cython method tree.query_radius is not directly picklable by
cloudpickle under PyPy. |
def validateDir(dir):
if not os.path.isdir(dir):
raise argparse.ArgumentTypeError('Directory "%s" doesn\'t exist.' % dir)
dirpath = os.path.abspath(dir)
head, tail = os.path.split(dirpath)
if tail.lower() != "include":
raise argparse.ArgumentTypeError(
'Include directory "%s"... | Check that dir is a valid directory named include. |
def open_in_browser(path):
import webbrowser
return webbrowser.open(path)
| Open directory in web browser. |
def is_prime(num):
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True
| check whether a number is a prime |
def add_suffix(tweet, domain):
words = [tmp + "@" + str(domain) for tmp in tweet.split()]
return tweet + " " + " ".join(words)
| Add suffix (time) to the end of word to explicitly show domain differences. |
def _all_csv_data(csv_files):
for c_file in csv_files:
with open(c_file, newline="") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
for row in reader:
yield row
| Return all data inside the csv files
input: csv_files: generator contain all the csv files path
output: return a generator contain all data inside csv_files |
def cut_regnum_from_pax(text):
pass_data = text.split()
return " ".join(pass_data[:-1]), pass_data[-1]
| Cut regnum from last pax in pax list. |
def find_pax(pnr, paxnum):
paxes = pnr["name"]
if len(paxes) < int(paxnum):
return None
return paxes[int(paxnum) - 1]
| Pax number is paxnum - 1 because paxes stored in list. |
def fix_status(status):
if status in ["NK", "KK", "NS"]:
return "HK"
return status
| Some predefined fix status conditions. |
def fix_arrtime(arrtime):
arrtime = arrtime.replace("+", "/")
arrtime = arrtime.replace("-", "/M")
return arrtime
| Fix raw arrival time format to TCH format for SIRENA. |
def output_dest_addr(pnr, settings):
return settings.dest_addr
| Output destination address in pnr header. |
def output_src_addr(pnr, settings):
out = []
out_append = out.append
out_append(".")
if pnr["remote_pnr"]:
out_append(pnr["remote_system"][:3])
out_append("RM")
out_append(pnr["remote_system"][3:])
else:
out_append("MOWRM1H")
out_append(" ")
out_append(datetim... | Output source address and current time in pnr header. |
def remove_osi_from_pnr(o, pnr):
pnr_osi = pnr["osi"]
for i, osi in enumerate(pnr_osi):
if osi == o:
del pnr_osi[i]
return
| Find and remove osi from pnr osis list. |
def output_elems(elems, pnr, settings, fn):
if not elems:
return None
out = []
out_append = out.append
for elem in elems:
if not elem:
continue
r = fn(elem, pnr, settings)
if r:
out_append(r)
return "\n".join(out)
| Generic function for output pnr elements like pnr['segment'].
All output functions get the same parameters. |
def extract_text(filename):
whole_text_in_file = pathlib.Path(filename).read_text()
blocks = re.findall(
r"//@(.*?)//@\nFunction(/\w+)*\s+(.*?\))", whole_text_in_file, flags=re.S | re.M
)
return [(b[0], b[2]) for b in blocks]
| Extract a help text from a file. |
def wait_for_file_creation(filename, timeout=25, check_interval=1):
if timeout < 1:
timeout = 1
now = time.time()
timeout_time = now + timeout
while time.time() <= timeout_time:
if os.path.exists(filename):
return True
else:
time.sleep(check_interval)
... | Return true if filename exists, if not keep checking once every check_interval seconds for time_limit seconds. |
def init_database():
db = sqlite3.connect(":memory:")
cur = db.cursor()
cur.execute(
"CREATE TABLE nat_entries (source_ip text, dest_ip text, source_port int, nat_port int, protocol text, time int)"
)
db.commit()
return db
| In-memory sqlite3 database to track NAT entries. |
def download_content_from_single_site(url, session):
with session.get(url) as response:
content_from_url = response.content
print(f"Read {len(content_from_url)} from {url}")
return content_from_url
| Gets content from url using requests package and returns it's content as a string. |
def _make_prefix(pwd_array):
string = ""
for path_part in pwd_array:
string = string + "/" + path_part
string = string + "/"
return string
| Given pwd_array concatenates all the elements of the array and puts a / between them. |
def save_model_as_string(args, model):
with open(args.log_root / "model_as_str.txt", "w+") as f:
f.write(str(model))
| save model as as string. |
def save_model_and_meta_learner_as_string(args, model, meta_learner=None):
with open(args.log_root / "model_as_str.txt", "w+") as f:
f.write(str(model))
if meta_learner is not None:
f.write(str(meta_learner))
| save model and meta-learner as string. |
def divide_params_by(W, net):
params = net.named_parameters()
dict_params = dict(params)
for name, param in dict_params.items():
if name in dict_params:
new_param = param / W
dict_params[name] = new_param
net.load_state_dict(dict_params)
return net
| make sure W is non-trainable if you wish to divide by a constant. |
def dont_train(net):
for param in net.parameters():
param.requires_grad = False
return net
| set training parameters to false. |
def initialize_to_zero(net):
for param in net.parameters():
param.zero_()
| sets weights of net to zero. |
def prev_this_next(it, sentinel=None):
i1, i2, i3 = itertools.tee(it, 3)
next(i3, None)
return zip(itertools.chain([sentinel], i1), i2, itertools.chain(i3, [sentinel]))
| Utility to return (prev, this, next) tuples from an iterator |
def append_in_list(dict_obj, key, value):
if key in dict_obj.keys():
dict_obj[key].append(value)
else:
dict_obj[key] = [value]
dict_obj[key] = list(set(dict_obj[key]))
return dict_obj
| Creates arg_from list inside of arg_from dictionary, adds values if this list exists already |
def calculate_accuracy(y_target, y_pred):
return y_target[y_target == y_pred].size * 1.0 / y_target.size
| Returns accuracy
Arguments
y_target: true label data
y_pred: estimated label data
Returns
accuracy |
def _dbconnstr(dbname=None):
the_str = "host=db user=postgres"
if dbname:
the_str += " dbname=%s" % dbname
return the_str
| Connect to test database on host db, user postgres. |
def identifier():
return str(uuid.uuid4())
| Returns valid UUID for Orange Button identifiers |
def def_value():
return "Not Present"
| This Function will return a default values for keys not present in a defaultdict. |
def log_sample_messages(logger_name):
logger = logging.getLogger(logger_name)
logger.debug("This is a debug message.")
logger.info("This is an info message")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
logger.critical("This is a critical message.")
| Sends a sample message for each logging level. |
def partition(collection):
pivot = collection.pop()
greater, lesser = [], []
for element in collection:
if element > pivot:
greater.append(element)
else:
lesser.append(element)
return lesser, pivot, greater
| This function will break the passed in collection into two collections based on the
value of the last element. |
def find_repos(base_dir):
repos = [
os.path.join(base_dir, o)
for o in os.listdir(base_dir)
if os.path.isdir(os.path.join(base_dir, o))
]
repos.sort()
return repos
| This function will return a list of repos (directories) found in the base dir.
It assumes that only folders which represent repos are in the base directory. |
def to_camel_case(snake_str):
components = snake_str.split("_")
return components[0] + "".join(x.title() for x in components[1:])
| Converts a snake string to lower camel case. |
def split_zoom_coord(z):
z = z.replace(",", "")
zoom_coord = re.search(r"(\S+):(\d+)-(\d+)", z)
if zoom_coord == None:
return None
zoom_chr, zoom_start, zoom_end = zoom_coord.groups()
zoom_start = int(zoom_start)
zoom_end = int(zoom_end)
if zoom_start > zoom_end:
return None
... | validate and split zoom coordinate.
coordinates must be UCSC formatted. |
def flip_intervals(a, b):
return (b, a)
| flip intervals, to ensure a < b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.