content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_variables_to_train(trainable_scopes, logger):
"""Returns a list of variables to train.
Returns:
A list of variables to train by the optimizer.
"""
if trainable_scopes is None or trainable_scopes == "":
return tf.trainable_variables()
else:
scopes = [scope.strip() for scop... | 70,200 |
def sample_lineage_counts(node, leaves,
popsizes, stimes, T, lineages, prob_counts):
"""
Sample lineage counts conditioned on counts at root and leaves
of species tree
"""
a, b = lineages[node]
if node not in leaves:
if len(node.children) == 2:
# tw... | 70,201 |
def password_change_done(request):
"""
View called when the new user password has been accepted
"""
messages.success(
request, _('Your password has been successfully changed.')
)
return redirect('common:current_user_details') | 70,202 |
def More(contents, out=None, prompt=None, check_pager=True):
"""Run a user specified pager or fall back to the internal pager.
Args:
contents: The entire contents of the text lines to page.
out: The output stream, log.out (effectively) if None.
prompt: The page break prompt.
check_pager: Checks the... | 70,203 |
def get_most_representative_notices(notice_ids: List[str], mongodb_client: MongoClient, top_k: int = None) -> List[str]:
"""
This function returns top_k the most representative notices, from the list of notices provided.
:param notice_ids:
:param mongodb_client:
:param top_k:
:return:
""... | 70,204 |
def remove_ldra_interface(
device, interface=None, vlan_id=None, policy=None, interface_id=None, **kwargs):
"""
Remove DHCP ldra remote-id
Args:
device ('obj'): device to use
interface ('str'): interface to configure
vlan_id ('str'): vlan_id to attach policy
... | 70,205 |
def borders(det):
"""
Calculates the borders for image
Parameters
--------------
det: int array
Detected face
Returns
----------------------
l: int list
Coordinates for left bound of border
r: int list
Coordinates for right bound of border
t: int... | 70,206 |
def DBToData(dbName, tableName, user='sysdba', password='masterkey', dupCol=-1, what='*', where='',
join='', pickleCol=-1, pickleClass=None, ensembleIds=None):
""" constructs an _MLData.MLDataSet_ from a database
**Arguments**
- dbName: the name of the database to be opened
- ... | 70,207 |
def get_line_row(lines, row):
"""
- lines: (Array string), array of lines
- row: int, >=0, the row index to grab
RETURN: string, if row greater than or equal to lines length, returns ''
"""
if row < len(lines):
return lines[row]
return '' | 70,208 |
def VerifyLimitsPotential(potential):
"""Verify if the potential seems to verify the borders conditions (to allow bound states). If it doesn't it ask to the user if he is sure that the potential respects these conditions
Parameters:
-----------
potential (str) : a string that indicates the mathemat... | 70,209 |
def _get_head_node_ip(stack_name):
"""
Get the IP Address of the head node.
:param stack_name: The name of the cloudformation stack
:param config: Config object
:return private/public ip address
"""
instances = describe_cluster_instances(stack_name, node_type=NodeType.head_node)
if not ... | 70,210 |
def build_datasets(config: DataConfig) -> Tuple[DataLoader, DataLoader]:
"""
Build training and validation data loaders for training.
Parameters
----------
config: DataConfig
Data configuration such as batch size and validation set.
Returns
-------
train_loader: DataLoader
... | 70,211 |
def fmt_begin_msg(app, fromuser, touser):
"""Format a PM begin message"""
msg = "/me began pestering {touser} {toInit} at {time}".format(touser=touser.display_name,
toInit=getInitials(app, touser,
... | 70,212 |
def filter_dict_null(d):
"""
Filters recursively null values from dictionary
"""
if isinstance(d, dict):
return dict(
(k, filter_dict_null(v))
for k, v in list(d.items())
if filter_dict_null(v) is not None
)
elif isinstance(d, list):
if len... | 70,213 |
def test_app_plans_limits_pricing_rules(
toolbox_update, modify_product, service, dest_client, dst_product, my_applications_plans, my_metrics):
"""Test app. pland, limits and pricing rules of the product"""
# pylint: disable=unused-argument
# pylint: disable=too-many-locals
# pylint: disable=too-... | 70,214 |
def client():
"""
osc-client is a really simple interactive UDP client to send OSC messages.
"""
print_title('osc-client')
client = pythonosc.udp_client.SimpleUDPClient(*_get_server_address())
print('Let\'s send messages !')
path = ''
value = []
while 1:
print('Enter th... | 70,215 |
def add_prefix(item: Any, prefix: str, divider: str = '') -> Any:
"""Adds 'prefix' to 'item' with 'divider' in between.
Args:
item (Any): item to be modified.
prefix (str): prefix to be added to 'item'.
divider (str): str to add between 'item' and 'prefix'. Defaults to '',
... | 70,216 |
def merge(predicates):
"""
Invoked with a set of predicates that should
be merged into a single AST. The new AST uses
the PushResults node to return the list of matching
predicates, and Both nodes to combine.
"""
# Merge the AST tree's together first using a tree
all_asts = [ast.PushResu... | 70,217 |
def main():
"""Barnes and Noble Upload."""
###########################################################################
# OpenSSH 7.0 and greater disable the ssh-dss (DSA) public key algorithm,
# which B&N use for authentication on their servers, so you have to add
# ssh-dss to the ssh/sftp comm... | 70,218 |
def optimize_threshold(model, X, y, TP=0, FP=0, TN=0, FN=0, minimize=True, pos_label=1):
"""
Find the optimal threshold
Returns a tuple containing:
A pandas dataframe used for plotting
The optimal threshold
The cost associated to that threshold
"""
y_pred = model.predict_prob... | 70,219 |
def get_backend_defaults_url(config, backend_type):
"""Return the URL for a backend's pulse defaults."""
hub = config.get('hub', None)
group = config.get('group', None)
project = config.get('project', None)
if hub and group and project:
return '/Network/{}/Groups/{}/Projects/{}/devices/{}/d... | 70,220 |
def test_houston_configmap():
"""Validate the houston configmap and its embedded data."""
docs = render_chart(
show_only=["charts/astronomer/templates/houston/houston-configmap.yaml"],
)
common_test_cases(docs)
doc = docs[0]
prod = yaml.safe_load(doc["data"]["production.yaml"])
# En... | 70,221 |
def ugly_numbers(n: int) -> int:
"""
Uses dynamic programming technique to return the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(1)
1
>>> ugly_numbers(20)
36
"""
ugly_nums = [0] * (n)
ugly_nums[0] = 1
i2, i3, i5 = 0, 0, 0
next_2 = ugly_nums[i2] * 2
... | 70,222 |
def get_publish_dates(df):
"""Get time distribution of publish dates for the given dataframe
Returns
-------
list[int]
Time distribution in a format friendly towards HighCharts
"""
return pd.to_datetime(df["publish_date"]).astype(np.int64) / int(1e6) | 70,223 |
def jdump(data):
"""Pass."""
print(json_reload(data)) | 70,224 |
def wave(image, amplitude, wave_length):
"""creates a "ripple" effect in the image by shifting
the pixels vertically along a sine wave whose amplitude and wavelength
is specified by the given parameters.
:param image: the target image.
:type image: :class:`wand.image.Image`
:param amplitude: th... | 70,225 |
def user_delete(request, pk=None):
"""User Delete View
Description:
view to delete users
"""
try:
user = Client.objects.get(id=pk)
except Exception as e:
messages.error(request, e.args[0])
return HttpResponseRedirect('.')
if request.method == 'GET':
_user ... | 70,226 |
def make_posts(
src, src_pattern, dst, layout, category_layout, comment_layout, comment_detail_layout, **params
):
"""Generate posts from posts directory."""
items = []
for posix_path in Path(src).glob(src_pattern):
src_path = str(posix_path)
content = read_content(src_path)
... | 70,227 |
def binary_search(array, item):
"""返回 item 在 array 中的下标,没找到返回 None。"""
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
guess = array[mid]
if guess == item:
return mid
elif guess > item:
high = mid - 1
else:
... | 70,228 |
def get_parser():
"""Create the argument parser"""
parser = argparse.ArgumentParser(prog="ivpm")
subparser = parser.add_subparsers()
subparser.required = True
subparser.dest = 'command'
update_cmd = subparser.add_parser("update",
help="Fetches packages specified in ivpm.yaml th... | 70,229 |
def is_update(flags):
"""Is the opcode in flags UPDATE?
*flags*, an ``int``, the DNS message flags.
Returns a ``bool``.
"""
return from_flags(flags) == Opcode.UPDATE | 70,230 |
def get_1obj_gt_scenario():
"""
Egovehicle stationary (represented by `o`).
Seqeuence of 4-nanosecond timestamps.
|-|
| |
|-|
|-|
| |
|-|
o (x,y,z) = (0,0,0)
|-|
| |
|-|
|-|
| | (x,y,z)=(-3,2,0)
|-|
"""
centers = []
# timestamp 0
cx = -3
cy = 2
cz = 0
centers += [(cx,cy,cz)]
# timestamp 1
... | 70,231 |
def list_folders(root):
"""
List the folders from a root path
:param root:
:return:
"""
commands = ["find", os.path.realpath(root), "-type","d"]
results = subprocess.check_output(commands)
return results.decode().split("\n")[1:] | 70,232 |
def _set_mem(args: [str]) -> Optional[rdcp_command.RDCPCommand]:
"""addr:int hexadecimal_string: str"""
addr = _parse_int_expression(args[0])
value = binascii.unhexlify("".join(args[1:]))
return rdcp_command.SetMem(addr, value, handler=print) | 70,233 |
def tarx(args: argparse.Namespace):
"""
Uncompress from .tar.gz
"""
tar_file = args.files[0]
if args.name:
if not os.path.exists(args.name):
cmd = f'mkdir {args.name}'
exec_cmd(cmd)
cmd = f'tar -xzvf {tar_file} -C {args.name}'
else:
cmd = f'tar -... | 70,234 |
def add_board():
"""Lets the user add a board."""
logger.info("My session is: %r" % session)
form = SQLFORM(db.bulletin_boards)
if form.process().accepted:
session.flash = T('Your board was created')
redirect(URL('default', 'bulletin_board', args=[form.vars.id]))
return dict(form=for... | 70,235 |
def fuel(i: int) -> int:
"""
>>> [fuel(i) for i in [12,14,1969,100756]]
[2, 2, 654, 33583]
"""
return i // 3 - 2 | 70,236 |
def show_Gingl_plane():
"""F = -63.2415 + 3.7504 T + 326.8702 dT/dt
3.7504 T + 326.8702 dT/dt - F - 63.2415 = 0
data is constrained:
T between 30-24
dT/dt between +- 0.03
F between 25- 55
TODO: make sure that the surface code is properly implemented
"""
point1 = np.array... | 70,237 |
def download_images(img_urls, dest_dir):
"""Given the urls already in the correct order, downloads
each image into the given directory.
Gives the images local filenames img0, img1, and so on.
Creates an index.html in the directory
with an img tag to show each local image file.
Creates the directory if neces... | 70,238 |
def veto_out_of_stock(sender, cartitem=None, added_quantity=0, **kwargs):
"""Listener which vetoes adding products to the cart which are out of stock."""
if config_value('PRODUCT','NO_STOCK_CHECKOUT') == False:
product = cartitem.product
need_qty = cartitem.quantity + added_quantity
... | 70,239 |
def about(request):
"""Renderea a about"""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
{
'year':datetime.now().year,
}
) | 70,240 |
def get_proc_name_from_pid(pid):
"""
using psutil to obtain proc name from pid
:param pid:
:return: proc name
"""
import psutil
return psutil.Process(pid).name() | 70,241 |
def update_dashboard(cloudwatch_client, labels, metric_name):
"""
Updates dashboard with specified dashboard-name and places specified metric from labels/metric_name
:param cloudwatch_client: Boto3 Cloudwatch_client passed in from caller
:param labels: Metric info passed from toml file, always contains ... | 70,242 |
def _create_local(name, shape=None, collections=None):
"""Creates a new local variable.
Args:
name: The name of the new or existing variable.
shape: Shape of the new or existing variable.
collections: A list of collection names to which the Variable will be added.
Returns:
The created variable.
... | 70,243 |
def old_project(old_repository):
"""Create a test project."""
repo = old_repository['repo']
repository_path = repo.working_dir
commit = repo.head.commit
os.chdir(repository_path)
yield {
'repo': repo,
'path': repository_path,
'exit_code': old_repository['exit_code']
... | 70,244 |
def ReadStampFile(target_os):
"""Return the contents of the stamp file, or '' if it doesn't exist."""
try:
with open(STAMP_FILE % target_os, 'r') as f:
return f.read().rstrip()
except IOError:
return '' | 70,245 |
def test_same_arg_as_i_and_o(some_thr):
"""
Tests that the same 'io' array can be used both as an input and as an output argument
of the same nested computation.
"""
N = 2000
coeff = 2
second_coeff = 3
A = numpy.ones((N,N)).astype(numpy.complex64) # get_test_array((N, N), numpy.complex6... | 70,246 |
def tts_langs(tld="com"):
"""Languages Naver Text-to-Speech supports.
Args:
tld (string): Top-level domain for the Google Translate host
to fetch languages from. i.e `https://translate.google.<tld>`.
Default is ``com``.
Returns:
dict: A dictionnary of the type `{ '<... | 70,247 |
def matmulBackward1(grad: Tensor, t1: 'Tensor', t2: 'Tensor') -> Tensor:
"""Gradient Function that is used when
a tensor is matrix multiplied to a tensor that
requires gradient.
- Math:
let A.shape == m x n
let B.shape == n x p
Y = A @ B
F(Y) = L
... | 70,248 |
def test_train_ignore_torch_seed(raw_dataset_fp: str, random_seed: int) -> None:
"""Test reproducibility of training API when an unrelated torch random operation is performed between the
Ludwig operations.
Args:
raw_dataset_fp (str): file path for data to be used as part of this test
random... | 70,249 |
def get_files(file_pat):
"""Grab files from globbing pattern or stream file"""
if os.path.exists(file_pat):
root, ext = os.path.splitext(file_pat)
if ext.lower() == ".ycsv":
df, d = read_ycsv(file_pat)
fns = df.index.tolist()
else:
f = open(file_pat, "... | 70,250 |
def make_rooks() -> List[Rook]:
"""Return list of rooks"""
rooks: List[Rook] = []
for k in range(2):
rooks.extend((
Rook(SQUARE_SIZE * k * 7, SQUARE_SIZE * 7, WHITE,
f'{PIECE_PATH}white_rook.png',),
Rook(SQUARE_SIZE * k * 7, SQUARE_SIZE * 0, BLACK,
... | 70,251 |
def _domains_in_part(part: dc.DesignPart, exclude_fixed: bool) -> List[Domain]:
"""
:param part:
DesignPart (e.g., :any:`Strand`, :any:`Domani`, Tuple[:any:`Strand`, :any:`Strand`])
:param exclude_fixed:
whether to exclude :any:`Domain`'s with :data:`Domain.fixed` == True
:return:
... | 70,252 |
def read_temporal_profiles(tracer, kind, filename):
"""\
Read temporal profiles for given `tracer` for
'weekly' or 'annual' profiles.
"""
data = {}
countries = []
snaps = []
filename = filename.format(tracer=tracer)
with open(filename, "r") as profile_file:
for line in prof... | 70,253 |
def test_list():
"""
Retrieve a list of tests as json objects.
See the README for details on the formatting.
"""
test_json_objs = []
for test_id, test_name in enumerate(tests):
exec("name = "+test_name+".name", globals())
exec("desc = "+test_name+".desc", globals())
... | 70,254 |
def _write_token_to_cache(token: str):
"""
Writes the token to the cache.
"""
cache_dir = settings.CACHE_DIR
if not cache_dir.exists():
logger.warning(f"Cache directory does not exist {cache_dir}. Token won't be saved.")
return
token_path = settings.CACHE_DIR / TOKEN_FILE_NAME
... | 70,255 |
def resolve_name(arguments, fname):
"""
Return right name and format for an output file.
"""
if arguments.output:
if len(arguments.filename) > 1:
if not os.path.exists(arguments.output):
os.mkdir(arguments.output)
if not os.path.isdir(arguments.output):
... | 70,256 |
def is_git_repo(path):
"""
Rudimentary tests for if I have a git repo. Simply look for .git directory
**Positional Arguments:**
path:
- The path that we are assessing
"""
return os.path.exists(os.path.join(path, ".git")) and \
os.path.isdir(os.path.join(path, ".git")) | 70,257 |
def load_embeddings(file_name: str, embeddings_format: str):
"""Load word embeddings from the given file, either in plain-text format ('text') or in gensim format ('gensim')"""
if embeddings_format == 'text':
return _load_w2v_model_file(filename=file_name)
else:
return _load_w2v_model_gensim... | 70,258 |
def favicon():
"""网站图标"""
# send_static_file是flask里面的寻找static静态文件的方法。通过查看源码得知
return current_app.send_static_file('news/favicon.ico') | 70,259 |
async def test_device(hass: HomeAssistant, target_domain):
"""Test the entity is added to the wrapped entity's device."""
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
test_config_entry = MockConfigEntry()
device_entry = device_registry.async_get_or_create(
conf... | 70,260 |
def test_valid_n_jobs(n_jobs: Any) -> None:
"""Test that valid n_jobs raise no errors."""
check_n_jobs(n_jobs) | 70,261 |
def MarkCurrentStep(fatal=True):
"""Mark the current step as having a problem.
If fatal is True, mark the current step as failed (red), otherwise mark it as
having warnings (orange).
"""
# See
# https://chromium.googlesource.com/chromium/tools/build/+/c63ec51491a8e47b724b5206a76f8b5e137ff1e7/scripts/master... | 70,262 |
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi! \n\nWelcome to Optical Character Recognizer Bot. \n\nJust send a clear image to the bot and it will recognize the text in the image and send it as a message!\nTo get my contact details tap /contact \nT... | 70,263 |
def gcp_application_default_creds_exist():
"""
Return true if the application default credentials file exists.
:return: True if we can find app default creds file otherwise False.
"""
cred_file = os.path.expanduser('~/.config/gcloud/application_default_credentials.json')
return os.path.exists(cr... | 70,264 |
def test_get_user_admin_get_other_user_successful(admin_token):
"""
成功获取其他用户信息,admin用户。admin_or_has_permission_self权限测试。
:param admin_token:
:return:
"""
result = http_get(get_user_url.format(user_id=2), token=admin_token)
assert result.json()['code'] == 0
assert result.json()['data']['i... | 70,265 |
def main():
"""
Main body of script.
"""
args = parse_args()
in_video = os.path.expanduser(args.in_video)
if not os.path.exists(in_video):
raise Exception("Input video doesn't exist: {}".format(in_video))
assert os.path.isfile(in_video)
interpreter = tf.lite.Interpreter(model_pa... | 70,266 |
def scriptExit():
"""Exit Nuke."""
pass | 70,267 |
def compute_tpm(
counts_df: pd.DataFrame, gene_id2length: pd.DataFrame
) -> pd.DataFrame:
"""Compute TPM values
Args:
counts_df: Dataframe containing counts
gene_id2length: Dictionary of gene ID to gene length
Returns:
pd.DataFrame: containing the TPM values
"""
scaling... | 70,268 |
def sample(env, policies, num_episodes=128, max_steps=1e6, policy_fn=None):
"""Generates a batch of episodes using the given policies"""
batch = Batch()
total_steps = 0
for _ in range(num_episodes):
# Initialize episode and episode batch
obs = env.reset()
current_step = 0
... | 70,269 |
def rhsso_setup(lifecycle_hooks, rhsso_service_info):
"""Have application/service with RHSSO auth configured"""
lifecycle_hooks.append(OIDCClientAuthHook(rhsso_service_info)) | 70,270 |
def lnprior(pzero_regions, paramSetup):
"""
Function that computes the ln prior probabilities of the model parameters.
"""
priorln = 0.0
mu = 1
# import pdb; pdb.set_trace()
# ensure all parameters are finite
if (pzero_regions * 0 != 0).any():
priorln = -numpy.inf
re... | 70,271 |
def _save_imported_filename_to_gcs(storage_client: storage.client.Client,
filename: str) -> None:
"""Helper function that records the imported file's name to a GCS bucket."""
print('Starting insert of import history record...')
completed_files_bucket_name = os.environ.get(
... | 70,272 |
def render_template_to_file(template_path, file_path=None, **values):
"""
Render a 'jinja' template resource to a temporary file.
:param template_path: relative path to the template.
:param file_path: absolute path to the desired output file.
:param values: keyword arguments passed to jinja.
"... | 70,273 |
async def connect(host: str, family: str = None, comm_addr: int = 0, timeout: int = 1, retries: int = 3) -> Inverter:
"""Contact the inverter at the specified host/port and answer appropriate Inverter instance.
The specific inverter family/type will be detected automatically, but it can be passed explicitly.
... | 70,274 |
def rebuild_category_map():
"""Rebuilds category map file"""
all_cats = dao.get_all_categories()
tree = build_category_tree(all_cats)
map_json = json.dumps([tree], separators=(',', ':'), ensure_ascii=False)
storage = staticstorage.GCSStorage()
storage.put('category_map.json', map_json.encode('ut... | 70,275 |
def get_extension(filename):
"""
Gets the extension of a file
Parameters
----------
str filename: the filename to extract extension from
"""
try:
return os.path.splitext(filename)[1].replace(".", "")
except (AttributeError, TypeError):
return "" | 70,276 |
def print_characters_slanted(sequence_of_strings):
"""
Same as the previous problem, but each string 'slants'.
For example, if the given argument is ['hi', 'bye', 'a_tie!'],
then this function prints:
h
i
b
y
e
a
_
t
i
e... | 70,277 |
def fit_generic_continuum(spectrum, median_window=3, model=Chebyshev1D(3),
fitter=LevMarLSQFitter(),
exclude_regions=None, weights=None):
"""
Basic fitting of the continuum of an input spectrum. The input
spectrum is smoothed using a median filter to remov... | 70,278 |
def test_add_missing_row():
"""
It should add missing row compare to a reference column
"""
input_df = pd.read_csv(os.path.join(fixtures_base_dir, 'add_missing_row.csv'))
new_df = add_missing_row(input_df, id_cols=['City', 'Country', 'Region'], reference_col='Year')
assert len(new_df) == 12
... | 70,279 |
def sdss_path():
"""Path for absorption/emission lines
"""
return join(_parent_path, 'SDSS') | 70,280 |
def filterExistingFiles(species,array_type,db,export_type):
"""Remove probesets entries (including 5' and 3' junction exons) from the database that don't indicate possible critical exons"""
export_exon_filename = 'AltDatabase/'+species+'/'+array_type+'/'+species+'_Ensembl_'+array_type+'_probesets.txt' ... | 70,281 |
def raise_helper(ctx, msg):
"""Allow "raise('msg')" to be used in templates"""
raise TemplateException(f'{ctx.name}: {msg}') | 70,282 |
def prepare_dibco(data_dir=DEFAULT_DATA_DIR,
out_dir=None,
force=False):
""" Downloads and extracts dibco dataset and its annotation data. """
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if out_dir is None:
out_dir = data_dir
if not os.path.exists(out_dir):... | 70,283 |
def test_make_file_locator_fobj(files_on_disk):
"""Test for make_file_locator with file object.
"""
tmpdir = files_on_disk
with open(os.path.join(tmpdir, "xxx.ged"), 'rb') as fobj:
loc = ged2doc_input.make_file_locator(fobj, "", tmpdir)
assert isinstance(loc, ged2doc_input._FSLocator)
... | 70,284 |
def confinement_force(sphere1, containing_sphere):
"""Returns the force exerted on sphere1 by its proximity to the confinement
sphere."""
pass | 70,285 |
def read_log_file(
log_file,
log_entries_to_get=[
"x_pixel_um",
"y_pixel_um",
"z_pixel_um",
"image_paths",
"registration_config",
],
separator=": ",
):
"""
Reads an amap log file, and returns a dict of entries corresponding to
"log_entries_to_get"
... | 70,286 |
def lookup_env(names):
"""
Look up for names in environment. Returns the first element
found.
"""
for name in names:
value = os.environ.get(name)
if value:
return value | 70,287 |
def test_func_amplitude_to_db_pipeline():
""" mindspore pipeline mode normal testcase:amplitude_to_db op"""
logger.info("test AmplitudeToDB op with default value")
generator = gen([CHANNEL, FREQ, TIME])
data1 = ds.GeneratorDataset(source=generator, column_names=["multi_dimensional_data"])
transfo... | 70,288 |
def add_member(code):
""" Adds code to the current member context. """
context.members.write(code) | 70,289 |
def update_project(project):
"""Updates the duration of the project's time"""
duration = None
# set local timezone
timezone = get_localzone()
local_tz = timezone.zone
# collect all of the logs that are part of this project
logs = Log.select().where(Log.project_id == project.id)
# iter... | 70,290 |
def miles_graph():
""" Return the cites example graph in miles_dat.txt
from the Stanford GraphBase.
"""
# open file miles_dat.txt.gz (or miles_dat.txt)
import gzip
fh = gzip.open('knuth_miles.txt.gz', 'r')
G = nx.Graph()
G.position = {}
G.population = {}
cities = []
for... | 70,291 |
def SetErrorHandler(*args):
"""SetErrorHandler(char const * pszCallbackName=None) -> CPLErr"""
return _gdal.SetErrorHandler(*args) | 70,292 |
def update_durability(group_file, models_durability):
"""Обновить прочность объектов в .Group файле"""
lines = []
next_durability = 0
wait_durability = False
with open(group_file) as file:
for line in file.readlines():
if line.strip().startswith('Model ='):
lines.... | 70,293 |
def parse_file_path(file_path: Union[str, Path], debug: int = 0) -> Dict:
"""Parse info of timestamp,region,locationId,year from file path.
expected in the string: region/locationId/YYYY/name_YYYYMMDD_HHMMSS
possibilities:
XYZ/random/region/locationId/YYYY/name_YYYYMMDD_HHMMSS_XXX000.stuf
... | 70,294 |
def get_shift_bits(n, bit_string, shift):
"""Given a bit-string, return an expression to map to the bit-string.
Each index of the given bit-string corresponds to the index of an n-bit
bit vector. This function returns those bits, using the variable for the bit
if the corresponding index in the bit-string is '1... | 70,295 |
def get_bag_count(list_of_bags: list, colour: str) -> int:
"""
Recursive function to loop through list.
Gather rules on line.
While there are still rules to be processed, get colour and recursively call function again.
Append to total.
:return: Total amount of bags inside colour.
:rtype: in... | 70,296 |
def get_wikidata_complexes():
"""Gets all Wikidata items with a Complex Portal ID property"""
get_macromolecular = """
SELECT ?item ?ComplexPortalID
WHERE
{
?item wdt:P7718 ?ComplexPortalID .
}"""
wikidata_complexes = WDItemEngine.execute_sparql_query(
get_macromolecular, as_da... | 70,297 |
def _pick_port():
"""
Returns an unused TCP port.
While we can not guarantee it will stay unused, it is very unlikely
that it will become used within a few seconds.
"""
with socket(AF_INET, SOCK_STREAM) as sock:
sock.bind(("", 0))
return sock.getsockname()[1] | 70,298 |
def connection_str():
""" SQLAlchemy connection string to test database """
return "postgresql://nebulo_user:password@localhost:4442/nebulo_db" | 70,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.