content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
def merge(source: Dict, destination: Dict) -> Dict:
"""
Deep merge two dictionaries
Parameters
----------
source: Dict[Any, Any]
Dictionary to merge from
destination: Dict[Any, Any]
Dictionary to merge to
Returns
-------
Dict[Any, Any]
... | 4ffba933fe1ea939ecaa9f16452b74a4b3859f40 | 3,650,400 |
async def async_api_adjust_volume_step(hass, config, directive, context):
"""Process an adjust volume step request."""
# media_player volume up/down service does not support specifying steps
# each component handles it differently e.g. via config.
# For now we use the volumeSteps returned to figure out ... | 85625118d4185842dd0398ec5dd0adbb951b5d67 | 3,650,401 |
import os
def load_recordings(path: str, activityLabelToIndexMap: dict, limit: int = None) -> 'list[Recording]':
"""
Load the recordings from a folder containing csv files.
"""
recordings = []
recording_files = os.listdir(path)
recording_files = list(filter(lambda file: file.endswith('.csv'),... | c5081c7f7b27eea080a1b1394a67bff158bdf243 | 3,650,402 |
import warnings
import io
def load_img(path, grayscale=False, color_mode='rgb', target_size=None,
interpolation='nearest'):
"""Loads an image into PIL format.
# Arguments
path: Path to image file.
grayscale: DEPRECATED use `color_mode="grayscale"`.
color_mode: The desired ... | 61709400c2bd6379864f2399c2c04c29e0b61b92 | 3,650,403 |
import logging
import platform
def check_compatible_system_and_kernel_and_prepare_profile(args):
"""
Checks if we can do local profiling, that for now is only available
via Linux based platforms and kernel versions >=4.9
Args:
args:
"""
res = True
logging.info("Enabled profilers: {... | 35da3151109ef13c7966ede991b871dca45f4d0b | 3,650,404 |
import os
import shutil
import subprocess
import glob
def crop_file(in_file, out_file, ext):
"""Crop a NetCDF file to give rectangle using NCO.
The file is automatically converted to [0,360] °E longitude format.
Args:
in_file: Input file path.
out_file: Output file path. It will not be o... | 3f185c4e86299270b2ef694d6b5505326873f7db | 3,650,405 |
def get_instance_string(params):
""" combine the parameters to a string mostly used for debug output
use of OrderedDict is advised
"""
return "_".join([str(i) for i in params.values()]) | ff9470cd9e308357b594c2ec0389c194d2d6ac00 | 3,650,406 |
import logging
import time
import re
def recv_bgpmon_updates(host, port, queue):
"""
Receive and parse the BGP update XML stream of bgpmon
"""
logging.info ("CALL recv_bgpmon_updates (%s:%d)", host, port)
# open connection
sock = _init_bgpmon_sock(host,port)
data = ""
stream = ""
#... | 6cf8e008b2b47437e80b863eab6f7c1fd4a54e18 | 3,650,407 |
import ast
def is_string_expr(expr: ast.AST) -> bool:
"""Check that the expression is a string literal."""
return (
isinstance(expr, ast.Expr)
and isinstance(expr.value, ast.Constant)
and isinstance(expr.value.value, str)
) | f61418b5671c5e11c1e90fce8d90c583659d40e3 | 3,650,408 |
import numba
def events_to_img(
xs: np.ndarray,
ys: np.ndarray,
tots: np.ndarray,
cluster_ids: np.ndarray,
x_img: np.ndarray,
y_img: np.ndarray,
minimum_event_num: int = 30,
extinguish_dist: float = 1.41422, # sqrt(2) = 1.41421356237
) -> np.ndarray:
... | ced70fc290157a4168c8e9ebd589263bbc410c6f | 3,650,409 |
import logging
import requests
def worker(job):
"""Run a single download job."""
logger = logging.getLogger("ncbi-genome-download")
ret = False
try:
if job.full_url is not None:
req = requests.get(job.full_url, stream=True)
ret = save_and_check(req, job.local_file, job.... | f7ddf815bc6689ac7086c3f8d04bc4ffd29fccbd | 3,650,410 |
def generate_ar(n_series, n_samples, random_state=0):
"""Generate a linear auto-regressive series.
This simple model is defined as::
X(t) = 0.4 * X(t - 1) - 0.6 * X(t - 4) + 0.5 * N(0, 1)
The task is to predict the current value using all the previous values.
Parameters
----------
n_... | a02b2bb242ecc0eb6cf3d5d23d0982c56d81b617 | 3,650,411 |
import subprocess
def get_current_commit_id() -> str:
"""Get current commit id.
Returns:
str: current commit id.
"""
command = "git rev-parse HEAD"
commit_id = (
subprocess.check_output(command.split()).strip().decode("utf-8") # noqa: S603
)
return commit_id | 978bd35fc3cfe71fcc133a6e49fbbe0e27d4feda | 3,650,412 |
import re
def get_raw_code(file_path):
"""
Removes empty lines, leading and trailing whitespaces, single and multi line comments
:param file_path: path to .java file
:return: list with raw code
"""
raw_code = []
multi_line_comment = False
with open(file_path, "r") as f:
for ro... | 6654a0423f024eaea3067c557984c3aa5e9494da | 3,650,413 |
import os
def load_content(file_path):
"""
Loads content from file_path if file_path's extension
is one of allowed ones (See ALLOWED_EXTS).
Throws UnsupportedMetaException on disallowed filetypes.
:param file_path: Absolute path to the file to load content from.
:type file_path: ``str``
:r... | b9fb74d90f181b7066643e82269c5a6915cb57e9 | 3,650,414 |
from typing import Pattern
import re
def _yaml_comment_regex() -> Pattern:
"""
From https://yaml-multiline.info/, it states that `#` cannot appear *after* a space
or a newline, otherwise it will be a syntax error (for multiline strings that don't
use a block scalar). This applies to single lines as we... | 3b5739f460c3d2c66f802dd46e061d2d07030525 | 3,650,415 |
def to_list(name: str) -> "Expr":
"""
Aggregate to list
"""
return col(name).list() | 2265c14d13ef92bb5481dc2eee17915288cf95e8 | 3,650,416 |
import re
def format_ipc_dimension(number: float, decimal_places: int = 2) -> str:
"""
Format a dimension (e.g. lead span or height) according to IPC rules.
"""
formatted = '{:.2f}'.format(number)
stripped = re.sub(r'^0\.', '', formatted)
return stripped.replace('.', '') | 60001f99b5f107faba19c664f90ee2e9fb61fe68 | 3,650,417 |
def mean_test(data, muy0, alternative = 'equal', alpha = 0.95):
"""
This function is used to create a confidence interval of two.sided hypothesis
Input:
data (1D array): the sample of the whole column that you want to evaluate
confidence (float) : confidence_level, must be in... | 9a798eeed1ba2debfe42dbb08ed33c8a1f463fd3 | 3,650,418 |
def __build_command(command, name, background=None, enable=None):
""" Constuct args for systemctl command.
Args:
command: The systemctl command
name: The unit name or name pattern
background: True to have systemctl perform the command in the background
enable: True to enable/disable, False to start... | 5f47c19bb24d05b66d02c6d93ed1bf90144afb63 | 3,650,419 |
import requests
def dockerFetchLatestVersion(image_name: str) -> list[str]:
"""
Fetches the latest version of a docker image from hub.docker.com
:param image_name: image to search for
:return: list of version suggestions for the image or 'not found' if error was returned
"""
base_url = "https:... | 5907dfe92b627c272132f97be9019d735aabd570 | 3,650,420 |
import torch
import torchvision
def _dataset(
dataset_type: str,
transform: str,
train: bool = True
) -> torch.utils.data.Dataset:
"""
Dataset:
mnist: MNIST
cifar10: CIFAR-10
cifar100: CIFAR-100
Transform:
default: the default transform for each data set
simclr: the tran... | cdfeefefede97db0a8d8ad6c3f4620855004062c | 3,650,421 |
def inferCustomerClasses(param_file, evidence_dir, year):
"""
This function uses the variable elimination algorithm from libpgm to infer the customer class of each AnswerID, given the evidence presented in the socio-demographic survey responses.
It returns a tuple of the dataframe with the probability... | 212906aacc2bc3d607e1589742591834953de14e | 3,650,422 |
def MidiSegInfo(segment):
""" Midi file info saved in config file for speed """
class segInfo:
iMsPerTick = 0
bpm = 4
ppqn = 480
total_ticks = 0
iLengthInMs = 0
iTracks = 0
trackList = []
ver = "1.5"
ret = segInfo()
savedVer = IniGetValue(... | 7d48b699ed52239cf08e57b217f5dd62f3c64a84 | 3,650,423 |
def num_in_row(board, row, num):
"""True if num is already in the row, False otherwise"""
return num in board[row] | ca9ab9de4514740e25e0c55f3613d03b2844cdb8 | 3,650,424 |
import urllib
def load_mnist(dataset="mnist.pkl.gz"):
"""
dataset: string, the path to dataset (MNIST)
"""
data_dir, data_file = os.path.split(dataset)
# download MNIST if not found
if not os.path.isfile(dataset):
origin = (
'http://www.iro.umontreal.ca/~lisa/deep/... | 2e499431bed7a8c1c775b04d6272153564d9c99f | 3,650,425 |
import os
from sys import path
def load_hs13_ZSBB_params():
"""Load the standard parameters to generate SocioPatterns HS13
surrogate networks using the ZSBB model.
Returns
-------
:obj:`dict`
The `kwargs` to pass to :func:`tacoma.ZSBB_model`.
"""
fn = os.path.join(path,'ht09_zsb... | a6a922fd696d19e2f0dc609cd14db814b84a1e4d | 3,650,426 |
def factorial_3(n, acc=1):
"""
Replace all recursive tail calls f(x=x1, y=y1, ...) with (x, y, ...) = (x1, y1, ...); continue
"""
while True:
if n < 2:
return 1 * acc
(n, acc) = (n - 1, acc * n)
continue
break | e067cf4564056bf488e56fe58bbd5b998b0175f3 | 3,650,427 |
def autocorr(x, axis=0, fast=False):
"""
Estimate the autocorrelation function of a time series using the FFT.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other axis.
:param ax... | e2e4105bd0a4aed3431af6acf4f3669bb3340825 | 3,650,428 |
import re
import dateutil
def parse_date(filename_html):
"""Parse a file, and return the date associated with it.
filename_html -- Name of file to parse.
"""
match = re.search(r"\d{4}-\d{2}-\d{2}", filename_html)
if not match:
return None
match_date = match.group()
file_... | 2ee45c3f70b75fc2d26b9c00861dbb1e7586d4af | 3,650,429 |
import os
def build_static_runtime(
workspace,
compiler,
module,
compiler_options,
executor=None,
extra_libs=None,
):
"""Build the on-device runtime, statically linking the given modules.
Parameters
----------
compiler : tvm.micro.Compiler
Compiler instance used to bui... | 2c9b451a3c0208fb7dc1439fdf887b1a17d749ce | 3,650,430 |
def mod(a1, a2):
"""
Function to give the remainder
"""
return a1 % a2 | f5c03a952aed373e43933bafe37dbc75e796b74d | 3,650,431 |
def select_theme_dirs():
"""
Load theme templates, if applicable
"""
if settings.THEME_DIR:
return ["themes/" + settings.THEME_DIR + "/templates", "templates"]
else:
return ["templates"] | df74bc751f701be63276b5481ac222e64ba914e7 | 3,650,432 |
def encode_string(s):
"""
Simple utility function to make sure a string is proper
to be used in a SQL query
EXAMPLE:
That's my boy! -> N'That''s my boy!'
"""
res = "N'"+s.replace("'","''")+"'"
res = res.replace("\\''","''")
res = res.replace("\''","''")
return res | 814822b9aa15def24f98b2b280ab899a3f7ea617 | 3,650,433 |
def email_manage(request, email_pk, action):
"""Set the requested email address as the primary. Can only be
requested by the owner of the email address."""
email_address = get_object_or_404(EmailAddress, pk=email_pk)
if not email_address.user == request.user and not request.user.is_staff:
messag... | 7a533fe34fdc13b737025c01bb0bb15dcbeae0f2 | 3,650,434 |
def get_container_service_api_version():
"""Get zun-api-version with format: 'container X.Y'"""
return 'container ' + CONTAINER_SERVICE_MICROVERSION | c6f83640b50132e24ce96889688afcda49ba6b1c | 3,650,435 |
import yaml
import os
def prepare_config(config_path=None,
schema_path=None,
config=None,
schema=None,
base_path=None) -> Munch:
"""
Takes in paths to config and schema files.
Validates the config against the schema, normalizes th... | 3bcf3a033134475ef873ab631410cc210c5b09a2 | 3,650,436 |
from django.utils.cache import get_cache_key
from django.core.cache import cache
def invalidate_view_cache(view_name, args=[], namespace=None, key_prefix=None):
"""
This function allows you to invalidate any view-level cache.
view_name: view function you wish to invalidate or it's named url pattern
... | 2622e6ee48cb7565014660858104edba5b20b9eb | 3,650,437 |
def compute_ray_features_segm_2d(seg_binary, position, angle_step=5., smooth_coef=0, edge='up'):
""" compute ray features vector , shift them to be starting from larges
and smooth_coef them by gauss filter
(from given point the close distance to boundary)
:param ndarray seg_binary: np.array<height, wid... | 18b830fe6ac83cf7282be39d368ad7c1261a890c | 3,650,438 |
def visualize_bbox(img, bbox, class_name, color=(255, 0, 0) , thickness=2):
"""Visualizes a single bounding box on the image"""
BOX_COLOR = (255, 0, 0) # Red
TEXT_COLOR = (255, 255, 255) # White
x_min, y_min, x_max, y_max = bbox
cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color=color, thick... | 147335c2e87b57f0bd0ba0840e9dae9f713b513f | 3,650,439 |
import json
def mock_light():
"""Mock UniFi Protect Camera device."""
data = json.loads(load_fixture("sample_light.json", integration=DOMAIN))
return Light.from_unifi_dict(**data) | ba83ae80ddb39ec9f9b6f30b77eabee39f998b39 | 3,650,440 |
def randomize_bulge_i(N, M, bp='G', target='none', ligand='theo'):
"""
Replace the upper stem with the aptamer and randomize the bulge to connect
it to the lower stem.
This is a variant of the rb library with two small differences. First, the
nucleotides flanking the aptamer are not randomized a... | aff8aa9e6ba276bb9d867f24c58c44e0e3c849f6 | 3,650,441 |
def JSparser(contents: str) -> str:
"""
Is supposed to replace URLs in JS.
Arguments:
contents: JS string
Returns:
Input JS string
"""
# TODO: URL replacement
return contents | 393216d8e10677405d888e4cdd6a884aebb0684a | 3,650,442 |
import logging
def parse_identifier(db, identifier):
"""Parse the identifier and return an Identifier object representing it.
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param identifier: String containing the identifier
:type identifier: str
:return: Identifier ob... | 390fc8d44014d2cdb17fc641dab9914ba13bc95e | 3,650,443 |
import textwrap
def wrap_name(dirname, figsize):
"""Wrap name to fit in subfig."""
fontsize = plt.rcParams["font.size"]
# 1/120 = inches/(fontsize*character)
num_chars = int(figsize / fontsize * 72)
return textwrap.fill(dirname, num_chars) | 7fb7430a01781c7c53637ae4a94c72c057faddab | 3,650,444 |
def resolve_shape(tensor, rank=None, scope=None):
"""Fully resolves the shape of a Tensor.
Use as much as possible the shape components already known during graph
creation and resolve the remaining ones during runtime.
Args:
tensor: Input tensor whose shape we query.
rank: The rank of the tensor, provi... | cc1c3a0bd2b5a35580dd94b6c45a2a36cc151e5a | 3,650,445 |
def gradient_clip(gradients, max_gradient_norm):
"""Clipping gradients of a model."""
clipped_gradients, gradient_norm = tf.clip_by_global_norm(
gradients, max_gradient_norm)
gradient_norm_summary = [tf.summary.scalar("grad_norm", gradient_norm)]
gradient_norm_summary.append(
tf.summary.scalar("clip... | 416f9560ad612ab364cd03de39851a559012d26b | 3,650,446 |
import subprocess
def get_sha_from_ref(repo_url, reference):
""" Returns the sha corresponding to the reference for a repo
:param repo_url: location of the git repository
:param reference: reference of the branch
:returns: utf-8 encoded string of the SHA found by the git command
"""
# Using su... | d7ab3e98217fa57e0831a6df94d34f1cf45e3d97 | 3,650,447 |
def list_species(category_id):
"""
List all the species for the specified category
:return: A list of Species instances
"""
with Session.begin() as session:
species = session.query(Species)\
.filter(Species.categoryId == category_id)\
.order_by(db.asc(Species.name))\... | c49283fdde11456ffc6e4eff4b5043d547fa9908 | 3,650,448 |
def get_motif_proteins(meme_db_file):
""" Hash motif_id's to protein names using the MEME DB file """
motif_protein = {}
for line in open(meme_db_file):
a = line.split()
if len(a) > 0 and a[0] == 'MOTIF':
if a[2][0] == '(':
motif_protein[a[1]] = a[2][1:a[2].find(')')]
else:
mot... | 88e42b84314593a965e7dd681ded612914e35629 | 3,650,449 |
import os
import sys
def get_files(search_glob):
""" Returns all files matching |search_glob|. """
recursive_glob = '**' + os.path.sep
if recursive_glob in search_glob:
if sys.version_info >= (3, 5):
result = iglob(search_glob, recursive=True)
else:
# Polyfill for recursive glob pattern matc... | 3e09c26b0e2a77f3c883fce048825af4c025d502 | 3,650,450 |
def pixellate_bboxes(im, bboxes, cell_size=(5,6), expand_per=0.0):
"""Pixellates ROI using Nearest Neighbor inerpolation
:param im: (numpy.ndarray) image BGR
:param bbox: (BBox)
:param cell_size: (int, int) pixellated cell size
:returns (numpy.ndarray) BGR image
"""
if not bboxes:
return im
elif not... | 8c028714467c350dfd799671b0b18739705393ba | 3,650,451 |
import sys
def in_ipython() -> bool:
"""try to detect whether we are in an ipython shell, e.g., a jupyter notebook"""
ipy_module = sys.modules.get("IPython")
if ipy_module:
return bool(ipy_module.get_ipython())
else:
return False | 7a6804b964bd7fbde6d5795da953954343575413 | 3,650,452 |
def StepToGeom_MakeHyperbola2d_Convert(*args):
"""
:param SC:
:type SC: Handle_StepGeom_Hyperbola &
:param CC:
:type CC: Handle_Geom2d_Hyperbola &
:rtype: bool
"""
return _StepToGeom.StepToGeom_MakeHyperbola2d_Convert(*args) | 6896b27c10526b3a7f1d5840a63209a6f30d163e | 3,650,453 |
def create_dict(local=None, field=None, **kwargs):
"""
以字典的形式从局部变量locals()中获取指定的变量
:param local: dict
:param field: str[] 指定需要从local中读取的变量名称
:param kwargs: 需要将变量指定额外名称时使用
:return: dict
"""
if field is None or local is None:
return {}
result = {k: v for k, v in local.items() ... | 19aceef7f648cc72f29fceba811085cde9d6d587 | 3,650,454 |
def sum_list_for_datalist(list):
"""
DB에 저장할 때, 기준일로부터 과거 데이터가 존재하지 않을 경우에는
0을 return 한다.
:param list:
:return: float or int
"""
mysum = 0
for i in range(0, len(list)):
if list[i] == 0:
return 0
mysum = mysum + list[i]
return mysum | bae8966f64c642176d92d31c27df691e0f255d6a | 3,650,455 |
def elu(x, alpha=1.):
"""Exponential linear unit.
Arguments:
x {tensor} -- Input float tensor to perform activation.
alpha {float} -- A scalar, slope of negative section.
Returns:
tensor -- Output of exponential linear activation
"""
return x * (x > 0) + alpha * (tf... | c40c7aa4a0553dc6b0b6c6dd9f583a701f022e70 | 3,650,456 |
def coalesce(*args):
"""
Compute the first non-null value(s) from the passed arguments in
left-to-right order. This is also known as "combine_first" in pandas.
Parameters
----------
*args : variable-length value list
Examples
--------
>>> import ibis
>>> expr1 = None
>>> ex... | 0fb1af5db75c7ad65f470e348d76d0f289ba5ff2 | 3,650,457 |
import json
def get_analysis(poem, operations, rhyme_analysis=False, alternative_output=False):
"""
View for /analysis that perform an analysis of poem running the different
operations on it.
:param poem: A UTF-8 encoded byte string with the text of the poem
:param operations: List of strings with... | 1f40376a4ecbbe6453caa909406f595707cc44be | 3,650,458 |
def get_detail_root():
"""
Get the detail storage path in the git project
"""
return get_root() / '.detail' | aa2c30ed839d32e084a11c52f17af621ecfb9011 | 3,650,459 |
def solve(strs, m, n):
"""
2D 0-1 knapsack
"""
def count(s):
m, n = 0, 0
for c in s:
if c == "0":
m += 1
elif c == "1":
n += 1
return m, n
dp = []
for _ in range(m + 1):
dp.append([0] * (n + 1))
for s ... | 3fb2b16fc9059227c0edce1199269988d18cb908 | 3,650,460 |
def bk_category_chosen_category():
"""Returns chosen category for creating bk_category object."""
return "Bread" | cbf1c933e5c2b69214e828afaab5babdba61dca8 | 3,650,461 |
import math
def apply_weights(
events,
total_num=1214165.85244438, # for chips_1200
nuel_frac=0.00003202064566, # for chips_1200
anuel_frac=0.00000208200747, # for chips_1200
numu_frac=0.00276174709613, # for chips_1200
anumu_frac=0.00006042213136, # for chips_1200
cosmic_frac=0.99714... | 81f35a51b3d28577204087511f9c405ff56afaaa | 3,650,462 |
def _pipe_line_with_colons(colwidths, colaligns):
"""Return a horizontal line with optional colons to indicate column's
alignment (as in `pipe` output format)."""
segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)]
return "|" + "|".join(segments) + "|" | 76dd17c761e7adb06fe57c5210645a4fe3872374 | 3,650,463 |
from datetime import datetime
def convert_to_dates(start, end):
"""
CTD - Convert two strings to datetimes in format 'xx:xx'
param start: String - First string to convert
param end: String - Second string to convert
return: datetime - Two datetimes
"""
start = datetime.strptime(start, "%H:... | 53ffb9924d31385aac2eafc66fe7a6159e5a310d | 3,650,464 |
def flipud(m):
"""
Flips the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
Args:
m (Tensor): Input array.
Returns:
Tensor.
Raises:
TypeError: If the input is not a tensor.
Supported Platforms:
... | 06770689d23ca365fb57a6b9d1e74654b30ddaf2 | 3,650,465 |
def get_book_url(tool_name, category):
"""Get the link to the help documentation of the tool.
Args:
tool_name (str): The name of the tool.
category (str): The category of the tool.
Returns:
str: The URL to help documentation.
"""
prefix = "https://jblindsay.github.io/wbt_bo... | daf6c8e0832295914a03b002b548a82e2949612a | 3,650,466 |
import hashlib
def game_hash(s):
"""Generate hash-based identifier for a game account based on the
text of the game.
"""
def int_to_base(n):
alphabet = "BCDFGHJKLMNPQRSTVWXYZ"
base = len(alphabet)
if n < base:
return alphabet[n]
return int_to_base(n // base)... | c218a2607390916117921fe0f68fc23fedd51fc3 | 3,650,467 |
import math
def thumbnail_url(bbox, layers, qgis_project, style=None, internal=True):
"""Internal function to generate the URL for the thumbnail.
:param bbox: The bounding box to use in the format [left,bottom,right,top].
:type bbox: list
:param layers: Name of the layer to use.
:type layers: ba... | aa405eae72eacd7fd7b842bf569cc1ba3bc19315 | 3,650,468 |
def evaluate_prediction_power(df, num_days=1):
""""
Applies a shift to the model for the number of days given, default to 1, and feed the data to
a linear regression model. Evaluate the results using score and print it.
"""
scores = {}
print "Num days: {}".format(range(num_days))
for... | d4e91c8eb656fea8fce16cc16eb1588415c80849 | 3,650,469 |
def get_select_file_dialog_dir():
""""
Return the directory that should be displayed by default
in file dialogs.
"""
directory = CONF.get('main', 'select_file_dialog_dir', get_home_dir())
directory = directory if osp.exists(directory) else get_home_dir()
return directory | 9ae485caf5c5162e0b0e4082cee3e99925861717 | 3,650,470 |
import os
def get_photo_filesystem_path(photos_basedir, album_name, filename):
"""
Gets location of photo on filesystem, e.g.:
/some/dir/album/photo.jpg
:param album_name:
:param filename:
:return:
"""
return os.path.join(photos_basedir, get_photo_filesystem_relpath(album_name, filenam... | 6bd754b31def01cf5b403bc924720efe999816dc | 3,650,471 |
import os
import imp
import random
from typing import OrderedDict
def getAdminData(self):
"""
Deliver admin content of module alarms (ajax)
:return: rendered template as string or json dict
"""
if request.args.get('action') == 'upload':
if request.files:
ufile = request.files[... | 38669746fe0b5436827999b51a4a57a3f294a76c | 3,650,472 |
def join_collections(sql_query: sql.SQLQuery) -> QueryExpression:
"""Join together multiple collections to return their documents in the response.
Params:
-------
sql_query: SQLQuery object with information about the query params.
Returns:
--------
An FQL query expression for joined and fi... | 62ad0cbad609e8218b4ac9d78f893fbcfc90618e | 3,650,473 |
def querylist(query, encoding='utf-8', errors='replace'):
"""Split the query component into individual `name=value` pairs and
return a list of `(name, value)` tuples.
"""
if query:
qsl = [query]
else:
return []
if isinstance(query, bytes):
QUERYSEP = (b';', b'&')
... | 25f726aa76c3b34a9aebc5e111b28162d0b91e3f | 3,650,474 |
def rotate_space_123(angles):
"""Returns the direction cosine matrix relating a reference frame B
rotated relative to reference frame A through the x, y, then z axes of
reference frame A (spaced fixed rotations).
Parameters
----------
angles : numpy.array or list or tuple, shape(3,)
Thr... | f62ac16e63591c4852681479ab9d39227bad3dfc | 3,650,475 |
import logging
import os
def parse_arguments():
"""Parse and return the command line argument dictionary object
"""
parser = ArgumentParser("CIFAR-10/100 Training")
_verbosity = "INFO"
parser.add_argument(
"-v",
"--verbosity",
type=str.upper,
choices=logging._nameTo... | 77264dfc1540b47835daf8bd5674484adc0a1d8e | 3,650,476 |
def get_tac_resource(url):
"""
Get the requested resource or update resource using Tacoma account
:returns: http response with content in xml
"""
response = None
response = TrumbaTac.getURL(url, {"Accept": "application/xml"})
_log_xml_resp("Tacoma", url, response)
return response | 4d3fce0c7c65a880bf565c79285bcda081d4ef5a | 3,650,477 |
def cosweightlat(darray, lat1, lat2):
"""Calculate the weighted average for an [:,lat] array over the region
lat1 to lat2
"""
# flip latitudes if they are decreasing
if (darray.lat[0] > darray.lat[darray.lat.size -1]):
print("flipping latitudes")
darray = darray.sortby('lat')
r... | 87a8722d4d0b7004007fbce966a5ce99a6e51983 | 3,650,478 |
def _GetSoftMaxResponse(goal_embedding, scene_spatial):
"""Max response of an embeddings across a spatial feature map.
The goal_embedding is multiplied across the spatial dimensions of the
scene_spatial to generate a heatmap. Then the spatial softmax-pooled value of
this heatmap is returned. If the goal_embedd... | 547e61b403d99f2c0a4b5a0f78c03f7051a10d5c | 3,650,479 |
def summarize_star(star):
"""return one line summary of star"""
if star.find('name').text[-2] == ' ':
name = star.find('name').text[-1]
else:
name = ' '
mass = format_star_mass_str(star)
radius = format_star_radius_str(star)
temp = format_body_temp_str(star)
metallicity = for... | f9860d742a646637e4b725e39151ed8f5e8adf0f | 3,650,480 |
def to_unicode(text, encoding='utf8', errors='strict'):
"""Convert a string (bytestring in `encoding` or unicode), to unicode."""
if isinstance(text, unicode):
return text
return unicode(text, encoding, errors=errors) | 1acb85930349832259e9309fed3669fbd1114cad | 3,650,481 |
def parse_pipfile():
"""Reads package requirements from Pipfile."""
cfg = ConfigParser()
cfg.read("Pipfile")
dev_packages = [p.strip('"') for p in cfg["dev-packages"]]
relevant_packages = [
p.strip('"') for p in cfg["packages"] if "nested-dataclasses" not in p
]
return relevant_packa... | 72f559193b77989afc3aa200b6806ef051280673 | 3,650,482 |
from typing import Mapping
def print_dist(d, height=12, pch="o", show_number=False,
title=None):
""" Printing a figure of given distribution
Parameters
----------
d: dict, list
a dictionary or a list, contains pairs of: "key" -> "count_value"
height: int
number of maximum lines f... | d6636edbca5b16de8984c36bf9533ae963e21e0e | 3,650,483 |
import os
import errno
def Per_sequence_quality_scores (file_path,output_dire, module):
""" Read Per sequence quality scores contents from a fastqc file and parses to output file.
Returns a list of data used to plot quality graph.
Data and genereted graphs are saved to output directory as pn... | fa8debfaa7adcb8d827efba929e009a07ec19ed4 | 3,650,484 |
def count_primes(num):
"""
Write a function that returns the number
of prime numbers that exist up to and including a given number
:param num: int
:return: int
"""
count = 0
lower = int(input())
upper = int(input())
for num in range(lower, upper + 1):
if num > 1:
... | 7a544265f3a7eca9118b0647bc8926c655cdb8ec | 3,650,485 |
def run_experiment(config):
"""
Run the experiment.
Args:
config: The configuration dictionary.
Returns:
The experiment result.
"""
return None | b12a8a5cbdb03d60ca618826f20c9a731a39fd2a | 3,650,486 |
def read_notification(notification_id):
"""Marks a notification as read."""
notification = Notification.query.get_or_404(notification_id)
if notification.recipient_email != current_user.email:
abort(401)
notification.is_read = True
db.session.add(notification)
db.session.commit()
ret... | b2d4066be7b202d680415831fa6d3aa60e2896dc | 3,650,487 |
def grayscale_blur(image):
"""
Convert image to gray and blur it.
"""
image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
image_gray = cv.blur(image_gray, (3, 3))
return image_gray | 4e8bf0479c653a3ed073481ad71e2530527ec4a3 | 3,650,488 |
import hmac
def calculate_stream_hmac(stream, hmac_key):
"""Calculate a stream's HMAC code with the given key."""
stream.seek(0)
hash_hmac = hmac.new(bytearray(hmac_key, "utf-8"), digestmod=HASH_FUNCTION)
while True:
buf = stream.read(4096)
if not buf:
break
hash_hm... | 35da77cc708b4dc8a256fbfcc012da8c68868c8c | 3,650,489 |
import os
def find(name, dir_path="." , p="r"):
"""
find(name: string, dirpath="." , p="r")
name: the name to find
dirpath: find in this directory
p = r recursive find sub dirs
"""
files = ls(dir_path, p)
ans = []
for fn in files:
head, tail = os.path.sp... | 5454a96cde6953f9d6112cdc3f4605dbf8ebf18c | 3,650,490 |
import re
def convert_tac(ThreeAddressCode):
"""Reads three adress code generated from parser and converts to TAC for codegen;
generates the three_addr_code along with leaders;
populates generate symbol table as per three_addr_code"""
for i in range(ThreeAddressCode.length()):
three_addr_inst... | 4a9408cfbd6b6f79a618b7eb89aa55e6aab25689 | 3,650,491 |
def is_english_score(bigrams, word):
"""Calculate the score of a word."""
prob = 1
for w1, w2 in zip("!" + word, word + "!"):
bigram = f"{w1}{w2}"
if bigram in bigrams:
prob *= bigrams[bigram] # / float(bigrams['total'] + 1)
else:
print("%s not found" % bigra... | 834e28a32806d0599f5df97d978bc6b9c1a51da7 | 3,650,492 |
def cat(fname, fallback=_DEFAULT, binary=True):
"""Return file content.
fallback: the value returned in case the file does not exist or
cannot be read
binary: whether to open the file in binary or text mode.
"""
try:
with open_binary(fname) if binary else open_text(fname) as f:... | b3f645d79607f1ed986fe76aa20689d0860ef9ca | 3,650,493 |
import os
import json
def _get_from_url(url):
"""
Note: url is in format like this(following OQMD RESTful API) and the result format should be set to json:
http://oqmd.org/oqmdapi/formationenergy?fields=name,entry_id,delta_e&filter=stability=0&format=json
Namely url should be in the form sup... | 3860ca4b73eb6e4842ff7afd48485dd12d6d3e45 | 3,650,494 |
import codecs
def createStringObject(string):
"""
Given a string (either a ``str`` or ``unicode``), create a
:class:`ByteStringObject<ByteStringObject>` or a
:class:`TextStringObject<TextStringObject>` to represent the string.
"""
if isinstance(string, string_type):
return TextStringOb... | 07c0ca42faa2b68dc347e1edad7f70a07930d891 | 3,650,495 |
import win32com.client
def _get_windows_network_adapters():
"""Get the list of windows network adapters."""
wbem_locator = win32com.client.Dispatch('WbemScripting.SWbemLocator')
wbem_service = wbem_locator.ConnectServer('.', 'root\cimv2')
wbem_network_adapters = wbem_service.InstancesOf('Win32_Network... | 796c25089411633d11b28fdd9c23d900db7005f0 | 3,650,496 |
def project(dim, states):
"""Qiskit wrapper of projection operator.
"""
ket, bra = states
if ket in range(dim) and bra in range(dim):
return st.basis(dim, ket) * st.basis(dim, bra).dag()
else:
raise Exception('States are specified on the outside of Hilbert space %s' % states) | 351a190ec183264af58de15944efb3af255c5b03 | 3,650,497 |
def check_service_status(ssh_conn_obj, service_name, status="running", device='server'):
"""
Author: Chaitanya Vella ([email protected])
Function to check the service status
:param ssh_conn_obj:
:param service_name:
:param status:
:return:
"""
st.log("##### Checking ... | d8f2a9be7a784ad874d218601fdc043babdafe6e | 3,650,498 |
def _persist_block(block_node, block_map):
"""produce persistent binary data for a single block
Children block are assumed to be already persisted and present in
block_map.
"""
data = tuple(_to_value(v, block_map) for v in block_node)
return S_BLOCK.pack(*data) | 2fb97099135fe931d1d387ed616b152ed7c28b34 | 3,650,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.