content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def evalexpr(data, expr, exprvars=None, dtype=float):
""" evaluate expression based on the data and external variables
all np function can be used (log, exp, pi...)
Parameters
----------
data: dict or dict-like structure
data frame / dict-like structure containing named columns
exp... | 5,305,200 |
def word_list_raw():
"""
Return the wordlist used for mnemonics.
"""
return """abandon
ability
able
about
above
absent
absorb
abstract
absurd
abuse
access
accident
account
accuse
achieve
acid
acoustic
acquire
across
act
action
actor
actress
actual
adapt
add
addict
address
... | 5,305,201 |
def bfs(graph: Graph, start: int) -> None:
"""
Print a breadth-first traversal of a graph
:param graph: graph to be traversed
:param start: starting point of traversal
:return: None
>>> graph = Graph(5)
>>> graph.add_edge(0, 1)
>>> graph.add_edge(0, 2)
>>> graph.add_edge(0, 4)
>>... | 5,305,202 |
async def test_motion(hass, rfxtrx_automatic):
"""Test motion entities."""
rfxtrx = rfxtrx_automatic
entity_id = "binary_sensor.x10_security_motion_detector_a10900_32"
await rfxtrx.signal(EVENT_MOTION_DETECTOR_MOTION)
assert hass.states.get(entity_id).state == "on"
assert hass.states.get(entit... | 5,305,203 |
def _ensure_data(values: ArrayLike) -> np.ndarray:
"""
routine to ensure that our data is of the correct
input dtype for lower-level routines
This will coerce:
- ints -> int64
- uint -> uint64
- bool -> uint64 (TODO this should be uint8)
- datetimelike -> i8
- datetime64tz -> i8 (in... | 5,305,204 |
def _check_dthetapsi(
dtheta=None, psi=None,
extenthalf_psi=None, extenthalf_dtheta=None,
ntheta=None, npsi=None,
include_summit=None,
):
""" Return formatted dtheta and psi
They are returned with the same shape (at least 1d arrays)
They can be:
- 'envelop': if psi of dtheta = 'env... | 5,305,205 |
def test_grid_layout_margins():
"""Verify GridLayout margins."""
nd = create_empty_nd()
with pytest.raises(ValueError) as e_info:
_ = layout.GridLayout(
nd,
(0.0, 0.0, 1.0, 1.5),
rows=[5],
cols=[10, 20, None, 20, None],
margins=(0.05, 0.05)... | 5,305,206 |
def find_beta_image_identifier(targetgrouparn):
"""Queries the tags on TargetGroups
Args:
targetgrouparn - Amazon ARN of the Target group that needs to be queried for the Tags
Returns:
identifier : tag key value of the target group , with KeyN... | 5,305,207 |
def fread(f,byteLocation,structFormat=None,nBytes=1):
"""
Given an already-open (rb mode) file object, return a certain number of bytes at a specific location.
If a struct format is given, calculate the number of bytes required and return the object it represents.
"""
f.seek(byteLocation)
if str... | 5,305,208 |
def challenge_three(turtle):
"""Draw many polygons with different colors."""
turtle.write_at_top("Challenge three.")
timmy.jump_to(-50, 200)
speed = turtle.speed()
turtle.speed(0)
turtle.draw_n_polygons(15)
turtle.speed(speed)
sleep(2)
turtle.clear() | 5,305,209 |
async def handle_post_projects(project: projects.schemas.project.ProjectCreate,
session: Session = Depends(session_scope)):
"""
Handles POST requests to /.
Parameters
----------
project : projects.schemas.project.ProjectCreate
session : sqlalchemy.orm.session.Sess... | 5,305,210 |
def _cast_types(args):
"""
This method performs casting to all types of inputs passed via cmd.
:param args: argparse.ArgumentParser object.
:return: argparse.ArgumentParser object.
"""
args.x_val = int(args.x_val) if args.x_val != 'None' else None
args.test_size = float(args.test_size)
# criterion (string)
# s... | 5,305,211 |
async def test_fan_registry_state_callback(
opp, pywemo_registry, pywemo_device, wemo_entity
):
"""Verify that the fan receives state updates from the registry."""
# On state.
pywemo_device.get_state.return_value = 1
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await opp.... | 5,305,212 |
def replace_and_concat(mac: str, vendor: str, python_option=True) -> str:
"""
Creates single string depending on the selected mode.
TODO: Make it simpler without the python_option flag
Args:
mac {str}: mac address
vendor {str}: vendor string
python_optio... | 5,305,213 |
def bruteforce_method(p1, p2):
"""Метод полного перебора"""
e_cnt = pf.e_normalize(p2)
pf.s_to_c(p2)
logging.debug('BruteForce: ' + str(p1) + str(p2))
split_subs = SplitSubstitution(p1, p2, EPL_method).algorithm()
# for sub in split_subs:
# if pf.NePL_test(sub, p2):
# if NePL... | 5,305,214 |
def inpt_program():
"""
Считываем строку пользователя и отправляем бат-код в устройство
"""
str_textProgram=''
while True:
us_input=input('Ukuvchi>>>') # получаем конкретную строку исходной программы
if us_input=='Quit':
break
if us_input!='E':
"""
... | 5,305,215 |
def prequalification(request, step):
"""
View for rendering pre-qualification questions.
If user is not authenticated with BCeID, temporarily store user responses to session
"""
template = 'prequalification/step_%s.html' % step
if not request.user.is_authenticated:
responses_dict = get_... | 5,305,216 |
def _read_netcdf_coordinate_units(root):
"""Get units for coodinate values.
Parameters
----------
root : netcdf_file
A NetCDF file.
Returns
-------
tuple of str
Units for each coordinate.
"""
units = []
for coordinate_name in _AXIS_COORDINATE_NAMES:
try:... | 5,305,217 |
def load():
"""load database from json file"""
global DEPARTMENTS, REF_COURSES
path = os.path.join(os.path.dirname(__file__), 'data', 'mitcl.dat')
if os.path.exists(path):
with open(path, 'r') as data:
DEPARTMENTS, REF_COURSES = pickle.load(data)
else:
print("download cou... | 5,305,218 |
def check(_user_id):
"""
checks whether it is a check.
"""
_board = boards[_user_id]
return _board.is_check() | 5,305,219 |
def angle_to_pixels(angle, screenDist, screenW, screenXY):
"""
Calculate the number of pixels which equals a specified angle in visual
degrees, given parameters. Calculates the pixels based on the width of
the screen. If the pixels are not square, a separate conversion needs
to be done with the heig... | 5,305,220 |
def toUrlsafe(filename):
"""Make a filename url-safe, keeping only the basename and killing all
potentially unfitting characters.
:returns: urlsafe basename of the file as string."""
filename = os.path.basename(filename)
filename = unicodedata.normalize('NFKD', filename).encode("ascii", "ignore")
... | 5,305,221 |
def _delete_conn_info(self, switch, port, dir):
""" Deletes existed connection between ``port1`` and ``port2`` an the switch
``dir`` could be ``bi``,``in`` or ``out``
"""
cli = self._clients[switch]
ip = cli["ip"]
conn_port = cli["port"]
session = cli["session"]
if dir == 'bi... | 5,305,222 |
def get_mask_for_tokens(tokens: List[str],
special_tokens: List[str] = []) -> List[int]:
"""Return a mask for a tokenized smiles, where atom tokens
are converted to 1 and other tokens to 0.
e.g. c1ccncc1 would give [1, 0, 1, 1, 1, 1, 1, 0]
Args:
smiles: Smiles string of... | 5,305,223 |
def fail_if_data_set_exists(zosmf_profile, dataset_name):
"""
Check whether data set exists and throw and exception if it does
"""
connection = {'plugin_profile': zosmf_profile}
files = Files(connection)
list_dsn = files.list_dsn(dataset_name)
if list_dsn['returnedRows'] == 0 :
retu... | 5,305,224 |
def snopt_opt(objfun, desvar, lb, ub, ncon=None, title=None, options=None,
sens='FD', jac=None):
"""
Find optimal values using SNOPT from pyoptsparse.
If SNOPT is not available, use other avaiilable optimizer. The desvar is an array of variables
named 'x', and the objective is named 'obj'... | 5,305,225 |
def yiq_to_web(yiq):
"""
Convert a YIQ color representation to a WEB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the
luma and chrominance.
:return: WEB r... | 5,305,226 |
def post_processing(data, start, scaler_1, scaler_2, delta):
"""Post-processing"""
data = scaler_2.inverse_transform(data)
data = data * np.exp(0.5 * delta * data **2)
data = scaler_1.inverse_transform(data)
data = np.exp(data)
post_data = np.empty((data.shape[0], ))
post_data[0] = star... | 5,305,227 |
def predict_accuracy(armas: tuple, sig: SwitchingArmaSignal) -> float:
""" Predict accuracy score from ARMA models.
Parameters
----------
armas
Pair of `Arma` models.
sig
Signal generated from the ARMA models.
Returns a predicted value for the expected accuracy score of... | 5,305,228 |
def get_contours_inner_angles(contour):
"""
Given a closed contour, return a list of its inner angles in radians
:param contour: a 2D numpy array
:return: 1D numpy array of angles in radions
"""
# Unroll all points triplets to vectors
a = contour
b = np.tile(contour, reps=(2, 1))[1:1 + ... | 5,305,229 |
def _get_year(obj):
"""
Get the year of the entry.
:param obj: year string object
:return: entry year or none if not valid value
"""
year = obj[0:4]
try:
year = int(year)
except ValueError:
year = None
return year | 5,305,230 |
def solve4y(x: float, m: float, b: float):
"""
y = m * x + b
"""
if m is np.nan:
return b
return m * x + b | 5,305,231 |
def download_from_rcsb(target_directory):
""" target_directory should be a directory (present or not) within /Databases. Include
only the path from there. """
# transform target_directory into its full path
target_directory = os.path.join(os.path.abspath('.'), '.', target_directory)
# acquire the source directory
... | 5,305,232 |
def _parse_arguments():
"""Return a parser context result."""
parser = argparse.ArgumentParser(description="CMake AST Dumper")
parser.add_argument("filename", nargs=1, metavar=("FILE"),
help="read FILE")
return parser.parse_args() | 5,305,233 |
def main():
"""Configure the logger and set configuration for the replications."""
start_time = time.time() # seconds for timing
now = datetime.datetime.now() # datetime for log file name
############################### user variables #################################
# Change these variables to... | 5,305,234 |
def search(query_string):
"""Search for stations containing QUERY_STRING."""
stations = national_rail.stations_by_string(query_string)
ui.list_stations(stations) | 5,305,235 |
def c2():
"""Compound CID 175."""
return Compound.from_cid(175) | 5,305,236 |
def create_user(request):
""" Creates a new user with specified settings
URL: /admin/Users/Create/
:param request:
:return:
"""
post = request.POST.dict()
username = post.get('username')
if username is None:
response = {'status':-1, 'status_message':'No username specified.'... | 5,305,237 |
def parse_arguments() -> argparse.Namespace:
"""Parse given command line arguments."""
parser = argparse.ArgumentParser(
allow_abbrev=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
calculation = parser.add_argument_group("crafting options")
verbosity = parser.add_argument_g... | 5,305,238 |
def hist_to_density_fullspace(counts, errs, bins, totalweight):
""" Normalize histogram to a unit integral density function
over total sum of event weights (not just the visible histogram range mass)
"""
norm = binwidth(bins) * totalweight
return counts/norm, errs/norm | 5,305,239 |
def epochPoints(abf):
"""Return a list of time points where each epoch starts and ends."""
if abf.abfVersion["major"] == 1:
return []
position = int(abf.sweepPointCount/64)
epochPoints = [position]
for epochNumber, epochType in enumerate(abf._epochPerDacSection.nEpochType):
pointCoun... | 5,305,240 |
def process_comment(user, comment):
"""
Process a single comment.
* Updates metrics
* Sanitizes and extracts chunks from comment.
"""
text = Util.sanitize_text(comment.text) # Sanitize comment text.
user.corpus += text.lower() # Add comment text to corpus.
comment_timestamp = datet... | 5,305,241 |
def attention_lm_moe_prepare_decoder(targets, hparams):
"""Prepare one shard of the model for the decoder.
Args:
targets: a Tensor.
hparams: run hyperparameters
Returns:
decoder_input: a Tensor, bottom of decoder stack
decoder_self_attention_bias: a Tensor, containing large negative values
t... | 5,305,242 |
def lat_meters(lat: float) -> float:
"""
Transform latitude degree to meters.
Parameters
----------
lat : float
This represent latitude value.
Returns
-------
float
Represents the corresponding latitude value in meters.
Examples
--------
Latitude in Fortale... | 5,305,243 |
def make_rpc_report(repo_dir, old_commit, new_commit,
args):
"""Create initial RST report header for OpenStack-Ansible."""
# Do we have a valid commit range?
# NOTE:
# An exception is thrown by osa_differ if these two commits
# are the the same, but it is sometimes necessary to ... | 5,305,244 |
def ensure_profile_exists(sender, instance, created, **kwargs):
"""If the User has just been created we use a signal to also create a TalksUser
"""
if created:
tuser, tuser_created = TalksUser.objects.get_or_create(user=instance) | 5,305,245 |
def setupSSH(key_rsa_path, key_append_path, key_gen_cmd, HostList):
"""Setups up passwordless SSH between the localhost
and other target hosts"""
# Generate SSH key on localhost
LocalKey = getLocalKey(key_gen_cmd, key_rsa_path)
# Setup passwordless SSH with each of the specified machines
for i ... | 5,305,246 |
def _make_repo_ovz(outdict, outfile):
"""write the history to a file
input: history in the form of a dictionary, output filename
output: the specified file as written to disk
"""
with open(outfile, "w") as _out:
for key in sorted(outdict.keys()):
_out.write('{}: {}\n'.format(out... | 5,305,247 |
def generic_blockvisibility_workflow(visfunction, vis_list, additive=True, *args, **kwargs):
""" Definition of interface for create_generic_blockvisibility_graph_visfunction.
:func visfunction: Function to be applied
:param vis_list: List of vis_graphs
:param additive: Add to existing visibility? (True... | 5,305,248 |
def year_parse(s):
"""Parses a year from a string."""
regex = r"((?:19|20)\d{2})(?:$|[-/]\d{2}[-/]\d{2})"
try:
year = int(re.findall(regex, ustr(s))[0])
except IndexError:
year = None
return year | 5,305,249 |
def recompute_etas_P(D, dataloader):
"""Recomputes etas integrating dD/dx over P
"""
etas = 0
n_samples = 0
for data in dataloader:
_, _, Ep_grad2 = compute_objective_terms(data, D, need_penalty_terms=True)
# Only 1 term, i.e. integrate over P ((P+Q)/2 would work also)
etas +... | 5,305,250 |
def write_parameters(data, run_dir, is_parallel):
"""Write the parameters file
Args:
data (dict): input
run_dir (py.path): where to write
is_parallel (bool): run in background?
"""
pkio.write_text(
run_dir.join(template_common.PARAMETERS_PYTHON_FILE),
generate_pa... | 5,305,251 |
def parse(fp, encoding='utf8'):
"""
Read PSD file from file-like object.
:rtype: ParseResult
Example::
from psd_tools.reader.reader import parse
with open('/path/to/input.psd', 'rb') as fp:
result = parse(fp)
"""
header = psd_tools.reader.header.read(fp)
retu... | 5,305,252 |
def median(x):
"""返回数据 x 的中位数"""
n = len(x)
sorted_x = sorted(x)
midpoint = n // 2
if n % 2 == 0:
# 如果是奇数,返回中间值
return sorted_x[midpoint]
else:
# 如果是偶数,返回中间两个值的均值
lo = midpoint - 1
hi = midpoint
return (sorted_x[lo] + sorted_x[hi]) / 2 | 5,305,253 |
def lost_to_gaia(gaia_ids):
"""Find villagers lost to specified gaia object types."""
query = """
select units.match_id, units.initial_player_number as number, units.destroyed::interval(0) as timestamp
from object_instances as gaia join object_instances as units on units.destroyed_by_instance_id... | 5,305,254 |
def getFilteredLexicon(lexicondict, allwords):
""" Returns a lexicon with just the necessary words.
Assumes all wanted keys exist in the given lexicon """
return { word: lexicondict[word] for word in allwords } | 5,305,255 |
def releases_info(c):
"""show sphinx releases=stff (test)
:param c:
:type c:
:return:
:rtype:
"""
print("releases.util.changelog2dict")
print("releases.util.make_app")
print(
"""
:param c:
:type c:
:return:
:rtype:
releases.util.parse_changelog(path, **kwargs)
r... | 5,305,256 |
def report_single(subdomain_list, hostname, format, quiet=False):
"""Report if subdomains were found."""
if format == 'json':
if not quiet:
print(banner)
print(json_format(subdomain_list, hostname))
else:
if not quiet:
print(banner)
if len(subd... | 5,305,257 |
def post(item):
""" blog item """
name = item.split(".")[0] # No extension
return render_template(
"post.html",
html_tab_title=f"Villoro - {item}".replace(".html", ""),
**u.get_content()["blog"][name],
) | 5,305,258 |
def test_set_method():
"""Test setting the method property."""
x = Concrete()
m = "sampling"
x.method = m
assert_equal(x.method, m) | 5,305,259 |
def relu(x, name=None):
"""
relu activation.
.. math::
out = max(x, 0)
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
name (str, optional): Name for the operation (optional, default is None).
For more information, please refer to :ref:`ap... | 5,305,260 |
def filter_suite(condition, suite):
"""Return tests for which ``condition`` is True in ``suite``.
:param condition: A callable receiving a test and returning True if the
test should be kept.
:param suite: A test suite that can be iterated. It contains either tests
or suite inheriting from ... | 5,305,261 |
def build_loss_fun():
"""Build the loss function."""
return get_loss_fun()() | 5,305,262 |
def test_transfer_with_allowance(released_token: Contract, customer: str, empty_address: str, allowed_party):
"""Tokens can be transferred with ECR-20 allowance approval."""
token = released_token
amount = 5000
initial_balance = token.call().balanceOf(customer)
token.transact({"from": customer}).ap... | 5,305,263 |
def test_part1() -> None:
"""
Examples for Part 1.
"""
assert add_snailfish("[1,2]", "[[3,4],5]") == "[[1,2],[[3,4],5]]"
assert explode("[1,2]") == "[1,2]"
assert explode("[[[[[9,8],1],2],3],4]") == "[[[[0,9],2],3],4]"
assert explode("[7,[6,[5,[4,[3,2]]]]]") == "[7,[6,[5,[7,0]]]]"
assert... | 5,305,264 |
def test_post_repo_commit_comment(get_auth):
"""
Please run this test with disabling capture
=======
Example
=======
$ pytest -s tests
"""
# test info
with open('test_post_repo_commit_comment_info.txt', 'r') as f:
info = [line.strip() for line in f.readlines()]
post_in... | 5,305,265 |
def github_push(branch: str):
"""Push to branch (or tag) `branch`, using github write token."""
origin_url = run("git config --get remote.origin.url", warn=True, hide="stdout").stdout
match = re.match(r"git@github.com:(.+.git)", origin_url)
if match is None:
print(f"Unexpected github origin URL ... | 5,305,266 |
def deleteAccident(id=None, object=None):
""" delete the photos then delete the Accident
perm : object = the Accident object"""
if id:
accident = Accident.query.get(id)
elif object:
accident = object
if not accident:
return False
# delete the photos
deletePhoto(accident)
# delete the person
db.sessi... | 5,305,267 |
def perms_canonical_labels(p, e=None):
"""
Relabel a list with a common conjugation such that two conjugated
lists are relabeled the same way.
INPUT:
- ``p`` is a list of at least 2 permutations
- ``e`` is None or a list of integer in the domain of the
permutations. If provided, then th... | 5,305,268 |
def trotterization(hamiltonian, time, trotter_order):
"""
Uses first order Trotter-Suzuki decomposition:
exp(iHt) = (exp(ih_1 t)exp(ih_2 t)exp(ih_n t))^N + O(t*delta_t),
where H = h_1 * h_2 * ... * h_n, delta_t is t/N
:param hamiltonian: is the Hamiltonian (H in the formula)
:param time: is... | 5,305,269 |
def text(img: Image, *, threshold: float = 0.8) -> Text:
"""Regcognize text line, background color should be black.
Args:
img (Image): Preprocessed text line.
Returns:
Text: Text content
"""
ret = ""
w, h = img.width, img.height
if img.height < _LINE_HEIGHT:
w = r... | 5,305,270 |
def collate_fn(batch):
"""Creates mini-batch tensors from the list of tuples (images,
triplets_local_indexes, triplets_global_indexes).
triplets_local_indexes are the indexes referring to each triplet within images.
triplets_global_indexes are the global indexes of each image.
Args:
... | 5,305,271 |
def test_eda():
""" """
u.log(u.yellow('TESTING eda: '), 'OK') | 5,305,272 |
def bit_size_decorator (bs) :
"""Return a decorator for `dusort`-ing by bit-size `bs`.
Integral byte sizes compare before sub-byte sizes, even sizes compare
before odd sizes, larger values compare before smaller values.
"""
return - byte_alignment ((bs + 4) >> 3), - bs | 5,305,273 |
def get_unused_filename(existing_files, filename):
"""Provides filename similar to given, not in the given list.
If filename is /path/to/file.ext, then either it is returned unchanged if it
is not found in existing_files, or a new path is returned looking like
/path/to/file13.ext.
Args:
existing_files: ... | 5,305,274 |
def wavelength2rgb(wavelength: float, gamma: float = 0.8) -> tuple[float, float, float]:
"""
http://www.noah.org/wiki/Wavelength_to_RGB_in_Python
This converts a given wavelength into an approximate RGB value.
The given wavelength is in nanometers.
The range of wavelength is 380 nm through 750 nm.
... | 5,305,275 |
def bytes_to_long(in_bytes):
"""Converts a byte string into a long"""
hexstr = ''.join(["%0.2x" % ord(byte) for byte in in_bytes])
return int(hexstr, 16) | 5,305,276 |
def addfile_handler(logger, filename=FILE_NAME, level=LOG_LEVEL, write_headers=False):
"""
Add a file handler to the input.
Parameters
----------
logger : logging.Logger or logging.Logger
Logger where to add the file handler.
filename : str, optional
Name of the output file. By ... | 5,305,277 |
def equalization(estimator, dir_path):
"""Reads equalization FIR filter or CSV settings
Args:
estimator: ImpulseResponseEstimator
dir_path: Path to directory
Returns:
- Left side FIR as Numpy array or FrequencyResponse or None
- Right side FIR as Numpy array or FrequencyRes... | 5,305,278 |
def func():
"""Return a new matrix of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
Shape of the empty matrix.
dtype : data-type, optional
Desired output data-type.
order : {'C', 'F'}, optional
Whether to store multi... | 5,305,279 |
def gcp_connect(module, provider, get_driver, user_agent_product, user_agent_version):
"""Return a Google libcloud driver connection."""
if not HAS_LIBCLOUD_BASE:
module.fail_json(msg='libcloud must be installed to use this module')
creds = _get_gcp_credentials(module,
... | 5,305,280 |
def test_gen_input_mods():
"""Test that the gen workers do not modify the top level input SAM config
"""
year = 2012
rev2_points = slice(0, 5)
res_file = TESTDATADIR + '/nsrdb/ri_100_nsrdb_{}.h5'.format(year)
sam_files = TESTDATADIR + '/SAM/i_pvwatts_fixed_lat_tilt.json'
# run reV 2.0 gener... | 5,305,281 |
def create_c1_opt(optimizer_config, exp):
"""
Create an object for C1 optimal control.
Parameters
----------
optimizer_config : str
File path to a hjson file containing the C1 configuration.
lindblad : boolean
Include lindbladian dynamics.
Returns
-------
C1
... | 5,305,282 |
def build_datasets(df, patients_train, patients_val, print_stats=True, normalize=True):
"""
Build PyTorch datasets based on a data table and a patient-wise train-test split.
Args:
df (pandas dataframe): The data table from ADNI.
patients_train (iterable of strings): The patients to include ... | 5,305,283 |
def choose_stance(info: GameInfo, my_car: Car, team, last_sent):
""" High level assignment of "stances"
Upon entering a stance, each Marujo is able to decide a few things to do
"""
ball = info.ball
teammates = info.get_teammates(my_car)
my_team = [my_car] + teammates
their_goal = ... | 5,305,284 |
def javadoc(metadata, indent = 4):
"""
Returns a function to format a markdown syntax text block as a
javadoc comment section, given a set of metadata
Args:
metadata: A Metadata instance, representing the top-level root
of the metadata for cross-referencing
indent: baseline level of indentation f... | 5,305,285 |
def deg2tilecoord(lat_deg, lon_deg, zoom):
"""
Convert latitude,longitude coordinates in degrees into tile coordinates for
given zoom.
"""
try:
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = (lon_deg + 180.0) / 360.0 * n
ytile = (1.0 - math.log(math.tan(lat_r... | 5,305,286 |
def p_expressions_empty(p):
"""expressions : discarded_expressions"""
p[0] = deque() | 5,305,287 |
def mode_generate_algo_symlinks(args):
"""
Print commmands to create symlinks for hashfile for every known algorithm
:return:
"""
current = os.path.realpath(sys.argv[0])
bindir = os.path.dirname(current)
for algo in AVAILABLE_ALGORITHMS:
print('ln -s %s %s' % (current, os.path.join(b... | 5,305,288 |
async def test_call_shell(mocker, is_success):
"""call should pass through a shell command string if shell is true"""
patched = mocker.async_patch("asyncio.create_subprocess_shell")
expected_return = 0 if is_success else 1
patched.return_value.wait = async_wrapper(lambda: expected_return)
cmd = "gi... | 5,305,289 |
def correctshape(result, original, size=None):
"""Corrects the result of style transfer to ensure shape is coherent with original image and desired output size
If output size is not specified, the result image is corrected to have the same shape as the original.
"""
assertshape(result, targetshape(orig... | 5,305,290 |
def clean_data(row: dict) -> dict:
"""
Function to clean film permit row.
"""
eventid = row['eventid']
addresses = _split_addresses(row['parkingheld'])
addresses = [
_get_intersections(address) for address in addresses
]
startdate = _clean_datetime(row['startdatetime'])
endd... | 5,305,291 |
def project_featurestore():
"""
Gets the project's featurestore name (project_featurestore)
Returns:
the project's featurestore name
"""
project_name = hdfs.project_name()
featurestore_name = project_name.lower() + constants.FEATURE_STORE.FEATURESTORE_SUFFIX
return featurestore_nam... | 5,305,292 |
def find():
"""
List all busses and returns a list of baseboards detected
"""
l = []
try:
for b in usb.core.find(find_all=True, idVendor=FISCHER_LT_VENDOR, idProduct=FISCHER_LT_PRODUCT):
l.append(usb_device(b))
except:
pass
return l | 5,305,293 |
def debug(func):
"""Print the function signature and return value"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
args_repr = [repr(a) for a in args] # Creates a list of positional arguments, repr() returns a string for each argument
kwargs_repr = [... | 5,305,294 |
def cli(ctx, library_id, access_in="", modify_in="", add_in="", manage_in=""):
"""Set the permissions for a library. Note: it will override all security for this library even if you leave out a permission type.
Output:
General information about the library
"""
return ctx.gi.libraries.set_library_permi... | 5,305,295 |
def type_encoding_table(tblname, arr):
"""Table of strings of all instructions."""
return string_table(tblname, (x[1] for x in arr)) | 5,305,296 |
def controller_unlock_foreign_drives(handle, controller_type,
controller_slot, security_key,
server_id=1):
"""
Unlocks on the given controller, drives encrypted on another controller.
Args:
handle (ImcHandle)
controll... | 5,305,297 |
def create(i):
"""
Input: {
data_uoa - virtual environment name
(force_detect) - if 'yes' force to detect installed python again
(template) - if !='', use scripts from this venv.template entry
at the end of venv creation.
... | 5,305,298 |
def _item_to_zone(iterator, resource):
"""Convert a JSON managed zone to the native object.
:type iterator: :class:`~google.cloud.iterator.Iterator`
:param iterator: The iterator that has retrieved the item.
:type resource: dict
:param resource: An item to be converted to a managed zone.
:rty... | 5,305,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.