content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def delete_domain(name: str):
"""
Deletes the configuration file of the corresponding domain.
:param name: The domain name that corresponds to the name of the file.
:type name: str
:return: Returns a status about the success or failure of the action.
"""
config_path = flask.current_app.con... | 59,000 |
def QueryEncode(q: dict):
"""
:param q:
:return:
"""
return "?" + "&".join(["=".join(entry) for entry in q.items()]) | 59,001 |
def checkChordValidity(coordDict, chord, axes, Tonnetz):
"""If coordinates weren't found for all notes throw ERROR."""
if(any(note not in coordDict for note in chord)):
print(chord, coordDict.items(), axes, Tonnetz)
raise BaseException("Lost chord") | 59,002 |
def generate_report(ofile, freq):
""" generate analysis report
Args:
ofile: output report
freq: TSC frequency of the device trace data from
Return:
None
"""
global TSC_BEGIN, TSC_END, TOTAL_NR_EXITS
csv_name = ofile + '.csv'
try:
with open(csv_name, 'a') as f... | 59,003 |
def call_task():
"""
初始化一个 connection 执行
"""
async_run_shell.apply_async(args=(), eta=datetime(), task_id='') | 59,004 |
def _Args(parser, support_global_access, support_l7_internal_load_balancing,
support_gfe3, support_l7_rxlb, support_psc_google_apis,
support_all_protocol, support_target_service_attachment,
support_l3_default, support_source_ip_range):
"""Add the flags to create a forwarding rule."""
... | 59,005 |
def _fast_suggest(term):
"""Return [] of suggestions derived from term.
This list is generated by removing punctuation and some stopwords.
"""
suggest = [term]
def valid(subterm):
"""Ensure subterm is valid."""
# poor man stopwords collection
stopwords = ['and', 'the', 'in'... | 59,006 |
def draw_result_screen(display, font, mean_rew, color, tw, th):
"""Draw result screen."""
white = (255, 255, 255)
black = (0, 0, 0)
score_str1 = 'Mean Reward {:.2f}'.format(mean_rew)
score_text1 = font.render(score_str1, True, color, black)
if mean_rew > -1:
judgement_str = 'Better tha... | 59,007 |
def generate_ranks_comparison(
all_data: pd.DataFrame,
):
"""Generate a ranks comparison between all methods.
Creates a violin plot that showcases the ranks that
the different methods achieve over all the tasks/datasets.
Parameters
----------
all_data: pd.DataFrame
A dataframe wher... | 59,008 |
def convert_dataset(queries, passages, qrels, tokenizer, fold, split):
""" Convert <query, passage> pairs to TFRecord. """
main_path = os.path.join(FLAGS.output_path, "fold-" + str(fold))
if not tf.gfile.Exists(main_path):
tf.gfile.MakeDirs(main_path)
out_query_passage = os.path.join(main_path, ... | 59,009 |
def urlparse(urlstring, scheme='', allow_fragments=True, *args, **kwargs):
"""A wrapper for :py:func:`urlparse.urlparse` with the following
differences:
* Handles buckets in S3 URIs correctly. (:py:func:`~urlparse.urlparse`
does this correctly sometime after 2.6.1; this is just a patch for older
... | 59,010 |
def configure_parser(parser):
""" Configure parser for this action """
qipkg.parsers.pml_parser(parser)
parser.add_argument("--pkg", action="store_true", dest="pkg",
help="Generate and install .pkg files")
parser.add_argument("dest")
parser.set_defaults(pkg=False) | 59,011 |
def ind2ij(a,index):
"""
returns a[j,i] for a.ravel()[index]
"""
n,m = shape(lon)
j = ceil(index/m).astype(int)
i = remainder(index,m)
return i,j | 59,012 |
def add_status(name, nvr, commit):
"""
Rule repositories should call this method in their package __init__ to
register their version information.
"""
RULES_STATUS[name] = {"version": nvr, "commit": commit} | 59,013 |
def recording(matrix, v1, v2, v3, v4, v5, NC=None):
"""
recording matrix with row [fx, gx, oracle-calls, time, step-size, direction-type]
and iteration as columns
"""
v = torch.tensor([v1, v2, v3, v4, v5], device = matrix.device)
if NC is not None:
if NC == 'NC':
v = tor... | 59,014 |
def build_res_u_net(n_input=1, n_output=2, size=256, arch="resnet18", pretrained=True):
"""First pretraining step for generator -> Use a pretrained U-Net
Args:
n_input: Image input dimension
n_output: Image output dimension
size:
arch:
pretrained:
Returns:
(... | 59,015 |
def get_mig_identification(system: System) -> str:
"""
Returns string of GPU & subsequent MIG instance identification.
Also checks if MIG is enabled and the MIG configuration is homogeneous.
Return string omits how many MIG instances are populated.
Args:
system (System):
The sys... | 59,016 |
def get_unmasked_indices(nc):
"""Make boolean array for converting to lat/lon pairs.
Geographic data in gridded dataset often contains many datapoints over
oceans that are not of current interest. Therefore it can be useful
instead of dealing with a 2D grid of lat/lon values to instead use a 1D
lis... | 59,017 |
def _test_rotary():
"""
Testing RoPE with a simple example
"""
x = torch.tensor([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]], dtype=torch.float)
x = x[:, None, None, :]
inspect(x)
rotary_pe = RotaryPositionalEmbeddings(3)
inspect(rotary_pe(x)) | 59,018 |
def logs(app_name, timestamps, follow, tail, previous, label, verbose):
"""Get container logs"""
set_verbosity(verbose)
hokusai.logs(KUBE_CONTEXT, timestamps, follow, tail, previous, label, namespace=clean_string(app_name)) | 59,019 |
def client(app: Flask) -> Iterator[FlaskClient]:
"""
Create a client for testing.
:return: The created test client.
"""
with app.test_request_context():
yield app.test_client() | 59,020 |
def normalize(text):
"""
Lemmatize tokens and remove them if they are stop words
"""
text = nlp(text.lower())
lemmatized = list()
for word in text:
lemma = word.lemma_.strip()
if (lemma and lemma not in SW ):
lemmatized.append(lemma)
return lemmatized | 59,021 |
def instance_digital_object(ref: str) -> dict:
"""
```
{
'instance_type': 'digital_object',
'digital_object': {'ref': ref}
}
```
"""
return {
'instance_type': 'digital_object',
'digital_object': _ref(ref)
} | 59,022 |
def download_gradle_files(
repo_name: str, github: GradleFileSearcher, outdir: str) -> bool:
"""Download gradle files from repository.
All files will end up in subdirectories of the following template:
<outdir>/<repo_name>/<path_in_repo>/build.gradle
:param str repo_name:
Identifier of... | 59,023 |
def test(carousel: element.Tag):
"""Test."""
carousel_inner = carousel.find_all("div", ["scbs-carousel-inner"])[0]
carousel_items = carousel_inner.find_all("div", ["scbs-carousel-item"])
item = carousel_items.pop(0)
assert item["class"] == ["scbs-carousel-item", "scbs-active"]
img = item.find_n... | 59,024 |
def clean_build(c): # type: ignore
"""Remove build artifacts."""
c.run("rm -rf build dist .eggs")
c.run("find . -name '*.egg-info' -exec rm -rf {} +")
c.run("find . -name '*.egg' -exec rm -f {} +") | 59,025 |
def _transform_track(track):
"""Transform result into a format that
more closely matches our unified API.
"""
large_artwork = None
medium_artwork = None
small_artwork = None
if track['artwork_url']:
large_artwork = (track['artwork_url']).replace('large', 't500x500')
medium_a... | 59,026 |
def fwhm(t_r, hrf): # pragma: no cover
"""Return the full width at half maximum of the HRF.
Parameters
----------
t : array, shape (n_times_atom, ), the time
hrf : array, shape (n_times_atom, ), HRF
Return
------
s : float, the full width at half maximum of the HRF
"""
peaks_i... | 59,027 |
def subtoken_cnn_encoder(*, namespace, inputs, padding_size,
subtoken_vocab_size, token_lengths,
num_filters=30, kernel_size=3,
subtoken_embedding_size=256,
padding='same', activation='tanh', strides=1):
""" Helper m... | 59,028 |
def test_message_handler():
"""
Test for MessageHandler.on_message and the different methods it dispatches into.
Each of them results in a call to a RaidenService method, which is checked with a Mock.
"""
our_address = factories.make_address()
sender_privkey, sender = factories.make_privkey_add... | 59,029 |
def brute_permutation(A, B):
"""
Re-orders the input atom list and xyz coordinates using the brute force
method of permuting all rows of the input coordinates
Parameters
----------
A : array
(N,D) matrix, where N is points and D is dimension
B : array
(N,D) matrix, where N i... | 59,030 |
async def vector_bsgn_2(x):
"""Compute bsgn_2(a) for all elements a of x in parallel."""
stype = type(x[0])
n = len(x)
await mpc.returnType(stype, n)
Zp = stype.field
p = Zp.modulus
legendre_p = lambda a: gmpy2.legendre(a.value, p)
s = mpc.random_bits(Zp, 6*n, signed=True) # 6... | 59,031 |
def barlamdel_to_kappal(q, barlaml, ell):
"""
$\kappa^{A,B}_\ell(\bar{\lambda}_\ell)$
Assume $q=M_A/M_B>=1$
"""
XA = q/(1.+q);
XB = 1. - XA;
blamfact = factorial2(2*ell-1) * barlaml;
p = 2*ell + 1;
kappaAl = blamfact * XA**p / q;
kappaBl = blamfact * XB**p * q;
return kapp... | 59,032 |
def start(vfs, vfs_blanket):
"""Start the VFs.
:param dict vfs: list of VFs as dict (e.g. {'eth0': '8', 'eth1': '4'}
:returns: None
"""
configure_vfs(vfs, vfs_blanket) | 59,033 |
def index():
"""index"""
return "Hello HBNB!" | 59,034 |
def remove_duplicates(objects, equiv=None, tol=1e-12):
"""Remove duplicate objects from
a list of objects.
Parameters
----------
objects : list of objects
A list of objects,
with possible duplicates.
equiv : function, optional
A function for checking equality
of... | 59,035 |
def upload_blueprint(archive, blueprint_id, blueprint_file):
"""execute cfy blueprints upload create
:param archive: the URL or path to a blueprint
:param blueprint_id: the blueprint ID
:param blueprint_file: the filename of the blueprint YAML
:type archive: string
:type blueprint_id: string
... | 59,036 |
def yolo_head(feats, anchors, num_classes):
"""Convert final layer features to bounding box parameters"""
num_anchors = len(anchors)
# reshape to batch, height, width, num_anchors, box_params
anchors_tensor = K.reshape(K.variable(anchors), [1, 1, 1, num_anchors, 2])
# dynamic implementation of conv ... | 59,037 |
def _extract_neighbors (command):
"""return a list of neighbor definition : the neighbor definition is a list of string which are in the neighbor indexing string"""
# This function returns a list and a string
# The first list contains parsed neighbor to match against our defined peers
# The string is the command to... | 59,038 |
def variables_get(args):
"""Displays variable by a given name"""
try:
if args.default is None:
var = Variable.get(args.key, deserialize_json=args.json)
print(var)
else:
var = Variable.get(args.key, deserialize_json=args.json, default_var=args.default)
... | 59,039 |
def intrinsic_to_opengl_projection(intrinsic_mat, left, right, top, bottom,
near, far):
"""
Converts intrinsic matrix to OpenGL format.
:param intrinsic_mat: Intrinsic matrix in row-major order.
:return: OpenGL perspective mat (including NDC matrix) in column-major
... | 59,040 |
def makeNullRow(df, null=np.nan):
"""
Creates a row of null values to the dataframe.
:param object null: value in row
:return dict: row
"""
row = {}
for column in df.columns.tolist():
row[column] = null
return row | 59,041 |
def build_custom_fortran(sources, includes={}, wraponly={}, name=None, srcdir="./",
outdir="./", tmpdir="./tmp/", compiler="gnu", mode="release", exflags="",
opt="O2", clean=True, verbose=True):
"""
This function is intended to allow arbitrary f2py extensions to... | 59,042 |
def character_embedding_network(char_placeholder: tf.Tensor,
n_characters: int = None,
emb_mat: np.array = None,
char_embedding_dim: int = None,
filter_widths=(3, 4, 5, 7),
... | 59,043 |
def test_aperture_plotting():
"""Generate aperture plots and save to png.
"""
save_plot = True
plot_dir = os.path.join(JWST_TEMPORARY_DATA_ROOT)
if not os.path.isdir(plot_dir):
os.makedirs(plot_dir)
instrument = 'NIRISS'
siaf = Siaf(instrument)
# plot all apertures in SIAF
... | 59,044 |
def instrument_altitude_to_model_pressure(inst, model, inst_name, mod_name,
mod_datetime_name, mod_time_name,
mod_units, inst_alt, mod_alt,
mod_alt_units, scale=100.,
... | 59,045 |
def download_toolchains_for_skia(*args):
"""
Point Bazel to the correct rules for downloading the different toolchains.
Args:
*args: multiple toolchains, see top of file for
list of supported toolchains.
"""
for toolchain_name in args:
if toolchain_name not in name_t... | 59,046 |
def _cast_list_by_data_type(field_type, list_values):
"""
将list结构的python数据转换为java能识别的数据类型
:param field_type: 字段类型,小写字符
:param list_values: list数据
:return: java能识别的数据类型构成的数组
"""
if isinstance(list_values, list):
return [_cast_value_by_data_type(field_type, value) for value in list_val... | 59,047 |
def fixture_perform_migrations_at_unlock():
"""Perform data migrations as normal during user unlock"""
return False | 59,048 |
def print_site(filehandle, site, columns):
"""Print the output lines for one site (one per sample).
filehandle must be open."""
for sample in site:
if sample['print']:
fields = [str(sample.get(column)) for column in columns]
filehandle.write('\t'.join(fields)+"\n") | 59,049 |
def test_add_related_bill():
""" Make sure related bills work """
b = toy_bill()
b.add_related_bill(name="HB 2020", session="2011A", chamber="upper", relation="companion")
assert len(b.related_bills) == 1
assert b.related_bills[0] == {'name': 'HB 2020', 'session': '2011A', 'chamber': 'upper',
... | 59,050 |
def calcOpticalFlowSparseToDense(from_, to, flow=None, grid_step=None, k=None, sigma=None, use_post_proc=None, fgs_lambda=None, fgs_sigma=None):
""" calcOpticalFlowSparseToDense(from, to[, flow[, grid_step[, k[, sigma[, use_post_proc[, fgs_lambda[, fgs_sigma]]]]]]]) -> flow """
pass | 59,051 |
def svn_repos_fs_begin_txn_for_update(*args):
"""svn_repos_fs_begin_txn_for_update(svn_repos_t * repos, svn_revnum_t rev, char const * author, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_fs_begin_txn_for_update(*args) | 59,052 |
def test_module(module_name):
"""
Adds a local module located under "modules/" directory to the list of available modules on REDCap.
"""
with settings(user=env.deploy_user):
dest = '/'.join([env.live_project_full_path, "modules/%s" % module_name])
if not os.path.exists(dest):
... | 59,053 |
def generate_rays_th(pixel_coords, pix2cam,
cam2world):
"""Generate camera rays from pixel coordinates and poses.
Args:
pixel_coords: [width, height, 2] pixel-space coordinates.
pix2cam: [*batch, 3, 3] batched inverse intrinsic matrix.
cam2world: [*batch, 3+, 4] batched inverse int... | 59,054 |
def translate_push(x):
"""Converts list.push(v1, v2, ....) to __ee_extra_push(list, v1, v2, ...)
Args:
x (str): JavaScript code to translate.
Returns:
str: Translated JavaScript code.
Examples:
>>> from ee_extra import translate_push
>>> text = '["Banana", "Orange", "A... | 59,055 |
def _check_and_fix(span_token_tup, span_drange, pred_field, complementary_field2ents):
"""
check if span_token_tup is in complementary_field2ents and fix result
Returns:
bool: if span_token_tup is in complementary ents
span_token_tup: fixed result
span_drange: fixed drange
"""
... | 59,056 |
def perp( vector ):
"""
returns a vector perpendicular to the input. the vector will lie in the x=y plane.
"""
perpvector = np.array([1,1,-(vector[0] + vector[1])/vector[2]])
return perpvector/np.sqrt(np.sum(perpvector**2)) | 59,057 |
def worker_history(request):
"""
跳转到工作经验证明的页面
:param request:
:return:
"""
return report.worker_history(request) | 59,058 |
def generate_ucinet(G):
"""Generate lines in UCINET graph format.
Parameters
----------
G : graph
A EasyGraph graph
Examples
--------
Notes
-----
The default format 'fullmatrix' is used (for UCINET DL format).
References
----------
See UCINET User Guide or htt... | 59,059 |
def generate_post_id() -> int:
"""This function creats a new directoy inside posts with post id and
returns it.
:rtype: int
"""
max_post_id = 0
for i in get_post_ids():
if i > max_post_id:
max_post_id = i
post_id = max_post_id + 1
post_path = get_post_path(post_id)... | 59,060 |
def getFileAbsolutePath(rel_path):
"""
Retorna o caminho absoluto de um arquivo a partir de seu caminho relativo no projeto
:param rel_path:
:return: absolute_path
"""
data_folder = Path("PythoWebScraper/src")
file_to_open = data_folder / rel_path
return file_to_open | 59,061 |
def load_release_android_gcc_settings(conf):
"""
Setup all compiler and linker settings shared over all android gcc configurations
for the "release" configuration
"""
conf.load_android_gcc_common_settings() | 59,062 |
def plot(
df_in,
x=None,
y=None,
kind="line",
figsize=None,
use_index=True,
title="",
grid=None, # TODO:
legend="top_right",
logx=False,
logy=False,
xlabel=None,
ylabel=None,
xticks=None,
yticks=None,
xlim=None,
ylim=None,
fontsize=None, # TODO:
... | 59,063 |
def _make_section_data(section, unique_sequences):
"""
Return a (CourseSectionData, List[ContentDataError]) from a SectionBlock.
Can return None for CourseSectionData if it's not really a SectionBlock that
was passed in.
This method does a lot of the work to convert modulestore fields to an input
... | 59,064 |
def get_connection(id: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetConnectionResult:
"""
This data source can be used to fetch information about a specific Glue Connection.
## Example Usage... | 59,065 |
def prepend_token(x_BxLxE, embed_VxE, token_id):
"""Prepend token_id embedding to a batch of sequence tensors.
Args:
x_BxLxE: sequence tensor
embed_VxE: embedding matrix
token_id: token to prepend
Returns:
x_Bx(L+1)xD tensor
"""
first_1xE = tf.nn.embedding_lookup(embed_VxE, [token_id])
fir... | 59,066 |
def gsas_change_max_tof(bank_number, val, debug=False):
""" This function changes the max time-of-flight for a histogram in 2-theta.
"""
cmd = ["gsas_change_max_tof", bank_number, val]
_external_call(cmd, debug) | 59,067 |
def residual_block(inputs, num_blocks):
"""
Applies several residual connections.
Args:
inputs (tf.Tensor): 4D (N,H,W,C) input tensor
num_blocks (int): Number of residual blocks
Returns:
tf.Tensor: 4D (N,H,W,C) output Tensor
"""
_, _, _, filters = inputs.shape
x = i... | 59,068 |
def make_links(existings, versions):
"""
With the maping file-url<->existing-version create a mapping
file-url<-> Other-Url if exist, other url is replaced by index.html
if said page does not exits.
"""
links = defaultdict(lambda: {})
for k, ve in existings.items():
for v in versions... | 59,069 |
def add_missing_keys(obj: dict, path: list, mapping: set, missing_value=None):
"""Add missing keys to a dictionary-like obj"""
lp = len(path) + 1
for key in mapping:
key_parts = key.split(':')
if len(key_parts) == lp and key_parts[:-1] == path:
mk = key_parts[-1]
v... | 59,070 |
def _add_update_associate_key(
node, weight_key: Account, key: Account, weight: int, contract: str
):
""" Handles both add and update calls due to commonality """
session_args = ABI.args(
[ABI.account(bytes.fromhex(key.public_key_hex)), ABI.u32(weight)]
)
return node.deploy_and_propose(
... | 59,071 |
def get_unacked_triggers(config):
"""Retrieves the unacked triggers from Zabbix.
:param config: config for zapi
:type config: dict
:return: list of triggers
"""
zapi = init(config)
all_triggers = zapi.trigger.get(only_true=1,
skipDependent=1,
... | 59,072 |
def passwd_hash(p):
"""Hashing password and convert it to hex number
password in range from 6 to 40 char's"""
return sha256(p.encode('utf-8')).hexdigest() | 59,073 |
def _append(path: Path, text):
"""Append some text to a path."""
path.write_text(path.read_text() + text) | 59,074 |
def _remove_test_files(files):
""" """
""" Remove all files and directories listed.
:param files: Files and directories to remove.
:type files: list
"""
# Loop over files
for f in files:
# Check if file.
if os.path.isfile(f):
os.remove(f)
# Check if dir... | 59,075 |
def generate_text(query, genre):
"""
Функция отправляет POST-запрос к Балабобе,
и получает ответ в виде словаря.
Параметры POST-запроса:
query: ключевая фраза
genre: id жанра, в котором Балабоба должен сгенерировать текст
"""
text_url = 'https://zeapi.yandex.net/lab/api/yalm/text3'
d... | 59,076 |
def read_batch(filename, batch_size, random=False):
"""
Read single batch.
"""
context_features = {
"lcl": tf.FixedLenFeature([], dtype=tf.int64),
"rcl": tf.FixedLenFeature([], dtype=tf.int64),
"eml": tf.FixedLenFeature([], dtype=tf.int64),
"uid": tf.FixedLenFeature([], d... | 59,077 |
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text("""Halo, kalian bisa bantu bot ini biar lebih pinter
di github.com/solehudindt/doscom-birth-reminder
""") | 59,078 |
def test_register_load_start(arango_db):
"""
Tests registering the start of a load with the db.
"""
create_timetravel_collection(arango_db, 'v')
create_timetravel_collection(arango_db, 'e', edge=True)
arango_db.create_collection('reg')
att = ArangoBatchTimeTravellingDB(arango_db, 'reg', 'v'... | 59,079 |
def delete_flowentry(fields, ip=DEV_VM_URL):
"""
Deletes a flowentry by using OVS REST API, flowentry is matched based on
the information in `fields`
"""
url = "http://%s:%d/stats/flowentry/delete_strict" % (ip, OF_REST_PORT)
data = json.dumps(fields)
return _ovs_api_request('POST', url, da... | 59,080 |
def update_local_job_status(status):
""" updates local job status """
ljdf["JobStatus"] = status
return | 59,081 |
def modify_variables(bd_milestone_directory, bd_output_glob,
n_trajectories, n_threads=None, seed=None,
output_file=None, restart=False,
n_trajectories_per_output=None):
"""
Modify several variables within the *_simulation.xml file at
runtim... | 59,082 |
def generate_email_distribution(conn, workbook):
""" Create an Excel worksheet containing the 'Email Distribution' dataset
"""
table_data = []
table_headers = [
{"header": "Department"},
{"header": "# of Employee"}
]
try:
cursor = conn.cursor()
statement = (
... | 59,083 |
def all_snippets_from_file(sample_file: str) -> Dict[str, str]:
"""Reads in a sample file and parse out all contained snippets.
Args:
sample_file (str): Sample file to parse.
Returns:
Dictionary of snippet name to snippet code.
"""
if not os.path.exists(sample_file):
return... | 59,084 |
def directive_exists(name, line):
"""
Checks if directive exists in the line, but it is not
commented out.
:param str name: name of directive
:param str line: line of file
"""
return line.lstrip().startswith(name) | 59,085 |
def search_set(n):
"""Search for an element in a set.
"""
my_set = set(range(n))
start = timeit.default_timer()
n in my_set # pylint: disable=pointless-statement
return timeit.default_timer() - start | 59,086 |
def get_state(address):
"""Getting the server state directly from remote queue"""
c = Client(address=address)
try:
return c.request('get_state', {})
except Exception:
logger.warn('error getting state', exc_info=True) | 59,087 |
def setup(app):
# type: (Sphinx) -> dict
"""Initialize Sphinx extension.
Notes
-----
TODO better latex output
but not really interested in this as it would be duplication of effort,
and if much better todo ipynb -> tex, rather than ipynb -> rst -> tex
TODO handling of svg in latex
... | 59,088 |
def change_to_with_delay(_path: str):
"""
Mock wallpaper.change_to with sleep to simulate feh doing work.
"""
time.sleep(1) | 59,089 |
def assert_safe_type(val, *safe_types):
"""
Raise an exception if val is not one of the declared safe types.
Calling Example:
assert_safe_type(my_func, function) # my_func must be a function
assert_safe_type(my_val, int, float) # my_val must be int or float
:param val: some value
... | 59,090 |
def ping(version):
"""
Send a simple ping to my server
to see how many people are using this script
"""
try:
import uuid
import requests
import json
import os
import time
data = {
"uuid": uuid.getnode(),
"version": ... | 59,091 |
def sweepnumber_fromfile(fname):
"""Returns the sweep number of a polar file based on its name"""
return int(os.path.basename(fname).split('.')[1]) | 59,092 |
def format_time():
"""Return a time in YYYY-mm-dd HH:MM:SS formatting."""
return time.strftime("%Y-%m-%d %H:%M:%S") | 59,093 |
def get_devices():
"""Gets a list of devices currently attached.
Querys `adb` from `get_sdk_dir()` for all emulator/device instances.
Returns:
A tuple of lists. The first value is a list of device ids suitable for
use in selecting a device when calling adb. The second value is a list
... | 59,094 |
def apply2(
ff: Optional[Callable[[A_in, B_in], C_out]],
fa: Optional[A_in],
fb: Optional[B_in]
) -> Optional[C_out]:
"""
Given two values and a function in the :class:`Optional` context,
applies the function to the values.
>>> ff = lambda x, y: f'{x}{y}'
>>> apply2(ff, None... | 59,095 |
def assert_has_at_least_same_unchanged_content(source_dir, target_dir):
"""Returns True if all files in the source dir are present and unchanged in the target dir.
Returns false otherwise.
NB, files in the target dir that are not in the source dir, are ignored.
"""
for entry in os.listdir(source_di... | 59,096 |
def show_graph(graph: GraphDict, size: str = None, simplified: bool = False):
"""
Show graphical representation of a graph as required by
:py:func:`transform_coords`
Requires `python-graphviz` package.
:param graph: Transformation graph to show.
:param size: Size forwarded to graphviz, must be... | 59,097 |
def add(printer_name, uri, ppd, location, description):
"""
Add a new printer to the system with the given parameters.
"""
try:
if ppd[:4] == 'drv:':
type = '-m'
else:
type = '-P'
with open(os.devnull, "w") as fnull:
args = ["lpadmin", "-p", p... | 59,098 |
def test_parser_gipsyx_gdcov():
"""Test that parsing gipsyx_gdcov gives expected output"""
parser = get_parser("gipsyx_gdcov").as_dict()
assert len(parser) == 8
assert "time_past_j2000" in parser
assert 376018350.0 in parser["time_past_j2000"] | 59,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.