content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main():
"""Main function"""
parser = ArgumentParser()
parser.add_argument("config", help="json cluster configuration file")
parser.add_argument("pattern", help="Filename pattern to download")
args = parser.parse_args()
config = get_config(parser, args)
pattern = args.pattern
copy_fil... | 18,500 |
def make_object(page, d):
"""Object block
Block loads a Object Model (Wavefront) along with it's *.mtl file. PARAM1
must be equal to *.obj and *.mtl filename (use lowercase extension). Files
must share same filename and must be loaded in the media/document folder.
If PARAM2 is set to 'scale', objec... | 18,501 |
def read_xls_as_dict(filename, header="top"):
"""
Read a xls file as dictionary.
@param filename File name (*.xls or *.xlsx)
@param header Header position. Options: "top", "left"
@return Dictionary with header as key
"""
table = read_xls(filename)
if (header == "top... | 18,502 |
def check_hostgroup(zapi, region_name, cluster_id):
"""check hostgroup from region name if exists
:region_name: region name of hostgroup
:returns: true or false
"""
return zapi.hostgroup.exists(name="Region [%s %s]" % (region_name, cluster_id)) | 18,503 |
def matlab_to_tt(ttemps, eng, is_orth=True, backend="numpy", mode="l"):
"""Load matlab.object representing TTeMPS into Python as TT"""
_, f = tempfile.mkstemp(suffix=".mat")
eng.TTeMPS_to_Py(f, ttemps, nargout=0)
tt = load_matlab_tt(f, is_orth=is_orth, mode=mode, backend=backend)
return tt | 18,504 |
def encode_mecab(tagger, string):
"""
string을 mecab을 이용해서 형태소 분석
:param tagger: 형태소 분석기 객체
:param string: input text
:return tokens: 형태소 분석 결과
:return indexs: 띄어쓰기 위치
"""
string = string.strip()
if len(string) == 0:
return [], []
words = string.split()
nodes = tagger.... | 18,505 |
def __vector__init__(self, obj=None):
"""Initializes the vector.
Argument 'obj':
If 'obj' is an integer, the vector is initialized as a vector of
'obj' elements. If 'obj' is a Python sequence. The vector is
initialized as an equivalence of 'obj' by invoking self.fromlist().
"""... | 18,506 |
def nutrient_limited_growth(X,idx_A,idx_B,growth_rate,half_saturation):
""" non-linear response with respect to *destination/predator* compartment
Similar to holling_type_II and is a reparameterization of holling II.
The response with respect to the origin compartment 'B' is approximately
linear for s... | 18,507 |
def aes128_decrypt(AES_KEY, _data):
"""
AES 128 位解密
:param requestData:
:return:
"""
# 秘钥实例
newAes = getAesByKey(AES_KEY)
# 解密
data = newAes.decrypt(_data)
rawDataLength = len(data)
# 剔除掉数据后面的补齐位
paddingNum = ord(data[rawDataLength - 1])
if paddingNum... | 18,508 |
def db(app):
"""Yield a database for the tests."""
_db.app = app
with app.app_context():
_db.create_all()
yield _db
# Explicitly close DB connection
_db.session.close()
_db.drop_all() | 18,509 |
def generate_lists(project_id):
"""takes a scopus facettes export and extracts the two columns for the most common journals and the moste common
keywords. writes the list to the two files 'keywords_facettes.txt and journal_facettes.txt"""
with app.app_context():
location = app.config.get("LIBINTEL_D... | 18,510 |
def test_finish_secret_finished():
""" Test that it doesn't update the secret if it's already AWSCURRENT"""
mock_secrets = Mock()
token = 'ver1'
mock_secrets.describe_secret.return_value = {
'VersionIdsToStages': {
'ver1': ['AWSCURRENT'],
'ver2': ['AWSPENDING']
}
... | 18,511 |
def human_readable_size(size, decimals=1):
"""Transform size in bytes into human readable text."""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if size < 1000:
break
size /= 1000
return f"{size:.{decimals}f} {unit}" | 18,512 |
def spec_save_pkl_matrix(w, f, filout, verb=False):
"""
Save pickle
"""
tpl = {'w': w, 'f': f}
with open(filout, 'wb') as handle:
pickle.dump(tpl, handle, protocol=pickle.HIGHEST_PROTOCOL)
# with open('filename.pickle', 'rb') as handle:
# b = pickle.load(handle)
if verb: p... | 18,513 |
def generichash_blake2b_final(statebuf, digest_size):
"""Finalize the blake2b hash state and return the digest.
:param statebuf:
:type statebuf: bytes
:param digest_size:
:type digest_size: int
:return: the blake2 digest of the passed-in data stream
:rtype: bytes
"""
_digest = ffi.... | 18,514 |
def walker_input_formatter(t, obs):
"""
This function formats the data to give as input to the controller
:param t:
:param obs:
:return: None
"""
return obs | 18,515 |
def test_parse_nextflow_exec_report_html():
"""Test finding and parsing of Nextflow workflow execution HTML report"""
path = exec_report.find_exec_report(dirpath)
assert str(path.absolute()) == str(input_html.absolute())
info = exec_report.get_info(dirpath)
assert isinstance(info, exec_report.Nextfl... | 18,516 |
def outpost_controller(
self: MonitoredTask, outpost_pk: str, action: str = "up", from_cache: bool = False
):
"""Create/update/monitor/delete the deployment of an Outpost"""
logs = []
if from_cache:
outpost: Outpost = cache.get(CACHE_KEY_OUTPOST_DOWN % outpost_pk)
LOGGER.debug("Getting o... | 18,517 |
def build_url_base(url):
"""Normalize and build the final url
:param url: The given url
:type url: str
:return: The final url
:rtype: str
"""
normalize = normalize_url(url=url)
final_url = "{url}/api".format(url=normalize)
return final_url | 18,518 |
def build_decoder(
latent_dim: int,
input_shape: Tuple,
encoder_shape: Tuple,
filters: List[int],
kernels: List[Tuple[int, int]],
strides: List[int]
) -> Model:
"""Return decoder model.
Parameters
----------
latent_dim:int,
Size of the latent vector.
encoder_shape:Tu... | 18,519 |
def execute_with_python_values(executable, arguments=(), backend=None):
"""Execute on one replica with Python values as arguments and output."""
backend = backend or get_local_backend()
def put(arg):
return Buffer.from_pyval(
arg, device=executable.DeviceOrdinals()[0], backend=backend)
arguments ... | 18,520 |
def update_kubeproxy(token, ca, master_ip, api_port, hostname_override):
"""
Configure the kube-proxy
:param token: the token to be in the kubeconfig
:param ca: the ca
:param master_ip: the master node IP
:param api_port: the API server port
:param hostname_override: the hostname override i... | 18,521 |
def vm_create(ctx, name, uuid, vport_id, mac, ipaddress):
"""Create VM for a given ID"""
params = {'name': name,
'UUID': uuid,
'interfaces': [{'VPortID': vport_id,
'MAC': mac,
'IPAddress': ipaddress}]}
result = ctx.obj['... | 18,522 |
def run_cmd(cmd, cwd=None):
"""
Runs the given command and return the output decoded as UTF-8.
"""
return subprocess.check_output(cmd,
cwd=cwd, encoding="utf-8", errors="ignore") | 18,523 |
def access_some_envs():
"""
A simple function used to demonstrate accessing environment
vars from within the contect of a virtual environment handled by Poetry
"""
my_env_var = os.environ.get("MY_ENV_VAR")
print(my_env_var) | 18,524 |
def _get_label_members(X, labels, cluster):
"""
Helper function to get samples of a specified cluster.
Args:
X (np.ndarray): ndarray with dimensions [n_samples, n_features]
data to check validity of clustering
labels (np.array): clustering assignments for data X
cluster (... | 18,525 |
def get_spectrum_by_close_values(
mz: list,
it: list,
left_border: float,
right_border: float,
*,
eps: float = 0.0
) -> Tuple[list, list, int, int]:
"""int
Function to get segment of spectrum by left and right
border
:param mz: m/z array
:param it: it intensities
:param l... | 18,526 |
def speak():
"""API call to have BiBli speak a phrase."""
subprocess.call("amixer sset Master 100%", shell=True)
data = request.get_json()
lang = data["lang"] if "lang" in data and len(data["lang"]) else "en"
#espeak.set_parameter(espeak.Parameter.Rate, 165)
#espeak.set_parameter(espeak.Paramete... | 18,527 |
def refresh_wrapper(trynum, maxtries, *args, **kwargs):
"""A @retry argmod_func to refresh a Wrapper, which must be the first arg.
When using @retry to decorate a method which modifies a Wrapper, a common
cause of retry is etag mismatch. In this case, the retry should refresh
the wrapper before attemp... | 18,528 |
def compute_frames_per_animation(
attacks_per_second: float,
base_animation_length: int,
speed_coefficient: float = 1.0,
engine_tick_rate: int = 60,
is_channeling: bool = False) -> int:
"""Calculates frames per animation needed to resolve a certain ability at attacks_pe... | 18,529 |
def pad_rect(rect, move):
"""Returns padded rectangles given specified padding"""
if rect['dx'] > 2:
rect['x'] += move[0]
rect['dx'] -= 1*move[0]
if rect['dy'] > 2:
rect['y'] += move[1]
rect['dy'] -= 1*move[1]
return rect | 18,530 |
async def yes_no(ctx: commands.Context,
message: str="Are you sure? Type **yes** within 10 seconds to confirm. o.o"):
"""Yes no helper. Ask a confirmation message with a timeout of 10 seconds.
ctx - The context in which the question is being asked.
message - Optional messsage that the ques... | 18,531 |
def test_read_source_spaces():
"""Test reading of source space meshes
"""
src = read_source_spaces(fname, add_geom=True)
# 3D source space
lh_points = src[0]['rr']
lh_faces = src[0]['tris']
lh_use_faces = src[0]['use_tris']
rh_points = src[1]['rr']
rh_faces = src[1]['tris']
rh_u... | 18,532 |
def test_activity_history(api):
"""
Test that the FacebookAPI class can retrieve account activity history.
"""
activity_history = api.get_ad_activity_history(
start_date=datetime.utcnow() - timedelta(days=7),
end_date=datetime.utcnow()
)
assert activity_history is not None | 18,533 |
def __validation(size: int, it1: int, it2: int, it3: int, it4: int) -> bool:
""" Проверка на корректность тура
size: размер маршрута
it1, it2, it3, it4: индексы городов: t1, t2i, t2i+1, t2i+2
return: корректен или нет
"""
return between(size, it1, it3, it4) and between(size, it4, it2, it1) | 18,534 |
def get_type_associations(base_type, generic_base_type): # type: (t.Type[TType], t.Type[TValue]) -> t.List[t.Tuple[t.Type[TValue], t.Type[TType]]]
"""Create and return a list of tuples associating generic_base_type derived types with a corresponding base_type derived type."""
return [item for item in [(get_gen... | 18,535 |
def df_to_asc(dfname, outname):
"""
:param outname:
:param dfname:
:return:
"""
dfname.to_csv(outname, sep='\t', encoding='utf-8', index=False) | 18,536 |
def identify_empty_droplets(data, min_cells=3, **kw):
"""Detect empty droplets using DropletUtils
"""
import rpy2.robjects as robj
from rpy2.robjects import default_converter
from rpy2.robjects.packages import importr
import anndata2ri
from rpy2.robjects.conversion import localconverter
... | 18,537 |
def catalog_category_RSS(category_id):
"""
Return an RSS feed containing all items in the specified category_id
"""
items = session.query(Item).filter_by(
category_id=category_id).all()
doc = jaxml.XML_document()
doc.category(str(category_id))
for item in items:
doc.... | 18,538 |
def get_caller_name(N=0, allow_genexpr=True):
"""
get the name of the function that called you
Args:
N (int): (defaults to 0) number of levels up in the stack
allow_genexpr (bool): (default = True)
Returns:
str: a function name
CommandLine:
python -m utool.util_dbg... | 18,539 |
def display_pos(output):
"""Render the `output` of a POS tagging model on the screen.
This makes use of the excellent visualization tools in spaCy's dispaCy.
"""
tokens = output["words"]
text = " ".join(tokens)
tags = [tag.upper() for tag in output["tags"]]
labels = [label.upper() for l... | 18,540 |
def make_build_dir(prefix=""):
"""Creates a temporary folder with given prefix to be used as a build dir.
Use this function instead of tempfile.mkdtemp to ensure any generated files
will survive on the host after the FINN Docker container exits."""
try:
inst_prefix = os.environ["FINN_INST_NAME"]... | 18,541 |
def unblock_node_port_random(genesis_file: str,
transactions: Union[str,int] = None,
pause_before_synced_check: Union[str,int] = None, best_effort: bool = True,
did: str = DEFAULT_CHAOS_DID, seed: str = DEFAULT_CHAOS_SEED,
wallet_name: str = DEFAULT_CHAOS_WALLET_NAME,
wallet_key: str = DEFAULT_CHAOS... | 18,542 |
def main():
"""Main method of Ansible module
"""
result = dict(
changed=False,
msg='',
specs=[]
)
module = AnsibleModule(
argument_spec=yaml.safe_load(DOCUMENTATION)['options'],
supports_check_mode=True,
)
# Set payload defaults
result['failed'] = ... | 18,543 |
def create_user(
*,
db: Session = Depends(deps.get_db),
user_in: schema_in.UserCreateIn,
) -> Any:
"""
Create new user.
"""
new_user = User(**{k: v for k, v in user_in.dict().items() if k != 'password'})
new_user.hashed_password = get_password_hash(user_in.password)
new_use... | 18,544 |
def number_format(interp, num_args, number, decimals=0, dec_point='.',
thousands_sep=','):
"""Format a number with grouped thousands."""
if num_args == 3:
return interp.space.w_False
ino = int(number)
dec = abs(number - ino)
rest = ""
if decimals == 0 and dec >= 0.5:
... | 18,545 |
def _serialization_expr(value_expr: str, a_type: mapry.Type,
py: mapry.Py) -> Optional[str]:
"""
Generate the expression of the serialization of the given value.
If no serialization expression can be generated (e.g., in case of nested
structures such as arrays and maps), None is... | 18,546 |
def get_init_hash():
""" 获得一个初始、空哈希值 """
return imagehash.ImageHash(np.zeros([8, 8]).astype(bool)) | 18,547 |
def get_vertex_between_points(point1, point2, at_distance):
"""Returns vertex between point1 and point2 at a distance from point1.
Args:
point1: First vertex having tuple (x,y) co-ordinates.
point2: Second vertex having tuple (x,y) co-ordinates.
at_distance: A distance at which to locate... | 18,548 |
def disable_cache(response: Response) -> Response:
"""Prevents cached responses"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response | 18,549 |
def get_dir(src_point, rot_rad):
"""Rotate the point by `rot_rad` degree."""
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
src_result = [0, 0]
src_result[0] = src_point[0] * cs - src_point[1] * sn
src_result[1] = src_point[0] * sn + src_point[1] * cs
return src_result | 18,550 |
def sparse_gauss_seidel(A,b,maxiters=100,tol=1e-8):
"""Returns the solution to the system Ax = b using the Gauss-Seidel method.
Inputs:
A (array) - 2D scipy.sparse matrix
b (array) - 1D NumPy array
maxiters (int, optional) - maximum iterations for algorithm to perform.
tol (floa... | 18,551 |
def delete_user(user_id):
"""Delete user from Users database and their permissions
from SurveyPermissions and ReportPermissions.
:Route: /api/user/<int:user_id>
:Methods: DELETE
:Roles: s
:param user_id: user id
:return dict: {"delete": user_id}
"""
user = database.get_user(user_id... | 18,552 |
def selectTopFive(sortedList):
"""
从sortedList中选出前五,返回对应的名字与commit数量列成的列表
:param sortedList:按值从大到小进行排序的authorDict
:return:size -- [commit数量]
labels -- [名字]
"""
size = []
labels = []
for i in range(5):
labels.append(sortedList[i][0])
size.append(sortedList[i][1... | 18,553 |
def get_license(file):
"""Returns the license from the input file.
"""
# Collect the license
lic = ''
for line in file:
if line.startswith('#include') or line.startswith('#ifndef'):
break
else:
lic += line
return lic | 18,554 |
def quote_query_string(chars):
"""
Multibyte charactor string is quoted by double quote.
Because english analyzer of Elasticsearch decomposes
multibyte character strings with OR expression.
e.g. 神保町 -> 神 OR 保 OR 町
"神保町"-> 神保町
"""
if not isinstance(chars, unicode):
chars = c... | 18,555 |
def change_team():
"""Change the value of the global variable team."""
# Use team in global scope
global team
# Change the value of team in global: team
team = "justice league" | 18,556 |
def run_generate_per_camera_videos(data_root: str, output_dir: str, num_workers: int) -> None:
"""Click entry point for ring camera .mp4 video generation."""
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
generate_per_camera_videos(data_root=Path(data_root), output_dir=Path(output_dir), num_wor... | 18,557 |
def copy_params(params: ParamsDict) -> ParamsDict:
"""copy a parameter dictionary
Args:
params: the parameter dictionary to copy
Returns:
the copied parameter dictionary
Note:
this copy function works recursively on all subdictionaries of the params
dictionary but does... | 18,558 |
def ConvertRaster2LatLong(InputRasterFile,OutputRasterFile):
"""
Convert a raster to lat long WGS1984 EPSG:4326 coordinates for global plotting
MDH
"""
# import modules
import rasterio
from rasterio.warp import reproject, calculate_default_transform as cdt, Resampling
# read the sou... | 18,559 |
def create_feature_from_school(train_df, test_df):
"""
Since schools generally play an important role in house hunting, let us create some variables around school.
"""
train_df["ratio_preschool"] = train_df["children_preschool"] / train_df["preschool_quota"].astype("float")
test_df["ratio_presch... | 18,560 |
def watch_list(request):
"""
Get watchlist or create a watchlist, or delete from watchlist
:param request:
:return:
"""
if request.method == 'GET':
watchlist = WatchList.objects.filter(user=request.user)
serializer = WatchListSerializer(watchlist, many=True)
return Respon... | 18,561 |
def write_coordinate_volumes(reference_filename,
output_x_filename,
output_y_filename,
output_z_filename):
"""Write 3 coordinate volumes in the geometry of a reference volume."""
reference_header = read_reference_header(refer... | 18,562 |
async def user_has_pl(api, room_id, mxid, pl=100):
"""
Determine if a user is admin in a given room.
"""
pls = await api.get_power_levels(room_id)
users = pls["users"]
user_pl = users.get(mxid, 0)
return user_pl == pl | 18,563 |
def ram_plot(df, ax, marker, markersize=None, markerfacecolor=None, color='None', linestyle='None', linewidth=None,
mew=None):
"""The function was named after Ram Yazdi that helped to solve this challenge in a dark hour"""
bars = df['topic'].unique()
mapping_name_to_index = {name: index for ind... | 18,564 |
def _set_read_options(request, eventual, transaction_id):
"""Validate rules for read options, and assign to the request.
Helper method for ``lookup()`` and ``run_query``.
:raises: :class:`ValueError` if ``eventual`` is ``True`` and the
``transaction_id`` is not ``None``.
"""
if eventu... | 18,565 |
def get_cgi_parameter_bool_or_default(form: cgi.FieldStorage,
key: str,
default: bool = None) -> Optional[bool]:
"""
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``,
other string = ``False``, absent/zero-length stri... | 18,566 |
def loss_function_1(y_true, y_pred):
""" Probabilistic output loss """
a = tf.clip_by_value(y_pred, 1e-20, 1)
b = tf.clip_by_value(tf.subtract(1.0, y_pred), 1e-20, 1)
cross_entropy = - tf.multiply(y_true, tf.log(a)) - tf.multiply(tf.subtract(1.0, y_true), tf.log(b))
cross_entropy = tf.reduce_mean(cr... | 18,567 |
def invert(seq: Sequence, axis_pitch=None) -> Iterator[Event]:
"""Invert the pitches about a given axis (mirror it
upside down). If axis_pitch is not given, invert about
the first pitch in the sequence.
"""
if axis_pitch is None:
try:
evt = next(seq.events)
except StopIte... | 18,568 |
def sanitize_for_json(tag):
"""eugh the tags text is in comment strings"""
return tag.text.replace('<!--', '').replace('-->', '') | 18,569 |
def load_data_and_labels(dataset_name):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
for i in [1]:
# Load data from files
positive_examples = list(open('data/'+str(dataset_name)+'/'+str(dataset_name)+'... | 18,570 |
def tileswrap(ihtORsize, numtilings, floats, wrapwidths, ints=[], readonly=False):
"""Returns num-tilings tile indices corresponding to the floats and ints, wrapping some floats"""
qfloats = [floor(f * numtilings) for f in floats]
Tiles = []
for tiling in range(numtilings):
tilingX2 = tiling * 2... | 18,571 |
def coerce(data, egdata):
"""Coerce a python object to another type using the AE coercers"""
pdata = pack(data)
pegdata = pack(egdata)
pdata = pdata.AECoerceDesc(pegdata.type)
return unpack(pdata) | 18,572 |
def setup_logging(level):
"""Setups a basic logger for this app.
Args:
level (str): What the log level should be set to i.e. INFO.
"""
logging.basicConfig(
stream=sys.stdout,
level=level,
format="%(asctime)s.%(msecs)03d %(levelname)s %(module)s: %(message)s",
da... | 18,573 |
def distorted_inputs(data_dir, batch_size, num_train_files, train_num_examples, boardsize, num_channels):
"""Construct distorted input for training using the Reader ops.
Args:
data_dir: Path to the data directory.
batch_size: Number of images per batch.
Returns:
images: Images. 4D tensor... | 18,574 |
def _write_mkaero1(model: Union[BDF, OP2Geom], name: str,
mkaero1s: List[MKAERO1], ncards: int,
op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int:
"""writes the MKAERO1
data = (1.3, -1, -1, -1, -1, -1, -1, -1,
0.03, 0.04, 0.05, -1, -1, -1, -1,... | 18,575 |
def _mesh_obj_large():
"""build a large, random mesh model/dataset"""
n_tri, n_pts = 400, 1000
node = np.random.randn(n_pts, 2)
element = np.array([np.random.permutation(n_pts)[:3] for _ in range(n_tri)])
perm = np.random.randn(n_tri)
np.random.seed(0)
el_pos = np.random.permutation(n_pts)[:... | 18,576 |
def cursor():
"""Return a database cursor."""
return util.get_dbconn("mesosite").cursor() | 18,577 |
def custom_field_check(issue_in, attrib, name=None):
""" This method allows the user to get in the comments customfiled that are not common
to all the project, in case the customfiled does not existe the method returns an
empty string.
"""
if hasattr(issue_in.fields, attrib):
value = str(eva... | 18,578 |
def validate_all_files(*yaml_files):
"""
Validate each YAML file
"""
for yaml_file in yaml_files:
validate_regex_in_yaml_file(yaml_file) | 18,579 |
def header(text, color='black', gen_text=None):
"""Create an HTML header"""
if gen_text:
raw_html = f'<h1 style="margin-top:16px;color: {color};font-size:54px"><center>' + str(
text) + '<span style="color: red">' + str(gen_text) + '</center></h1>'
else:
raw_html = f'<h1 style="m... | 18,580 |
def test_06() -> None:
""" Runs OK """
run(SAMPLE2, 5) | 18,581 |
def replace_dataset_targets(dataset, num_classes):
"""
Replaces dataset targets with random targets. These random targets are also broadcasted to other processes from
the main process when using distributed training.
:param dataset: dataset whose targets are to be replaced.
:param num_classes: numbe... | 18,582 |
def block_pose(detection, block_size=0.05):
# type: (AprilTagDetection, float) -> PoseStamped
"""Given a tag detection (id == 0), return the block's pose. The block pose
has the same orientation as the tag detection, but it's position is
translated to be at the cube's center.
Args:
detectio... | 18,583 |
async def batch_omim_similarity(
data: models.POST_OMIM_Batch,
method: str = 'graphic',
combine: str = 'funSimAvg',
kind: str = 'omim'
) -> dict:
"""
Similarity score between one HPOSet and several OMIM Diseases
"""
other_sets = []
for other in data.omim_diseases:
try:
... | 18,584 |
def test_pylint_libs(libfiles_parametrize):
""" Run pylint on each lib """
command = "pylint --rcfile='{}' '{}'".format(os.path.join(pytest.sfauto_dir, "pylintrc"), libfiles_parametrize)
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)... | 18,585 |
def vector(*,
unit: _Union[_cpp.Unit, str, None] = default_unit,
value: _Union[_np.ndarray, list]):
"""Constructs a zero dimensional :class:`Variable` holding a single length-3
vector.
:param value: Initial value, a list or 1-D numpy array.
:param unit: Optional, unit. Default=di... | 18,586 |
def read_lidar(filename, **kwargs):
"""Read a LAS file.
Args:
filename (str): Path to a LAS file.
Returns:
LasData: The LasData object return by laspy.read.
"""
try:
import laspy
except ImportError:
print(
"The laspy package is required for this func... | 18,587 |
async def async_setup_entry(
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], bool], None],
) -> None:
"""Set up WLED sensor based on a config entry."""
wled: WLED = hass.data[DOMAIN][entry.entry_id][DATA_WLED_CLIENT]
sensors = [
WLEDEstimatedCurr... | 18,588 |
def get_gene_starting_with(gene_symbol: str, verbose: bool = True):
""" get the genes that start with the symbol given
Args:
- gene_symbol: str
- verbose: bool
Returns:
- list of str
- None
"""
gene_symbol = gene_symbol.strip().upper()
ext = "search/symbol/{}*".format(gene_sy... | 18,589 |
def initialize_engine(ip, port, username, password, project_name):
"""Initializes the calm dsl engine"""
set_server_details(ip, port, username, password, project_name)
init_db()
sync_cache()
click.echo("\nHINT: To get started, follow the 3 steps below:")
click.echo("1. Initialize an example bl... | 18,590 |
def gen_timestamp():
"""
Generates a unique (let's hope!), whole-number, unix-time timestamp.
"""
return int(time() * 1e6) | 18,591 |
def learningCurve(X, y, Xval, yval, Lambda):
"""returns the train and
cross validation set errors for a learning curve. In particular,
it returns two vectors of the same length - error_train and
error_val. Then, error_train(i) contains the training error for
i examples (and similarly for error_val(i... | 18,592 |
def decode_xml(text):
"""Parse an XML document into a dictionary. This assume that the
document is only 1 level, i.e.:
<top>
<child1>content</child1>
<child2>content</child2>
</top>
will be parsed as: child1=content, child2=content"""
xmldoc = minidom.parseString(text)
retur... | 18,593 |
def _qcheminputfile(ccdata, templatefile, inpfile):
"""
Generate input file from geometry (list of lines) depending on job type
:ccdata: ccData object
:templatefile: templatefile - tells us which template file to use
:inpfile: OUTPUT - expects a path/to/inputfile to write inpfile
""... | 18,594 |
def arrangements(ns):
"""
prime factors of 19208 lead to the "tribonacci" dict;
only needed up to trib(4)
"""
trib = {0: 1, 1: 1, 2: 2, 3: 4, 4: 7}
count = 1
one_seq = 0
for n in ns:
if n == 1:
one_seq += 1
if n == 3:
count *= trib[one_seq]
one_seq = 0
return count
# # one-liner...
# return r... | 18,595 |
def vtpnt(x, y, z=0):
"""坐标点转化为浮点数"""
return win32com.client.VARIANT (pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z)) | 18,596 |
def get_time_delta(pre_date: datetime):
"""
获取给定时间与当前时间的差值
Args:
pre_date:
Returns:
"""
date_delta = datetime.datetime.now() - pre_date
return date_delta.days | 18,597 |
def test_wfasnd_ndst_updatespl_1(plugin):
""" workflow as a node
workflow-node with one task,
splitter for node added after add
"""
wfnd = Workflow(name="wfnd", input_spec=["x"])
wfnd.add(add2(name="add2", x=wfnd.lzin.x))
wfnd.set_output([("out", wfnd.add2.lzout.out)])
# TODO: wi... | 18,598 |
def render_checkbox_list(soup_body: object) -> object:
"""As the chosen markdown processor does not support task lists (lists with checkboxes), this function post-processes
a bs4 object created from outputted HTML, replacing instances of '[ ]' (or '[]') at the beginning of a list item
with an unchecked box,... | 18,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.