content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def generate_bit_byte_overview(inputstring, number_of_indent_spaces=4, show_reverse_bitnumbering=False):
"""Generate a nice overview of a CAN frame.
Args:
inputstring (str): String that should be printed. Should be 64 characters long.
number_of_indent_spaces (int): Size of indentation
... | 32,000 |
def setup_env(deployment_name: str):
"""Ensures the environment is set up appropriately for interacting
with Local Grapl (running inside a Docker Compose network locally)
from *outside* that network (i.e., from your workstation).
"""
# NOTE: These values are copied from local-grapl.env. It's
# ... | 32,001 |
def return_list_of_file_paths(folder_path):
"""Returns a list of file paths
Args:
folder_path: The folder path were the files are in
Returns:
file_info: List of full file paths
"""
file_info = []
list_of_file_names = [fileName for fileName in listdir(folder_path) if... | 32,002 |
def artificial_signal( frequencys, sampling_frequency=16000, duration=0.025 ):
"""
Concatonates a sequence of sinusoids of frequency f in frequencies
"""
sins = map( lambda f : sinusoid(f, sampling_frequency, duration), frequencys)
return numpy.concatenate( tuple(sins) ) | 32,003 |
def _sources():
"""Return the subdir name and extension of each of the contact prediction types.
:return: Contact prediction types and location.
:rtype: dict [list [str]]
"""
sources = _sourcenames()
confiledir = ["deepmetapsicov", "deepmetapsicov", "deepmetapsicov"]
confilesuffix = ["psic... | 32,004 |
def pdns_forward(hostname):
"""Get the IP addresses to which the given host has resolved."""
response = get(BASE_API_URL + "pdns/forward/{}".format(hostname))
return response | 32,005 |
def make_conv(in_channels, out_channels, conv_type="normal", kernel_size=3, mask_activation=None, version=2, mask_init_bias=0, depth_multiplier=1, **kwargs):
"""Create a convolution layer. Options: deformable, separable, or normal convolution
"""
assert conv_type in ("deformable", "separable", "normal")
... | 32,006 |
def url_to_html_func(kind="requests") -> Callable:
"""Get a url_to_html function of a given kind."""
url_to_html = None
if kind == "requests":
import requests
def url_to_html(url):
r = requests.get(url)
if r.status_code != 200:
print(
... | 32,007 |
def get_payload_command(job):
"""
Return the full command for executing the payload, including the sourcing of all setup files and setting of
environment variables.
:param job: job object.
:raises PilotException: TrfDownloadFailure.
:return: command (string).
"""
show_memory_usage()
... | 32,008 |
def assert_equal(
actual: statsmodels.tsa.statespace._kalman_filter.dKalmanFilter,
desired: statsmodels.tsa.statespace._kalman_filter.dKalmanFilter,
):
"""
usage.statsmodels: 2
"""
... | 32,009 |
def parseExonBounds(start, end, n, sizes, offsets):
"""
Parse the last 2 columns of a BED12 file and return a list of tuples with
(exon start, exon end) entries.
If the line is malformed, issue a warning and return (start, end)
"""
offsets = offsets.strip(",").split(",")
sizes = sizes.strip... | 32,010 |
def head(filename, format=None, **kwargs):
"""
Returns the header of a file. Reads the information about the content of the file
without actually loading the data. Returns either an Header class or an Archive
accordingly if the file contains a single object or it is an archive, respectively.
Parame... | 32,011 |
def write_gpt(beam,outfile,verbose=0,params=None,asci2gdf_bin=None):
""" Writes particles to file in GPT format """
watch = StopWatch()
# Format particles
gpt_units={"x":"m", "y":"m", "z":"m","px":"GB","py":"GB","pz":"GB","t":"s"}
qspecies = get_species_charge(beam.species... | 32,012 |
def uncomment_magic(
source, language="python", global_escape_flag=True, explicitly_code=True
):
"""Unescape Jupyter magics"""
parser = StringParser(language)
next_is_magic = False
for pos, line in enumerate(source):
if not parser.is_quoted() and (
next_is_magic
or is... | 32,013 |
def infer_dtype_from_object(dtype: Literal["float64"]):
"""
usage.koalas: 3
"""
... | 32,014 |
def clean_nice_ionice_parameters(value):
"""Verify that the passed parameters are not exploits"""
if value:
parser = ErrorCatchingArgumentParser()
# Nice parameters
parser.add_argument("-n", "--adjustment", type=int)
# Ionice parameters, not supporting -p
parser.add_arg... | 32,015 |
def get_interest_data(src, targ, tuples: dict, case: str):
"""extract the interested part of the whole .npy data
Args:
src ([str]): [source location of the main .npy files]
targ ([str]): [target location of the interested .npy files]
tuples (dict): [dict holding the interest range tupls... | 32,016 |
def rand_alnum(length=0):
"""
Create a random string with random length
:return: A random string of with length > 10 and length < 30.
"""
jibber = ''.join([letters, digits])
return ''.join(choice(jibber) for _ in xrange(length or randint(10, 30))) | 32,017 |
def _GenerateGstorageLink(c, p, b):
"""Generate Google storage link given channel, platform, and build."""
return 'gs://chromeos-releases/%s-channel/%s/%s/' % (c, p, b) | 32,018 |
def parse_decl(inputtype, flags):
"""
Parse type declaration
@param inputtype: file name or C declarations (depending on the flags)
@param flags: combination of PT_... constants or 0
@return: None on failure or (name, type, fields) tuple
"""
if len(inputtype) != 0 and inputtype[-1] != ';':... | 32,019 |
def post_attention(h, attn_vec, d_model, n_head, d_head, dropout, is_training,
kernel_initializer, residual=True):
"""Post-attention processing."""
monitor_dict = {}
# post-attention projection (back to `d_model`)
proj_o = tf.get_variable("o/kernel", [d_model, n_head, d_head],
... | 32,020 |
def get_recursively(in_dict, search_pattern):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in in_dict.items():
if key == search_pattern:
fields_found.append(value)
elif ... | 32,021 |
def _send_pubsub_message(project_id, reporting_topic, pubsub_payload):
"""Sends a pubsub message.
Args:
project_id: ID of the Google Cloud Project where the solution is deployed.
reporting_topic: Pub/Sub topic to use in the message to be sent.
pubsub_payload: Payload of the Pub/Sub message to be sent.
... | 32,022 |
def neals_funnel(ndims = 10,
name = 'neals_funnel'):
"""Creates a funnel-shaped distribution.
This distribution was first described in [1]. The distribution is constructed
by transforming a N-D gaussian with scale [3, 1, ...] by scaling all but the
first dimensions by `exp(x0 / 2)` where `x0`... | 32,023 |
def _has_desired_permit(permits, acategory, astatus):
"""
return True if permits has one whose
category_code and status_code match with the given ones
"""
if permits is None:
return False
for permit in permits:
if permit.category_code == acategory and\
permit.status_co... | 32,024 |
def colon(mac):
""" aa:aa:aa:aa:aa:aa """
return _reformat(mac, separator=':', digit_grouping=2) | 32,025 |
def greet(info: Info, string: str, repeat: int, out: TextIO):
"""
Print 'Hello <string>!' <repeat> times.
"""
if info.verbose:
click.echo("'greet' is running in verbose mode.")
click.echo('Home directory is {}'.format(info.home_directory))
for _ in range(0, repeat):
click.echo('H... | 32,026 |
def create_strings_from_wikipedia(minimum_length, count, lang):
"""
Create all string by randomly picking Wikipedia articles and taking sentences from them.
"""
sentences = []
while len(sentences) < count:
# We fetch a random page
page_url = "https://{}.wikipedia.org/wiki/Speci... | 32,027 |
def test_get_post_stac_search__pagination__page_1__limit_2():
"""[GET|POST] /stac/search"""
service = STAC(url)
params = {
"bbox": [ -68.0273437, -25.0059726, -34.9365234, 0.3515602 ],
"datetime": "2019-12-22T00:00:00/2020-01-22T23:59:00",
"page": 1,
"limit": 2
}
e... | 32,028 |
def computeHashCheck(ringInputString, ringSize):
"""Calculate the knot hash check.
Args:
ringInputString (str): The list of ints to be hashed as a comma-separated list.
ringSize (int): The size of the ring to be \"knotted\".
Returns:
int: Value of the hash check.
"""
ringI... | 32,029 |
def emPerformance(filesAndDirectories=None, resultsFileName=None, iterationCount=3, modes=None, testTypes=None, viewports=None, verbose=False):
"""
Same as emPerformanceTest but the options separated into different
arguments. Legacy support.
filesAndDirectories : List of locations in which to f... | 32,030 |
def delete_tag(xmltree: Union[etree._Element, etree._ElementTree],
schema_dict: 'fleur_schema.SchemaDict',
tag_name: str,
complex_xpath: 'etree._xpath' = None,
occurrences: Union[int, Iterable[int]] = None,
**kwargs: Any) -> Union[etree._Element... | 32,031 |
def cart2pol_vectorised(x, y):
"""
A vectorised version of the cartesian to polar conversion.
:param x:
:param y:
:return:
"""
r = np.sqrt(np.add(np.power(x, 2), np.power(y, 2)))
th = np.arctan2(y, x)
return r, th | 32,032 |
def encryption(text):
"""
encryption function for saving ideas
:param text:
:return:
"""
return AES.new(cipher_key, AES.MODE_CBC, cipher_IV456).encrypt(text * 16) | 32,033 |
def add_common_arguments(parser):
"""Add parser arguments common to train and test."""
parser.add_argument(
"--config",
is_config_file=True,
dest="config",
required=False,
help="config in yaml format",
)
parser.add_argument(
"--pretrain_url",
help=... | 32,034 |
def alteryx_job_path_is_file(job_dict: dict) -> bool:
"""
Alteryx job path must point to an existing file.
"""
if not os.path.isfile(job_dict["path"]):
raise InvalidFilePathError("Alteryx path file not exists")
return True | 32,035 |
def _concat(to_stack):
""" function to stack (or concatentate) depending on dimensions """
if np.asarray(to_stack[0]).ndim >= 2:
return np.concatenate(to_stack)
else:
return np.hstack(to_stack) | 32,036 |
def make_orthonormal_matrix(n):
"""
Makes a square matrix which is orthonormal by concatenating
random Householder transformations
Note: May not distribute uniformly in the O(n) manifold.
Note: Naively using ortho_group, special_ortho_group in scipy will result in unbearable computing time! Not us... | 32,037 |
def device_to_target(device: Device):
"""Map a Netbox VirtualMachine to a Prometheus target"""
target = Target(device.name)
target.add_label("type", TargetType.DEVICE.value)
target.add_label("status", device.status)
extract_tenant(device, target)
if hasattr(device, "primary_ip") and device.prim... | 32,038 |
def build_synthetic_dataset_cae(window_size:int, **kwargs:Dict)->Tuple[SingleGapWindowsSequence, SingleGapWindowsSequence]:
"""Return SingleGapWindowsSequence for training and testing.
Parameters
--------------------------
window_size: int,
Windows size to use for rendering the synthetic datase... | 32,039 |
def montecarlo_2048(game, simulations_per_move, steps, count_zeros=False, print_averages=True, return_scores=False):
"""
Test each possible move, run montecarlo simulations and return a dictionary of average scores,
one score for each possible move
"""
# Retrieve game score at the current state
... | 32,040 |
def getAggregation(name, local=False, minOnly=False, maxOnly=False):
"""
Get aggregation.
"""
toReturn = STATISTICS[name].getStatistic()
if local:
return STATISTICS[name].getLocalValue()
elif minOnly and "min" in toReturn:
return toReturn["min"]
elif maxOnly and "max" in toRe... | 32,041 |
def get_gene_symbol(row):
"""Extracts gene name from annotation
Args:
row (pandas.Series): annotation info (str) at 'annotation' index
Returns:
gene_symbol (str): gene name(s)
"""
pd.options.mode.chained_assignment = None
lst = row["annotation"].split(",")
genes = [token.sp... | 32,042 |
def session_login():
"""
Session login
:return:
"""
print("Session Login")
# Get the ID token sent by the client
# id_token = request.headers.get('csfToken')
id_token = request.values.get('idToken')
# Set session expiration to 5 days.
expires_in = datetime.timedelta(days=5)
t... | 32,043 |
def get_cache_factory(cache_type):
"""
Helper to only return a single instance of a cache
As of django 1.7, may not be needed.
"""
from django.core.cache import get_cache
if cache_type is None:
cache_type = 'default'
if not cache_type in cache_factory:
cache_factory... | 32,044 |
def ruleset_from_pickle(file):
""" Read a pickled ruleset from disk
This can be either pickled Rules or Ryu Rules.
file: The readable binary file-like object, or the name of the input file
return: A ruleset, a list of Rules
"""
if six.PY3:
ruleset = pickle.load(file, encodi... | 32,045 |
def gpu_memory_usage():
""" return gpu memory usage for current process in MB """
try:
s = nvidia_smi(robust=False)
except Exception:
return 0
gpu_processes = _nvidia_smi_parse_processes(s)
my_pid = os.getpid()
my_memory_usage_mb = 0
for gpu_idx, pid, type, process_name, ... | 32,046 |
def get_templates_for_angular(path, all_html_files, appname, underscore_js_compile, comment):
"""
Creates templates.js files for AngularJs
"""
f = []
pat = r"<!--template=\"([a-zA-Z0-9\\-]+)\"-->"
f.append("//")
f.append("//Knight generated templates file.")
if comment is not... | 32,047 |
def print_words(text, disable_tokenizers=None, delimiter=" ",
additional_tokenizers=None):
"""
Method to compare the segmented words.
Print the results of the compared word segmentation.
Parameters
----------
texts : str
An input text
disable_tokenizers : list
... | 32,048 |
def delayed_read_band_data(fpar_dataset_name, qc_dataset_name):
"""Read band data from a HDF4 file.
Assumes the first dimensions have a size 1.
FparLai_QC.
Bit no. 5-7 3-4 2 1 0
Acceptable values:
000 00 0 0 0
001 01 0 0 0
Unacceptable mask:
110 10 1 1... | 32,049 |
def _aggregate_pop_simplified_comix(
pop: pd.Series, target: pd.DataFrame
) -> pd.DataFrame:
"""
Aggregates the population matrix based on the CoMix table.
:param pop: 1-year based population
:param target: target dataframe we will want to multiply or divide with
:return: Retuns a dataframe tha... | 32,050 |
def questions_test():
"""
method to execute tests on questions route
"""
get_questions(client) | 32,051 |
def authenticate():
"""
Uses HTTP basic authentication to generate an authentication token.
Any resource that requires authentication can use either basic auth or this token.
"""
token = serialize_token(basic_auth.current_user())
response = {'token': token.decode('ascii')}
return jsonify(response) | 32,052 |
def split_image(image, N):
"""
image: (B, C, W, H)
"""
batches = []
for i in list(torch.split(image, N, dim=2)):
batches.extend(list(torch.split(i, N, dim=3)))
return batches | 32,053 |
def _upsample_add(x, y):
"""Upsample and add two feature maps.
Args:
x: (Variable) top feature map to be upsampled.
y: (Variable) lateral feature map.
Returns:
(Variable) added feature map.
Note in PyTorch, when input size is odd, the upsampled feature map
with `F.upsample(..., sca... | 32,054 |
def get_eta_and_mu(alpha):
"""Get the value of eta and mu. See (4.46) of the PhD thesis of J.-M. Battini.
Parameters
----------
alpha: float
the angle of the rotation.
Returns
-------
The first coefficient eta: float.
The second coefficient mu: float.
"""
if alpha == 0... | 32,055 |
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to fi... | 32,056 |
def install_hooks(context):
"""Installs pre-commit hooks"""
print('Installing pre-commit hook')
context.run('pre-commit install') | 32,057 |
def play(session, bpm=125, shuffle=0.0, forever=False):
"""
:type session: sails.session.Session
:type forever: bool
"""
playback = BasicPlayback()
clock = BasicClock(bpm=bpm, shuffle=shuffle)
pos = (-1, 0)
last_ctl_pos = max(session._ctl_timelines)
with session[last_ctl_pos]:
... | 32,058 |
def donot_servicegroup_modify_labonly(cc, args):
"""LAB ONLY Update a servicegroup. """
# JKUNG comment this out prior to delivery
patch = utils.args_array_to_patch("replace", args.attributes[0])
try:
iservicegroup = cc.smapiClient.iservicegroup.update(args.iservicegroup, patch)
except exc.H... | 32,059 |
def predict_model(predictor: str, params: Params, archive_dir: str,
input_file: str, output_file: str, batch_size: int = 1):
"""
Predict output annotations from the given model and input file and produce an output file.
:param predictor: the type of predictor to use, e.g., "udify_predictor... | 32,060 |
def write_error_row(rowNum, errInfo):
"""Google Sheets API Code.
Writes all team news link data from RSS feed to the NFL Team Articles speadsheet.
https://docs.google.com/spreadsheets/d/1XiOZWw3S__3l20Fo0LzpMmnro9NYDulJtMko09KsZJQ/edit#gid=0
"""
credentials = get_credentials()
http = credential... | 32,061 |
def ghr():
"""
>>> import os
>>> os.environ.update(dict(OS="ubuntu-latest"))
>>> ghr() # doctest: +ELLIPSIS
::set-output name=GHR_BINARY_PATH::...ghr_v0.13.0_linux_amd64...ghr
>>> os.environ["OS"] = "macos-latest"
>>> ghr() # doctest: +ELLIPSIS
::set-output name=GHR_BINARY_PATH::...ghr... | 32,062 |
def generate_submit(tab):
""" tab->list : prediction
create the file and write the prediction
have to be in the good order
"""
with open("answer.txt", 'w') as f:
for i in tab:
f.write(str(i) + '\n') | 32,063 |
def get_last_transaction():
""" return last transaction form blockchain """
try:
transaction = w3.eth.get_transaction_by_block(w3.eth.blockNumber, 0)
tx_dict = dict(transaction)
tx_json = json.dumps(tx_dict, cls=HexJsonEncoder)
return tx_json
except Exception as err:
... | 32,064 |
def test_vectorizers_n_jobs(Estimator):
"""Check that parallel feature ingestion works"""
text = ["Εν οίδα ότι ουδέν οίδα"]
vect = Estimator(n_jobs=2)
vect.fit(text)
vect.transform(text)
with pytest.raises(ValueError, match="n_jobs=0 must be a integer >= 1"):
Estimator(n_jobs=0).fit(te... | 32,065 |
def get_tp_model() -> TargetPlatformModel:
"""
A method that generates a default target platform model, with base 8-bit quantization configuration and 8, 4, 2
bits configuration list for mixed-precision quantization.
NOTE: in order to generate a target platform model with different configurations but wi... | 32,066 |
def IsARepoRoot(directory):
"""Returns True if directory is the root of a repo checkout."""
return os.path.exists(
os.path.join(os.path.realpath(os.path.expanduser(directory)), '.repo')) | 32,067 |
def check_sparv_version() -> Optional[bool]:
"""Check if the Sparv data dir is outdated.
Returns:
True if up to date, False if outdated, None if version file is missing.
"""
data_dir = paths.get_data_path()
version_file = (data_dir / VERSION_FILE)
if version_file.is_file():
retu... | 32,068 |
def grav_n(expt_name, num_samples, num_particles, T_max, dt, srate, noise_std, seed):
"""2-body gravitational problem"""
##### ENERGY #####
def potential_energy(state):
'''U=sum_i,j>i G m_i m_j / r_ij'''
tot_energy = np.zeros((1, 1, state.shape[2]))
for i in range(state.shape[0]):
... | 32,069 |
def fit_spline_linear_extrapolation(cumul_observations, smoothing_fun=simple_mirroring, smoothed_dat=[],
plotf=False, smoothep=True, smooth=0.5, ns=3, H=7):
"""
Linear extrapolation by splines on log daily cases
Input:
cumul_observations: cumulative observati... | 32,070 |
def container():
"""The container subcommand.
The `container` command interacts with containerised virtual environment,
such as Docker and Singularity containers. This provides an uniform
interface for creating either Docker or Singularity containers from the
same directories, as long as the corres... | 32,071 |
def test_incompatible_expected_units():
"""Test error is raised if value and expected_units are not equivalent."""
pytest.raises(
ValueError,
unp.UnitParameter,
name="unp1",
value=3 * units.m,
tols=(1e-9, 1 * units.m),
expected_units=units.Jy,
) | 32,072 |
def import_chrome(profile, bookmark_types, output_format):
"""Import bookmarks and search keywords from Chrome-type profiles.
On Chrome, keywords and search engines are the same thing and handled in
their own database table; bookmarks cannot have associated keywords. This
is why the dictionary lookups ... | 32,073 |
def test_time():
"""Test instantiating a time object."""
time = Time(step=1e-3, duration=1e-1)
assert time.step == 1e-3
assert time.duration == 1e-1
assert time.nsteps == 100
assert time.nsteps_detected == 100
assert len(time.values) == time.nsteps | 32,074 |
def auto_discover():
"""自动发现内置的拼音风格实现"""
for path in glob.glob(current_dir + os.path.sep + '*.py'):
filename = os.path.basename(path)
module_name = filename.split('.')[0]
if (not module_name) or module_name.startswith('_'):
continue
full_module_name = 'pypinyin.style... | 32,075 |
def compute_dl_target(location):
"""
When the location is empty, set the location path to
/usr/sys/inst.images
return:
return code : 0 - OK
1 - if error
dl_target value or msg in case of error
"""
if not location or not location.strip():
loc = "... | 32,076 |
def hz_to_angstrom(frequency):
"""Convert a frequency in Hz to a wavelength in Angstroms.
Parameters
----------
frequency: float
The frequency in Hz.
Returns
-------
The wavelength in Angstroms.
"""
return C / frequency / ANGSTROM | 32,077 |
def main():
""" main. """
app.run(proc_argv) | 32,078 |
def sync(
query: List[str],
downloader: Downloader,
m3u_file: Optional[None] = None,
) -> None:
"""
Removes the songs that are no longer present in the list and downloads the new ones.
### Arguments
- query: list of strings to search for.
- downloader: Already initialized downloader ins... | 32,079 |
def is_literal(token):
"""
リテラル判定(文字列・数値)
"""
return token.ttype in T.Literal | 32,080 |
def test_non_batching_collated_task_dataset_getitem_bad_index(
non_batching_collated_task_dataset, index):
"""Test NonBatchingCollatedTaskDataset.__getitem__ dies when index != 0."""
with pytest.raises(IndexError, match='.*must be 0.*'):
non_batching_collated_task_dataset[index] | 32,081 |
def PutObject(*, session, bucket, key, content, type_="application/octet-stream"):
"""Saves data to S3 under specified filename and bucketname
:param session: The session to use for AWS connection
:type session: boto3.session.Session
:param bucket: Name of bucket
:type bucket: str
:param key: Name of file
... | 32,082 |
def insert_sequences_into_tree(aln, moltype, params={},
write_log=True):
"""Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
params: dict of parameters ... | 32,083 |
def billing_invoice_download(client,
account_name=None,
invoice_name=None,
download_token=None,
download_urls=None):
"""
Get URL to download invoice
:param account_name: The ID that uniquely ... | 32,084 |
def find_classes(text):
"""
find line that contains a top-level open brace
then look for class { in that line
"""
nest_level = 0
brace_re = re.compile("[\{\}]")
classname_re = "[\w\<\>\:]+"
class_re = re.compile(
"(?:class|struct)\s*(\w+)\s*(?:\:\s*public\s*"
+ classname... | 32,085 |
def kineticEnergyCOM(robot : object, symbolic = False):
"""This function calculates the total kinetic energy, with respect to each center of mass, given linear and angular velocities
Args:
robot (object): serial robot (this won't work with other type of robots)
symbolic (bool, optional): used t... | 32,086 |
def get_input(request) -> str:
"""Get the input song from the request form."""
return request.form.get('input') | 32,087 |
def _unit_circle_positions(item_counts: dict[Hashable, tuple[int, int]], radius=0.45, center_x=0.5,
center_y=0.5) -> dict[Hashable, tuple[float, float]]:
"""
computes equally spaced points on a circle based on the radius and center positions
:param item_counts: item dict LinkedNe... | 32,088 |
def times(*args):
"""Select time steps"""
try: state.time_selection.parse_times(" ".join(args))
except timestep_selection.Error, err: raise BlotishError(err)
print " Select specified whole times"
print " Number of selected times = %d" % len(state.time_selection.selected_indices)
print | 32,089 |
def rate_table_download(request, table_id):
"""
Download a calcification rate table as CSV.
"""
def render_permission_error(request, message):
return render(request, 'permission_denied.html', dict(error=message))
table_permission_error_message = \
f"You don't have permission to down... | 32,090 |
def gui():
"""
Launch the igel gui application.
PS: you need to have nodejs on your machine
"""
igel_ui_path = Path(os.getcwd()) / "igel-ui"
if not Path.exists(igel_ui_path):
subprocess.check_call(
["git"] + ["clone", "https://github.com/nidhaloff/igel-ui.git"]
)
... | 32,091 |
def normalize_path(path):
""" Normalize a pathname by collapsing redundant separators and up-level references """
from os.path import normpath, sep
result = normpath(path)
result = result.replace("/",sep)
result = result.replace("\\",sep)
return adapt_path(result) | 32,092 |
def rgb_to_RGB255(rgb: RGBTuple) -> RGB255Tuple:
"""
Convert from Color.rgb's 0-1 range to ANSI RGB (0-255) range.
>>> rgb_to_RGB255((1, 0.5, 0))
(255, 128, 0)
"""
return tuple([int(round(map_interval(0, 1, 0, 255, c))) for c in rgb]) | 32,093 |
def test_torch_rnn_classifier(X_sequence):
"""Just makes sure that this code will run; it doesn't check that
it is creating good models.
"""
train, test, vocab = X_sequence
mod = torch_rnn_classifier.TorchRNNClassifier(
vocab=vocab, max_iter=100)
X, y = zip(*train)
X_test, _ = zip(*t... | 32,094 |
def setup_logging(log_level):
""" Used to test functions locally """
if len(logging.getLogger().handlers)>0:
logging.getLogger().setLevel(log_level)
else:
logging.basicConfig(filename='script.log',
format="%(name)s - %(module)s - %(message)s",
level=log_level)
... | 32,095 |
def check_blinka_python_version():
"""
Check the Python 3 version for Blinka (which may be a later version than we're running this script with)
"""
print("Making sure the required version of Python is installed")
if get_python3_version() < blinka_minimum_python_version:
shell.bail("Blinka re... | 32,096 |
def check_rest_version(host="http://www.compbio.dundee.ac.uk/jpred4/cgi-bin/rest", suffix="version", silent=False):
"""Check version of JPred REST interface.
:param str host: JPred host address.
:param str suffix: Host address suffix.
:param silent: Should the work be done silently?
:type silent: :... | 32,097 |
def test_car_move():
"""Sprawdzanie czy pojazd porusza się prawidłowo w dwóch kierunkach"""
car = Car(60, 60, BLACK)
car.move((80, 80))
assert car.xpos == 80
assert car.ypos == 80
assert car.xv == 20
assert car.yv == 20
car.move((60, 60))
assert car.xpos == 60
assert car.ypos == ... | 32,098 |
def quads(minlon, minlat, maxlon, maxlat):
""" Generate a list of southwest (lon, lat) for 1-degree quads of SRTM1 data.
"""
lon = floor(minlon)
while lon <= maxlon:
lat = floor(minlat)
while lat <= maxlat:
yield lon, lat
lat += 1
... | 32,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.