content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def g_logv(s):
"""read a logical variable
:param str s:
:return bool:
"""
return s == '1' or s.lower() == 'yes' or s.lower() == 'true' | 5,321,000 |
def line_control():
"""
This function uses the difference between the two color sensor values as the input for a PID controller.
The output will modify the base speed of the motors to make the robot turn.
This control, called repeatedly, should make the robot follow the line.
"""
global li... | 5,321,001 |
def join_auto_join_groups(user):
"""Let new users join groups that are set for auto-joining."""
auto_join_groups = Group.objects.filter(groupsettings__is_auto_join_group=True)
for group in auto_join_groups:
user.groups.add(group) | 5,321,002 |
def record_mode(request):
"""Manage compatibility with DD client libraries."""
mode = os.getenv("RECORD", "false")
if mode is not None:
if mode == "none":
request.config.option.disable_vcr = True
else:
setattr(
request.config.option,
"v... | 5,321,003 |
def frame(win_length, hop_length):
"""A data node to frame signal, prepend by zero.
Parameters
----------
win_length : int
The length of framed data.
hop_length : int
The length of input data.
Receives
--------
data : ndarray
The input signal.
Yields
--... | 5,321,004 |
def get_number_of_engine_threads():
"""
Returns the number of engine threads.
"""
command = 'ps aux | grep "./build/engine" | grep -v "grep" | wc -l'
n_threads = int(common.run_local_cmd(command, get_output = True))
return n_threads | 5,321,005 |
def check_sample_correctishness_bc01(f):
"""
Tests that the sample mean converges to the conditional
expectation given by the function
Tests that p really is the max of the samples
Tests that at most one h in a group is on
"""
batch_size = 5
rows = 32
cols = 30
channels = 3
... | 5,321,006 |
def metadata_repr_as_list(metadata_list):
"""
Turn a list of metadata into a list of printable representations
"""
output = []
for metadata_dict in metadata_list:
try:
output.append('%s - %s' % (MetadataType.objects.get(
pk=metadata_dict['id']), metadata_dict.get(... | 5,321,007 |
def imagesArrayComparisonDisplay(arrays, fileName, startIndex=0, endIndex=None):
"""
Display sample images from arrays side-by-side in a matrix format
Each array is a column
Each index is a row
"""
numArrays = len(arrays)
numElementsToDisplay = (min(map(len, arrays)) if endIndex is None else... | 5,321,008 |
def cli(ctx, location, runtime, output_dir, name, no_input):
""" \b
Initialize a serverless application with a SAM template, folder
structure for your Lambda functions, connected to an event source such as APIs,
S3 Buckets or DynamoDB Tables. This application includes everything you need to
... | 5,321,009 |
def dip_reconstructor(dataset='ellipses', name=None):
"""
:param dataset: Can be 'ellipses' or 'lodopab'
:return: The Deep Image Prior (DIP) method for the specified dataset
"""
try:
standard_dataset = load_standard_dataset(dataset)
params = Params.load('{}_dip'.format(dataset))
... | 5,321,010 |
def plot_spectrum(wavelength, flux, error, dq, rootname):
"""
plot the spectrum, error and spectrum with flagged pixels removed
"""
wavelength, flux, error, dq = wavelength[wavelength > 1160], flux[wavelength > 1160], error[wavelength > 1160], dq[wavelength > 1160] #cut off the scrappy bit at the beginn... | 5,321,011 |
def convert_listofrollouts(paths):
"""
Take a list of rollout dictionaries
and return separate arrays,
where each array is a concatenation of that array from across the rollouts
"""
observations = np.concatenate([path["observation"] for path in paths])
actions = np.concatenate([p... | 5,321,012 |
def get_iex_corporate_actions(start=None, **kwargs):
"""
Top-level function to retrieve IEX Corporate Actions from the ref-data
endpoints
Parameters
----------
start: datetime.datetime, default None, optional
A month to use for retrieval (a datetime object)
kwargs: Additional Reques... | 5,321,013 |
def set_logging(loglevel = logging.INFO):
"""
Sets up logging
:param loglevel
"""
logging.basicConfig(filename='log.txt', level=loglevel,format='%(asctime)s - %(levelname)s - %(message)s')
root = logging.getLogger()
root.setLevel(loglevel)
ch = logging.StreamHandler(sys.stdout)
ch.s... | 5,321,014 |
def mc_generation_costs(df_ren, h2_demand, year_diff, capex_extra, capex_h2, lifetime_hours, electrolyser_efficiency,
elec_opex,
other_capex_elec, water_cost,
capex_wind, opex_wind, capex_solar, opex_factor_solar,
intere... | 5,321,015 |
def karyogram():
"""
"""
# Save to global var for using track
global my_snapshot
if not my_snapshot:
# Save the initial state of memory
my_snapshot = tracemalloc.take_snapshot()
else:
lines = []
# Get the statistics to comparison between current and initial memory... | 5,321,016 |
def relax(u, f, nu):
"""
Weighted Jacobi
"""
n = len(u)
Dinv = 1.0 / (2.0 * ((n+1)**2))
omega = 2.0 / 3.0
unew = u.copy()
for steps in range(nu):
unew = unew + omega * Dinv * residual(unew, f)
return unew | 5,321,017 |
def doi_to_id(doi, timestamp):
"""Query translator to convert book DOI to specified schema."""
params = {
'uri': doi,
'filter': f'uri_scheme:{URI_SCHEME}',
'strict': URI_STRICT
}
headers = {'Authorization': AUTH} if AUTH else {}
response = requests.get(URI_API_ENDP, params=... | 5,321,018 |
def forward_influence_centrality(graph, weight=None):
"""Returns the forward influence centrality of the nodes in a network as an array.
Parameters
----------
graph : Graph, array
A NetworkX graph or numpy/sparse array
weight : string or None
If you have weighted edges i... | 5,321,019 |
def createOFlow():
"""None"""
pass | 5,321,020 |
def try_to_replace_line_json(line, json_type, new_json, json_prefix=""):
"""Attempts to replace a JSON declaration if it's on the line.
Parameters
----------
line: str
A line from a JavaScript code file. It's assumed that, if it declares
a JSON, this declaration will only take up one line... | 5,321,021 |
def createInvoice(request):
"""
Invoice Generator page it will have Functionality to create new invoices,
this will be protected view, only admin has the authority to read and make
changes here.
"""
heading_message = 'Formset Demo'
if request.method == 'GET':
formset = LineItemForms... | 5,321,022 |
def GetTopLevelParent(*args, **kwargs):
"""GetTopLevelParent(Window win) -> Window"""
return _misc_.GetTopLevelParent(*args, **kwargs) | 5,321,023 |
def slotnick(x, k):
"""
Relation between velocity and depth
Parameters
----------
x : 1-d ndarray
Depth to convert
k : scalar
velocity gradient
Notes
-----
typical values of velocity gradient k falls in the range 0.6-1.0s-1
References
----------
.. [1] ... | 5,321,024 |
def NodeEvolution(tensor, directed=False):
"""Temporal evolution of all nodes' input and output communicability or flow.
Parameters
----------
tensor : ndarray of rank-3
Temporal evolution of the network's dynamic communicability. A tensor
of shape timesteps x n_nodes x n_nodes, where n... | 5,321,025 |
def transform_symbol(ctx, name):
"""Transform the symbol NAME using the renaming rules specified
with --symbol-transform. Return the transformed symbol name."""
for (pattern, replacement) in ctx.symbol_transforms:
newname = pattern.sub(replacement, name)
if newname != name:
print " symbol '%s' t... | 5,321,026 |
def get_active_resources_in_grid(grid):
"""Get active resources in grid.
:param powersimdata.input.grid.Grid grid: a Grid instance.
:return: (*set*) -- name of active resources in grid.
"""
_check_grid_type(grid)
active_resources = set(grid.plant.loc[grid.plant["Pmax"] > 0].type.unique())
r... | 5,321,027 |
def getReflectionandTransmission(
sig1,
sig2,
f,
theta_i,
eps1=epsilon_0,
eps2=epsilon_0,
mu1=mu_0,
mu2=mu_0,
dtype="TE",
):
"""
Compute reflection and refraction coefficient of plane waves
"""
theta_i = np.deg2rad(theta_i)
omega = 2 * np.pi * f
k1 = np.sqrt(... | 5,321,028 |
def tile(lng, lat, zoom, truncate=False):
"""Get the tile containing a longitude and latitude
Parameters
----------
lng, lat : float
A longitude and latitude pair in decimal degrees.
zoom : int
The web mercator zoom level.
truncate : bool, optional
Whether or not to trun... | 5,321,029 |
def test_list_string_white_space_nistxml_sv_iv_list_string_white_space_1_4(mode, save_output, output_format):
"""
Type list/string is restricted by facet whiteSpace with value
collapse.
"""
assert_bindings(
schema="nistData/list/string/Schema+Instance/NISTSchema-SV-IV-list-string-whiteSpace-... | 5,321,030 |
def read(file_path, lines=False):
"""Returns contents of file either as a string or list of lines."""
with open(file_path, 'r') as fp:
if lines:
return fp.readlines()
return fp.read() | 5,321,031 |
def diff(tv: vs.VideoNode, bd: vs.VideoNode,
thr: float = 72,
height: int = 288,
return_array: bool = False,
return_frames: bool = False) -> Union[vs.VideoNode, Tuple[vs.VideoNode, List[int]]]:
"""
Creates a standard :py:class:`lvsfunc.comparison.Stack` be... | 5,321,032 |
def extract_wheel(wheel_file: str, extras: List[str]) -> str:
"""Extracts wheel into given directory and creates a py_library target.
Args:
wheel_file: the filepath of the .whl
extras: a list of extras to add as dependencies for the installed wheel
Returns:
The Bazel label for the ... | 5,321,033 |
def random_choice(choices: List[float]) -> float:
"""Selects a random choice within a list."""
return choices[np.random.choice(len(choices), size=1)[0]] | 5,321,034 |
def UnescapeUnderscores(s: str):
"""Reverses EscapeWithUnderscores."""
i = 0
r = ''
while i < len(s):
if s[i] == '_':
j = s.find('_', i + 1)
if j == -1:
raise ValueError('Not a valid string escaped with `_`')
ss = s[i + 1:j]
if not ... | 5,321,035 |
def login(base_config):
"""
返回登录后的
:return:
"""
username = base_config.get("username")
password = base_config.get("password")
base_url = base_config.get("base_url")
company_id = base_config.get("company_id")
app_id = base_config.get("app_id")
app_secret = base_config.get("app_sec... | 5,321,036 |
def filter_(stream_spec, filter_name, *args, **kwargs):
"""Alternate name for ``filter``, so as to not collide with the
built-in python ``filter`` operator.
"""
return filter(stream_spec, filter_name, *args, **kwargs) | 5,321,037 |
def angle_normalization_0_2pi(angle):
"""Automatically normalize angle value(s) to the range of 0-2pi.
This function relies on modular arithmetic.
Parameters
----------
angle : array_like
The angles to be converted
Returns
-------
normalized_angles : ndarray
... | 5,321,038 |
def config_resolve_context(cookie, in_context, in_size):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("ConfigResolveContext")
method.cookie = cookie
method.in_context = str(in_context)
method.in_size = str(in_size)
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
... | 5,321,039 |
def svi_label(svi_df_list: list, SVI_label = [190.0, 140.0], SV_label = [2.5, 3.0] ):
"""
Adds label columns in each dataframe in svi dataframe list,
Using "label_data" function.
Added columns are: 'SV_label', 'SVI_label'.
Parameters
----------
svi_df_list: list
"""
# define bor... | 5,321,040 |
def test_nested_if(fieldset, mode):
"""Test nested if commands"""
class TestParticle(ptype[mode]):
p0 = Variable('p0', dtype=np.int32, initial=0)
p1 = Variable('p1', dtype=np.int32, initial=1)
pset = ParticleSet(fieldset, pclass=TestParticle, lon=0, lat=0)
def kernel(particle, fieldset,... | 5,321,041 |
def bots_endpoint(page=1):
"""
Return bots from the BotList.
Use the url parameters `url` or `username` to perform a search on the BotList.
The @-character in usernames can be omitted.
:param page: The page to display
:return: All bots (paginated) or the search result if url parameters were us... | 5,321,042 |
def launch_visit_test(args):
"""
Runs a single VisIt test.
"""
idx = args[0]
test = args[1]
opts = args[2]
top_dir = visit_root()
test_script = abs_path(test_path(),"visit_test_main.py")
test_dir, test_file = os.path.split(test)
test_cat = os.path.split(test_dir)[1]
... | 5,321,043 |
def parse_secrets(raw: List[str]) -> Dict[str, str]:
"""Parses secrets"""
result: Dict[str, str] = {}
for raw_secret in raw:
keyval = raw_secret.split('=', 1)
if len(keyval) != 2:
raise ValueError(f'Invalid secret "{raw_secret}"')
result[keyval[0]] = keyval[1]
return ... | 5,321,044 |
def run():
"""Main method that parses command options and executes the rest of the script"""
# create a client
client_out = create_client_out(
host=os.environ["MQTT_HOST"],
port=int(os.environ["MQTT_PORT"]),
username=os.environ["MQTT_USERNAME"],
password=os.environ["MQTT_PAS... | 5,321,045 |
def test_spec_to_column_number_float():
"""
GIVEN schema with number type and float format
WHEN column_factory is called with the schema
THEN SQLAlchemy Float column is returned.
"""
column = column_factory._spec_to_column(spec={"type": "number", "format": "float"})
assert isinstance(column... | 5,321,046 |
async def detect_custom(model: str = Form(...), image: UploadFile = File(...)):
"""
Performs a prediction for a specified image using one of the available models.
:param model: Model name or model hash
:param image: Image file
:return: Model's Bounding boxes
"""
draw_boxes = False
predict_batch = False
try:
... | 5,321,047 |
def ensure_databases_alive(max_retries: int = 100,
retry_timeout: int = 5,
exit_on_failure: bool = True) -> bool:
"""
Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries``
attempts to reach any backend ar... | 5,321,048 |
def __maxCrossingSubArr(seq, low, mid, high):
"""
寻找seq[low..high]跨越了中点mid的最大子数组
总循环次数为high-low+1,线性的
"""
leftSum = float('-Inf')
sumTemp = 0
for i in range(mid, low - 1, -1):
sumTemp += seq[i]
if sumTemp > leftSum:
leftSum = sumTemp
maxLeft = i
ri... | 5,321,049 |
def transition_matrix(embeddings, word_net=False, first_order=False, sym=False, trans=False, **kwargs):
"""
Build a probabilistic transition matrix from word embeddings.
"""
if word_net:
L = wordnet_similarity_matrix(embeddings)
elif not first_order:
L = similarity_matrix(embeddings... | 5,321,050 |
def read_met_data():
"""
Reads in the streamflow data and returns them as dataframe.
Expects to be in the dir were the data is stored.
:return: stream_df: Column names are the stream ids. Index is the date.
"""
# Set the cwd to the directory of the file
os.chdir(os.path.dirname(sys.argv[... | 5,321,051 |
def gen_review_vecs(reviews, model, num_features):
"""
Function which generates a m-by-n numpy array from all reviews,
where m is len(reviews), and n is num_feature
Input:
reviews: a list of lists.
Inner lists are words from each review.
Outer lists... | 5,321,052 |
def ott(high, low, close, length=None,_shift=None, multiplier=None, **kwargs):
"""Indicator: Supertrend"""
# Validate Arguments
high = verify_series(high)
low = verify_series(low)
close = verify_series(close)
length = int(length) if length and length > 0 else 7
shift = int(_shift) if ... | 5,321,053 |
def lambda_cut_series(x, mfx, n):
"""
Determines a series of lambda-cuts in a sweep from 0+ to 1.0 in n steps.
Parameters
----------
x : 1d array
Universe function for fuzzy membership function mfx.
mfx : 1d array
Fuzzy membership function for x.
n : int
Number of st... | 5,321,054 |
def test_perfect_classifier_no_shift(construct_predictions) -> None:
"""Check if we can rediscover the true prevalence if no shift
is present and the classifier is perfect."""
training_samples = [60, 40, 10]
predictions = construct_predictions(training_samples)
prevalences = algorithms.expectation... | 5,321,055 |
def list():
"""
Execute list as default fab command
"""
local('fab -l') | 5,321,056 |
def validate_schema(request, schema_instance):
""" A decorator function that validates schema againt request payload """
def decorator(func):
@wraps(func)
def wrapper_function(*args, **kwargs):
json_payload = request.get_json()
schema_instance.load_json_into_schema(json_... | 5,321,057 |
def has_inference_based_loaders(cfg: CfgNode) -> bool:
"""
Returns True, if at least one inferense-based loader must
be instantiated for training
"""
return len(cfg.BOOTSTRAP_DATASETS) > 0 | 5,321,058 |
def get_terrain_for_coord(x, y):
"""Get the terrain type for a coordinate.
:param int x: The x coordinate
:param int y: The y coordinate
:returns tuple(Terrain, bool): The terrain type and whether it is diverse
"""
elevation, moisture, temperature, diversity = _render_map_data(
1, 1, (... | 5,321,059 |
def test_update_channel_type(mock_client, channel_type, indexing_decorator):
"""Test create_channel for channel_type"""
user = UserFactory.create()
channel = api.Api(user=user).update_channel("name", channel_type=channel_type)
assert channel == mock_client.subreddit.return_value
mock_client.subreddi... | 5,321,060 |
def dtopo2kml(dtopo_file_name, dtopo_type, color='8888FF'):
"""
Create a kml file putting a box around the region covered by a dtopofile.
Color is pink by default.
"""
import os
from clawpack.geoclaw import dtopotools
dtopo = dtopotools.DTopography()
dtopo.read(dtopo_file_name, d... | 5,321,061 |
def test_update_create_table(sql):
"""Updating a table that doesn't exist should always raise an error, even
if autoadjust_sql_objects=True."""
table_name = "##test_update_create_table"
dataframe = pd.DataFrame({"_pk": [0, 1], "ColumnA": [1, 2]}).set_index(keys="_pk")
with pytest.raises(custom_er... | 5,321,062 |
def test_PipeJsonRpcSendAsync_7_fail():
"""
Method not found (other `json-rpc` errors will raise the same exception).
"""
def method_handler1():
pass
conn1, conn2 = multiprocessing.Pipe()
pc = PipeJsonRpcReceive(conn=conn2, name="comm-server")
pc.add_method(method_handler1, "method... | 5,321,063 |
def read_Image8(Object, Channel, iFlags=0):
"""
read_Image8(Object, Channel, iFlags=0) -> bool
read_Image8(Object, Channel) -> bool
"""
return _Channel.read_Image8(Object, Channel, iFlags) | 5,321,064 |
def Linear(in_features, out_features, dropout=0):
"""Weight-normalized Linear layer (input: N x T x C)"""
m = nn.Linear(in_features, out_features)
m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))
m.bias.data.zero_()
return nn.utils.weight_norm(m) | 5,321,065 |
def _writeFileLog(log, log_file=None):
"""
Write THOR file log. The file log tracks all supplemental data
files that different components of THOR may need. Examples
include SPICE kernels, the MPC observatory code file, the
MPC orbit catalog etc...
Parameters
----------
log : dict
... | 5,321,066 |
def cli(info: Info,
verbose: int):
"""
This is the txauthor API service. You can use gunicorn or another
production host to run the service, but this command-line interface provides
some other handy help and utilities.
"""
# Use the verbosity count to determine the logging level...
... | 5,321,067 |
def get_state(initial, input_value=None):
"""Get new state, filling initial and optional input_value."""
return {
'last_position': None,
'initial': [initial],
'input': [input_value] if input_value is not None else [],
'output': [],
} | 5,321,068 |
def predictkNNLabels(closest_neighbors, y_train):
"""This function predicts the label of a individual point
in X_test based on the labels of the nearest neighbour(s).
And sums up the total of appearences of the labels and
returns the label that occurs the most """
labelPrediction = {}
for i in ... | 5,321,069 |
def fetch_dataset(filename):
"""
Useful util function for fetching records
"""
buffer_size = 32 * 1024 * 1024 # 32 MiB per file
dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)
return dataset | 5,321,070 |
def get_alma_project(ra,de, radius_arcsec=10/3600):
"""Return ALMA project IDs (if exists) given coordinates."""
# set up connection
cnx = db.get_cnx(cfg.mysql['user'], cfg.mysql['passwd'],
cfg.mysql['host'], cfg.mysql['db_sdb'])
if cnx is None:
return
cursor = cnx.curs... | 5,321,071 |
def read_certification_data(reader: PdfFileReader) -> Optional[DocMDPInfo]:
"""
Read the certification information for a PDF document, if present.
:param reader:
Reader representing the input document.
:return:
A :class:`.DocMDPInfo` object containing the relevant data, or ``None``.
... | 5,321,072 |
def from_independent_matroid(matroid: tuple[set[T], list[set[T]]]) -> list[set[T]]:
"""Construct circuits from a matroid defined by independent sets.
Args:
matroid (tuple[set[T], list[set[T]]]): A matroid defined by independent sets.
Returns:
list[set[T]]: The circuits of a given matroid.
... | 5,321,073 |
def join_dimensions(expr: sympy.Expr) -> sympy.Expr:
"""
ModularIndexing(i0, 1, 32) + 32 * ModularIndexing(i0, 32, 4)
becomes
ModularIndexing(i0, 1, 128)
This type of pattern can come from view operations
"""
from .ir import ModularIndexing
if not isinstance(expr, sympy.Add):
r... | 5,321,074 |
def trks_stats(filename):
"""For a given trks_file, find the Number of cell tracks,
the Number of frames per track, and the Number of divisions.
Args:
filename (str): full path to a trks file.
Raises:
ValueError: filename is not a .trk or .trks file.
"""
ext = os.path.splite... | 5,321,075 |
def main_model(args=None):
"""Main function called by the `HENfspec` command line script."""
import argparse
description = ('Fit frequency spectra (PDS, CPDS, cospectrum) '
'with user-defined models')
parser = argparse.ArgumentParser(description=description)
parser.add_argument("... | 5,321,076 |
def map_trans_tfrecord(vcf_tfrecord, phenotype_df, covariates_df, interaction_s=None, return_sparse=True, pval_threshold=1e-5, maf_threshold=0.05, batch_size=50000, logger=None):
"""Run trans-QTL mapping from genotypes in tfrecord"""
if logger is None:
logger = SimpleLogger()
assert np.all(phenotype... | 5,321,077 |
def test_round_to_hour():
"""Test rounding up/down to nearest hour"""
dt = datetime.datetime(2009,1,3,9,30,46)
dt_rounded = datetime.datetime(2009,1,3,10,0,0)
assert dateutil.round_to_hour(dt) == dt_rounded
dt = datetime.datetime(2009,1,3,9,29,14)
dt_rounded = datetime.datetime(2009,1,3,9,0,0)
... | 5,321,078 |
def tabulate(
rows: List[Iterable[str]], *, gap=2, titles: List[str] = None
) -> Generator[str, None, None]:
"""Align fields from rows by width and add underlined header.
Works only when titles and all items in rows have same length,
throws ValueError otherwise.
:param rows: table data.
:param... | 5,321,079 |
def evolve(model, mutator, population, tournament_size=4):
"""
Performs crossover and mutation and doubles population size
:param model: Instance of Model
:param mutator: Instance of Mutator
:param population: List of points
:param tournament_size: Size of tournament
:return: List of population + List of ... | 5,321,080 |
def element_statistics(tree, element_type):
"""
Prints the names and counts of all elements present in an
`etree._ElementTree`, e.g. a SaltDocument::
SStructure: 65
SSpan: 32
SToken: 154
STextualDS: 1
Parameters
----------
tree : lxml.etree._ElementTree
... | 5,321,081 |
def cell_snippet(x, is_date=False):
"""create the proper cell snippet depending on the value type"""
if type(x) == int:
return {
'userEnteredValue': {'numberValue': x},
'userEnteredFormat': {
'numberFormat': {
'type': 'NUMBER',
... | 5,321,082 |
def load_image(image_path: str) -> np.ndarray:
"""
Read image from disk.
:param image_path: Path to input image.
:return: uint8 numpy array sized H x W.
"""
# load image
img = io.imread(image_path)
# assert img dtype
assert img.dtype == 'uint8'
return img | 5,321,083 |
def test_vsi_path_zip():
"""A zip:// URLs vsi path is correct (see #1377)"""
url = 'zip:///path/to/zip/some.zip!path/to/file.txt'
assert vsi_path(parse_path(url)) == '/vsizip//path/to/zip/some.zip/path/to/file.txt' | 5,321,084 |
def image_contrast_intervals(image, n):
"""
Generate a number of images with different contrast levels using linear
interpolation to choose levels between 0 (black) and 1 (original image) as
well as between 1 and 2.
Results will not include contrast level 0, 1 or 2 images.
"""
n = int(n)
... | 5,321,085 |
def lowerUserList(inputList):
"""Lowercase user inputLists in case there are misspellings. (e.g. 3-6KB)"""
# clean list
loweredList = []
for item in inputList:
loweredItem = item.lower()
loweredList.append(loweredItem)
return loweredList | 5,321,086 |
def main():
"""
Define main method to analyse PPO, and MBDQN runs specified in the global
vars above.
"""
analyse_PPO(PPO_RUNS, "PPO Learning rate", "ppo")
analyse_MBDQN(MBDQN_1PIECE_RUNS,
"(a) MBDQN learning rate for single piece episodes", "mbdqn-1piece")
analyse_MBDQN(
... | 5,321,087 |
def na_cmp():
"""Binary operator for comparing NA values.
Should return a function of two arguments that returns
True if both arguments are (scalar) NA for your type.
By default, uses ``operator.or``
"""
return lambda x, y: x is None and y is None | 5,321,088 |
def get_list_files(initializer):
""" """
# get settings for find
roots, listOfExtension, ignoreLists, ignoreLists, ignoreLists = initializer()
resultArgv = ''
for pathes in roots:
for at in listOfExtension:
listSlice = list()
listSlice.append(at)
... | 5,321,089 |
def constant(name, shape, value, dtype=tf.float32):
""" Creates a variable which is initiated to a constant value.
:param name: The name of the variable.
:param shape: The shape of the variable.
:param value: The constant value of the tensor.
:param dtype: The data type.
:return: A constant-ini... | 5,321,090 |
def _cat_blob(repo, obj, bad_ok=False):
"""Call `git cat-file blob OBJ`.
Parameters
----------
repo : GitRepo
obj : str
Blob object.
bad_ok : boolean, optional
Don't fail if `obj` doesn't name a known blob.
Returns
-------
Blob's content (str) or None if `obj` is no... | 5,321,091 |
def get_disp_samples(max_dis, feature_map, stage_id=0, disprity_map=None, step=1, samp_num=9, sample_spa_size=None) :
"""function: get the sampled disparities
args:
max_dis: the maximum disparity;
feature map: left or right feature map, N*C*H*W;
disprity_map: if it is not the first stage... | 5,321,092 |
def load_data(database_filepath):
"""
Load cleaned data from database_filepath
INPUT
database_filepath --filepath to csv dataset
OUTPUT
X - message column to predict Y values
Y - list of columns to be predicted
category_names - name of Y column names
"""
# load data from ... | 5,321,093 |
def write_deprecated_member_functions(s, spec, traits):
"""
Writes the deprecated member functions for backwards compatibility
"""
for field in spec.parsed_fields():
if (field.is_array):
s.write(' ROS_DEPRECATED uint32_t get_%s_size() const { return (uint32_t)%s.size(); }\n'%(field.... | 5,321,094 |
def sigma_clip(array, flags=None, sigma=4.0, axis=0, min_N=4):
"""
one-iteration robust sigma clipping algorithm. returns clip_flags array.
Warning: this function will directly replace flagged and clipped data in array with
a np.nan, so as to not make a copy of array.
Parameters:
-----------
... | 5,321,095 |
def get_model(type_: str, name_: str) -> Union:
"""
Utility to get the class of required function
:param type_: "ac" for Actor Critic, "v" for Value, "p" for Policy
:param name_: Name of the specific structure of model. (
Eg. "mlp" or "cnn")
:type type_: string
:returns:... | 5,321,096 |
def _preprocess_data(data, data_type, auth=None):
"""Preprocess input data according to the specified type.
Possoble data types are:
- "raw" use data as is provided in the request
- "json_pgframe" create a PandasPGFrame from the provided JSON repr
- "nexus_dataset" download a JSON dataset from Nex... | 5,321,097 |
def apple_universal_binary_test_suite(name):
"""Test suite for apple_universal_binary.
Args:
name: the base name to be used in things created by this macro
"""
test_target = "//test/starlark_tests/targets_under_test/apple:multi_arch_cc_binary"
analysis_target_outputs_test(
name = "{}... | 5,321,098 |
def short_comment(x):
"""Ham comments are often short, such as 'cool video!'"""
return len(x.text.split()) < 5 | 5,321,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.