content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def global_bluetooth_lock():
"""Initialize the global bluetooth lock inside the current event loop."""
global GLOBAL_BLUETOOTH_LOCK # pylint: disable=global-statement
if GLOBAL_BLUETOOTH_LOCK is None:
GLOBAL_BLUETOOTH_LOCK = asyncio.Lock()
return GLOBAL_BLUETOOTH_LOCK | 59,300 |
def max_profit(prices):
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Note that you cannot s... | 59,301 |
def intrinsic_photo_all(
request,
category_id='all',
filter_key='all',
template="intrinsic/photo_all.html",
extra_context=None):
""" View judgements in images with each image taking up a block and the
list of photo categories on the left """
entries = Photo.objects.... | 59,302 |
def get_authenticated_api_session(username, password):
"""
:return: an authenticated api session
"""
session = MoJOAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
session.fetch_token(
token_url=get_request_token_url(),
... | 59,303 |
def add_customer_invoice(customer_invoice_data):
"""
添加信息
:param customer_invoice_data:
:return: None/Value of user.id
:except:
"""
return db_instance.add(CustomerInvoice, customer_invoice_data) | 59,304 |
def get_matrix_from_cellranger_mtx(filedir: str) \
-> Dict[str, Union[sp.csr.csr_matrix, List[np.ndarray], np.ndarray]]:
"""Load a count matrix from an mtx directory from CellRanger's output.
For CellRanger v2:
The directory must contain three files:
matrix.mtx
barcodes.tsv
... | 59,305 |
def model_as_json(bot_entries):
""" Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB
@param
bot_entries (list) list of sub-lists
@returns
json_list (list) list of modeled dictionaries
... | 59,306 |
def encompasses_broadcastable(b1, b2):
"""
Parameters
----------
b1
The broadcastable attribute of a tensor type.
b2
The broadcastable attribute of a tensor type.
Returns
-------
bool
True if the broadcastable patterns b1 and b2 are such that b2 is
broad... | 59,307 |
def demo2():
""" Smiled Monalisa """
np.random.seed(1234)
image = np.array(Image.open("images/monalisa.jpg"))
height, width, _ = image.shape
# Define deformation grid
gridX = np.arange(width, dtype=np.int16)
gridY = np.arange(height, dtype=np.int16)
vx, vy = np.meshgrid(gridX, ... | 59,308 |
def test_greeter(test_case):
""" Do we introduce customers correctly? """
assert greeter(test_case["input"]) == test_case["output"] | 59,309 |
def setup_app(command, conf, vars):
"""Place any commands to setup lr here"""
# Don't reload the app if it was loaded under the testing environment
if not pylons.test.pylonsapp:
load_environment(conf.global_conf, conf.local_conf)
assert init_plugins() is not None, "Plugins not Loading!!!!"
... | 59,310 |
def get_key_dict_overload(arr):
"""returns dictionary and possibly a byte_vec for multi-key case
"""
# get byte_vec dict for multi-key case
if isinstance(arr, types.BaseTuple) and len(arr.types) != 1:
n_bytes = 0
context = numba.targets.registry.cpu_target.target_context
for t in... | 59,311 |
def get_file_names_from_dir(dir, extension):
""" gets all file names with extension from directory
Args:
dir (string): directory to look for files
extension (string): extension with no '.' ie 'tif', 'JPG'
"""
return [y for x in os.walk(dir) for y in glob(os.path.join(x[0], '*.'+extensio... | 59,312 |
def week():
"""Get latest weekly ranks."""
url = f"{BASE_URL}/week/index.htm"
return utils.get_ranks(url, SELECTOR, parser) | 59,313 |
def cone(toplexes, subcomplex, coneVertex="*"):
"""Construct the cone over a subcomplex. The cone vertex can be renamed if desired. The resulting complex is homotopy equivalent to the quotient by the subcomplex."""
return toplexes + [spx + [coneVertex] for spx in subcomplex] | 59,314 |
async def read_item(
*,
con: AsyncIOConnection = Depends(db.get_con),
item_id: UUID,
current_user: schemas.User = Depends(auth.get_current_active_user),
) -> Any:
"""
Get item by id.
"""
item = await crud.item.get(con, id=item_id)
if not item:
raise HTTPException(status_code=... | 59,315 |
async def get_max_power(
token: str,
cups: str,
distrubutor_code: int,
start_date: str,
end_date: str,
authorized_nif: str = None,
) -> List[MaxPower]:
"""Search the maximum power and the result will appear in kW
Args:
token (str): Bearer token
cups (str): Cups code. Get... | 59,316 |
def filter_remove_keyword_images(keywords_set, keyword_list, use_lemma=True):
"""Filter keyword-image pairs removing all images with keywords in the specified list.
NOTE: this should be used instead of `filter_remove_images` to remove all
image instances associated with remove keyword, including pairs with... | 59,317 |
def find(s, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice... | 59,318 |
def replace(correct, guess, correct2):
"""
Find out if your guess is in the correct answer or not, if yes, put it into your answer
"""
ans = ''
i = 0
for ch in correct:
if guess == ch:
ans += correct[i]
else:
ans += correct2[i]
i += 1
# for i i... | 59,319 |
def V_morse_1dof(x, par):
"""
Parameters
----------
x : TYPE
independent variable value of the potential energy function.
par : TYPE
parameters of the potential energy function.
Returns
-------
V : TYPE
potential energy of the 1 DOF morse osci... | 59,320 |
def broadcastable(shape_1, shape_2):
"""Returns whether the two shapes are broadcastable."""
return (not shape_1 or not shape_2 or
all(x == y or x == 1 or y == 1
for x, y in zip(shape_1[::-1], shape_2[::-1]))) | 59,321 |
def getAccount():
"""
API has been changed to accept only POST requests. Path of API has been changed.
Now the body of POST must be
{
"username" : 17BECXXXX,
"password" : password
}
"""
# First check if query is okay or not
data = json.loads(request.data)
username = ... | 59,322 |
def mesos_cluster_memory_resource_total_range(cluster_id, start, end):
"""mesos集群内存总量, 单位MB"""
step = (end - start) // 60
prom_query = f"""
max by (cluster_id) (bkbcs_scheduler_cluster_memory_resource_total{{cluster_id="{cluster_id}"}})
""" # noqa
resp = query_range(prom_query, start, end, ... | 59,323 |
def bipartite_sets(bg):
"""Return two nodes sets of a bipartite graph.
Parameters:
-----------
bg: nx.Graph
Bipartite graph to operate on.
"""
top = set(n for n, d in bg.nodes(data=True) if d['bipartite']==0)
bottom = set(bg) - top
return (top, bottom) | 59,324 |
def parse_args():
"""
The argument parser
"""
logger = logging.getLogger()
parser = argparse.ArgumentParser(
description=help_description(), epilog=help_epilog()
)
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.add_argument(
"-i", "--input_file",... | 59,325 |
def partition_start(cmd_ctx, cpc, partition, **options):
"""
Start a partition.
In addition to the command-specific options shown in this help text, the
general options (see 'zhmc --help') can also be specified right after the
'zhmc' command name.
"""
cmd_ctx.execute_cmd(lambda: cmd_partiti... | 59,326 |
def log(args, msg):
"""
Prints the message if debugging is turned on.
"""
def __now():
return datetime.utcnow().isoformat()
if args.debug:
print(f"[{__now()}] {msg}") | 59,327 |
def documents_report(log_file, recid_list_file):
"""Provide documents migration summary."""
document_migration_report(log_file, recid_list_file) | 59,328 |
def match_any(audit_id, result_to_compare, args):
"""
Match list of strings
:param result_to_compare:
The value to compare.
:param args:
Comparator dictionary as mentioned in the check.
"""
log.debug('Running string::match_any for check: {0}'.format(audit_id))
for option_to... | 59,329 |
def find_mqtt_topic(name: str) -> str:
"""
Based on the button name find the corresponding mqtt command
"""
if name == BUTTON_SHUFFLE:
return PHONIEBOX_CMD_PLAYER_SHUFFLE
if name == BUTTON_SCAN:
return PHONIEBOX_CMD_SCAN
if name == BUTTON_REWIND:
return PHONIEBOX_CMD_PLAY... | 59,330 |
def next(aList, index):
""" Return the index to the next element (compared to the element
with index "index") in aList, or 0 if it already is the last one.
Useful to make a list of loop.
"""
return (index+1) % len(aList) | 59,331 |
def admin_info():
"""Shows address of the admin instance."""
click.echo(f"Admin instance is at: {AdminInstance.instance().address}") | 59,332 |
def load_shp_data(path, drivername='ESRI Shapefile'):
"""
Returns shp file dataset
Parameters
----------
path : str
Path to shp file
drivername : str, optional
ogr driver name (default: 'ESRI Shapefile')
Returns
-------
shp : object
shp data object
"""
... | 59,333 |
def test_rshift_into_node(clear_default_graph):
"""Test the node rshift operator with an INode as target.
Note that OutputPlug >> INode is tested in the plug tests."""
@Node(outputs=["marker"])
def Node1():
return {"marker": None}
@Node(outputs=[])
def Node2(marker):
return {}
... | 59,334 |
def htmlize(widget):
"""
Jinja filter to render a widget to a html string
"""
html = widget.render(widget)
try:
html = html.decode('utf-8')
except Exception:
pass
return html | 59,335 |
def tokens(text: str) -> Iterator[str]:
""" Generator for token stream """
toklist = list(tokenize(text, convert_measurements=True, replace_html_escapes=True))
if len(toklist) > 1 and all(t.kind != TOK.UNKNOWN for t in toklist):
# For each sentence, start and end with empty strings
yield ""
... | 59,336 |
def parse_date_format(string: str) -> str:
"""
Parses the date-format string for date-type attributes.
TODO: Implement. csterling
:param string: The date-format string to parse.
:return: Currently, just the input.
"""
return string | 59,337 |
def _folder_exists(path: Path, errors: list, warnings: list) -> tuple:
"""Checks that the i18n folder exists and is a folder"""
if not path.exists():
errors.append((1, f"Cannot continue with the checks: folder \"{path}\" doesn't exist"))
elif not path.is_dir():
errors.append((2, f"Canno... | 59,338 |
def parallel_pre_compile_op(job: TbeJob):
"""
Parallel pre compile op
:param job:
:return:
"""
compute_op_info_list = get_compute_op_list(job.content)
if len(compute_op_info_list) != 1:
job.error("Invalid op compute num ({}) in pre compile op".format(len(compute_op_info_list)))
... | 59,339 |
def create_silhouette_of_img(input_image_path: str, output_image_path: str) -> None:
"""Creates a silhouette image
Args:
input_image_path: The name of the image you want to create a silhouette
output_image_path: The name of the file that you want to output the silhouette too
Returns:
... | 59,340 |
def transformFromOutputMatrix(curveMatrix=None, transformType='locator', showLocalAxis=True):
"""create a connected transform for each output.outputMatrix"""
curveMatrix = (mc.ls(curveMatrix, type='prCurveMatrix') or
mc.ls(sl=True, type='prCurveMatrix') or
[None])[0]
tr... | 59,341 |
def search_sensor_id(endpoint: str) -> int:
""" Retrieve list of connected sensors from:
Integration: VMware Carbon Black EDR (Live Response API).
Command: cb-list-sensors.
Args:
endpoint: Endpoint name - hostname/IP
Returns:
str: sensor id if found else empty string... | 59,342 |
def test_2_trains():
"""
two trains of loads are approaching each other.
train 123 going from 1 to 14
train 4567 going from 14 to 1.
At intersection 4 train 123 can be broken apart and
buffered, so that train 4567 can pass.
The reverse (buffering train 4567) is not possible.
"""
g... | 59,343 |
def get_packing_recipe(args, sequence_lengths):
"""Given program arguments and a list of sequence lengths return the packing recipe.
A "packing recipe" primarily consists of a set of strategies "strategy_set" and the "mixture"
which states how many times each one of these strategies should be applied in or... | 59,344 |
def delete_file(file_name):
"""
:param file_name:
:return:
"""
try:
os.remove(file_name)
except:
pass | 59,345 |
def _merge_block(internal_transactions, transactions, whitelist):
"""
Merge responses with trace and chain transactions. Remove non-whitelisted fields
Parameters
----------
internal_transactions : list
List of trace transactions
transactions : list
List of chain transactions
... | 59,346 |
def registerPlayer(name):
"""
Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique).
"""
# return i... | 59,347 |
def make_skies_for_a_brick(survey, brickname, nskiespersqdeg=None, bands=['g', 'r', 'z'],
apertures_arcsec=[0.75], write=False):
"""Generate skies for one brick in the typical format for DESI sky targets.
Parameters
----------
survey : :class:`object`
`LegacySurveyDat... | 59,348 |
def county_breakdown_plot(age_df, county_df):
"""Geographical plot of county average of low birth weights."""
# County FIPS codes.
county_fips = county_df.FIPS.tolist()
# Sort birth weights by county.
age_sort_df = age_df.groupby(by=['county', 'weight_indicator']
).... | 59,349 |
def findProcesses(user=None, exe=None):
"""Find processes in process list.
Args:
user: str, optional, username owning process
exe: str, optional, executable name of process
Returns:
dictionary of pids = {
pid: {
'user': str, username owning pr... | 59,350 |
def parse_item(location: str, item_type: Type[T], item_name_for_log: str = None,
file_mapping_conf: FileMappingConfiguration = None,
logger: Logger = default_logger, lazy_mfcollection_parsing: bool = False) -> T:
"""
Creates a RootParser() and calls its parse_item() method
:pa... | 59,351 |
def tpow(x: T.Tensor, a: float) -> T.Tensor:
"""
Elementwise power of a tensor x to power a.
Args:
x: A tensor.
a: Power.
Returns:
tensor: Elementwise x to the power of a.
"""
return ne.evaluate('x**a') | 59,352 |
def test_tts_say():
"""Test TtsSay."""
assert TtsSay.topic() == "hermes/tts/say" | 59,353 |
def test_new_question_with_details(db):
"""
Check that question/answer is set when details are populated.
This simulates what would happen in the update command, which is expected
to look at each question modification operation and determine if a value
was supplied to the argument. If not, the comm... | 59,354 |
def get_last_price(base,quote, return_price_only):
"""
Args:
'DOT', 'USDT'
"""
tickers = spot_api.list_tickers(currency_pair=f'{base}_{quote}')
assert len(tickers) == 1
t = tickers[0]
if return_price_only:
return t.last
logger.info(f"GET PRICE: {t.currency_pair} | last={... | 59,355 |
def load_state_dict_from_url(url: str, path: str, md5: str=None) -> os.PathLike:
"""
Download and load a state dict from url
"""
if not os.path.isdir(path):
os.makedirs(path)
download.get_path_from_url(url, path, md5)
return load(os.path.join(path, os.path.basename(url))) | 59,356 |
def decrypt_lsa_key_nt5(lsakey, syskey):
"""
This function decrypts the LSA key using the syskey
"""
dg = hashlib.md5()
dg.update(syskey)
for i in xrange(1000):
dg.update(lsakey[60:76])
arcfour = RC4(dg.digest())
deskey = arcfour.encrypt(lsakey[12:60])
return [deskey[16 * x:1... | 59,357 |
def builtins_preview():
""" I want print to be output like cli.log """
# Output below without hook
print("No builtins_hook here")
cli.builtins_hook()
# Output below from the hook
# After hook cli = console
print("builtins_hook here")
console.write("console.write")
console.log("... | 59,358 |
def __iot_policy_version_exists(cleaner, iot_policy_name, iot_policy_version_id):
"""
Verifies if a policy version exists. This is should be replaced once iot supports Waiter objects for policy
deletion.
:param cleaner: A Cleaner object from the main cleanup.py script
:param iot_policy_version_id: C... | 59,359 |
def milne_predictor_corrector_method(f: Callable[[float, float], float],
y0: float,
x: list[float],
h: float,
yl: list[float]) -> float:
"""Finds the value of y(x) for ... | 59,360 |
def go_test(name, pure = False, library = None, **kwargs):
"""Build a go test.
Args:
name: name of the output binary.
pure: should it be built without cgo.
library: the library to embed.
**kwargs: rest of the arguments to pass to _go_test.
"""
if pure:
kwargs["pu... | 59,361 |
def walk_modules(module, name="", path=(), depth=-1):
"""Generator. Walks through a PyTorch Module and outputs Trace tuples"""
if not name:
name = module.__class__.__name__
named_children = list(module.named_children())
path = path + (name,)
yield Trace(path, len(named_children) == 0 or (len... | 59,362 |
def value_at_risk_percent(df: pd.DataFrame, t: int, period=10, alpha=0.95, price_col='Close'):
"""Calculates the Value at Risk (VaR) of time period
"""
# t must be bigger than 2 to evaluate percentile
if t-period+2 < 0:
var_df = df.iloc[1:t+1]
else:
var_df = df.iloc[t-period+1:t+1]
... | 59,363 |
def read_xml(f: Path) -> ElementTree.Element:
"""Read an XML file and return the root"""
with open(f, "r") as xml_file:
return ElementTree.XML(xml_file.read()) | 59,364 |
def test_pwd_of_config_eval(): # This used to be test 01
""" Test that the config file is evaluated from the test dir """
testpath = os.path.join(os.path.abspath(os.path.split(__file__)[0]),
'test_dirs','evalpath')
try:
shutil.rmtree(testpath)
except:
pass
os.makedir... | 59,365 |
def dcg_score(y_true, y_score, k=10, gains="exponential"):
"""Discounted cumulative gain (DCG) at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k : int
... | 59,366 |
def get_resource_file(resource_name):
"""
:param resource_name: The name of the resource file placed in `SFUTranslate/resources` directory
:return: an object of `pathlib.PosixPath` which can be directly opened or traversed
"""
return Path(get_resources_dir(), resource_name) | 59,367 |
def _conv_number(number, typen=float):
"""Convert a number.
Parameters
----------
number
Number represented a float.
typen :
The default is ``float``.
Returns
-------
"""
if typen is float:
try:
return float(number)
except:
... | 59,368 |
def is_simple_path(G: nx.Graph, path: VertexList) -> bool:
"""Is the path simple in the graph?
Args:
G: input graph
path: Ordered sequence of vertices
Returns:
True if the path is simple in the graph
"""
return is_walk(G, path) and len(path) == len(set(path)) | 59,369 |
def _build_image(client, tag, path) -> Image:
"""
Helper function to get a correct type
"""
try:
return _try_build_image(client, tag, path)
except DppError as e:
message.stdout_progress_error(e)
sys.exit(1) | 59,370 |
def str_to_datetime(sdt: str) -> datetime:
"""try convert str to datetime with DATETIME_TYPE format until no exception"""
if sdt:
for k in DATETIME_TYPE:
try:
return datetime.strptime(sdt, k.value)
except:
pass
raise IndexError(BaseLocal.ge... | 59,371 |
def manifest(targets, mfname='MANIFEST'):
"""
Produce a manifest file given `targets`.
"""
with open(mfname, 'w') as mfh:
def append_hash(fname):
fname = normalize_path(fname)
digest = hash_target(fname)
mfh.write('{} {}\n'.format(digest, fname))
l... | 59,372 |
def Movie_suppressionTaches(self):
"""Suppression des billes qui n'ont pas bougées -> taches"""
eps = 10
for i in range(self.nbilles):
if self.billesValides[i]:
if self.dist(i, -1, i, 0) < eps:
self.billesValides[i] = False | 59,373 |
def rimea_test_4(screen_width=500):
""" Create environment for RiMEA scenario 4 in task 5 """
grid_size = 80
app = Tk()
grid = CellGrid(app, grid_size, int(screen_width / grid_size), is_rimea_4=True)
grid.pack()
grid.focus_set() # to receive inputs form keyboard
# draw corridor (two lines ... | 59,374 |
def remove_virtual_slot_cmd(lpar_id, slot_num):
"""
Generate HMC command to remove virtual slot.
:param lpar_id: LPAR id
:param slot_num: virtual adapter slot number
:returns: A HMC command to remove the virtual slot.
"""
return ("chhwres -r virtualio --rsubtype eth -o r -s %(slot)s "
... | 59,375 |
def daily_quota(day=None):
"""Return the daily quota for a given day.
:param day: date object (defaults to today)
"""
if day is None:
day = datetime.today()
if HAPPY_HOUR_START <= day and day < HAPPY_HOUR_END:
return HAPPY_HOUR_QUOTA
elif day.weekday() in {5, 6}:
return... | 59,376 |
def check_config(config):
""" checks whether the config file is correct """
if not config.has_key("username"):
exit_with_error("No username specified in config.")
if config["username"] not in get_osx_usernames():
exit_with_error(
"Username '{username}' unknown.\nPlease use your O... | 59,377 |
def dict_to_bytestring(dictionary):
"""Converts a python dict to json formatted bytestring"""
return json.dumps(dictionary).encode("utf8") | 59,378 |
def login():
"""
Login user to ZenType account.
"""
r = request.get_json()
user_email = r.get('email', None)
user_password = r.get('password', None)
userDO = UserAuth.find_user_and_validate_password(
email=user_email,
password=user_password
)
if userDO is not None:
# if the user was created successfu... | 59,379 |
def DataClass(name, columns, constraint=None):
"""
Use the DataClass to define a class, but with some extra features:
1. restrict the datatype of property
2. restrict if `required`, or if `nulls` are allowed
3. generic constraints on object properties
It is expected that this class become a rea... | 59,380 |
def _run_prop_dos(
frequencies, mode_prop, ir_grid_map, ir_grid_points, num_sampling_points, bz_grid
):
"""Run DOS-like calculation."""
kappa_dos = KappaDOS(
mode_prop,
frequencies,
bz_grid,
ir_grid_points,
ir_grid_map=ir_grid_map,
num_sampling_points=num_samp... | 59,381 |
def load_data(database_filepath):
"""
Read the input database to create and return separate numpy arrays for
messages, category values, and names of categories respectively
"""
# creating sqlite engine to interact with database
engine = create_engine('sqlite:///'+database_filepath)
df =... | 59,382 |
def Client(**kwargs):
"""Get a SoftLayer API Client using environmental settings.
Deprecated in favor of create_client_from_env()
"""
warnings.warn("use SoftLayer.create_client_from_env() instead",
DeprecationWarning)
return create_client_from_env(**kwargs) | 59,383 |
def footprint_check(part):
"""Footprint check"""
fp = part.footprint.split(":")
assert not part.footprint or len(fp) == 2, "Invalid footprint '%s'" % part.footprint
if part.footprint:
libname = fp[0] + ".pretty"
fpname = fp[1] + ".kicad_mod"
fppath = os.path.join(PCBLIB_PATH, lib... | 59,384 |
def _merge_candidate_name(src, dest):
"""Returns the formatted name of a merge candidate branch."""
return f"xxx-merge-candidate--{src}--{dest}" | 59,385 |
def feature(enabled=True, default_rule=True, conditions=True, operator=None):
"""Generates feature structure like parsed JSON from server"""
return {
'key': fake.word(),
'variantSalt': fake.word(),
'enabled': enabled,
'offVariantKey': fake.word(),
'rules': [rule(default_... | 59,386 |
def print_coverage(data, emb):
"""
print coverage of embeddings emb on the dataset data
"""
print "Coverage of the embedding on the dataset:"
not_found = []
n_total = 0
pairs = 0
for x1, x2 in data.X:
x1_not_found, x2_not_found = False, False
if emb.get(x1) is None:
... | 59,387 |
def to_datetime(
arg,
errors="raise",
dayfirst=False,
yearfirst=False,
utc=None,
box=True,
format=None,
exact=True,
unit=None,
infer_datetime_format=False,
origin="unix",
):
"""Convert the arg to datetime format. If not Ray DataFrame, this falls
back on pandas.
... | 59,388 |
def cv_process(data=None, current_column=1, potential_column=0, area=5, reference='she', thermo_potential=0, export_data=False, save_dir='processed', **kwargs):
"""
Processes cyclic voltammetry data
Can either process pre-loaded data or load and process data files. If called with no arguments, loads and processes a... | 59,389 |
def OpenNormalFVFile(fv_file, type_str):
"""
Open a normalized frequency vector file and check to make sure it's valid.
The first line of a valid normalized FV file contains the number of vectors
in the file followed by the char ':' and an optional char 'w'.
Subsequent lines contain an optional we... | 59,390 |
def td3(env_fn, actor_critic=core.MLPActorCritic, ac_kwargs=dict(), seed=0,
steps_per_epoch=4000, epochs=100, replay_size=int(1e6), gamma=0.99,
polyak=0.995, pi_lr=1e-3, q_lr=1e-3, batch_size=100, start_steps=10000,
update_after=1000, update_every=50, act_noise=0.1, target_noise=0.2,
noi... | 59,391 |
def meta(condition):
"""Return a class with a subclassing relation defined by condition.
For example, a dataclass is a subclass of `meta(dataclasses.is_dataclass)`,
and a class which name starts with "X" is a subclass of
`meta(lambda cls: cls.__name__.startswith("X"))`.
Arguments:
conditio... | 59,392 |
def create_folders(model, _start_over_report):
""" Creates folders for a column in a dataset
:param _start_over_report: True/False. True allows creating a new report and False allows appending to the existing report
:return:
"""
main_folder = model.config.current_experiment_folder
# Create inpu... | 59,393 |
def queue_once_key(name, kwargs, restrict_to=None):
"""
Turns a list the name of the task, the kwargs and allowed keys
into a redis key.
"""
keys = ['qo', name]
# Restrict to only the keys allowed in keys.
if restrict_to is not None:
restrict_kwargs = {key: kwargs[key] for key in res... | 59,394 |
def get_outliers(training_data, unlabeled_data, number=10):
"""Get outliers from unlabeled data in training data
Returns number outliers
An outlier is defined as the percent of words in an item in
unlabeled_data that do not exist in training_data
"""
outliers = []
total_feature_count... | 59,395 |
def add_object_args(parser):
"""Add Object settings to argparse or argument group instance parser."""
# Disk scanning
parser.add_argument('--skip', action='append', default=['README.md', '.DS_Store'],
help='directories and files to ignore')
parser.add_argument('--normalization', ... | 59,396 |
def is_cdn_cache_hit(response):
"""Checks the response for evidence of a cache hit on the CDN."""
return is_cloudfront_cache_hit(response) | 59,397 |
def main():
"""
x = [1,2,1,2]
y = [1,1,2,2]
i = [1,np.NaN,3,4]
x = np.array(x)
y = np.array(y)
N = int(len(x)**.5)
i = np.array(i)
i = i.reshape(N,N)
print(i)
plt.imshow(i, extent = (np.min(x), np.max(x), np.min(y), np.max(y)),
cmap = cm.brg)#... | 59,398 |
def mms_feeps_energy_table(probe, eye, sensor_id):
"""
This function returns the energy table based on
each spacecraft and eye; based on the table from:
FlatFieldResults_V3.xlsx
from Drew Turner, 1/19/2017
Parameters:
probe: str
probe #, e.g., '4' for MMS4
... | 59,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.