content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def cost_of_equity_exdiv(d, Mv):
"""
Calculates the cost of capital or equity shareholder required rate of
return for an investment in which dividend is expected to remain constant
forever (dividend has just been paid)
parameters:
-----------
Mv = ex-dividend share price
"""
ke = d/Mv
return round(ke, 4) | d2bb1ce38a76b635e2994e355434c4c7caabaa9b | 646,189 |
def make_input(tokens, pid = 0):
"""
make input for util.build_index
"""
s = []
for t in tokens:
if len(t[0]) > 0:
s.append( t[0] + ' ' + str(pid) + '_' + str(t[1]) + '_' + str(t[2]) )
if t [0] == '.':
s.append ('')
return s | 82da42a8b017ea5b182936ef0fd7c5e6ba8c3297 | 646,190 |
import numpy
def snr_to_rniirs(bandwidth_area, signal, noise):
"""
Calculate the information_density and RNIIRS estimate from bandwidth area and
signal/noise estimates.
It is assumed that geometric effects for signal and noise have been accounted for
(i.e. use SigmaZeroSFPoly), and signal and noi... | 9c74dd200b3a1deb0ca9750a9376ee76d570f49e | 646,191 |
import requests
from bs4 import BeautifulSoup
def get_cap_url():
"""returns captcha url"""
sis='https://sis.manipal.edu/'
page=requests.get('https://sis.manipal.edu/studlogin.aspx')
pagetext=page.text
soup=BeautifulSoup(pagetext,"lxml")
cap=soup.findAll('img')[2]
cap=cap['src']
url=sis... | 4d19d100f6d648d97635749f1c22d5bacb5e89bf | 646,192 |
def chained_join(*relationships):
"""
Return a chained Join object for given relationships.
"""
property_ = relationships[0].property
if property_.secondary is not None:
from_ = property_.secondary.join(
property_.mapper.class_.__table__,
property_.secondaryjoin
... | 824289d20506c9ee2088e4724b7c8ebb02eebf0d | 646,193 |
def is_prime_bakup(number):
""" 采用 平方 和 while 循环 来判断是否为素数
"""
n = number if number>0 else -number
if not n%2: # replace n%2==0:
return n==2
i = 3
prime = True
while i*i <= n:
if not (n % i): # replace n % i == 0:
prime = False
break # skip the w... | a042888227f4509a5a8f52f3bb8c3417d8a8a948 | 646,194 |
import torch
def load_model_args(fsave):
"""
load model's args from disk
"""
save = torch.load(fsave, map_location=lambda storage, loc: storage)
return save["args"] | b093aa85d1423b0b1793558d9e77ad8f862d0712 | 646,195 |
def GetLabel(plist):
"""Plists have a label."""
return plist['Label'] | b6692b603c72e829fe819e22dc219905f6db151f | 646,196 |
def rgba2hex(rgba):
"""Convert rgba values to hex."""
# Slice the tuple so that
# we don't get alpha and
# convert values to 8 bit ints
rgb = tuple([min(max(int(255 * i), 0), 255) for i in rgba[:3]])
return "#{0:02x}{1:02x}{2:02x}".format(*rgb) | 7a793c54829376999a0a470d1c051a2523dfcf98 | 646,197 |
import asyncio
def synchronize_function(async_func, *args, **kwargs):
"""
Execute synchronously an asynchronous function
"""
try:
r = asyncio.run(async_func(*args, **kwargs))
except AttributeError:
loop = asyncio.new_event_loop()
r = loop.run_until_complete(async_func(*arg... | 22fdd5d33916f9761a1eb682c95c505660adf4cd | 646,198 |
def init_words(lang):
"""initialize words"""
words = []
dict_filename = "dicts/%s.csv" % lang
with open(dict_filename) as dict_file:
words_set = set()
for line in dict_file:
word = line.strip().split(",")[0]
lower_word = word.lower()
word_len = len(wor... | c3b66b318a964b917ccbeeffa51c0a5151ff0eee | 646,199 |
import torch
def mag_phase_to_complex(mag, phase, power=1.0):
"""
input_signal: mag(*, N, T) , phase(*, N, T), power is optional
output: *, N, T, 2
"""
mag_power_1 = mag.pow(1 / power)
spec_real = mag_power_1 * torch.cos(phase)
spec_imag = mag_power_1 * torch.sin(phase)
spec_complex = ... | 45272de7dbac29c07f7fe60e20b08f9d73ae9897 | 646,200 |
import math
def get_evaldiff(evalue1, evalue2):
"""Return absolute value of the order of magnitude evalue difference for
two given E-values. """
return round(abs(math.log(float(evalue1),10) - math.log(float(evalue2),10))) | 7919a3213c6ca3ba671b541281cba05856fcbe2d | 646,201 |
def get_initial_lock_expiration(block_number, settle_timeout):
""" Returns the expiration for first hash-time-lock in a mediated transfer. """
# The initiator doesn't need to learn the secret, so there is no need to
# decrement reveal_timeout from the settle_timeout.
#
# The lock_expiration could be... | e125518810afd65950f77586f0036ac32e7b1b4b | 646,202 |
def catch_input(default_value, desired_type, input_message = "Input: ",
failure_message = "Invalid input.",
default_message = "Default value used.", num_attempts = 3):
"""
Function to better catch type errors in user input. If the input can be
parsed using desired_type, th... | c3177bfabff11c9875e6ef80c22f06d251b2447a | 646,203 |
def split_safe(x, *args, **kwargs):
"""
See strip_safe().
"""
try:
return x.split(*args, **kwargs)
except AttributeError:
return x | 02069e14da2b20c6e2eed68d9c24c287349a7eb0 | 646,204 |
def boolean_type(text):
"""Custom Parse Type to parse a boolean value.
The same values are parsed as YAML does:
http://yaml.org/type/bool.html
Plus 0 and 1
"""
text = text.lower()
return text == "1" or text.startswith("y") or text == "true" or text == "on" | 7409c3e6c06460bda22d82843005d05a5ec92125 | 646,205 |
def template_filter(name=None):
"""
If you want to register your own filters in Jinja2 you have two ways to do
that. You can either put them by hand into the jinja_env of the application
or use the template_filter() decorator.
The two following examples work the same and both reverse an object::
... | a3b4dd3c8f59cf72b913a6e9a2c13bc70ff19f95 | 646,206 |
import subprocess
import json
def parse_str(s):
"""Run pandoc on `s` and output as JSON."""
process = subprocess.run(
["pandoc", "-t", "json", "-f", "markdown"],
input=s.encode(),
capture_output=True,
check=True,
)
return json.loads(process.stdout) | 2d33d21cc9aea230dbf79c769d6dc927d415b96d | 646,207 |
from pathlib import Path
def get_relative_paths():
""""Return relavent relative paths in the project"""
logConf_path = Path(__file__).parent / 'logs/conf.yaml'
log_path = Path(__file__).parent / 'logs/'
schema_path = Path(__file__).parent / 'parameters/schema.yaml'
output_path = Path(__file__).pa... | e1dc04ceaf5b6603ed86ae06b4a812771c89060b | 646,208 |
def can_merge(bbox1, bbox2, direction, align_thr=0.2, merge_left_thr=0.3, merge_right_thr=0.15):
"""whether the two bbox can merge
Args:
bbox1 tuple (x1, y1, x2, y2, score)
bbox2 tuple(x1, y1, x2, y2, score)
Returns:
Bool
"""
if direction == 0:
h = bbox1[3] - bbox1... | 816953fce60eced39181c5c9997ec64c49453ae8 | 646,209 |
def to_bool(string):
"""Returns a boolean from a string.
string -- string in format yes|no|true|false
"""
if string.lower() in ("yes", "y", "true", "1"):
return True
elif string.lower() in ("no", "n", "false", "0"):
return False
raise ValueError(str(string) + ' not in ["yes", "... | 0bb8c355b44539bf468fec37c764d4117ec89879 | 646,210 |
import torch
from typing import Union
def knn_gather(
x: torch.Tensor, idx: torch.Tensor, lengths: Union[torch.Tensor, None] = None
):
"""
A helper function for knn that allows indexing a tensor x with the indices `idx`
returned by `knn_points`.
For example, if `dists, idx = knn_points(p, x, leng... | 5e72639f0b9671a69451fbd9b8f53aeb76b0af62 | 646,211 |
import numpy as np
def meanExclDiag(A):
"""
exclude the values from the diagonal of matrix A for calculating the mean.
This way ignore the backprojection to self. Just take care about
correlation of projections into other subjects
"""
sumExclDiag = np.sum((np.triu(A),np.tril(A))) - 2... | 9739aa09a42cad954f2904bea7429085b0b13463 | 646,212 |
def OrangeAndRed(delegates_table):
"""
Sorts delegates from delegates table with 'Not forging'
and 'Missed block' statuses.
'STATUS': 'CIRCLE' =>
"Forging": "green", "Awaiting slot (ok)": "green".
"Awaiting slot (missed block)": "orange", "Missed block": "orange".
"Not forging": "red".
... | bd4ea096862cf180935e28fe036dec3a8be78560 | 646,213 |
def get_date(date):
"""
Getting date in the format %B %d.
:param date: datetime.datetime
:return: str
"""
return date.strftime("%B %d").replace(" 0", " ") | 2b7bd897412b599ba1fc70f0eea5ecd01ea04b2a | 646,214 |
def averageRDCs_on(models, my_data):
"""Returns a dictonary with the average RDCs for the given RDC type:
averageRDC[residue] = value"""
averageRDC = {}
for model_num, model in enumerate(my_data):
if model_num not in models:
continue
for resnum in model:
if ... | f67e84e5d442f301a7590c4387c6923ffd2bdcad | 646,215 |
def convert_to_mole(normalised_element_list):
""" This function converts the normalised oxides weigh percent into
mole percent that is used for the silicate melt viscosity model"""
converted_element_list = []
molar_mass = {
'SiO2': 60.0843,
'TiO2': 79.8658,
'Al2O3': 101.961276,... | 58727da310869d52b45180c2fafdae43d77a1aae | 646,216 |
def sec_to_time(seconds, days_only=False, ):
"""Convert seconds in human readable values
:param int seconds: Time in seconds
:param bool days_only: Output only in days
:return str: Human readable string """
seconds = int(seconds)
if seconds == 0:
seconds = 1
if seconds < 0:
... | 3ffbacc819201756416df30cc78e93a30bb3e12f | 646,217 |
import argparse
def parse_args():
"""
Wrapper to parse CLI arguments.
:return: args
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-dp", "--datapath", default="/tmp", help="Path where to save data."
)
args = parser.parse_args()
# opts is dic in parlai
ar... | 39a52c9966d62e5e426f8311c8ddd22dbbc8cb35 | 646,219 |
def add_missing_columns(df_in, required_columns, fill_val=0.0):
"""Adds columns to the DataFrame 'df_in' if it does not contain all of the
columns in the list 'required_columns'. 'fill_val' is the value that is used
to fill the new columns.
"""
missing_cols = set(required_columns) - set(df_in.colum... | 0375934c7fe91e16c174dbb73041cd643de8ebe7 | 646,220 |
def load_stop_words(filename):
"""Load a set of stop words from a file.
One word each line."""
# you are using CPython, don't you?
# http://stackoverflow.com/a/11027437/1240620
stopwords = {w.strip() for w in open(filename)}
return stopwords | e23ec9a1d20396a0694bdd366a283bfbafb66f2b | 646,221 |
import os
import re
def determine_live_mode():
"""
Returns True if LIVEMODE is set to true in the shell environment, False for
all other cases.
"""
if 'LIVEMODE' in os.environ:
return re.search(r'(?i)^true$', os.environ['LIVEMODE']) is not None
else:
return False | 793f1d37c42b7153a89aef6e24db180f7116246d | 646,222 |
import re
def regex_replace(s, find, replace):
"""A non-optimal implementation of a regex filter"""
return re.sub(find, replace, s) | 6777dcf977eeec8f890b79b0315a37d287e440bc | 646,223 |
def OVER(n):
"""
Returns control codes to set or unset XOR mode text. This has interesting results when
text or graphics is overwritten. Notably, writing text OVER the same text will erase the text.
See the ZX Spectrum manual for more details.
Use this in a ``PRINT`` or ``SET`` command. Example... | df2f56852ba512fdd34c0222ed84c43174eb9c72 | 646,224 |
def piece_to_index(piece_value):
"""
Maps piece value ton valid index
"""
if piece_value == -1:
return 0
elif piece_value == 1:
return 1
else:
return -1 | 4654c0fd1c672333086ae5b3b7e78879701068b6 | 646,226 |
def get_date(filingPath):
"""From FinBert"""
accession_code = filingPath.split('/')[-2]
ticker = filingPath.split('/')[-4]
filing_type = filingPath.split('/')[-3]
#print(accession_code, ticker, filing_type)
code = accession_code+'.txt'
with open(filingPath, 'r') as f:
readlin = f.rea... | 076ddb5ab9d97e1f125f8facce914398cf9fc04a | 646,228 |
def num_permutazioni2(n):
"""ritorna il numero di permutazioni di n oggetti"""
if n==0:
return 1
risp=0
for first in range(n):
risp += num_permutazioni2(n-1)
return risp | c697d0e22b8f97377fd25abe27b72d505ad01a02 | 646,229 |
def uniquify_str(str_, str_set):
"""Uniquifies :attr:`str_` if :attr:`str_` is included in :attr:`str_set`.
This is done by appending a number to :attr:`str_`. Returns
:attr:`str_` directly if it is not included in :attr:`str_set`.
Args:
str_ (string): A string to uniquify.
str_set (se... | 0cd412cedf3c676604e184916a9db5d80cd721c8 | 646,231 |
def transform_images(X, max_x_value=255):
"""Flatten and rescale input."""
# Divide by a fixed value to be sure that we are making the same
# transformation on training and test data.
return X.reshape(X.shape[0], -1) / max_x_value | fd876b96e90732e5f071d571a9fed5bbbf4902f7 | 646,232 |
def keyname(name, i, okey):
"""
>>> keyname('x', 3, [None, None, 0, 2])
('x', 3, 0, 2)
"""
return (name, i) + tuple(k for k in okey if k is not None) | 8b00124775565882b89a1c680515fa7c6b21409b | 646,233 |
import math
def get_nearest_location(x, places):
"""
Given a location `x`, and a list of locations, `places`,
returns the list index corresponding to the minimum distance,
and the minimum distance.
"""
min_dist, min_i = 1e10, 0
for i, place in enumerate(places):
name = place['name'... | 251e97cc0ad2117f40e68e9690dfb6094e18205e | 646,234 |
import os
def has_fasta_index(fasta_file):
"""Check to see if fasta_file has an index"""
return os.path.exists(fasta_file + ".index") | dfbacb54e14b97e97fb4755fb7caa829ccd0161f | 646,235 |
import sqlite3
import hashlib
def check_for_username(username, password, db):
"""Check for validity of username and password."""
global conn
global cursor
conn = sqlite3.connect(db)
cursor = conn.cursor()
# first, check if the username is there
try:
cursor.execute("SELECT username ... | 1fd6fb1a472c1fd8c5843d88d892139c5e577e73 | 646,236 |
import json
def simplify_stack_objects_current_object_for_display(stack_objects):
"""
simplifies the current_object used by the stack_objects,
to make it smaller and more suitable for being displayed in error messages.
The simplified object should have a limited size no matter what.
All strings ge... | e0f3f623262a9719b26ab2284592e78c21c132d0 | 646,237 |
def model_paths():
"""
Returns models (dict): Best models' paths for all label sizes.
"""
models = {
"100":[
["best_models/60/C_epoch_23_label_100.pt","best_models/60/D_epoch_23_label_100.pt","best_models/60/G_epoch_23_label_100.pt"],
["best_models/61/C_epoch_15_lab... | cfb8a9698299f684c134125cf2a4cf9c47816153 | 646,238 |
import re
def remove_namespace(xml):
"""
Strips the namespace from XML document contained in a string.
Returns the stripped string.
"""
regex = re.compile(' xmlns(:ns2)?="[^"]+"|(ns2:)|(xml:)')
return regex.sub("", xml) | 1a53503032fab79a2123e69d73481c5f5eceaadb | 646,239 |
from datetime import datetime
def datetime_to_iso(date):
"""
Converts a datetime to the ISO8601 format, like: 2014-05-20T06:11:41.733900.
Parameters:
date -- a `datetime` instance.
"""
if not isinstance(date, datetime):
date = datetime.combine(date, datetime.min.time())
return dat... | 1fc89c2b96d6a4ec3021d87630b6fa611ee0653d | 646,240 |
def mean(*args):
"""
Calculates the mean of a list of numbers
:param args: List of numbers
:return: The mean of a list of numbers
"""
index = 0
sum_index = 0
for i in args:
index += 1
sum_index += float(i)
return (sum_index / index) if index != 0 else "Division by z... | 4857118cf841f82274c5eaf712b5241a261e1033 | 646,241 |
def _expand_dim_specification(image_shape, dim_spec):
"""Expand mex dimension specification.
The dimension specification can be 2 or 3 long, it is
processed in two steps:
1. If it is of length 2, a -1 is prepended to it
2. Each dimension with -1 is replaced with the whole corresponding image dimens... | 35ec014d3624ae078ca8d84eb74613f3f79059f2 | 646,242 |
def atttyp(att: str) -> str:
"""
Helper function to return attribute type as string.
:param str: attribute type e.g. 'U002'
:return: type of attribute as string e.g. 'U'
:rtype: str
"""
return att[0:1] | 275e90c7403109bc2caae57b5ed26c811a5c7702 | 646,243 |
def test_single_threaded_tree() -> list:
"""Return tree data for building a test single threaded tree."""
return [
(4, ""),
(1, ""),
(7, ""),
(3, ""),
(5, ""),
(8, ""),
(2, ""),
(6, ""),
] | 8668d20d52bde347a1abe8784b07e92d717df24e | 646,244 |
def createDictFromAttr(objList, attr):
"""\
Group the objects in objList based on their value for a specific attribute.
Return: A dict where each key is one of the values attested for the attribute. The value associated with each key is a list of objects whose value for attr was the same as the key.
Parameters:
... | 6774068b04dc8d6a126afc4054e1b503dec37182 | 646,245 |
def normal_range(mean, sd, treshold=1.28):
"""
Returns a bottom and a top limit on a normal distribution portion based on a treshold.
Parameters
----------
treshold : float
maximum deviation (in terms of standart deviation). Rule of thumb of a gaussian distribution: 2.58 = keeping 99%, 2.33... | 8f130a40d85ab423770ef9a6ee1bf731db72cc9a | 646,247 |
def count_calls(f):
"""A decorator that counts the call count of the decorated method for
testing purposes
:param f: the function to be decorated
:return: function
"""
def wrapper(*args, **kwargs):
# first arg is the self
self = args[0]
function_name = f.__name__
... | 348637a69c67398062bbdb0c2eb50625f64d3701 | 646,248 |
def get_authorization_header(request):
"""Returns the dict with Authorization header for using in a request to TIT API. """
try:
access_token = request.COOKIES['accessToken']
return {'Authorization': f'Bearer {access_token}'}
except KeyError:
"""Access token doesn't exist in cookies... | 4cf1d9df96d59f46998e964b0e740c6c9dbb2a6d | 646,249 |
def Variants(barcode):
"""
barcode: (str) a string of a DNA sequence
"""
out = []
baseseq = barcode.upper()
for i in range(len(baseseq)):
pre = baseseq[0:i]
char = baseseq[i]
post = baseseq[i+1:]
if not char in ["A","C","G","T"]:
continue
for ... | 85c63e9e6bd773403a90b02dd3630626277d84f2 | 646,250 |
def grouping(df, col_name):
"""
:param df: Pandas DataFrame.
:param col_name: Name of column.
:return DataFrame grouped by given column with count aggregation function
"""
return df.groupby(col_name)['rating'].count() | 880a92587ac5462d41db1f3f75c4ec00b4e6c849 | 646,251 |
def has_shape(a):
"""Returns True if the input has the shape attribute, indicating that it is
of a numpy array type.
Note that this also applies to scalars in jax.jit decorated functions.
"""
try:
a.shape
return True
except AttributeError:
return False | 7c3883509a0ec0d8a9b805c93cb31a56db2070c5 | 646,252 |
import binascii
from typing import Mapping
import json
def serialize(obj) -> str:
"""NamedTuple-flavored serialization to JSON."""
def contents_to_primitive(o):
if hasattr(o, '_asdict'):
o = {**o._asdict(), '_type': type(o).__name__}
elif isinstance(o, (list, tuple)):
r... | 91d572c9eb73c9fed29ac3e64a54d127147a4c8a | 646,253 |
import logging
def stylesheets(soup=None):
"""Find stylesheet URLs in HTML code.
:param soup: The parsed HTML, defaults to None
:param soup: BeautifulSoup, optional
:return: All stylesheet URLs from link tags
:rtype: list
"""
if soup is None:
logging.info('⚠️ No HTML content avail... | 5651c58352c1d22e25b903271724e28fd0a73ede | 646,254 |
def format_media_type(media_type: str) -> str:
"""
Formats the media type.
"""
MediaType = {
"TV": "TV",
"MOVIE": "Movie",
"OVA": "OVA",
"ONA": "ONA",
"TV_SHORT": "TV Short",
"MUSIC": "Music",
"SPECIAL": "Special",
"ONE_SHOT": "One Shot",
... | 63deda848e1259400d2846512f89d1b8d43ec0a3 | 646,255 |
def build_traversal_spec(client_factory, name, type, path, skip,
select_set):
"""Builds the traversal spec object.
:param client_factory: Factory to get API input specs
:param name: Name for the traversal spec
:param type: Type of the managed object reference
:param path: P... | 79b38d40f48f03b69d7ef41a452bee4a4e086485 | 646,256 |
def tmp_memory():
"""Dict to use when one wants to store sth between steps.
Because of use of multiple browsers, the correct format would be:
{'browser1': {...}, 'browser2': {...}, ...}
"""
return {} | 5a3a727601baa01c7f618e67e9112ceaa4034155 | 646,257 |
def two_sum(target, ls):
"""
Check if two numbers within input array sum to target
"""
complements = set()
for num in ls:
if num in complements:
return True
complements.add(target - num)
return False | 21cab4cd4b214f48a8c84e0e4a8c48265ea68844 | 646,258 |
def tuple_remove(tup, *items):
"""Return a copy of a tuple with some items removed.
:param tup: The tuple to be copied.
:param items: Any number of items. The first instance of each item will
be removed from the tuple.
"""
tuple_list = list(tup)
for item in items:
tuple_list.rem... | 8d14f15b2c674f465171e951f06735b9ace28ebb | 646,259 |
import torch
def stft3d(x: torch.Tensor, *args, **kwargs):
"""Multichannel functional wrapper for torch.stft
Args:
x (Tensor): audio waveform of
shape (nb_samples, nb_channels, nb_timesteps)
Returns:
STFT (Tensor): complex stft of
shape (nb_samples, nb_channels, nb... | 07ff5c547f7419e62f8408adecaba7bdf0a3299f | 646,260 |
def get_worst_case(metrics: list) -> int:
"""Get worst case"""
if metrics:
return max(int(item.get_text()) for item in metrics)
else:
return 0 | 170aa1d698f887ccc622489289cf4ce876f10f46 | 646,261 |
from datetime import datetime
def time_until(next_mins):
"""
Given N minutes, this function calculates the
timestamp (in UTC) when the Nth minute next occurs.
Example: If the time is 16:43:02 and we run time_until(15)
the string 17:15:00 will be returned.
Args:
next_mins (int): The n... | c4009c16d81be925e02998aaabedfbffbb930166 | 646,262 |
import subprocess
def get_xygrid(image):
"""
Get the ``xygrid`` of the input image.
"""
subprocess.check_call(["punlearn", "get_sky_limits"])
subprocess.check_call([
"get_sky_limits", "image=%s" % image, "verbose=0"
])
xygrid = subprocess.check_output([
"pget", "get_sky_lim... | 9bdb538d0b8ef0923fa4dcc46cbad2d5049568bb | 646,264 |
import tempfile
def _mdk_mktempdir():
"""Create temporary directory."""
return tempfile.mkdtemp() | 0c52fba085ecf89e2d130b2f80474599bf1c1f03 | 646,265 |
def num_occurance_atob(a,b,df):
"""
find num occurance of activity a followed by activity b in dataframe df
args: a: activity number (dtype: int)
b: activity number (dtype: int)
df: dataframe (pandas) where a, b occur (must have ActivityID column)
returns: num_occurance (dtype: int... | ba533b42809879aa5589ebb6280d19a5aaed4e27 | 646,267 |
def fatorial(n):
""" Retorna o fatorial de um número n """
if n == 1:
return 1
else:
for c in range(n, 0+1, -1):
c -= 1
n = n*c
return n | 6241c7cdcfd2df6cffde97e4d79a36a7aff3fc16 | 646,268 |
def createICDdictionary(filename):
"""This function takes the sorted_icd_codes file as an arg. and create the following dictionary:
ex. {'1': 'BEXT', '3': 'CALI', '2': 'BINT',....,'35': 'XTRN'}"""
fh = open(filename)
ICDdict = {}
for line in fh:
line = line.strip().split()
ICDdict[li... | 34effc8a933ceea55a86fabf7e41bdbae2b8df10 | 646,269 |
def get_column_names(data_frame):
"""Returns a list of every column name in data_frame.
Args:
data_frame: A pandas.DataFrame.
Returns:
A list of every column name in data_frame.
"""
data_frame.columns.get_values()
return data_frame.columns.get_values() | 492971ff14ba9db1b364e9394b5c2a26a5c60558 | 646,270 |
def files_changed(ctx):
"""
Return the list of file changed in the current branch compared to `master`
"""
changed_files = ctx.run('git diff --name-only master...', hide='out').stdout.splitlines()
# Remove empty lines
return [f for f in changed_files if f] | 29af46c492466fb15e3b9a7a46bc6d47c9f8a52f | 646,271 |
from pathlib import Path
import os
def shorten_path(path: Path) -> Path:
"""
Returns the path relative to the current working directory if possible. Otherwise return the path unchanged.
"""
try:
return path.relative_to(os.getcwd())
except ValueError:
return path | 35513060db56867212a8e26cba0fbcf5f48ba6b0 | 646,272 |
def parse_payload_v1(event):
"""
Get HTTP request method/path/body for v1 payloads.
"""
body = event.get('body')
method = event.get('httpMethod')
try:
package, *_ = event['pathParameters']['package'].split('/')
except KeyError:
package = None
return (method, package, body... | 2a32dd96bcaf916efdb53ba3dd8430ba4c5eef5d | 646,273 |
import os
def get_files(dirs):
"""Return a list of all hpp/cpp files within the given folders."""
file_pairs=[]
for root_dir in dirs:
for root, _, files in os.walk(root_dir):
for filename in files:
if (filename[-2:] == 'pp'):
file_pairs.append([root,... | 987aaad70c326df998b181016b8561ab843b3243 | 646,274 |
def adjust_learning_rate(base_lr, lr_ramp_steps, lr_decay, lr_decay_multiplier, optimizer, global_step):
"""Sets the learning rate to the initial LR decayed every lr_decay epochs"""
if global_step < lr_ramp_steps:
lr = base_lr * (global_step / lr_ramp_steps)
else:
lr = base_lr * (lr_decay_mu... | d7150bfa0997bf1a7879e3fbc8eaafc283d4e043 | 646,275 |
import unicodedata
def punctuate_character(char: str) -> int:
"""Create a punctuation based on special characters and upper letters"""
punctuation = 0
if not unicodedata.is_normalized("NFKD", char):
punctuation += 30
if char.isupper():
punctuation += 10
return punctuation | eaad0bcffac1c4689d995df3baefd551f9311a7d | 646,276 |
import torch
import os
def load_model_from_statedict(model, args):
"""
This function is implemented to match the keys in state dict
"""
nomalized_model_type = args.model_type.split('/')[-1].split('-')[0]
if torch.cuda.is_available():
print('> load model path : ', os.path.join(args.dir_path... | 3c8b40c1ebf146f01e76a578a76f90c0761c4399 | 646,278 |
import json
def getConfigNames(xen, session, logger, ref):
"""
Return all config names associated with the given disk by reading the disk's other config in Xen.
:param logger: A logger used for logging possible errors.
:type logger: seealso:: :class:`logging:Logger`
:param ref: Xen reference of ... | d108c718b244163a23ee974ca456714fdca88ee9 | 646,279 |
import platform
import os
import logging
import tempfile
def get_user_home():
"""A reasonable platform independent way to get the user home folder.
If PCSE runs under a system user then return the temp directory as returned
by tempfile.gettempdir()
"""
user_home = None
if platform.system() == ... | 77a574a73c0e14a7fa8ef9bc418a7404b2079107 | 646,284 |
def initial_sigmoid_params(x, y):
"""Reasonable initial guesses for the parameters."""
b = 7.0 / max(x)
r = max(y)
m = (max(x) + min(x)) / 2.0
return [b, r, m] | 499925d5175f8c79d591e9ca0e4d9b3e3b78c6d1 | 646,285 |
def s_hint(ans):
"""
:param ans: str, the answer for user to guess
:return: str, dashed version of "ans" to show number of character within this word as a hint for user
"""
hint = ''
for i in range(len(ans)):
hint += '-'
return hint | 2a18966db7ad979775225c13b273783ea03ddebf | 646,286 |
from datetime import datetime
import calendar
def get_first_and_last_dates_of_month(month: int, year: int):
"""Return first and last dates for a given month and year."""
start_date = datetime.now().replace(day=1, year=year, month=month)
end_date = start_date.replace(day=calendar.monthrange(year=year, mont... | 06b58e5257dd0bde1002f7d2ccbb5f1937de87e9 | 646,287 |
def trajectory_reward(xtr, phi, reward, rollout):
"""Get discounted reward of a trajectory
Args:
xtr (mdp_extras.DiscreteExplicitExtras): MDP extras
phi (mdp_extras.FeatureFunction): Feature function to use with linear reward
parameters.
reward (mdp_extras.RewardFunction): R... | e60d23e09c514555fec6cb2b5bbcfc61f9dd3707 | 646,288 |
def total_seconds(delta):
"""Return the total seconds of datetime.timedelta object.
Compute total seconds of datetime.timedelta, datetime.timedelta
doesn't have method total_seconds in Python2.6, calculate it manually.
"""
try:
return delta.total_seconds()
except AttributeError:
... | e138b08fdadaf3675a0ff42a50875e09b823c883 | 646,289 |
def get_geojson_data(geojson, name):
"""
返回指定名称的geojson对象
Args:
geojson: 所有省份的geojson对象
name: 省份名称
Returns:
返回json对象
"""
for i in range(0, len(geojson["features"])):
feature = geojson["features"][i]
if (name in feature["properties"]["name"]):
... | c3d9a687b98acbea641ecbd154f5b9dc4ab3a5a0 | 646,290 |
def squeeze(input, downscale_factor: int = 2):
"""
[:, C, H*r, W*r] -> [:, C*r^2, H, W]
"""
batch_size, in_channels, in_height, in_width = input.size()
out_channels = int(in_channels * (downscale_factor ** 2))
out_height = in_height // downscale_factor
out_width = in_width // downscale_fact... | 7ca409bc15deaae44e6801e5430aecb2b9fddef0 | 646,291 |
def clean_value(value):
"""
Clean the value; if N/A or empty
:param value: original value
:return: cleaned value
"""
if value:
value = value.strip()
if value.lower() == 'n/a':
value = None
if value == '':
value = None
return value | eaaf71b8e4cf931e50c319bebee59d41b33fcfb9 | 646,292 |
import json
def import_map(inpath):
"""import json"""
with open(inpath) as j_file:
map_dict = json.load(j_file)
print(f"Successful Import of Map: {inpath}")
return map_dict | 31d4b16f4c0518674bf497b9f6c8701c0fe3b54f | 646,293 |
def contains_word(root, input_word):
"""Check if word is in the Trie and return True/False."""
cNode = root
for char in list(input_word):
found_match = False
for node in cNode.nodes:
if node.char == char:
found_match = True
cNode = node
... | cd9aaac234900bac80fbd23bc1ce42ce8f88f6aa | 646,294 |
def list_videos():
"""
pega a lista dos videos disponiveis e retorna uma string com LISTA_DE_VIDEOS
e uma lista com os nomes dos videos
:returnf'LISTA_DE_VIDEOS lista_dos_videos_para_reproducao':
"""
return f'LISTA_DE_VIDEOS lista_dos_videos_para_reproducao' | a6f3bfc21c3e55080fa9da4a574739dc5c1eae33 | 646,296 |
def find_cutlag(weight):
"""Compute the maximum valid lag time from trajectory weights.
Parameters
----------
weights : (n_frames,) ndarray
Weight of each configuration in a trajectory.
Returns
-------
int
Maximum valid lag time in units of frames.
"""
last = len(... | 436f3a3b5b05e7edf26867ab9674fa7c6d1f7e31 | 646,298 |
def update_keeper(keeper, next_point):
"""
Update values of the keeper dict.
"""
keeper["prev_point"] = keeper["curr_point"]
keeper["curr_point"] = next_point
keeper["coverage_path"].append(next_point)
# If everything works this conditional
# should evaluate to True always
if not ke... | 9e9aa43488080d4c8af8b90989712f609238ba4a | 646,299 |
import os
import random
def shuffle_every_epoch(data_path):
"""Return a list of shuffled sample file names.
Args:
data_path: the folder path of the samples (string)
Returns:
alist: list of file names of the samples (string)
"""
alist = os.listdir(data_path)
rand... | 354da9a5a1c0f4fcd29f292abd47236ce989841c | 646,300 |
import argparse
import os
def arg_parse():
"""
Parse arguements to the detect module
"""
parser = argparse.ArgumentParser(description='YOLO v3 Training Module')
parser.add_argument("--cfg", dest='cfgfile', help="Config file", type=str, default=os.path.join("cfg","yolov3.cfg"))
parser.add_argu... | 830723a6d258f5f1ee32783adad10af0ec313ddb | 646,302 |
import os
import fnmatch
def find_files(path, extension):
""" Simple utility script to find files with given file extension in path.
"""
matches = []
for root, dirnames, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, extension):
matches.append(os.path.join(r... | 569da1be667550e736fac77e69809ce691ca3d24 | 646,303 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.