content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def verify_stack_size(
func: Fn,
stack: Stack,
signature: Optional[Signature] = None,
) -> int:
"""Verifies that the stack contains required number of arguments for function call.
Args:
func: a function.
stack: arguments available for the call.
signature: optional signature ... | 5,286,500 |
def list_or_starargs(func):
"""This is a decorator to specify that a function either takes iterable input in the form of an iterable or a list of passed arguments.
If other arguments are needed, the function will need to use kwargs.
This passes the list as the first argument."""
def decorated(*args, **k... | 5,286,501 |
def isen_nozzle_mass_flow(A_t, p_t, T_t, gamma_var, R, M):
"""
Calculates mass flow through a nozzle which is isentropically expanding
a given flow
Input variables:
A_t : nozzle throat area
gamma_var : ratio of specific heats
p_t : pressure at throat
T_t : temperature at throat
M : Mach num... | 5,286,502 |
def GenerateConfig(context):
"""Generate configuration."""
base_name = context.env['name']
# Properties for the container-based instance.
instance = {
'zone': context.properties['zone'],
'machineType': ZonalComputeUrl(context.env['project'],
context.properties['... | 5,286,503 |
async def test_get_mqtt(hass):
"""Verify that custom components with MQTT are found."""
test_1_integration = _get_test_integration(hass, "test_1", True)
test_2_integration = _get_test_integration(hass, "test_2", True)
with patch("homeassistant.loader.async_get_custom_components") as mock_get:
m... | 5,286,504 |
def calc_overturning_stf(ds,grid,doFlip=True):
"""
Only for simple domains, compute meridional overturning streamfunction
Parameters
----------
ds : xarray Dataset from MITgcm output, via
e.g. xmitgcm.open_mdsdataset
must contain 'V' or 'VVELMASS'... | 5,286,505 |
def test_selection_sort_with_neg():
"""Test the selection sort on integers with neg integer."""
assert selection_sort([54, 26, 93, 17, 77, 31, 44, -55, 20]) == [-55, 17, 20, 26, 31, 44, 54, 77, 93] | 5,286,506 |
def support_annotation_or_set(method):
"""
Decorator to allow a method that normally takes a start and end
offset to take an annotation or annotation set, or any other object that has
"start" and "end" attributes, or a pair of offsets instead.
It also allows to take a single offset instead which wil... | 5,286,507 |
def test_empty_object_returned_with_authentication(api_client):
"""If the Authorization and X-Forwarded-For headers are correct, then
the correct, and authentic, data is returned
"""
sender = auth_sender()
response = api_client.get(
URL,
content_type='',
HTTP_AUTHORIZATION=se... | 5,286,508 |
def add_or_update_user_followers(user_name, next_page_link=None):
"""
Fetches, updates and creates all followers of a given user. If the user
itself doesnt exist it is created. The task returns without changing any
data if the followers count on disk matches the last count from github.
"""
if no... | 5,286,509 |
def test_find_frequent():
"""
Test find_frequent
"""
for min_sup in MIN_SUPS:
transactions, counts = generate_test_data()
candidates = [c for c in counts.keys() if len(c) == 1]
output, _ = find_frequent(candidates, transactions, min_sup)
for k, v in output.items():
... | 5,286,510 |
def address_dict(obj, prefix='address'):
"""
Creates a dictionary for the address fields with the given prefix
to be used as nested object.
"""
if obj is None:
return None
mapping = {
'line_1': _attrgetter_with_default(f'{prefix}_1', ''),
'line_2': _attrgetter_with_defau... | 5,286,511 |
def Message_MsgFile_Msg(*args):
"""
:param key:
:type key: char *
:rtype: TCollection_ExtendedString
* Gives the text for the message identified by the keyword <key> If there are no messages with such keyword defined, the error message is returned. In that case reference to static string is returned,... | 5,286,512 |
def register_user(email, name, password, password2, balance):
"""
Register the user to the database
:param email: the email of the user
:param name: the name of the user
:param password: the password of user
:param password2: another password input to make sure the input is correct
:return: ... | 5,286,513 |
def VerifyManagementEngineLocked(options):
"""Verify Management Engine is locked."""
return GetGooftool(options).VerifyManagementEngineLocked() | 5,286,514 |
def save_foreign_title_ref(new_titles: dict, filename: str):
"""
Map xx/author-name-in-foreign-language.xml to en/author-name.xml
Does this by creating a file of key:value pairs in each language dir
@param new_titles: dictionary with iso language -> name pairs
@param filename: where the references ... | 5,286,515 |
def compile(msg):
"""Compile an OpenFlow message template."""
controller = Controller.singleton()
if isinstance(msg, str):
return CompiledString(controller, msg)
if 'type' in msg:
return CompiledObject(controller, msg)
return CompiledObjectRPC(controller, msg) | 5,286,516 |
def test_block_quotes_213ax():
"""
Test case 213a: variation of 213 that continues after the first
line because of the block quote start
"""
# Arrange
source_markdown = """> - foo
> - bar"""
expected_tokens = [
"[block-quote(1,1)::> \n> ]",
"[ulist(1,3):-::4: ]",
... | 5,286,517 |
def datetime_from_filename(filename):
"""Create Python datetime object from bag file name.
:param: base name of bag file.
:type: str
:returns: corresponding Python datetime.datetime object.
:note: This implementation assumes the base file name has a
four-character prefix and '.bag' su... | 5,286,518 |
def to_root(df, path, tree_key="default", mode='w', *args, **kwargs):
"""
Write DataFrame to a ROOT file.
Parameters
----------
path: string
File path to new ROOT file (will be overwritten by default)
tree_key: string
Name of tree that the DataFrame will be saved as
mode: str... | 5,286,519 |
def load_data(train=True, batch_size=50, shuffle=False):
"""
加载数据集
:param train: 训练集 or 测试集
:param batch_size: batch的大小
:return: 返回加载好的Dataloader
"""
if train:
# 针对训练数据随机打乱
shuffle = True
# 加载CIFAR10数据集,若不存在则下载
dataset = datasets.CIFAR10('./data',
... | 5,286,520 |
def route_filter_create_or_update(name, resource_group, **kwargs):
"""
.. versionadded:: 2019.2.0
Create or update a route filter within a specified resource group.
:param name: The name of the route filter to create.
:param resource_group: The resource group name assigned to the
route fi... | 5,286,521 |
def get_featured_dashboard(slug):
"""
Grab a dashboard of featured things.
{% get_featured_dashboard 'homepage' as featured_stuff %}
"""
try:
return Dashboard.objects.get(slug=slug)
except Dashboard.DoesNotExist:
msg = "Dashboard `{}` probably doesn't exist.".format(slug)
... | 5,286,522 |
def value_to_member(value: Any, cls: Type[Any]) -> str:
"""
Get a member of a class that matches the value given
"""
members = get_class_members(cls)
for member in members:
if getattr(cls, member) == value:
return member
return "No member with value found." | 5,286,523 |
def file_dialog(lines, prompt='', start_dir='', ext=''):
"""Ensures existence of start_dir and prompts user for file name.
Then attempts to write lines into that file.
Args:
lines (list): List of lines.
prompt (str) opt: Prompt for user.
start_dir (str) opt: Path to start directory f... | 5,286,524 |
def adaptive_rejection_sampling(logpdf: callable,
a: float, b: float,
domain: Tuple[float, float],
n_samples: int,
seed=None):
"""
Adaptive rejection sampling samples exactly (all samp... | 5,286,525 |
def player(board):
"""
Returns player who has the next turn on a board.
"""
flattened = [inner for outer in board for inner in outer]
return O if flattened.count(X) > flattened.count(O) else X | 5,286,526 |
def viterbi(nodes,trans_p, initial_state = None, return_max = True, start_p = None):
"""
nodes: array, [{"<TAG>": <float>}]
trans_p: dict, {"<TAG_A>": {"TAG_B": <float>}}, TAG_A -> TAG-B
return_max=True: bool, set to False if your want to avoid ill endding tag and find your own.
initial_state=None: ... | 5,286,527 |
def loop_body_whole(it, ckpt_path, raw_arr, gt_arr, rgb_arr, H, W, config):
"""
forward input raw_array patches seperately, then h_stack and v_stack these patches into whole.
"""
print(time.ctime())
print("Load checkpoint: {}".format(ckpt_path))
h, w = raw_arr[0][0].shape[:2]
low_thres = co... | 5,286,528 |
def get_gaia_radec_at_time(gaia_tbl, date=2015.5, format='decimalyear'):
"""
Use `~astropy.coordinates.SkyCoord.apply_space_motion` to compute GAIA positions at a specific observation date
Parameters
----------
gaia_tbl : `~astropy.table.Table`
GAIA table query, e.g., provided by `get_g... | 5,286,529 |
def dissociate(op, args):
"""Given an associative op, return a flattened list result such
that Expr(op, *result) means the same as Expr(op, *args)."""
result = []
def collect(subargs):
for arg in subargs:
if arg.op == op: collect(arg.args)
else: result.append(arg)
col... | 5,286,530 |
def ClearAppData(package):
"""Clears the app data.
Args:
package: Application package name.
Raises:
AdbError: if any step fails.
"""
cmd = ['shell', 'pm clear %s' % package]
# am/pm package do not return valid exit codes.
out = RunAdbCommand(cmd)
if 'Success' not in out:
raise AdbError('Fa... | 5,286,531 |
def ways_to_fill(amount: int, containers: List[int]) -> int:
"""The number of ways to pour amount of liquid into containers.
All containers used must be filled up entirely."""
if amount == 0:
# Reached an acceptable configuration.
return 1
if amount < 0 or not containers:
# No l... | 5,286,532 |
def AggregateData(data,period):
"""Create a clean dataset
Arguments:
- data -- np.array of np.float64, size (N,6)
data[:,0] is unix times (seconds), start of the interval
data[:,1] is close price, dollars
data[:,2] is high price, dollars
data[:,3] is low price, dollars
data[:,... | 5,286,533 |
def get_tolerance(camera=None,
legacyzpts_product=None):
"""Returns dict giving maximum 'plus/minus' difference for each numeric column
Note, dont fill in if differnce should be zero, that's default
Args:
camera: CAMERAS
legacyzpts_product: legacypipe,zpt,star-photom,star... | 5,286,534 |
def kspace_setup(box_lengths, angle_averaging, max_k_harmonics, max_aa_harmonics):
"""
Calculate all allowed :math:`k` vectors.
Parameters
----------
max_k_harmonics : numpy.ndarray
Number of harmonics in each direction.
box_lengths : numpy.ndarray
Length of each box's side.
... | 5,286,535 |
def predict_transport_mode(triplegs, method="simple-coarse", **kwargs):
"""
Predict the transport mode of triplegs.
Predict/impute the transport mode that was likely chosen to cover the given
tripleg, e.g., car, bicycle, or walk.
Parameters
----------
triplegs: GeoDataFrame (as trackintel ... | 5,286,536 |
def test_long_sql_statements(sdc_builder, sdc_executor, database):
"""Test Oracle CDC correctly handles long SQL statements.
When querying LogMiner content (i.e. V$LOGMNR_CONTENT view), any database operation whose SQL statement is
longer than 4000 bytes is split into several records. In that case, Oracle ... | 5,286,537 |
def get_site_name():
""" Retuns site's name """
domain = getattr(settings, 'SITE_NAME')
return domain | 5,286,538 |
def execute_adaptive_model(model: AdaptiveModel, dataset: Dataset, series: DataSeries) -> ModelResults:
"""
Executes the neural network on the given data series. We do this in a separate step
to avoid recomputing for multiple budgets. Executing the neural network is relatively expensive.
Args:
... | 5,286,539 |
def split_tensor_lastdim(ten):
"""Split last dimension into two tensors."""
# TODO(vrama): Generalize this to other splits than 2.
assert ten.get_shape().as_list()[-1] % 2 == 0, ('Last dimension'
'must be divisible by 2.')
ten1, ten2 = tf.split(ten, 2, axis=len(... | 5,286,540 |
def finite_diff_hessian(x, grad, epsilon=FINITE_DIFF_EPSILON):
""" Approximate the Hessian of a function using finite difference in the partial gradient.
:param np.ndarray x: point at which to evaluate derivative
:param function grad: function that returns the gradient
"""
fwd_x = np.copy(x)
bwd... | 5,286,541 |
def value_at_diviner_channels(xarr):
"""Return value of xarr at each diviner channel."""
dwls = [
3,
7.8,
8.25,
8.55,
(13 + 23) / 2,
(25 + 41) / 2,
(50 + 100) / 2,
(100 + 400) / 2,
] # [microns]
return xarr.interp({"wavelength": dwls}) | 5,286,542 |
def test_from_long_to_nested(n_instances, n_columns, n_timepoints):
"""Test from_long_to_nested for correctness."""
X_long = generate_example_long_table(
num_cases=n_instances, series_len=n_timepoints, num_dims=n_columns
)
nested_df = from_long_to_nested(X_long)
assert is_nested_dataframe(n... | 5,286,543 |
def to_str(obj):
""" Convert something to a string, if it isn't one. """
# NOTE: unicode counts as a string just fine. We just want objects to call
# their __str__ methods.
if not isinstance(obj, basestring):
obj = str(obj)
return obj | 5,286,544 |
def get_field(addr: gdb.Value, n: int) -> gdb.Value:
"""
This assumes addr is a pointer to a struct that consists entirely
of pointers. Returns the n-th pointer in the struct.
"""
return gdb.parse_and_eval(f"((uintptr_t*){addr})[{n}]") | 5,286,545 |
def validate_rdkit(mol):
"""
Validates RDKit molecules (single or in a list).
:param mol: an RDKit molecule or list/np.array thereof
:return: boolean array, True if the molecules are chemically valid, False
otherwise
"""
if rdc is None:
raise ImportError('`validate_rdkit` requires ... | 5,286,546 |
def GIF_maker(path, output_file_name="out.gif", interval=None, time_per_frame=0.1):
"""make GIF image from images in path
* order of GIF frame is images file's name
:type path: str
:type output_file_name: str
:type interval: int
:type time_per_frame: float
:param path: source imag... | 5,286,547 |
def setup(hass, config):
""" Tracks the state of the sun. """
logger = logging.getLogger(__name__)
if not validate_config(config,
{ha.DOMAIN: [CONF_LATITUDE, CONF_LONGITUDE]},
logger):
return False
try:
import ephem
except Impor... | 5,286,548 |
def generate_graph_for_path_search(edges, transactions, amount_sat):
"""Generate pseudo edges and generate graph for path search."""
targets = list(transactions["target"].unique())
#sources = list(transactions["source"].unique())
#participants = set(sources).union(set(targets))
# drop edges with low... | 5,286,549 |
def make_slab(page, d):
"""Slab default BIM block.
An horizontal partition. Gets dimensions from block scaling. PART sets
partition type (TODO). Gets ceiling material from first component and
floor material from third component.
"""
d['rx'] = round(fabs(d["41"]), 4)
d['ry'] = round(fabs(d["... | 5,286,550 |
def processViewPendingRequests(self, data, connection):
""" Helper to view pending requests """
# GUI|viewPendingRequests|username
auth = viewPendingRequests(data.split('|')[2])
message = data.split("|")
if "successful" in auth:
# Update username in login list
self.login_list[message... | 5,286,551 |
def set_fastening_attribute(elements: List[int], value: str) -> None:
"""Sets the element fastening attribute
Args:
elements (List[int]): element IDs
value (str): Value element fastening attribute
""" | 5,286,552 |
def _msg(s, newln=True):
"""
print messages instantly (flush stdout buffer)
"""
print s,
if newln:
print
sys.stdout.flush() | 5,286,553 |
def setup(obj):
"""
:type obj: FixturesMixin
"""
obj.unload_fixtures()
obj.load_fixtures() | 5,286,554 |
def point_nonmatch_count(dist_array: np.ndarray, thresh: float = 5) -> int:
"""Given an array of distances, returns number which are not <= threshold."""
return dist_array.shape[0] - point_match_count(dist_array, thresh) | 5,286,555 |
def prune_source_literals(
plan: Plan, *, inplace: bool, predicate: Optional[Callable[[Literal], bool]] = None
) -> Plan:
"""
Prunes source literals. When predicate is present, the literal will only be pruned if it returns true.
"""
plan = get_mutable_plan(plan, inplace=inplace)
graph = plan.gra... | 5,286,556 |
def test_warnings():
"""Test features that raise a warning as they're unimplemented."""
if settings.TEST_SERVER_MODE:
raise SkipTest("Can't capture warnings in server mode")
client = boto3.client("firehose", region_name=TEST_REGION)
s3_dest_config = sample_s3_dest_config()
# DeliveryStream... | 5,286,557 |
def isodatesec(text):
"""Date. Returns the date in ISO 8601 format, including
seconds: "2009-08-18 13:00:13 +0200". See also the rfc3339date
filter.
"""
return util.datestr(text, '%Y-%m-%d %H:%M:%S %1%2') | 5,286,558 |
def pull_docker_image(docker_client, url):
""" Pull Docker image
Args:
docker_client (:obj:`docker.client.DockerClient`): Docker client
url (:obj:`str`): URL for Docker image
Returns:
:obj:`docker.models.images.Image`: Docker image
"""
try:
return docker_client.imag... | 5,286,559 |
def NTPasswordHash(password):
""" Return NTPasswordHash """
phash = MD4.new()
phash.update(unicode(password).encode("utf-16le"))
return phash.digest() | 5,286,560 |
def analyze_url(url, options, logfile):
"""Analyze a URL using wappalyzer and execute corresponding scans."""
wappalyzer = Wappalyzer.Wappalyzer.latest()
page = requests_get(url, options)
if not page:
return
if page.status_code == 200:
webpage = Wappalyzer.WebPage(url, page.text, pag... | 5,286,561 |
def main():
"""Program Entry point."""
DEFAULT_LOCALE = locale.getdefaultlocale()[1]
host, port = __resolve_hp()
logger.info("Connecting to the Reverse Shell server...")
shutdown = False
while not shutdown:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
log... | 5,286,562 |
def test_update_add_cputune(make_mock_vm):
"""
Test virt.update(), adding CPU tuning parameters
"""
domain_mock = make_mock_vm()
cputune = {
"shares": 2048,
"period": 122000,
"quota": -1,
"global_period": 1000000,
"global_quota": -3,
"emulator_period":... | 5,286,563 |
def authenticate(user, password):
"""return a user's hash"""
user_pass = User.query.filter_by(user=user).first()
if user_pass is None:
raise UserNotFound(user)
else:
return user_pass.serialize_user()["hash"] | 5,286,564 |
def txt2list(path: str) -> List:
"""
Opens a text file and converts to list by splitting on new lines
"""
with open(path, "r") as f:
txt = f.read()
return list(filter(None, txt.split("\n"))) | 5,286,565 |
def get_db():
"""Fetch db session from the context var"""
session = session_context_var.get()
if session is None:
raise Exception("Missing session")
return session | 5,286,566 |
def process(
api: act.api.Act,
shorteners: List[Text],
user_agent: Text,
proxies: Dict[Text, Text],
output_format: Text = "json",
) -> None:
"""Read queries from stdin, resolve each one through passivedns printing
generic_uploader data to stdout"""
for query in sys.stdin:
query ... | 5,286,567 |
def _create_table(client, database, table, schema, partition_cols, path):
"""
Create Glue table
"""
client.create_table(
DatabaseName=database,
TableInput={
"Name": table,
"PartitionKeys": [{"Name": x, "Type": "string"} for x in partition_cols],
"Table... | 5,286,568 |
def upload_file(bucket: str, key: str, data: bytes):
"""
Upload file with gzip
"""
try:
bio = BytesIO()
with gzip.GzipFile(fileobj=bio, mode="wb") as gz:
gz.write(data)
bio.seek(0)
s3.upload_fileobj(bio, bucket, key, ExtraArgs={"ContentEncoding": "gzip"})
... | 5,286,569 |
def prepCohortOneYear(data_config, sql_template_config, year_index, mode, db_engine, logger):
"""
Prepare the cohort table for training or validation data
:param data_config: data config from yaml
:param sql_template_config: sql template config from yaml
:param year_index: the index of cohort, label... | 5,286,570 |
def get_files_for_project(project_name):
"""Get the set of files for a learn project"""
found_files = set()
project_dir = "{}/{}/".format(LEARN_GUIDE_REPO, project_name)
for file in os.listdir(project_dir):
if "." in file:
cur_extension = file.split(".")[-1]
if cur_extens... | 5,286,571 |
def WriteXlsxBoardSummaries(board_list, sheet):
""" Writes a summary of play organized by board.
Args:
board_list: A list of Board objects in ascending order.
sheet: sheet in which the summaries will be written.
"""
sheet.title = 'Summary by Board'
NS_TEAM_TEXT = 'NS Team'
EW_TEAM_TEXT = 'EW Te... | 5,286,572 |
def test_abstract_reader__methods_implemented(backend: typing.Type, function: str):
"""Checks if all functions of AbstractDataFrameReader are implemented"""
method = getattr(backend, function)
assert not hasattr(
method, "__isabstractmethod__"
), f"{function}() not implemented for {backend}" | 5,286,573 |
def create_rsa_encrypted_pem(private_key, passphrase):
"""
<Purpose>
Return a string in PEM format (TraditionalOpenSSL), where the private part
of the RSA key is encrypted using the best available encryption for a given
key's backend. This is a curated (by cryptography.io) encryption choice and
the ... | 5,286,574 |
def convert_code_list_to_hierarchy(cl, as_list=False):
"""
Receives a list of codes. Codes are sorted lexicographically (to include numbers).
Two types of coding schemes are supported by assuming that trailing zeros can be ignored to match parent -> child
relations. The first is uniformly sized codes (... | 5,286,575 |
def test_dep_rpath(wrapper_environment):
"""Ensure RPATHs for root package are added."""
check_args(
cc, test_args,
[real_cc] +
target_args +
common_compile_args) | 5,286,576 |
def precisionAtK(result, k):
"""
Precision@K:
Set a rank threshold K
Compute % relevant in top K
Ignores documents ranked lower than K
"""
if k<result.shape[1]:
result = result[:, :k]
score = 0.0
for i in range(len(result)):
score += np.sum(result[i,:]) /... | 5,286,577 |
def load_model(model_dir):
"""
Loads a graph based tf saved model and also the classes for detection.
Accepts:
model_dir => directory in which model's pb or pbtxt file is placed
"""
return tf.saved_model.load(os.path.join(os.getcwd(),model_dir)) | 5,286,578 |
def obtain_value(entry):
"""Extract value from entry.
The entries could be like: '81.6', ': ', '79.9 e', ': e'.
"""
entry = entry.split(' ', maxsplit=-1)[0] # Discard notes.
if not entry or entry == ':':
return None
return float(entry) | 5,286,579 |
def load_schema(path):
"""Load the card schema from disk.
Parameters
----------
path : path_like
location of the schema yaml file
Returns
-------
`dict`
dictionary schema
"""
with open(path, 'r') as fid:
return yamlr.load(fid) | 5,286,580 |
def print_basic_info(input_object):
""" for debugging print basic info """
print('--------input info------------')
print('type: ', type(input_object))
print('shape: ', input_object.shape)
if isinstance(input_object, pd.core.frame.DataFrame):
print('cols names: ', list(input_object))
... | 5,286,581 |
def test_create_cccl_member_min_ipv6_config(pool, members):
"""Test of ApiPoolMember create with IPv6 address."""
cfg_name = "member_min_ipv6_config"
partition = "Common"
# pdb.set_trace()
member = ApiPoolMember(
name=None,
partition=partition,
pool=pool,
**members[c... | 5,286,582 |
def list_main():
"""Entry point for the application script"""
description = ""
parser = argparse.ArgumentParser(usage=None, description=description)
parser.add_argument("file", type=str, help=("textgrid file"))
argcomplete.autocomplete(parser)
args = parser.parse_args()
list_tiers(tg_fil... | 5,286,583 |
def call_solver(p,quiet):
"""
Calls solver.
:param p: Convex cvxpy_program.
Assumed to be expanded.
:param quiet: Boolean.
"""
# Set printing format for cvxopt sparse matrices
opt.spmatrix_str = opt.printing.spmatrix_str_triplet
# Expand objects defined via parti... | 5,286,584 |
def TNaming_Naming_Name(*args):
"""
* Creates a Namimg attribute at label <where> to identify the shape <Selection>. Geometry is Standard_True if we are only interested by the underlying geometry (e.g. setting a constraint). <Context> is used to find neighbours of <S> when required by the naming. If KeepOrientat... | 5,286,585 |
def build_call_seq_nb(target_shape, group_lens, call_seq_type=CallSeqType.Default):
"""Build a new call sequence array."""
if call_seq_type == CallSeqType.Reversed:
out = np.full(target_shape[1], 1, dtype=np.int_)
out[np.cumsum(group_lens)[1:] - group_lens[1:] - 1] -= group_lens[1:]
out ... | 5,286,586 |
def convert_amazon_time_to_local(s):
""" parse a date-time string given by Amazon and outputs the string of the local time"""
return datetime.datetime.strftime(datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ"), '%c') | 5,286,587 |
def main(): # Main function call #{{{
""" Main Function call for testing Tree class
my_file='altitude.csv'
header = 1 # Turn this option on if there is a header in the csv being read!!!!
class_label = 'Class'
attribute = 'Direction'
"""
my_file = 'training.csv'
chi_squared_file='chisquared.... | 5,286,588 |
def statistics_customer_data(request):
"""returns totals for statistics as JSON"""
cutoff_date = now() - datetime.timedelta(days=FREIGHT_STATISTICS_MAX_DAYS)
finished_contracts = Q(contracts_issuer__status=Contract.Status.FINISHED) & Q(
contracts_issuer__date_completed__gte=cutoff_date
)
cu... | 5,286,589 |
def save_all():
"""
:return: bool success
"""
return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(bus.Broadcast, "SaveAllDocuments") | 5,286,590 |
def retweet_or_no(link):
"""
Function to decide whether or not to retweet the link represented by
the bioarxiv article
Parameters
----------
link : link to bioarxiv article
Returns
-------
bool : True, if female or ambiguous
False, if male or unknown
"""
... | 5,286,591 |
def add_tenants(key, tenant_names):
"""Add the given tenant_names if they don't already exist"""
for tenant_name in tenant_names:
if not get_tenant(key, tenant_name):
key.tenants.create(tenant_name=tenant_name, enabled=True)
return True | 5,286,592 |
def get_tilting_angles(
struct: Structure,
b_cation: str = 'Pb',
x_anion: str = 'I',
distance_between_b_cations: float = 6.6,
distance_between_b_x: float = 3.8,
algorithm: str='neighbors',
verbose: bool = False,
):
"""
Calculates tilting angles (between B-X-B) for a given structure.... | 5,286,593 |
def create_persistence_distance_file(
orig_path: str,
interpol_path: str,
savefile: bool = True,
distance_type: ["wasserstein", "bottleneck"] = "wasserstein",
filtration: ["alpha", "rips", "witness"] = "rips",
amount_of_files: int = 100
) -> np.ndarray:
"""
Creates from two directories w... | 5,286,594 |
def _write_json(fname, dictionary, overwrite=False, verbose=False):
"""Write JSON to a file."""
if op.exists(fname) and not overwrite:
raise FileExistsError(f'"{fname}" already exists. '
'Please set overwrite to True.')
json_output = json.dumps(dictionary, indent=4)
... | 5,286,595 |
def test_ncbi_genome(genome="ASM2732v1", provider="NCBI"):
"""Test NCBI.
Download smallest genome from NCBI and retrieve a
specific sequence.
"""
tmp = mkdtemp()
genomepy.install_genome(genome, provider, genome_dir=tmp)
g = genomepy.Genome(genome, genome_dir=tmp)
seq = g["ANONYMOUS"][80... | 5,286,596 |
def time_str_fixer(timestr):
"""
timestr : str
output
rval : str
if year is 2006, hysplit trajectory output writes year as single digit 6.
This must be turned into 06 to be read properly.
"""
if isinstance(timestr, str):
temp = timestr.split()
year = str(int(temp[0])).zf... | 5,286,597 |
def plot_corr_map(
sourceTable, sourceVar, targetTables, targetVars,
dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2,
temporalTolerance, latTolerance, lonTolerance, depthTolerance,
method='spearman', exportDataFlag=False, show=True
... | 5,286,598 |
def abs(x):
"""Element-wise absolute value.
# Arguments
x: Tensor or variable.
# Returns
A tensor.
"""
return tf.abs(x) | 5,286,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.