content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_testing_eeg_data():
"""Create testing data with HFO and a spike."""
freqs = [2.5, 6.0, 10.0, 16.0, 32.5, 67.5, 165.0,
250.0, 425.0, 500.0, 800.0, 1500.0]
random_state = 0
fs = 5000
n = fs * 10
data = np.zeros(n)
hfo_samps = []
# basic_amp = 10
x = np.arange(n... | 69,200 |
def configure_monitor_host():
"""Configure extra monitor host for better network failure detection"""
log('Checking monitor host configuration', level=DEBUG)
monitor_host = config('monitor_host')
if monitor_host:
if not pcmk.crm_opt_exists('ping'):
log('Implementing monitor host conf... | 69,201 |
def getNodeDictVlans(nodesInfo, hostname, switchName):
"""Get Node dictionary."""
if not nodesInfo:
return None, {}
for _, nodeDict in list(nodesInfo['nodes'].items()):
if nodeDict['hostname'] == hostname:
for intf, intfDict in list(nodeDict['NetInfo'].items()):
p... | 69,202 |
def intersect(*windows):
"""Test if windows intersect.
Parameters
----------
windows: list-like of window objects
((row_start, row_stop), (col_start, col_stop))
Returns
-------
boolean:
True if all windows intersect.
"""
from rasterio._io import windows_intersect
... | 69,203 |
def check_state(seed):
"""Turn seed into a np.random.RandomState instance
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
... | 69,204 |
def gen_edo(x, DBplot=False):
"""Generate EDO Γ[x(n)] from simple formula in the time domain:
Γ[x(n)] = y(n)² + H[y(n)]²
where y(n) is the derivative of x(n) using the central-finite method and H[.] is the
Hilbert transform.
Parameters
----------
x: ndarray
input signal
DBplot... | 69,205 |
def test_add_ns(kg_test):
"""
Coverage:
* KnowledgeGraph.get_ns_dict()
* KnowledgeGraph.get_ns
"""
assert len(kg_test.get_ns_dict()) == 30
iri2 = "http://schema.org/"
prefix2 = "test2"
kg_test.add_ns(
prefix = prefix2,
iri = iri2
)
assert len(kg_test.get_ns_dict()... | 69,206 |
def polyPyramid(*args, **kwargs):
"""
The pyramid command creates a new polygonal pyramid.
Returns: `string[]` Object name and node name.
"""
pass | 69,207 |
def fetch_mps_government_roles_raw():
"""Fetch government roles for all MPs."""
return members.fetch_government_roles_raw(
house=constants.PDP_ID_HOUSE_OF_COMMONS) | 69,208 |
async def test_commands_purecool(
hass: HomeAssistant,
device: DysonPureCool,
service: str,
service_data: dict,
command: str,
command_args: list,
) -> None:
"""Test sending commands to a PureCool fan."""
await hass.services.async_call(
PLATFORM_DOMAIN,
service,
{
... | 69,209 |
def test_categorical(monkeypatch, space):
"""Test computing for categorical"""
mock_train_regressor(monkeypatch)
partial_dependencies = partial_dependency(data, space, params=["z"], n_samples=10)
assert set(partial_dependencies.keys()) == {"z"}
assert partial_dependencies["z"][0]["z"] == ["a", "b"... | 69,210 |
def delayed_plus1(x):
"""Sleeps for 100ms then returns x+1."""
time.sleep(0.1)
return x + 1 | 69,211 |
def view_link(url, args, appended='', text='View'):
""" Helper function for generating view links """
return '<a href="' + reverse(url, args=args) + appended + '">' + text + '</a>' | 69,212 |
def rob(nums):
"""
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent... | 69,213 |
def dashboard():
"""Displays the dashboard template.
Returns:
str: HTML Template
"""
data = {}
try:
data = {
'experiments': Experiment.get_status(current_app.config.get('container')),
'migrations': get_migration_status(),
}
except InvalidRequestE... | 69,214 |
def tamiz1(m):
"""Algoritmo clásico para el tamiz de Eratóstenes"""
l, n = [i for i in range(2, m+1)], 2
while n:
for i in l[l.index(n)+1:]:
if i % n == 0:
l.remove(i)
if l.index(n) +1 < len(l):
n = l[l.index(n) + 1]
else:
return l | 69,215 |
def delete(workspace_config_file, yes, workspace_name):
"""Delete a workspace and the associated cloud resources."""
# TODO: Implement deleting of workspace based on cloud provider.
delete_workspace(workspace_config_file, yes, workspace_name) | 69,216 |
def _sincfunc(x, dx, dampfac=3.25):
"""sinc helper function for sincshift()"""
if dx != 0.0:
xx = (x+dx)*np.pi #- cache shifted array for 30% faster evals
return np.exp( -(xx/(dampfac*np.pi))**2 ) * np.sin(xx) / xx
else:
xx = np.zeros(len(x))
xx[len(x)//2] = 1.0
retu... | 69,217 |
def scanDatasets():
"""
Retrieves the name of each dataset present in the framework
:return: list with name of each dataset as element
:rtype: List
"""
datasets = os.listdir(str(os.path.join(path, "preprocessed_datasets")))
datasets.remove("README.rst")
return datasets | 69,218 |
def data_preprocess(data):
""" Perform data procession
"""
field_list = []
### On `param_1`(76% is null), `param_2`(86% is null), `param_3` (89% is null)
# This three params are text-type, and most of them are empty.
# Concat `description`+`title`+`param_1`+'param_2'+`param_3`+`city`
... | 69,219 |
def test_person__PersonEditForm__18(
address_book, FullPersonFactory, browser, login):
"""It cannot be accessed by some roles."""
FullPersonFactory(address_book, u'Test')
browser.login(login)
browser.assert_forbidden(browser.PERSON_EDIT_URL) | 69,220 |
def get_random_string(length=5):
""" Generates a random string of fixed lenght """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length)) | 69,221 |
def FragGraph(G, bondOrderThreshold=1.2):
"""
Fragment all bonds with Wiberg Bond Order less than threshold
Parameters
----------
G: NetworkX graph
bondOrderThreshold: int
thershold for fragmenting graph. Default 1.2
Returns
-------
subgraphs: list of subgraphs
"""
... | 69,222 |
def compute_conv_idx(
counts_gene: np.ndarray, knn: int, p_zeros: float,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Given a GENE x CELL matrix, and an index to select from, calculates the convolution of reads for that gene index.
The function returns the
"""
y_probs = np.bincount(counts_gene) / len... | 69,223 |
def worker_process(local_rank: int, world_size: int, device: torch.device,
train_class: object, crop_size: int,
args: Namespace) -> None:
"""
Initiate training in a new process.
In each new process launched by the main function, setup the environment to
communicate... | 69,224 |
def update_df(result: dict, target_key: str,
key: str, col_name: str='Ref_Wave', deg_col='Test_Wave',
file_name_key: str='reference_file', test_file_name_key='degraded_file', **kwargs):
"""Update the dataframe being used based on the col_name and re... | 69,225 |
def plot_referendum_map(referendum_result_by_regions):
"""Plot a map with the results from the referendum.
* Load the geographic data with geopandas from `regions.geojson`.
* Merge these info into `referendum_result_by_regions`.
* Use the method `GeoDataFrame.plot` to display the result map. The result... | 69,226 |
def keep(attrs, tweets):
"""Strip each tweet so as to keep only the given attributes.
Attributes are given as a list of the form:
['text', 'user.screen_name', 'user.name']
where the dot notation represent embedded dicts:
tweet = {
'text': "This is a tweet."
'user':... | 69,227 |
def get_payload() -> bytes:
"""This function returns the data to send over the socket to the server.
This includes everything - the 4 bytes for size, the nop slide, the
shellcode, the return address (and the zero at the end).
WARNINGS:
0. Don't delete this function or change it's name/parameters -... | 69,228 |
def get_density_plots(estimators_list, simulators_dict, path_to_results, exp_prefix="question1_noise_reg_x", task_ids=None):
"""
This function allows to compare plots from estimators and simulators (i.e. fitted and true densities). Two modes are currently available:
1) by specifying estimators and simulator, the ... | 69,229 |
def control_thread(rate):
"""
Actual control loop. Uses goal pose from the feedback thread
and current robot states from the subscribed messages to compute
task-space force, and then the corresponding joint torques.
"""
while not rospy.is_shutdown():
error = 100.
whil... | 69,230 |
def _get_last_playthrough_information(last_playthrough_model):
"""Returns an ExpUserLastPlaythrough domain object given an
ExpUserLastPlaythroughModel loaded from the datastore.
Args:
last_playthrough_model: ExpUserLastPlaythroughModel. The last
last playthrough information loaded from ... | 69,231 |
def process_html(html):
"""Processes HTML for embedded code using SyntaxHighlighter
Determines languages used by checking class attribute of pre tags
with name="code".
Args:
html: HTML to be processed for embedded code
Returns:
The modified html and a list of strings giving the em... | 69,232 |
def print_about():
"""
Print information about the program and return to caller
"""
print()
print("Acerca del juego")
print("El juego consiste en eliminar los cuadros adyacentes del mismo color de un tablero.")
print("Los cuadros están colocados de manera aleatoria.")
print("Cuando se el... | 69,233 |
def get_movie_info(cap: cv2.VideoCapture) -> Tuple[int, int, int, float]:
"""get movie information
Args:
cap (cv2.VideoCapture): cv2 video object
Returns:
Tuple[int, int, int, float]: W, H, total frame, fps of movie
"""
W = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
H = int(cap.get(cv2.C... | 69,234 |
def delete_file(filename):
"""delete file and catch any exceptions while doing it"""
try:
if os.path.exists(filename):
os.remove(filename)
logging.debug("Deleting " + filename)
return {'success': True}
except Exception as e:
logging.error("Cannot delete fi... | 69,235 |
def _buildAsnPrimary(fasn,output,img1,frame=None,refimage=None):
""" Creates complete Primary header for ASN table based on template.
'fasn' is the file handle of the newly opened ASN table file.
Uses keyword values from 'img1' to update ASN header keywords.
"""
origin_str = 'Astropy Version '+astro... | 69,236 |
def getMetrics(sector, symbols):
"""Returns a 2xN numpy.Array of metrics for the given symbols from the
given sector.
"""
metrics = [ # hard-coded for now, could easily be parameterized
"Price Performance (52 Weeks)",
"Standard Deviation (1 Yr Annualized)"
]
table = numpy.zero... | 69,237 |
def test_check(spec, expected_result):
"""
GIVEN spec and the expected result
WHEN check is called with the spec
THEN the expected result is returned.
"""
returned_result = validation.unmanaged.check(spec=spec)
assert returned_result == expected_result | 69,238 |
def delete_dp_reports():
"""Deletes all datapane reports."""
try:
import datapane as dp
reports = dp.Report.list()
for item in reports:
print(item["name"])
report = dp.Report.get(item["name"])
url = report.blocks[0]["url"]
print(f"Deleting... | 69,239 |
def expand_if_large_archive(input_bucket, input_key, download_path, byte_size):
"""Expand the file if it is an archival type and larger than ClamAV Max Size"""
if byte_size > MAX_BYTES:
file_name = f"{download_path}/{input_key}"
try:
command = ["7za", "x", "-y", f"{file_name}", f"-o{... | 69,240 |
def get_prediction_datas(date=None):
"""
retourne les donnees predictes
"""
if not date:
# on prend partant de la date actuelle
#date = datetime.datetime.now()
pass
date = config.TEST_DATE
# datas
datas_df = model_request.get_prediction_datas(date)
# data... | 69,241 |
def testConnection(base_url=server_address):
"""
:param base_url: String; server address with port number.
:return: Boolean; True if connection is done, false otherwise.
"""
try:
get(base_url, timeout=5)
return True
except ConnectionError or Timeout:
return False | 69,242 |
def getUser(username: str):
"""Get user login and url."""
return getGithubApiRequestJson("users/" + username) | 69,243 |
def initStandard(cls, init=None):
"""
Standard initialization for population distributions,
inserted by :class:`PopulationDistributionMeta`. Will
call the provided initialization method as well.
:param cls: The class being initialized
:type cls: A class of type :cl... | 69,244 |
def get_best_downloader(downloader=None):
"""Choose among a set of 4 popular downloaders, in the following order:
- wget
- curl
- powershell
- insecure (Python)
Args:
downloader (str, optional): Use a given downloader. One of wget|curl|powershell|insecure.
Defaults to None.
... | 69,245 |
def np_parse_pcap_worker(filename):
"""Parse a pcap file into a numpy matrix.
Inputs:
- filename : a pcap file that contains packets to parse
Returns:
- a numpy matrix where each row is a packet and each column is a
different field
- a numpy column array containing the correspondi... | 69,246 |
def get_btis(gtis, start_time=None, stop_time=None):
"""
From GTIs, obtain bad time intervals, i.e. the intervals *not* covered
by the GTIs.
GTIs have to be well-behaved, in the sense that they have to pass
``check_gtis``.
Parameters
----------
gtis : iterable
A list of GTIs
... | 69,247 |
def greedy_find_clique(graph, progress=False, nodes=None, ordering_func=None,
node_deletion=True):
"""Finds the graph's clique (largest complete subgraph)
"""
graph_order = graph.order()
if graph_order == 0:
return []
if nodes is None:
nodes = list(gr... | 69,248 |
def patch_truck(client, truck_id, **kwargs):
"""
attempts to change the specified row in truck
:param client: the client to make the request with
:param truck_id: the id of the truck to change
:param kwargs: the data that needs to be changed
:return:
"""
return client.patch(f'/ap... | 69,249 |
def print_games(games):
""" Print a tabular games list. """
row = '{:<50} {:<10} {}'
print(row.format('Name', 'App Id', 'Location'))
for game in games:
print(row.format(game['name'], game['appid'], game['installdir'])) | 69,250 |
def _dump_kline_hdf5(symbol_key, date_key, dump_df, delete_key=None):
"""
针对hdf5存储模式,根据symbol_key,date_key存储dump_df金融时间序列
:param symbol_key: str对象,eg. usTSLA,hdf5模式下为数据的索引key
:param date_key: str对象,eg. usTSLA_20100214_20170214,hdf5模式下为金融时间序列实体key
:param dump_df: 需要存储的金融时间序列实体pd.DataFrame对象
:para... | 69,251 |
def CheckTransaction(tx):
"""Basic transaction checks that don't depend on any context.
Raises CheckTransactionError
"""
if not tx.vin:
raise CheckTransactionError("CheckTransaction() : vin empty")
if not tx.vout:
raise CheckTransactionError("CheckTransaction() : vout empty")
... | 69,252 |
def to_klio_message(incoming_message, kconfig=None, logger=None):
"""Serialize ``bytes`` to a :ref:`KlioMessage <klio-message>`.
.. tip::
Set ``job_config.allow_non_klio_messages`` to ``True`` in
``klio-job.yaml`` in order to process non-``KlioMessages`` as
regular ``bytes``. This func... | 69,253 |
def get_lists(tab=None, cfg="tlut"):
"""
Returns:
loss_list, acc_list
"""
if cfg == 'tlut':
# loss = get_cell_vals(tab, 'B6:B20')
loss = [0.0296, 0.044, 0.0612, 0.0997, 0.1713, 0.2981, 1.6251, 1.9081, 2.0437, 1.8245, 2.1162, 2.2531, 2.2789, 2.3028, 2.3035]
# acc = get_ce... | 69,254 |
def import_models(config, checkpoints_logdir, device, verbose=1):
"""Import model from configuration file
"""
model_manager = models.ModelManager(checkpoints_logdir, config['task_ids'])
model, last_ckpt = model_manager.load_model(
model_name=config['models']['name'],
model_weight... | 69,255 |
def greater_than_equal_to_validator(start) -> Validator:
"""
Validate that a given value is greater or equal to a number.
Can be used with int, float or BaseImageContainer.
:param start: the value to be greater than or equal to
"""
if not isinstance(start, (float, int)):
raise TypeError(... | 69,256 |
def single_text_phrase(context, slug=None, language=None):
"""
for using this template tag you must
enable one of the text_phrase context_processors.
this templatetag will return the first text phrase object,
if there is more then one object.
if you want single text phrase in special language se... | 69,257 |
def verify_remote_clone_id(remote_clone_job_id):
"""
:param remote_clone_job_id: Remote Clone Job ID
:raises: ValueError: invalid ID
"""
list_err = ['{0} is not a valid Remote Clone ID.'.format(_id)
for _id in remote_clone_job_id.split(',') if
not is_valid_remote_clon... | 69,258 |
def slow_trajectory(robot, joints, path, min_fraction=0.1, ramp_duration=1.0, **kwargs):
"""
:param robot:
:param joints:
:param path:
:param min_fraction: percentage
:param ramp_duration: seconds
:param kwargs:
:return:
"""
time_from_starts = instantaneous_retime_path(robot, joi... | 69,259 |
def make_request(func: Callable) -> Callable:
"""
Allows clients to customize how they want to make a request to the
service undergoing fuzz testing.
"""
get_abstraction().request_method = func
return func | 69,260 |
def _login_pw(driver, userid, userpw):
""" Helper routine to log in by password with the supplied credentials. """
loginid = driver.find_element_by_id("loginid")
loginid.clear()
loginid.send_keys(userid)
loginpw = driver.find_element_by_id("loginpw")
loginpw.clear()
loginpw.send_keys(userpw... | 69,261 |
def _find_files(root_dir, should_include):
"""
Return a list of paths to all modules below the given directory.
Arguments:
should_include: a function that accepts a file path and returns True or False.
"""
paths = [] # Return value.
is_module = lambda path: path.endswith(".py")
#... | 69,262 |
def renderScene(
background_plane, assembly, component_poses,
camera_pose=None, camera_params=None, object_appearances=None):
""" Render a scene consisting of a spatial assembly and a background plane.
Parameters
----------
Returns
-------
"""
# Start by rendering the back... | 69,263 |
def split_train_test():
"""
Import the dataset via sklearn, shuffle and split train/test.
Return training, target lists for `n_clients` and a holdout test set
"""
print("Loading data")
diabetes = load_diabetes()
y_raw = diabetes.target
X_raw = diabetes.data
# print(type(y_ra... | 69,264 |
def effector(*args, **kwargs):
"""
The effector command is used to set the name or hidden flag for the effector.
Returns: `string` Command result
"""
pass | 69,265 |
def load_np_arr(save_path, file_name):
# type: str -> str -> ()
"""
Load array from <save_path/file_name.npy>.
"""
with open(os.path.join(save_path, file_name + '.npy'), 'r') as f:
return np.load(f) | 69,266 |
def markdown_loader(text, metadata):
"""A loader function for markdown."""
# TODO: Remove debug code here
# if metadata['basename'] == "DH_Materials":
# print(text)
# print(markdown.markdown(text))
return markdown.markdown(text) | 69,267 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Spider thermostat."""
if discovery_info is None:
return
devices = [SpiderPowerPlug(hass.data[SPIDER_DOMAIN]['controller'], device)
for device in hass.data[SPIDER_DOMAIN]['power_plugs']]
add_entiti... | 69,268 |
def plot_dist_mat_multi_row(D, figsize=(3,3), titles=None, ylabels=None, wspace=0, hspace=0, sharex=False, sharey=False, cmap='Greys'):
"""Plots distaince matrices in a multi column and multi row manner (square matrix)."""
nr = len(D)
nc = len(D[0])
titles = titles or [None] * nc
ylabels = ylabels... | 69,269 |
def read_several_fasta(input_files):
"""
Read several fasta files
Note that each fasta file may contain several sequences.
Parameters
----------
input_files: a list of fasta file paths.
Returns
-------
pb_name: a list of the headers
pb_seq: a list of the sequences
"""
... | 69,270 |
def load_objects_from_xl(file_name):
"""
Loads the excel file worksheets into dictionaries
Args:
object: excel file names
Returns:
object: dictionaries
"""
# global excel_info
SAT_dict = {}
TRSP_dict = {}
VSAT_dict = {}
EARTH_COORD_GW_dict = {}
GW_dict = {}
... | 69,271 |
def list_file_data():
"""
Function: list_file_data\n
Parameters: None\n
Return: list of data in output file\n
"""
epsilon = 0.0
learning_rate = 0.0
decay_factor = 0.0
with open('input_files/scenario_input.json', 'r') as file_pointer:
file_data = json.load(file_pointer)
... | 69,272 |
def _pip_cmd(env):
"""Retrieve pip command for installing python packages, allowing configuration.
"""
anaconda_pip = os.path.join(env.system_install, "anaconda", "bin", "pip")
if env.safe_exists(anaconda_pip):
to_check = [anaconda_pip]
else:
to_check = ["pip"]
if "pip_cmd" in en... | 69,273 |
def collect_sim_params(aperiodic_params, periodic_params, nlv):
"""Collect simulation parameters into a SimParams object.
Parameters
----------
aperiodic_params : list of float
Parameters of the aperiodic component of the power spectrum.
periodic_params : list of float or list of list of fl... | 69,274 |
def _test_result_aggregation_for_classification(files: List[RunResultFiles],
plotting_config: PlotCrossValidationConfig,
expected_aggregate_metrics: List[str],
expected_epochs:... | 69,275 |
def dut_addr(dut, execute_helper):
"""Fixture to return the DUT address."""
return get_dut_address(dut, execute_helper) | 69,276 |
def insert_linked_list(linked_list, pair):
"""Metoda insert_linked_list vlozi na konec (za prvek last) seznamu
novy uzel s hodnotou pair.
"""
node = Node()
node.pair = pair
node.prev = linked_list.last
if linked_list.first is None:
linked_list.first = node
else:
linked_li... | 69,277 |
def WriteSimpleTestResults(results_path, test_completed):
"""Writes simplified test results file.
Used when test status is not available.
"""
simple_isolated_script_output = {
'valid': test_completed,
'failures': [],
'version': 'simplified',
}
with open(results_path, 'w') as output_file:... | 69,278 |
def encodeDPID (vendor,role, location, id):
"""
Generates a DPID that is encoded as follow:
DPID format: byte7 byte6 byte5 byte4 byte3 byte2 byte1 byte0
vendor type reserved <--- ASCII Name ------> id
:param location: 4 letters max. location (i.e. STAR, LBNL).
:param vendor:... | 69,279 |
def smooth_segmentation(data_img, seg_img, fwhm, noise_img=None,
inplace=False):
"""Filter each compartment of a segmentation with an isotropic gaussian.
Parameters
----------
data_img : nibabel image
3D or 4D image data.
seg_img : nibabel image
3D label imag... | 69,280 |
def remove_node(**kwargs):
"""
删除节点任务
"""
code, res = SaltClient.operate_cetus_node(kwargs.get('id'), 'abort')
if not code:
TbCetusNodeInfo.objects.filter(pk=kwargs.get('id')).delete()
PeriodicTask.objects.filter(name='node_%s_monitor' % kwargs.get('id')).delete()
return '删除... | 69,281 |
def setup_training(layer_info,prob, trinit=1e-3,refinements=(.5,.1,.01),final_refine=None ):
""" Given a list of layer info (name,xhat_,newvars),
create an output list of training operations (name,xhat_,loss_,nmse_,trainop_ ).
Each layer_info element will be split into one or more output training operations... | 69,282 |
def permute_Ediag_inplace(
ABCDE,
Nst=None,
Nco=None,
location="upper left",
nonzero_test=nonzero_test,
rank_nonzeroE=rank_nonzeroE,
):
"""
Permutes the E matrix to be on the location='upper left' or 'upper right'
and as diagonal as possible.
return ABCDE, and then Ndiag, Ndiag ... | 69,283 |
def update_messages_incoming(
messages_outgoing: jnp.ndarray,
nodes_factor_masks: jnp.ndarray,
nodes_indices: jnp.ndarray,
nodes_factor_indices: jnp.ndarray,
perturbation_configurations: jnp.ndarray,
):
"""update_messages_incoming.
Args:
messages_outgoing: Array of shape (n_nodes, n... | 69,284 |
def convert(req: SongMetadataForDownload, background_tasks: BackgroundTasks, request: Request):
"""Start download and conversion of song with given metadata in the background"""
uid = uuid.uuid4()
jobs[uid] = DownloadJob(request_id=uid, status=Status.WAITING, percentage_done=0.0, last_update=time.time())
... | 69,285 |
def linear_scale(input, in_low, in_high, out_low, out_high):
""" (number, number, number, number, number) -> float
Linear scaling. Scales old_value in the range (in_high - in-low) to a value
in the range (out_high - out_low). Returns the result.
>>> linear_scale(0.5, 0.0, 1.0, 0, 127)
63.5
""... | 69,286 |
def meme_rand():
""" Generate a random meme """
img = random.choice(imgs)
quote = random.choice(quotes)
path = meme.make_meme(img, quote.body, quote.author)
return render_template('meme.html', path=path) | 69,287 |
def main():
"""Command line tool for pytest-django-queries.""" | 69,288 |
def magma_snrm2(n, dx, incx):
"""
Euclidean norm (2-norm) of vector.
"""
return _libmagma.magma_snrm2(n, int(dx), incx) | 69,289 |
def lowerCase(length: int = 1) -> str:
"""
returns random lowercase letter strings
:parameters:
length: defines the length of the character sequence
if length is not given, the function returns only a single character
"""
return "".join(choice(lowercase) for i in range(length)) | 69,290 |
def the_one_with_an_overriding_span_event(this_span: wtt.Span) -> None:
"""Use an overriding-span to event this function."""
logging.info("the_one_with_an_overriding_span_event()") | 69,291 |
def process_commits(
commits: List[CommitInfo],
check_merge_commits: bool,
) -> Dict[str, List[str]]:
"""
Process commit information to detect DCO infractions.
:param commits: the list of commit info
:param check_merge_commits: true to check merge commits, false otherwise
:return: the infra... | 69,292 |
def single_time_vis(channel: dict,
bt=0,
tt=0,
chart_type: Optional[str] = None,
enable_playback: bool = True,
height: int = 50,
params=None,
title: str = '',
s... | 69,293 |
def once():
"""
TODO: Documentation
"""
def wrapped(func: Callable):
if hasattr(func, '_type') and not hasattr(func, '_thread'):
# only declare once on existing hooked functions that aren't threads
func._once = True
return func
return wrapped | 69,294 |
def cart_contents(request):
"""
Ensures that the cart contents are available when rendering
every page
"""
cart = request.session.get('cart', {})
cart_items = []
total = 0
destination_count = 0
for id, quantity in cart.items():
destination = get_object_or_404(Destinations, p... | 69,295 |
def set_underlineback():
"""This function underline the back and set italic"""
text_description_aboutgame = pygame.font.Font("freesansbold.ttf", 23)
text_description_aboutgame.set_underline(True)
text_description_aboutgame.set_italic(True)
go_back1 = text_description_aboutgame.render("<BACK", T... | 69,296 |
def main():
"""
Main.
:return:
"""
args = get_args()
# Validate connection string
if not re.match(ZK_CONNECTION_STRING_RE, args.connection):
print "Zookeeper connection string is not valid"
sys.exit(2)
hosts = []
for host in args.connection.split(','):
if '... | 69,297 |
def _set_location_splits(split2samples: DefaultDict[str, List[Sample]],
db: NuPlanDB,
core_splits_names: List[str]) -> None:
"""
Populates split2samples with splits by region and country done on top of core splits.
For example:
"train" -> "train", "... | 69,298 |
def main():
"""Funçao index"""
print('Init do main_route')
#window_id = str(get_window_id())
#print('1')
#set_base_context(window_id)
#print('2')
#ctx_dict = get_context(window_id)
ctx_dict = {'titulo':'Portal de Compras Públicas'}
from cp_documento import Documento
resQueryDocLe... | 69,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.