content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import fnmatch
def get_user_id(gi,email):
"""
Get the user ID corresponding to a username email
Arguments:
gi (bioblend.galaxy.GalaxyInstance): Galaxy instance
email : email address for the user
Returns:
String: user ID, or None if no match.
"""
user_id = None
try:
... | 89b72a4291b789ab61f276a7e4563c17c2c4e4b7 | 20,700 |
import os
def get_tests_directory() -> str:
"""
Returns the path of the top level directory for tests.
Returns: The path of the top level directory for tests.
This is useful for constructing paths to the test files.
"""
module_file_path = os.path.abspath(__file__)
return os.path.dirname(m... | 35b445342ea6cf6c6f659118d32b0b8c9724a7e8 | 20,701 |
def ldns_pkt_size(*args):
"""LDNS buffer."""
return _ldns.ldns_pkt_size(*args) | 833223ed702fdee4525f0c330f4c803bd867daa3 | 20,702 |
def getUser(userID):
""" Takes a user ID as an argument and returns the user associated
with that ID.
Args:
userID -- The ID of a user stored in the Patrons table
"""
user = session.query(Patrons).filter_by(id = userID).one()
return user | 7da06a0baaef540826fd9e902129e1a625f5bfd9 | 20,703 |
import warnings
def guard_transform(transform):
"""Return an Affine transformation instance"""
if not isinstance(transform, Affine):
if tastes_like_gdal(transform):
warnings.warn(
"GDAL-style transforms are deprecated and will not "
"be supported in Rasterio... | 1c19f92331c0bb99841c86302c1c1d4c13a07649 | 20,704 |
import pandas
import math
def create_heatmap(piek_json,
antske_json,
output_path=None,
verbose=0):
"""
"""
# initialize dataframe
likert_values = [1, 2, 3, 4, 5, 6, 7]
df = pandas.DataFrame()
default_values = [None for _ in range(len(li... | 4e26331c3290d8282e98f7473cd7ee6ffbb46146 | 20,705 |
def get_classification_report(true_labels, pred_labels, labels=None, target_names=None, output_dict=False):
"""
true_labels = [0, 1, 2, 3, 4, 1] # Y
pred_labels = [0, 1, 1, 2, 2, 1] # X
target_names = ["A", "B", "C", "D", "E"]
out_result = get_classification_report(true_labels, pred_labels, target... | 37467891f004175ec228adac6ca1e1347c71ca15 | 20,706 |
import random
from sys import prefix
from datetime import datetime
import time
def generate_message(minutes_to_next=None):
"""
Using the list of exercises, this function generates a new exercise message. Optionally it
takes a minutes_to_next parameter which it uses to add an indication of when the next ex... | 2bbf7d4a9a1baa7f7239d3d9758d96b14474b484 | 20,707 |
def yx():
"""
测试印象笔记服务
:return:
"""
client = EvernoteClient(token=dev_token,sandbox=False)
client.service_host = 'app.yinxiang.com'
userStore = client.get_user_store()
user = userStore.getUser()
print user
return "yx" | 9bfdcccddfc9a99d445deea5d920256e19e0bcc5 | 20,708 |
def generate_frequency_result_for_time_precedence_query_workload(config_map, time_interval, spatial_interval):
"""
:param config_map:
:param time_interval:
:param spatial_interval:
:return:
"""
frequency_result = {}
for key in config_map.keys():
region_param_list = config_map.g... | c477acb9652ea40f498a2d92aa91840e868b1736 | 20,709 |
def delete(request):
"""退出登录,清除session"""
request.session.flush()
return redirect('/login/') | 0f10480f3259c52bc1a203ccd9e9746cdf9776ed | 20,710 |
import warnings
def acovf(x, unbiased=False, demean=True, fft=None, missing='none', nlag=None):
"""
Autocovariance for 1D
Parameters
----------
x : array
Time series data. Must be 1d.
unbiased : bool
If True, then denominators is n-k, otherwise n
demean : bool
If T... | c318d80a13bcb4f87117ce84351001a8f320c6d0 | 20,711 |
import re
def ParseTimeCommandResult(command_result):
"""Parse command result and get time elapsed.
Args:
command_result: The result after executing a remote time command.
Returns:
Time taken for the command.
"""
time_data = re.findall(r'real\s+(\d+)m(\d+.\d+)', command_result)
time_in_seconds... | fc92d4b996716ddb2253bf4eb75ed9860c43b2d7 | 20,712 |
import os
import tempfile
def _GetTmpDir():
"""Determines the right temporary dir to use and creates it if necessary.
Returns:
path to temporary directory.
"""
tmp_dir = FLAGS.emulator_tmp_dir or os.path.abspath(
tempfile.mkdtemp('android-emulator-launch'))
if not os.path.exists(tmp_dir):
os... | 90526a849b3967f733369c7ab3b7d4d3a2f94658 | 20,713 |
import requests
import json
def _push_aol_to_dativetop_server(aol):
"""Make a PUT request to the DativeTop server in order to push ``aol`` on to
the server's AOL.
"""
try:
resp = requests.put(c.DATIVETOP_SERVER_URL, json=aol)
resp.raise_for_status()
return resp.json(), None
... | 19581efa535e4022fd844292576f56532e9b0cdd | 20,714 |
def dual_single(lag_mul: float, val: np.ndarray, count: np.ndarray) -> float:
"""Weighted average minus 1 for estimate of F_0.
Computes phi_n(lambda_n) - 1.
Args:
lag_mul: The normalized Lagrangian multiplier. Must be
strictly between 0 and 1.
val: Likelihood values (excluding... | 699b33b824e8a0cae1b35f1290281a08a910f7ef | 20,715 |
def _execute(
repository_ctx,
cmdline,
error_msg = None,
error_details = None,
empty_stdout_fine = False,
environment = {}):
"""Executes an arbitrary shell command.
Args:
repository_ctx: the repository_ctx object
cmdline: list of strings, the command ... | 1d1a291380ca540ab7ec34bbcec4780b695cc0d1 | 20,716 |
import warnings
def parse_tagged_block(block):
"""
Replaces "data" attribute of a block with parsed data structure
if it is known how to parse it.
"""
key = block.key.decode('ascii')
if not TaggedBlock.is_known(key):
warnings.warn("Unknown tagged block (%s)" % block.key)
decoder =... | 2c06fb4a20e05690a3b72b85dd09b5a2f04a6513 | 20,717 |
import numpy
def floatX(arr):
"""Converts data to a numpy array of dtype ``theano.config.floatX``.
Parameters
----------
arr : array_like
The data to be converted.
Returns
-------
numpy ndarray
The input array in the ``floatX`` dtype configured for Theano.
If `arr` ... | 261064f1685b4e393d493c5cc657b1ab76d5e89f | 20,718 |
def getNumberOfPublicIp():
"""Get the total number of public IP
return: (long) Number of public IP
"""
#No need to calculate this constant everytime
return 3689020672
# Real implementation:
#ranges = getValidPublicIpRange()
#number_of_ip = 0
#for range in ranges:
# number_of_ip = number_of_ip + (r... | 79221376f64d0a44da06746bc28f0bb7db808b0f | 20,719 |
import os
def framework_find(fn, executable_path=None, env=None):
"""
Find a framework using dyld semantics in a very loose manner.
Will take input such as:
Python
Python.framework
Python.framework/Versions/Current
"""
error = None
try:
return dyld_find(fn, exe... | 63baebf968a78e39940fbb787c7d9abd0c638046 | 20,720 |
import sys
def find_modules(path):
"""
Funtion to list all the modules in a repository.
"""
modules = set()
packages = find_packages(path)
for pkg in packages:
modules.add(pkg)
pkgpath = path + "/" + pkg.replace(".", "/")
if sys.version_info.major == 2 or (
... | fe98c28b45e01317be2f732a32159bbbdaa4fcc0 | 20,721 |
def cart2sph(x, y, z):
"""
Convert Cartesian coordinates x, y, z
to conventional spherical coordinates r, p, a
:param x: Cartesian coordinate or vector x
:type x: float or np.ndarray
:param y: Cartesian coordinate or vector y
:type y: float or np.ndarray
:param z: Cartesian coordinates ... | 9487d44a8892f450a2920997f277f0f699a89e2d | 20,722 |
def hdfs_open(server, username, path, **args):
"""Read a file.
Returns a filelike object (specifically, an httplib response object).
"""
datanode_url = datanode_url(server, username, path, **args)
response = _datanode_request(server, username, 'GET', datanode_url)
if response.status == httplib... | 6ddc83d6d571d63ce5536f7c34a00c7c3b04f1fc | 20,723 |
def get_serv_loader(desc_file=SERVICES_FILE):
"""Get a ServiceLoader with service descriptions in the given file.
Uses a "singleton" when the file is `SERVICES_FILE`.
"""
global _serv_loader
if desc_file == SERVICES_FILE:
if _serv_loader is None:
with open(desc_file, "r") as fp:... | 3693b4fd11bc2efcd394eac94e6667b84d110b34 | 20,724 |
import socket
def check_reverse_lookup():
"""
Check if host fqdn resolves to current host ip
"""
try:
host_name = socket.gethostname().lower()
host_ip = socket.gethostbyname(host_name)
host_fqdn = socket.getfqdn().lower()
fqdn_ip = socket.gethostbyname(host_fqdn)
return host_ip == fqdn_ip
... | 4979ba32d03782258f322ec86b2cd1c24fb4de2c | 20,725 |
from pathlib import Path
def render_pages(site_data: SiteData) -> dict[Path, str]:
"""Create page content."""
homepage = (site_data.homepage, rendering.render_homepage(site_data))
record_pages = [
(page, rendering.render_record_page(site_data, uri))
for uri, page in site_data.record_pages.... | 7549e4687a5142b7cc0a4a8054a91fb00575bea6 | 20,726 |
import os
def download_file(clean_url, download_folder, downloaded_file_name, depth=0, error_output=True):
""" Downloads a specific file.
:param clean_url: Decoded URL to the file.
:param download_folder: Folder to place the downloaded file in.
:param downloaded_file_name: File name to save the downl... | f2b3b564d5ed78bca678bfd35f20e548278013c6 | 20,727 |
from typing import Sequence
def _clean_bar_plot_data(df_in: pd.DataFrame,
sweep_vars: Sequence[Text] = None) -> pd.DataFrame:
"""Clean the summary data for bar plot comparison of agents."""
df = df_in.copy()
df['env'] = pd.Categorical(
df.bsuite_env, categories=_ORDERED_EXPERIMENT... | a62feba3511dccd0d6a909531d5f50b96348e072 | 20,728 |
def file_resources():
"""File Resources."""
return {
'mock_file': CustomFileResource(service=FileService()),
'mock_file_action': CustomFileActionResource(service=FileService()),
} | 412bdb59f04c2092c7bd77ef677cfac43bbc27ff | 20,729 |
import pickle
def prepare_data(features=None):
"""Prepare data for analysis
Args:
features (list of str): list with features
Returns:
X_train (np.matrix): train X
X_test (np.matrix): test X
y_train (np.matrix): train y
y_test (np.matrix): test y
"""
# Rea... | b880e89c4bd5b8df80c385141f7f34e71164dc37 | 20,730 |
def choose_my_art_date(my_location, google_maps_key, mapping = False, search_range = 500, min_rating = 4.3):
"""
Function to select an artsy date and dinner; randomly selects local arts event from NY ArtBeat API
found at https://www.nyartbeat.com/resources/doc/api, and uses the arts event data to determine... | a33ffc38c4bfb648fd4a68087844484817c8ee02 | 20,731 |
import os
from typing import MutableMapping
def flatten_repo_tree(d, parent_key=''):
"""Flatten a dict to so that keys become nodes in a path."""
items = []
for k, v in d.items():
new_key = os.path.join(parent_key, k)
try:
repo = Repo(**v)
except (ValidationError, Type... | f47091609a62549b575d883561d8a009aa08c98f | 20,732 |
import hashlib
def hash_text(message: str, hash_alg: str = 'keccak256') -> str:
"""get the hash of text data
:param message: str
:param hash_alg: str, `keccak256` or `sha256`, the default value is `keccak256`
:return: hex str, digest message with `keccak256` or `sha256`
"""
if hash_alg == 'k... | da161ee7573ff1af9d644e04641cbb844b2311ca | 20,733 |
def get_grains_connected_to_face(mesh, face_set, node_id_grain_lut):
"""
This function find the grain connected to the face set given as argument.
Three nodes on a grain boundary can all be intersected by one grain
in which case the grain face is on the boundary or by two grains. It
is therefore su... | cb4adff2d6ffe3c32e2a1fc8058e6ad1fed9b2c9 | 20,734 |
def get_git_projects(git_worktree, args,
default_all=False,
use_build_deps=False,
groups=None):
""" Get a list of git projects to use """
git_parser = GitProjectParser(git_worktree)
groups = vars(args).get("groups")
if groups:
use_bu... | afcb3e68d5e023937bbcdb9e86f9d50f9dc63e78 | 20,735 |
from typing import Literal
def RmZ(
ps: Table,
r_band: Literal["9601", "9602"] = "9602",
z_band: Literal["9801", "9901"] = "9901",
**kw
) -> units.mag:
"""R-Z color.
Parameters
----------
ps : astropy.table.Table
need arguments for r(z)_band functions
r_band: {'9601', '96... | 9c659933788a36409361941f65c4d29e73ec0b9f | 20,736 |
from typing import List
def get_table_names(connection: psycop.extensions.connection) -> List[str]:
"""
Report the name of the tables.
E.g., tables=['entities', 'events', 'stories', 'taxonomy']
"""
query = """
SELECT table_name
FROM information_schema.tables
WHERE table_ty... | 7602e998b8d4431041eb688cc5ed2450f4dc49bc | 20,737 |
def mrpxmrp(sigmaset1, sigmaset2):
"""in work; returns transformation [FN] = [FB(s2)][BN(s1)]
"""
q1 = np.array(sigmaset1)
q2 = np.array(sigmaset2)
sig1_norm = norm(sigmaset1)
sig2_norm = norm(sigmaset2)
scalar1 = 1 - sig1_norm**2
scalar2 = 1 - sig2_norm**2
scalar3 = 2.
denom = 1... | 4df11a8f93c857e44fc98a59ff9a5a4325d29eef | 20,738 |
def continuous_partition_data(data, bins='auto', n_bins=10):
"""Convenience method for building a partition object on continuous data
Args:
data (list-like): The data from which to construct the estimate.
bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-space... | 07ab1663a4b2a4d62f2e8fce3c49d0c8c135d9e7 | 20,739 |
import csv
def readInput(infile,genefile, segfile):
"""
Reads input files.
Extended description of function.
Parameters:
infile (str): File containing list of genes to be analyzed
genefile (str): File containing gene range definitions
segfile (str): File containing cell line intervals... | 225a0403c1b8875ec7f40c6511edc1c1828dd2aa | 20,740 |
def library_name(name, suffix=SHLIB_SUFFIX, is_windows=is_windows):
"""
Convert a file basename `name` to a library name (no "lib" and ".so" etc.)
>>> library_name("libpython3.7m.so") # doctest: +SKIP
'python3.7m'
>>> library_name("libpython3.7m.so", suffix=".so", is_windows=False... | 56c19da17acd6d00006e9c1e4308148ab7bc18d8 | 20,741 |
def add_light(light_type: str = 'POINT') -> str:
"""
Add a light of the given type to the scene, return
the name key of the newly added light
:param light_type:
:return: The named key used to index the object
"""
if utils.is_new_api():
bpy.ops.object.light_add(type=light_type)
el... | ac1f5e66a3baf90f2e603069e967b8ed3a76bf8d | 20,742 |
def set_constants(ze=40, p=0.4,
kc_min=0.01, kc_max=1.0,
snow_alpha=0.2, snow_beta=11.0,
ke_max=1.0,
a_min=0.45, a_max=0.90):
"""
:param ze:
:param p: the fraction of TAW that a crop can extract from the root zone without suffering wat... | d2c02eb49c59c203b9520b32e94aaceac611abcc | 20,743 |
def project_poses(poses, P):
"""Compute projected poses x = Pp."""
assert poses.ndim == 2 and poses.shape[-1] == 3, \
'Invalid pose dim at ext_proj {}'.format(poses.shape)
assert P.shape == (3, 4), 'Invalid projection shape {}'.format(P.shape)
p = np.concatenate([poses, np.ones((len(poses)... | 943c935791744ec3ec6f476c16911d7c90f2024b | 20,744 |
def argmin(x):
"""
Returns the index of the smallest element of the iterable `x`.
If two or more elements equal the minimum value, the index of the first
such element is returned.
>>> argmin([1, 3, 2, 0])
3
>>> argmin(abs(x) for x in range(-3, 4))
3
"""
argmin_ = None
min_... | 8d6778182bf3c18ffa6ef72093bf19a818d74911 | 20,745 |
def find_spot(entry, list):
"""
return index of entry in list
"""
for s, spot in enumerate(list):
if entry==spot:
return s
else:
raise ValueError("could not find entry: "+ str(entry)+ " in list: "+ str(list)) | e218822e5e56a62c40f5680751c1360c56f05f4a | 20,746 |
def parse_file(path, game=None, path_relative_to_game=True, verbose=False):
"""
Parse a single file and return a Tree.
path, game:
If game is None, path is a full path and the game is determined from that.
Or game can be supplied, in which case path is a path relative to the game directory.... | 64673afea557ad2d74eb4cdcc56d6f6f6e2cd1f6 | 20,747 |
def svn_repos_fs_commit_txn(*args):
"""svn_repos_fs_commit_txn(svn_repos_t * repos, svn_fs_txn_t * txn, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_fs_commit_txn(*args) | 6aebf604435485aba694b46ab58f5e4ca7d1b549 | 20,748 |
import os
import asyncio
from datetime import datetime
async def run_command(
cmd: list, cwd: str = None, log_path=None, environ=None) -> str:
"""
Run a command.
If 'log_path' is provided, stdout and stderr will be written to this
location regardless of the end result.
:raises subprocess.... | d4b1ebb52ac57424ae36235ff6884e80737d6a23 | 20,749 |
def iter_dir(temp_dir, blast_db, query_name, iteration):
"""
Get the work directory for the current iteration.
We need to call this function in child processes so it cannot be in an
object.
"""
name = '{}_{}_{:02d}'.format(
basename(blast_db), basename(query_name), iteration)
retur... | e4a8acf79fa3ef6b3822d91406cd6cf007477308 | 20,750 |
def zoomSurface(src, zoomx, zoomy, smooth):
"""Zooms a surface with different x & y scaling factors.
This function renders to a new surface, with optional anti-aliasing. If a
zoom factor is negative, the image will be flipped along that axis. If the
surface is not 8-bit or 32-bit RGBA/ABGR, it will be ... | 08e7ad74a4420f5b02a6924d47cdecf3dc09229b | 20,751 |
import struct
def array(*cols: Column) -> Column:
"""
Return column of arrays
"""
return (struct(*cols).apply(list)).alias(f"[{', '.join([Column.getName(c) for c in cols])}]") | 65599cd0fa7b0ea5b670555656a9b615e0e68664 | 20,752 |
def addtodo(request):
"""
:param request: HttpRequest object
:return: None. Redirects to Webpage.
if pk is not available defaults to id=0.
"""
pk = request.POST.get("id_todo", 0)
if pk:
todoobj = Todo.objects.get(pk=pk)
newtodoform = NewTodoForm(request.POST, instance=todoob... | 9b7fdb53d98b935106f1878135223cd9731503b5 | 20,753 |
def prepare_inputs(boxes, digits_occurrence):
"""
:param boxes:
2D list of 81 gray OpenCV images (2D numpy arrays)
:param digits_occurrence:
2D numpy array that contains True or False values that represent occurrence of digits
:return:
if no digit was found returns None;
otherwise returns 4D numpy array wit... | 27c97e374f9cbdb0d427acacb5645819d05a2aea | 20,754 |
def evaluate_constants(const_arrays, expr): # pragma: no cover
"""Convert constant arguments to cupy arrays, and perform any possible
constant contractions.
"""
return expr(*[to_cupy(x) for x in const_arrays], backend='cupy', evaluate_constants=True) | 7a371d0cb262fb530873825dee02a8201913b2c1 | 20,755 |
def setup_family(dompc, family, create_liege=True, create_vassals=True,
character=None, srank=None, region=None, liege=None,
num_vassals=2):
"""
Creates a ruler object and either retrieves a house
organization or creates it. Then we also create similar
ruler objects for... | 9cd1fda01685c071f79e876add49e5ffe5b23642 | 20,756 |
def normalize_line(line: dict, lang: str):
"""Apply normalization to a line of OCR.
The normalization rules that are applied depend on the language in which
the text is written. This normalization is necessary because Olive, unlike
e.g. Mets, does not encode explicitly the presence/absence of whitespac... | f158d3d9811752e009a7f0aa6f94b4a67e322960 | 20,757 |
def attribute_summary(attribute_value, item_type, limit=None):
"""Summarizes the information in fields attributes where content is
written as an array of arrays like tag_cloud, items, etc.
"""
if attribute_value is None:
return None
items = ["%s (%s)" % (item, instances) for
... | a835e985ce4f9c6d82bdaa267589a802fb865d26 | 20,758 |
import json
def root():
"""Base view."""
new_list = json.dumps(str(utc_value))
return new_list | 7d94ea10dc944d1cef13dfea7cc12ccc5bc9f742 | 20,759 |
def plc_read_db(plc_client, db_no, entry_offset, entry_len):
"""
Read specified amount of bytes at offset from a DB on a PLC
"""
try:
db_var = plc_client.db_read(db_no, entry_offset, entry_len)
except Exception as err:
print "[-] DB read error:", err
sys.exit(1)
db_val =... | 324c81b1192c90c3909bf4e6cb65e590ce48f59a | 20,760 |
import os
def getPath(path=__file__):
"""
Get standard path from path. It supports ~ as home directory.
:param path: it can be to a folder or file. Default is __file__ or module's path.
If file exists it selects its folder.
:return: dirname (path to a folder)
.. note:: It is the ... | ef1a0997de2febea075b9ce44414c533806f6125 | 20,761 |
def rank_adjust(t, c=None):
"""
Currently limited to only Mean Order Number
Room to expand to:
Modal Order Number, and
Median Order Number
Uses mean order statistic to conduct rank adjustment
For further reading see:
http://reliawiki.org/index.php/Parameter_Estimation
Above reference... | c79d308dd333c96abe64274918fcd294d24f7d40 | 20,762 |
from datetime import datetime
import requests
def login_captcha(username, password, sid):
"""
bilibili login with captcha.
depend on captcha recognize service, please do not use this as first choice.
Args:
username: plain text username for bilibili.
password: plain text password for bi... | de0ee5d865ea11b32f155fb3a3470fff9b13202b | 20,763 |
def ml_transitions(game, attach=True, verbose=False):
"""
dataframe to directional line movement arrays
"""
transition_classes = []
prev = [None, None]
for i, row in game.iterrows():
cur = list(row[["a_ml", "h_ml"]])
transition_class = analyze.classify_transition(prev, cur)
... | 3156f377f4c78b30cabe27f1dc37a277b25ebde6 | 20,764 |
def plugin_uninstall(plugin, flags=None, kvflags=None):
"""
Uninstall a Helm plugin.
Return True if succeed, else the error message.
plugin
(string) The plugin to uninstall.
flags
(list) Flags in argument of the command without values. ex: ['help', '--help']
kvflags
(d... | f162d37cb48e3cc0ebb3294ec4fe33b9fc56d8f0 | 20,765 |
def geom_to_tuple(geom):
"""
Takes a lat/long point (or geom) from KCMO style csvs.
Returns (lat, long) tuple
"""
geom = geom[6:]
geom = geom.replace(" ", ", ")
return eval(geom) | 003f25a0ebc8fd372b63453e4782aa52c0ad697c | 20,766 |
def b_s_Poole(s, V_max, z, halo_type, bias_type):
""" This function expresses Equation (2) of Poole et al (2014)
and fetches the parameters needed to compute it.
Args:
s (numpy.ndarray) : scale values
V_max (float) : halo maximum circular velocity
z (float) : redshift of in... | 7ee59c4e3052cab74932c9e78dfc04af92a2284e | 20,767 |
from sys import path
def find_places_location():
"""Finds the location of the largest places.sqlite file"""
location = ""
filesize = 0
for user in listdir('/Users'):
profile_dir = '/Users/' + user + '/Library/Application Support/Firefox/Profiles/'
if path.exists(profile_dir):
for profile in listdir(profile... | f0af00dadb76ae56a9424fdab0c24c5b6ab342a4 | 20,768 |
import sys
def argumentParser(listOfArguments):
"""Parses arguments"""
argumentParserFilter = {}
for argument in listOfArguments:
if argument in sys.argv:
argumentParserFilter[listOfArguments[argument]] = True
else:
argumentParserFilter[listOfArguments[argument]] ... | 939cfea9c6b4f8deec08b4afb73427183b551ccc | 20,769 |
def rasterize_polygon(poly_as_array, shape, geo_ref):
"""
Return a boolean numpy mask with 1 for cells within polygon.
Args:
poly_as_array: A polygon as returned by ogrpoly2array (list of numpy arrays / rings)
shape: Shape (nrows, ncols) of output array
geo_ref: GDAL style georeference ... | 506fbc7b1e215e52e1ee469cb88ffc4b4d45dd89 | 20,770 |
def _model_columns(ins):
""" Get columns info
:type ins: sqlalchemy.orm.mapper.Mapper
:rtype: list[SaColumnDoc]
"""
columns = []
for c in ins.column_attrs:
# Skip protected
if c.key.startswith('_'):
continue
# Type
column_type = c.columns[0].type # ... | 331ae5725f82ac7fb5d685951caabcf7b1258b20 | 20,771 |
def get_reg_part(reg_doc):
"""
Depending on source, the CFR part number exists in different places. Fetch
it, wherever it is.
"""
potential_parts = []
potential_parts.extend(
# FR notice
node.attrib['PART'] for node in reg_doc.xpath('//REGTEXT'))
potential_parts.extend(
... | 33f4c2bb9a4e2f404e7ef94a3bfe3707a3b1dd93 | 20,772 |
from pathlib import Path
import json
def load_configuration(module: str, configs_path=None) -> dict:
"""
Load the configuration and return the dict of the configuration loaded
:param module: The module name to load the configuration.
:type module: str
:param configs_path: path where to check conf... | 2a5e0a798b3c3c3dd1570ee79d1e3ce5d6eff97b | 20,773 |
def direct(input_writer, script_str, run_dir, prog,
geo, charge, mult, method, basis, **kwargs):
""" Generates an input file for an electronic structure job and
runs it directly.
:param input_writer: elstruct writer module function for desired job
:type input_writer: elstruct fun... | e14e41aac6f682d283094a4e0755dcc8949de269 | 20,774 |
def get_ids(records, key):
"""Utility method to extract list of Ids from Bulk API insert/query result.
Args:
records (:obj:`list`): List of records from a Bulk API insert or SOQL query.
key (:obj:`str`): Key to extract - 'Id' for queries or 'id' for inserted data.
Returns:
(:obj:`l... | e1373aee926406a4a780f6c344069702350cb16d | 20,775 |
import codecs
import os
def read(*parts):
"""
Build an absolute path from *parts* and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f:
return f.read() | 8914c5e14240faa1afeb930e135651f1c5bb1b31 | 20,776 |
def auto_help(func):
"""Automatically registers a help command for this group."""
if not isinstance(func, commands.Group):
raise TypeError('Auto help can only be applied to groups.')
cmd = commands.Command(_call_help, name='help', hidden=True)
func.add_command(cmd)
return func | bfcbd0d951dcffb43363b87b6bc4162226db1413 | 20,777 |
import itertools
import operator
def unique_justseen(iterable, key=None):
"""
List unique elements, preserving order. Remember only the element just seen.
>>> [x for x in unique_justseen('AAAABBBCCDAABBB')]
['A', 'B', 'C', 'D', 'A', 'B']
>>> [x for x in unique_justseen('ABBCcAD', str.lower)]
... | 97323df08e9a001b5cd81cbcb88ae3e8ae486a8b | 20,778 |
def unique_rows(arr, thresh=0.0, metric='euclidean'):
"""Returns subset of rows that are unique, in terms of Euclidean distance
http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array
"""
distances = squareform(pdist(arr, metric=metric))
idxset = {tuple(np.nonzero(v)[0]) for v in... | 79afdddc50239ed1479deeb75a41ea19d2dec9ca | 20,779 |
import json
def backdoors_listing(request,option=None):
"""
Generate the Backdoor listing page.
:param request: Django request.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', 'csv', or 'inline'.
:returns: :c... | f4c8d2b2be68c40de7ec9e79a29e592618afbb44 | 20,780 |
def my_join(x):
"""
:param x: -> the list desired to join
:return:
"""
return ''.join(x) | bffc33247926c2b1ebe1930700ed0ad9bcb483ec | 20,781 |
import argparse
import configparser
def config_parse_args(configfile=None):
""" Command line arguments and configuration file setting """
parser = argparse.ArgumentParser(
description='nanoping log importer to InfluxDB')
parser.add_argument('--config', type=str, required=True,
... | 477ec101da00ed3f256ccc652ea4b9a9e852f6e2 | 20,782 |
def visualize_code_vectors(code_vectors, cmap='Paired', inter='none',
origin='upper', fontsize=16, aspect='auto',
colorbar=True):
"""
Document
"""
to_plot = np.array(code_vectors)
# First the parameters
to_plot_title = 'Code Vectors in Time... | 39269d46a8ec544ccf415a363489b83f43d7fbc0 | 20,783 |
def get_displacements_and_forces(disp_dataset):
"""Return displacements and forces of all atoms from displacement dataset.
This is used to extract displacements and forces from displacement dataset.
This method is considered more-or-less as a converter when the input is in
type-1.
Parameters
-... | 998f3fd6319ad777b4dfa523b8464b45ce9bae52 | 20,784 |
from typing import Dict
from datetime import datetime
def GetUserAllBasicData(user_url: str) -> Dict:
"""获取用户的所有基础信息
Args:
user_url (str): 用户个人主页 Url
Returns:
Dict: 用户基础信息
"""
result = {}
json_obj = GetUserJsonDataApi(user_url)
html_obj = GetUserPCHtmlDataApi(user_url)
... | 1965484ef2aa638f9084720e38c5f660d9000665 | 20,785 |
def get_trace(session, trace_uuid):
"""Retrieves traces given a uuid.
Args:
sesssion: db session
trace_uuid: uuid of trace in question
Returns 2-tuple of plop, flamegraph input or None if trace doesn't exist
(or was garbage collected.
"""
trace = session.query(PerfProfile).filt... | 0f44ebce393277a3660810ae1b359b437f733ec1 | 20,786 |
def first_kind_discrete(orientations, order=4):
"""
Calc orientation tensors of first kind for given discrete vectors
"""
# Normalize orientations
orientations = [np.array(v) / np.linalg.norm(v) for v in orientations]
# Symmetrize orientations
# orientations_reversed = [-v for v in orien... | 4b28f426ea551d7ef6a744091a65be11d418e324 | 20,787 |
def prep_pointcloud(input_dict,
root_path,
voxel_generator,
target_assigner,
db_sampler=None,
max_voxels=20000,
class_names=['Car'],
remove_outside_points=False,
... | ab28c0d1343858bafd51f60c35b3aec322c34528 | 20,788 |
def fix_repo_url(repo_url, in_type='https', out_type='ssh', format_dict=format_dict):
""" Changes the repo_url format """
for old, new in izip(format_dict[in_type], format_dict[out_type]):
repo_url = repo_url.replace(old, new)
return repo_url | 6382136693bfce4b72e122cdc016fa9eee1fb78f | 20,789 |
from typing import Optional
def add_nodes_to_graph(
G: nx.Graph,
protein_df: Optional[pd.DataFrame] = None,
verbose: bool = False,
) -> nx.Graph:
"""Add nodes into protein graph.
:param G: ``nx.Graph`` with metadata to populate with nodes.
:type G: nx.Graph
:protein_df: DataFrame of prote... | b58ae2d3f9bc4feeb2721e8258869f6d69d38f8e | 20,790 |
def mc(dataset):
"""
Modulus calculation.
Calculates sqrt(real^2 + imag^2)
"""
return np.sqrt(dataset.real ** 2 + dataset.imag ** 2) | 8c7d94ed07c7d4102b2650baef11ea470e5673ea | 20,791 |
from typing import List
def _get_fields_list(data: Data) -> List[Field]:
"""Extracts all nested fields from the data as a flat list."""
result = []
def map_fn(value):
if isinstance(value, GraphPieceBase):
# pylint: disable=protected-access
tf.nest.map_structure(map_fn, value._data)
else:
... | ad6a9b4c11749b085edaf639e318e84e75e58cc7 | 20,792 |
def constructAdvancedQuery(qryRoot):
"""
Turns a qry object into a complex Q object by calling its helper and supplying the selected format's tree.
"""
return constructAdvancedQueryHelper(
qryRoot["searches"][qryRoot["selectedtemplate"]]["tree"]
) | 4a1a23c4810e7b4f30a86c620f0e949da8af4ef8 | 20,793 |
def slice_and_dice(text=text):
"""Strip the whitespace (newlines) off text at both ends,
split the text string on newline (\n).
Next check if the first char of each (stripped) line is lowercase,
if so split the line into words and append the last word to
the results list. Make sure the y... | 16d3bb77c60738d654a61ac40b3fc7216ee6ed52 | 20,794 |
def solution(data):
""" Solution to the problem """
seats, first_visible_seats, dim_y, dim_x = preprocess(data)
solver = Simulation(seats, first_visible_seats, dim_y, dim_x)
return solver.solve() | 6bbfa11df003b2dce24430cf50420d6d2bcf9683 | 20,795 |
from typing import Tuple
def add_received_ip_tags(
rows: beam.pvalue.PCollection[Row],
ips_with_metadata: beam.pvalue.PCollection[Tuple[DateIpKey, Row]]
) -> beam.pvalue.PCollection[Row]:
"""Add tags for answer ips (field received.ip) - asnum, asname, http, cert
Args:
rows: PCollection of measureme... | 36dcbd0ced327a1f4ed0645b7c1edfe65bdeb9f8 | 20,796 |
def set_selector(*args):
"""set_selector(sel_t selector, ea_t paragraph) -> int"""
return _idaapi.set_selector(*args) | 8c4b7119979dda3d4b21b56865d20cfa60900a3a | 20,797 |
def other_features(tweet):
"""This function takes a string and returns a list of features.
These include Sentiment scores, Text and Readability scores,
as well as Twitter specific features"""
tweet_text = tweet["text"]
##SENTIMENT
sentiment = sentiment_analyzer.polarity_scores(tweet_text)
... | d4b1e158a80b6d9502c02dc0c2380e8749bb0b6f | 20,798 |
def template(spec_fn):
"""
>>> from Redy.Magic.Classic import template
>>> import operator
>>> class Point:
>>> def __init__(self, p):
>>> assert isinstance(p, tuple) and len(p) is 2
>>> self.x, self.y = p
>>> def some_metrics(p: Point):
>>> return p.x + 2 * p... | a8fd64926cdbec73c1a31c20a27174c86af3405e | 20,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.