content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def dataset_urls():
"""Returns a list of legacy datasets available for testing"""
legacy_data_directory = os.path.join(os.path.dirname(__file__), 'data', 'legacy')
versions = os.listdir(legacy_data_directory)
urls = ['file://' + os.path.join(legacy_data_directory, v) for v in versions]
return urls | 5,287,200 |
def test_getNewTimes_with_half_phase_one_day_bin():
"""
Test to make sure times are shifted
properly if the phase optional argument
is used.
"""
times = np.random.uniform(0, 10, 75)
newtimes = wm.getNewTimes(times, 1.)
newtimes2 = wm.getNewTimes(times, 1., phase=0.5)
assert np.round(... | 5,287,201 |
def test_publication_index_page_gets_created(publication_index_page):
"""Test that we have a publication index page created by the fixture"""
assert publication_index_page is not None | 5,287,202 |
def _open(path: _StrOrPath, *args: Any, **kwargs: Any) -> ContextManager[Any]:
"""Opens the file; this is a hook for the built-in open()."""
return open(path, *args, **kwargs) | 5,287,203 |
def partition(groups, train_part=0.8, val_part=0.1, test_part=0.1):
"""Splits groups into training, validation, and test partitions.
Args:
groups (list): list of units (e.g. dicts).
train_part (float): proportion in [0, 1] of units for training.
val_part (float): self-explanatory.
... | 5,287,204 |
def click_z_origin(im):
"""
Records user clicks that indicate the desired origin and z-axis in an
image. These can be used to calculate the r-coordinate measured off the
z-axis.
Parameters
----------
im : (M x N x 3) or (M x N) numpy array of floats or uint8s
Image that will be shown... | 5,287,205 |
def identify_sam_transcripts(sam_transcripts, gene_tree, transcripts, exon_tree,
intron_tree, vertices, counter, dataset,
novel_ids, abundance):
""" Assign each sam transcript an annotated or a novel transcript identity
Returns:
Modifie... | 5,287,206 |
def get_logger_config(caller_file_path: Union[str, Path], name: str=None) -> dict:
"""
Get logger config as dictionary
:param caller_file_path: file path of the caller, __file__
:param name: the name(section in logme.ini) of the config to be passed. (optional, default: 'logme')
:return: logger con... | 5,287,207 |
def _optimizer(program, fun_list, n_features, n_program_sum, metric,
X, y, weight):
"""Simplify a program and then optimize its numerical parameters.
Parameters
----------
program : list
The program to be optimized.
fun_list : list of length 6
List mapping the operations in ord... | 5,287,208 |
def full():
"""Returns human friendly full date of current UTC time"""
return obj().strftime("%A, %d %B %Y %I:%M%p") | 5,287,209 |
def need_to_login():
"""A route used to indicate the user needs to authenicate for some page."""
year = date.today().year
return render_template("website/login.html",
message="Need to login to proceed further.",
route=Routes,
y... | 5,287,210 |
def set_random_forest_sample_size(nobs):
"""
Override default behavior of scikit-learn random forest models to
sample the same number of rows from the original data with replacement.
Instead, this forces random forest to fit each tree on a sample of size
nobs, greatly speeding up the algorithm on la... | 5,287,211 |
def unload():
"""
Unload the savefig hook and revert to the light interface
"""
plt.Figure.savefig = _savefig_orig
light() | 5,287,212 |
def test_versions_displayed_in_log_file(accelize_drm, conf_json, cred_json, async_handler):
"""Test versions of dependent libraries are displayed in log file"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
log_path = realpath("./drmlib-%d.log" % getpid())
log_type =... | 5,287,213 |
def get_peaks(sig, onsets):
"""
Perform an algorithm to identify a series of peaks given a
signal and it's onsets
:param sig: The signal requiring the calculation
:param onsets: An array of containing the list of onsets for the signal
:return: An array containing the list of peaks in the s... | 5,287,214 |
def combine_datasheets(list_of_dicts,economy):
"""
Combine individual data sheets into one datasheet.
Combined datasheet will be written to Excel then processed by otoole.
"""
tmp_directory = 'tmp/{}'.format(economy)
try:
os.mkdir('./tmp')
except OSError:
#print ("Creation o... | 5,287,215 |
def build_schm(tool, source_data, make_shell, override_source_text=None, create=False):
"""Build schematic data out of YAML description"""
print(f"build_schm(\n tool={tool},\n source_data={source_data},\n"
" make_shell={make_shell},\n override_source_text={override_source_text})")
load_from_file = ... | 5,287,216 |
def phpinfo(interp, arg):
""" Outputs information about PHP's configuration"""
if arg & get_const('standard', 'INFO_MODULES'):
for ext in EXTENSIONS:
interp.writestr(ext + "\n")
return interp.space.w_True | 5,287,217 |
def prefix_repo_nwo(filename):
"""
Replaces an absolute path prefix with a GitHub repository name with owner (NWO).
This function relies on `git` being available.
For example:
/home/alice/git/ql/java/ql/src/MyQuery.ql
becomes:
github/codeql/java/ql/src/MyQuery.ql
If we can't d... | 5,287,218 |
def assert_edge_connections(edges_list, pairs_list):
"""Assert that the list of Edge objects connects the nodes with IDs specified in the pairs_list"""
for e, (from_id, to_id) in zip(edges_list, pairs_list):
assert e.node_from_id==from_id and e.node_to_id==to_id | 5,287,219 |
def get_graph(name, hetmat=False, directory=None):
"""
If hetmat=True, import graph into a hetmat located on-disk at directory.
"""
if name not in hetnet_urls:
raise ValueError(
f"{name} is not a supported test hetnet.\n"
"Choose from the following currently defined hetne... | 5,287,220 |
def check_parallel(name, X, y):
"""Check parallel computations in classification"""
ForestEstimator = FOREST_ESTIMATORS[name]
forest = ForestEstimator(n_estimators=10, n_jobs=3, random_state=0)
forest.fit(X, y)
assert_equal(len(forest), 10)
forest.set_params(n_jobs=1)
y1 = forest.predict(X... | 5,287,221 |
def insert_project_files(sandbox):
""" Fixture factory for inserting config files into tmp project dir """
def inner(package=False, lock=False):
if package:
sandbox['proj_package'].write_text(PACKAGE_JSON)
if lock:
sandbox['proj_lock'].write_text(LOCK_JSON)
return... | 5,287,222 |
def reset_random_state():
"""
Reset the random stat - for testing purposes
"""
rng.set_state(state) | 5,287,223 |
def scoutChangeIp(ip, username, password, newIp, subnetMask):
"""Function that identifies SSH info, collects sys args,
calls the scout_change_ap_ip command set, opens a SSH connection
to the AP, executes the IP change, terminates the old SSH connection,
opens a new one, and runs the scout_do_wr command ... | 5,287,224 |
def get_first_last_onset(csv_file):
"""Gets the first and last onset times."""
with open(csv_file) as f:
full_track = list(csv.reader(f))
first_onset = float(full_track[0][0])
if first_onset < 0:
first_onset = abs(first_onset) # we only store the first onset if it is
... | 5,287,225 |
def extractBivectorParameters_complicated(B):
"""
B must be a general rotation object on the format $ \phi*P + t n_{\inf}} $
"""
omega = float(B | E0)
phi, P, t_par, t_nor = extractBivectorParameters(B - omega * E0)
return phi, P, t_par, t_nor, omega | 5,287,226 |
def app_logs(app):
"""
Stream app's logs from a specific edgeflow via rancher
"""
all_ef = app._cc.get_all_edgeflows()
if len(all_ef) == 1:
edgeflow = all_ef[0]
else:
# find which of multiple edgeflow from which to access logs for the specified app
if len(sys.argv) != 3:... | 5,287,227 |
async def get_file(session, hashval):
"""
:param session:
:param hashval:
:return:
"""
sample_path = os.path.join(SAMPLE_DIR, sha256_key(hashval))
if os.path.exists(sample_path):
return "exists"
sample_dir = os.path.dirname(sample_path)
url = "%s/file/download" % BASE_URL
... | 5,287,228 |
def ionic_strength(c,z):
"""Compute ionic strength from charges and concentrations
Arguments:
c: bulk concentrations [concentration unit, i.e. mol m^-3]
z: number charges [number charge unit, i.e. 1]
Returns:
float: I, ionic strength ( 1/2 * sum(z_i^2*c_i) ) [concentration unit, i.e. mol m^-3]... | 5,287,229 |
def patch_wise_training(data_path,
train_subs,
test_subs,
lambda_loss,
epochs,
batch_size,
lr,
conv_filters,
cv_fold,
... | 5,287,230 |
def sign_extend_3(val, width, tmp):
""" Sign extension. High-order bit of val is left extended.
:param val: VexValue
:param width: VexValue
:param tmp: VexValue of 0xffffffff
"""
mask_sign_bit = (1 << (width-1)).cast_to(Type.int_32)
cond_sign_bit_1 = extend_to_32_bits(val & mask... | 5,287,231 |
def __check_if_alive(processes):
"""
Quickly check if at least one of the list of processes is alive.
Returns True if at least one process is still running.
"""
c = set([x.exitcode for x in processes])
return None in c | 5,287,232 |
def check_idtype_dict(graph_dtype, tensor_dict):
"""check whether the dtypes of tensors in dict are consistent with graph's dtype"""
for _, v in tensor_dict.items():
check_same_dtype(graph_dtype, v) | 5,287,233 |
def previous_next_placement(doc_filter: DocumentFilter) -> pd.DataFrame:
"""
Calculate mu teamPlacement before and after a teamPlacement.
:param doc_filter: Input DocumentFilter.
:type doc_filter: DocumentFilter
:return: Previous and next expected placement based on current placement.
:rtype: p... | 5,287,234 |
def prices_to_returns(prices: pd.DataFrame, log: bool = False):
"""
Calculate the returns given prices.
Parameters
----------
:param prices: pd.DataFrame
A pandas DataFrame with asset prices
:param log: bool
Whether to compute logarithmic returns
Default is False -> line... | 5,287,235 |
def test_mixing_energies_are_reduced_with_ridge_alpha(datasets_db):
"""Tests that given mixing energy data, the excess parameter is fit."""
phase_models = {
"components": ["AL", "B"],
"phases": {
"LIQUID" : {
"sublattice_model": [["AL", "B"]],
"sublatt... | 5,287,236 |
def check_array(arr: Data) -> np.ndarray:
"""
Utility function for checking and validating input arrays.
"""
# Check array type
if isinstance(arr, (pd.DataFrame, pd.Series)):
arr = arr.to_numpy()
elif sparse.issparse(arr):
arr = arr.toarray()
elif isinstance(arr, np.nd... | 5,287,237 |
def _SeriesFactory(ser):
"""
Return an instance of the appropriate subclass of _BaseSeries based on the
xChart element *ser* appears in.
"""
xChart_tag = ser.getparent().tag
try:
SeriesCls = {
qn("c:areaChart"): AreaSeries,
qn("c:barChart"): BarSeries,
... | 5,287,238 |
def create_access_token(
subject: Union[str, Any], expires_delta: timedelta = None
) -> str:
"""Encodes a JWT
Args:
subject (Union[str, Any]): The content of the JWT.
expires_delta (timedelta, optional): The JWT expiry timedelta. Defaults to None.
Returns:
str: The JWT hash.
... | 5,287,239 |
def chown(
path: _PATH,
user: Optional[str] = None,
group: Optional[str] = None,
include_parent: bool = False
) -> None:
"""Change ownership of a path.
This function processes the given ``path`` with
:obj:`~flutils.normalize_path`.
If the given ``path`` does NOT exist, ... | 5,287,240 |
def peristimulus_time_trial_average_plot(sigs, times, tags, extra_event_times=None, ylim=None, ax=None,
method='ci95'):
"""
TODO: enable feeding error bars
Take in list of signal groups plot hued line plots in ax.
:param sigs: np.ndarray or list of disparate sign... | 5,287,241 |
def n_mat_propostas(votadas = True):
""" Recebe um boleano que define se o retorno.
Se votadas for verdadeiro retorna um dicionário cuja chave é o nome do parlamentar
e o conteudo é o número de matérias propostas, pelo parlamentar, que foram votadas.
Se votadas for falso retorna um dicionário cuja chave é o nome... | 5,287,242 |
def browser(webdriver_instance):
""" Provides a WebDriver instance and performs some cleanups afterwards. """
yield webdriver_instance
webdriver_instance.delete_all_cookies() | 5,287,243 |
def update_modules(database=None, modules=None):
"""Update modules. Requires running odoo."""
if database is not None:
set_database_name(database)
if modules is not None:
env.odoo_modules = modules.split(":")
client = get_odoo_client()
try:
client.upgrade(*env.odoo_modules... | 5,287,244 |
def test_correct(execute_save_result_process, s3_stub_generator, create_result_object, parameters, expected_result_filename):
"""
Test save_result process with correct parameters
"""
s3_stub = s3_stub_generator(create_result_object(expected_result_filename))
result = execute_save_result_process(... | 5,287,245 |
def CreateDictionary(name_fmt, codeset, src_dir, out_dir, wrapper=None):
"""Creates a dictionary used for configs."""
exports = {}
if wrapper is None:
wrapper = lambda c: c
for code_class in registry.classes.values():
def Closure(code_class):
def Registerer(src, *args, **kwargs):
codeset.a... | 5,287,246 |
def draw_parking_spot_x(ctx, frame: Polygon):
"""Draw two crossing lines (X) in the given frame to represent a blocked spot.
Args:
frame: Frame of the parking spot.
**Points of the frame must be given in the right order!**
first point : left lower corner of parking spot
... | 5,287,247 |
def test_data_list() -> list:
"""Return the list of paths to the test input data files
Parameters:
None
Returns:
list: The list of paths to the test input data files
"""
return glob.glob("test_data/*.rws.gz") | 5,287,248 |
def test_module(client, params):
"""
Returning 'ok' indicates that the integration works like it is supposed to. \
Connection to the service is successful. Anything else will fail the test.
:param client: client to use
:param params: parameters obtained from demisto.params()
"""
res = clien... | 5,287,249 |
def _url(data={}):
"""Helper method to generate URLs."""
data = "&".join(["{}={}".format(name, value) for
name, value in data.items()])
return "{}{}locative?{}".format(HTTP_BASE_URL, const.URL_API, data) | 5,287,250 |
def model_from_json(json_string, custom_objects=None):
"""Parses a JSON model configuration string and returns a model instance.
Usage:
>>> model = tf.keras.Sequential([
... tf.keras.layers.Dense(5, input_shape=(3,)),
... tf.keras.layers.Softmax()])
>>> config = model.to_json()
>>> loaded_model ... | 5,287,251 |
def route_vm_logic(logicFn):
"""
Decorates a function to indicate the viewmodel logic that should be executed after security checks and business
logic passes.
:param logicFn: The viewmodel logic function to assign.
:return: The decorated function.
"""
def decorator(fn):
fn.route_vm_... | 5,287,252 |
def format_obs_ensemble(obs_ensemble, obgnme):
"""
Reformat observation ensemble.
Parameters:
===========
obs_ensemble: pd.DataFrame, the observation ensemble
Returns:
===========
obs_ensemble: pd.DataFrame, the observation ensemble after new format.
"""
obs_ensemble.index =... | 5,287,253 |
def remove_notification_time(user_id, column_name):
"""
指定ユーザーの通知時間の設定を削除して、結果を通知します
Parameters
----------
user_id : string
ユーザーID
column_name : string
設定対象(gomi_today/gomi_day_beforeのどちらか、usersテーブル上のカラム名と同じにしています)
"""
if column_name == 'gomi_today' or column_name == 'go... | 5,287,254 |
def to_ideogram_html_str(gene_symbols: Iterable[str]) -> str:
"""Get an Ideogram HTML document as a string."""
annotations = get_ideogram_annotations(gene_symbols)
logger.info("using %d annotations in ideogram", len(annotations))
return get_ideogram_template().render(annotations=annotations) | 5,287,255 |
def read2byte(i2cBus: SMBus, i2cAddr: int, lowByteAddr: int, highByteAddr: int) -> int:
"""
Read two byte from i2c Bus by using SMBus library
:param i2cBus: SMBus instance
:type i2cBus: SMBus
:param i2cAddr: i2c address, a one byte address
:type i2cAddr: int
:param lowByteAddr: the low byte... | 5,287,256 |
def typechecked(f):
"""
Use the @typechecked decorator on a function to perform run-time typechecking.
The docstring for `check_type` describes how type annotations should look.
"""
argspec = inspect.getfullargspec(f)
annotations = f.__annotations__
@wraps(f)
def g(*args, **kwargs):
... | 5,287,257 |
def unload_launch_agent():
"""Helper method to unload the LaunchAgent
"""
launch_agent_file_path = get_launch_agent_file_path()
load_launch_agent_cmd = subprocess.Popen(['launchctl', 'unload', launch_agent_file_path])
load_launch_agent_cmd.wait() | 5,287,258 |
def top_k_incidence_decision(k: int = 3) -> IncidenceDecisionFunctionType:
"""Select exactly k subjects with highest probabilities.
Chooses random subjects if less than k subjects have positive probability.
Parameters
----------
k: int
the maximum number of subjects that are selected and r... | 5,287,259 |
def draw_turn(row, column, input_list, user):
"""
Draw the game board after user typing a choice.
Arguments:
row -- the row index.
column -- the column index.
input_list -- a two dimensional list for game board.
user -- the user who type the choice
Returns:
input_list -- a two ... | 5,287,260 |
def normal_vec(triplet):
"""
Return the unit normal vector to the plane defined by a triplet of atom positions [[x1,y1,z1],[x2,y2,z2],[x3,y3,z3]]
"""
p1 = [triplet[0][0], triplet[0][1], triplet[0][2]]
p2 = [triplet[1][0], triplet[1][1], triplet[1][2]]
p3 = [triplet[2][0], triplet[2][1], tr... | 5,287,261 |
def t_from_CT(SA, CT, p):
"""
Calculates *in-situ* temperature from Conservative Temperature of
seawater.
Parameters
----------
SA : array_like
Absolute salinity [g kg :sup:`-1`]
CT : array_like
Conservative Temperature [:math:`^\circ` C (ITS-90)]
p : array_like
... | 5,287,262 |
def is_open_port(port):
"""
Check if a port is open (listening) or not on localhost.
It returns true if the port is actually listening, false
otherwise.
:param port: The port to check.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',po... | 5,287,263 |
def hashid(obj, suffix=""):
"""
Returns a per-class unique hash that combines the object's
class name with its idnum and creation time. This makes this id unique also
between different typeclassed entities such as scripts and
objects (which may still have the same id).
"""
if not obj:
... | 5,287,264 |
def window_indices(frame, window=30, center=None, **kwargs):
"""
Get the linear indices for each satellite spot
Parameters
----------
frame : ArrayLike
image frame
window : float, Tuple, optional
window size, or tuple for each axis, by default 30
center : Tuple, optional
... | 5,287,265 |
def test_riomucho_arrayread(tmpdir, test_1_tif, test_2_tif):
"""Distribution of an array reading user function works"""
with rasterio.open(str(test_1_tif)) as src:
options = src.profile
options.update(count=2)
with riomucho.RioMucho(
[str(test_1_tif), str(test_2_tif)],
str(t... | 5,287,266 |
def open_pbobject(path, pb_class, verbose=True):
"""Load JSON as a protobuf (pb2) object.
Any calls to load protobuf objects from JSON in this repository should be through this function.
Returns `None` if the loading failed.
Parameters
----------
path: str
JSON file path to load
p... | 5,287,267 |
def _is_table(client, dataset_id, table_id, project_id):
"""Check whether a `table_id` is a view or not."""
if (dataset_id is None) or (table_id is None):
return False
dataset_ref = bigquery.DatasetReference(project_id, dataset_id)
table_ref = dataset_ref.table(table_id)
table = client["b... | 5,287,268 |
def class_name(n):
"""
Formats a valid C# class name from the name format used in the XML.
@param n: The class name to format in C# style.
@type n: string
@return The resulting valid C# class name
@rtype: string
"""
if n == None: return None
try:
return native_types... | 5,287,269 |
def autodoctest():
""" Test the module using autodoc
Example:
>>> import oapackage
>>> arrayclass=oapackage.arraydata_t(2, 40, 0, 7)
>>> print(arrayclass)
arrayclass: N 40, k 7, strength 0, s {2,2,2,2,2,2,2}, order 0
"""
return | 5,287,270 |
def batched_soft_nms(boxes, scores, idxs, method, sigma, threshold):
"""
Performs soft non-maximum suppression in a batched fashion.
Each index value correspond to a category, and NMS
will not be applied between elements of different categories.
Args:
boxes (Tensor[N, 4]):
boxes w... | 5,287,271 |
def match_id(url):
"""匹配歌单ID"""
try:
res = re.findall('id=(\d{4,12})', url)
return res[0]
except Exception as e:
pass
return None | 5,287,272 |
def test_n_cbirths():
"""Test module n_cbirths.py by downloading
n_cbirths.csv and testing shape of
extracted data has 1450 rows and 15 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = n_cbirths(test_path)
try:
assert x_train.shape == (1450, 15)
except:
shutil.rmtree(test_path)
... | 5,287,273 |
def create_config():
"""
Creates the configuration file. If a file is already present, asks the user if he'd like to overwrite it or keep
the current configuration.
"""
# check if configuration is not already present. In case it's present, ask the user confirmation to edit.
config_exists = confi... | 5,287,274 |
def base_kinesis_firehose_delivery_stream(construct, **kwargs):
# TODO: ADD ROLES, BUCKETS, AND FIREHOSE MINIMUM SETTINGS
"""
Function that generates a Kinesis Firehose Delivery Stream.
:param construct: Custom construct that will use this function. From the external construct is usually 'self'.
:pa... | 5,287,275 |
def decompress_files(filepaths, remove=False):
"""
This function ...
:param filepaths:
:param remove:
:return:
"""
# Initialize a list for the decompressed file paths
new_paths = []
# Loop over the files
for filepath in filepaths:
# Get the name of the file
fi... | 5,287,276 |
def new_combo_column(title,
data_func=None,
changed_callback=None,
edited_callback=None,
editing_started_callback=None,
editing_canceled_callback=None,
spacing=0,
visible=True,
resizable=True,
sizing=1,
fixed_width=-1,
min_width=-1,... | 5,287,277 |
def query_summary(fname):
"""Query and opsim database for visits
Args:
- fname :: the name of the sqlite3 database file
Returns:
a named tuple with the summary and proposal tables
"""
table_contents = []
with contextlib.closing(sqlite3.connect(fname)) as conn:
for table_n... | 5,287,278 |
def readuncombinedspinerfile(rfilepath):
"""
read spine data from uncombined data
input: file path to real or ficticious spine.r file
output: SpineData from uncombined data
"""
# construct the directory and call the other routine:
if not os.path.isabs(rfilepath):
raise... | 5,287,279 |
def prepare_pcoa(pcoa, number_of_features):
"""Selects top N biplot features by magnitude (coped from q2-emperor).
Parameters
----------
pcoa : skbio.stats.ordination.OrdinationResults
number_of_features : int
Returns
-------
skbio.stats.ordination.OrdinationResults
"""
feats =... | 5,287,280 |
def enable_debugger(args):
"""
Enables pudb if args.pudb, or pdb if args.pdb
:param:
- `args`: an argument namespace
"""
if args.pudb:
try:
import pudb
pudb.set_trace()
return
except ImportError:
print "Unable to import pudb"
... | 5,287,281 |
def _jupyter_bundlerextension_paths():
"""
Entrypoint for Jupyter Notebook Bundler
Shows up in the 'Download' menu on Jupyter Classic Notebook
"""
return [{
'name': 'chrome_pdf_export',
'label': 'PDF via Chrome (.pdf)',
'module_name': 'nbpdfexport.bundler',
'group': ... | 5,287,282 |
def DecodeVigenereLongueurCle(message, mot=3):
"""
Cette fonction determine la longueur de la clé, elle
repère les groupes de trois lettres qui se répète dans le message codé
et suppose qu'il y a une très forte probabilité qu'un même groupe de trois
lettres soit codé avec les mêmes trois lettres du ... | 5,287,283 |
def fetch_and_store_feed(url: str, tags: List[TagModel], user: UserModel) -> None:
"""Fetches a feed from the given URL, parses it, adds a source if necessary, updates one if it already exists.
:param url: The URL of the feed.
:param tags: Tags to add to the source.
:param user: User adding/updating th... | 5,287,284 |
def median(data_list):
"""
Finds the median in a list of numbers.
:type data_list list
"""
data_list = list(map(float, data_list))
length = len(data_list)
data_list.sort()
# Test whether the length is odd
if length & 1:
# If is is, get the index simply by dividing it in half... | 5,287,285 |
def write_if_changed(output_file_path: str, new_contents: str) -> None:
"""Write new_contents to output_file_path if new_contents != the contents
of output_file_path.
This prevents downstream recompiles when codegen runs but does not change
a given file.
"""
old_contents = read_file_contents(output_file_pa... | 5,287,286 |
def on_package_attributes(**attr_dict):
"""Decorator: executes instance function only if object has attr valuses.
Executes the decorated method only if at the moment of calling the
instance has attributes that are equal to certain values.
Args:
attr_dict (dict): dictionary mapping attribute na... | 5,287,287 |
def preprocess_n100(n100_raw, n100_processed, processed_info):
"""
Create well structured csv files from n100 data. Output has
date as index and n100 concentration as the other column.
"""
make_directory(n100_processed)
initial_info = 'Measurementsites_info.txt'
preprocess_n100_info(n1... | 5,287,288 |
def test_boolean_parameter_value():
"""Test getting argument value for a boolean parameter."""
para = Bool('0000', 0, 'name')
# Values that convert to True.
assert para.cast(True)
assert para.cast(1)
assert para.cast('1')
assert para.cast('T')
assert para.cast('true')
# Values that c... | 5,287,289 |
def filelineno():
"""
Return the line number in the current file. Before the first line
has been read, returns 0. After the last line of the last file has
been read, returns the line number of that line within the file.
"""
if not _state:
raise RuntimeError("no active input()")
retur... | 5,287,290 |
def create_dual_point_kernel(size, distance_apart, padding=0):
"""Generates a square float image with two, single-pixel point sources.
The top source has double the intensity of the bottom source. The sources
are distributed along the vertical center and are spaced a set distance apart.
:param size... | 5,287,291 |
def auc(actual, posterior):
"""
auc
"""
r = tied_rank(posterior)
num_positive = len([0 for x in actual if x == 1])
num_negative = len(actual)-num_positive
sum_positive = sum([r[i] for i in range(len(r)) if actual[i] == 1])
auc = ((sum_positive - num_positive * (num_positive + 1) / 2.0) /... | 5,287,292 |
def is_django_unittest(item):
"""Returns True if the item is a Django test case, otherwise False"""
try:
from django.test import SimpleTestCase as TestCase
except ImportError:
from django.test import TestCase
if sys.version_info < (3, 0):
return (hasattr(item.obj, 'im_class') an... | 5,287,293 |
async def test_invalid_sensor_data_2():
"""Test with invalid sensor data."""
with open("tests/data/stations.json") as file:
stations = json.load(file)
with open("tests/data/station.json") as file:
station = json.load(file)
session = aiohttp.ClientSession()
with aioresponses() as se... | 5,287,294 |
def parametrized(f):
"""Is this function or object decorated with @parametrize or @matrix?"""
return Mark.marked(f, PARAMETRIZED) or Mark.marked(f, MATRIX) or Mark.marked(f, DEFAULTS) | 5,287,295 |
def analyze_body(sdf, address=("127.0.0.1", 11346)):
"""
Single body analyzer. Opens a new connection, analyzes the
body, and returns the result. If you already have a manager
running doing other things, create an instance of `BodyAnalyzer`
instead.
:param sdf: SDF object consisting of BodyPart... | 5,287,296 |
def remove(args):
"""Implements vc rm <file> command"""
if len(args) == 1:
filename = input("File to remove: ")
elif len(args) == 2:
filename = args[1]
else:
print('- command syntax is "vc rm <file-to-remove>"')
return
if not os.path.isfile(filename):
print('-... | 5,287,297 |
def cmd_trade_info(strategy: Strategy, strategy_trader: StrategyTrader, data: dict) -> dict:
"""
Get trade info according data on given strategy_trader.
@note If trade-id is -1 assume the last trade.
"""
results = {
'messages': [],
'error': False
}
trade_id = -1
... | 5,287,298 |
def drift_confidence(df_resample, out_path, fps, pca=1, save_fig=0):
"""
Args:
df_resample:
out_path:
fps:
pca:
save_fig:
Returns:
"""
if pca:
flow_key = 'diffflow_pca'
acc_key = 'acc_pca'
else:
flow_key = 'diff_flowx'
ac... | 5,287,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.