content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def factors_list(n):
"""Return a list containing all the numbers that divide `n`
evenly, except for the number itself. Make sure the list is in
ascending order.
>>> factors_list(6)
[1, 2, 3]
>>> factors_list(8)
[1, 2, 4]
>>> factors_list(28)
[1, 2, 4, 7, 14]
"""
all_factors ... | 1d2dd96f62399c714f5b61be12aaad2ea891b5ea | 653,619 |
from bs4 import BeautifulSoup
def create_soup(url):
"""
Create soup object from url
"""
try:
html_report_part1 = open(url,'r')
soup = BeautifulSoup( html_report_part1, "html.parser")
return soup
except Exception as e:
print("[ERROR] Error occurred in requesting html... | 29d9a23c9edde02484c2eee7adef77372ccaa00f | 653,622 |
def to_list(dataseq):
"""Converts a ``ctypes`` array to a list."""
return list(dataseq) | 3a4a7ce1a8e987a7c3ae69e6b0e8b32a077cd6f3 | 653,623 |
def write(content, path):
"""
Write string to utf-8 pure text file
"""
with open(path, "wb") as f:
return f.write(content.encode("utf-8")) | 22205d076479ddde192573450b6cf7b74a6be231 | 653,624 |
def _append_if_error(errors, sentence_id, test, explanation, token=None):
"""
If a test fails, append an error/warning dictionary to errors.
Args:
errors: a list of errors
sentence_id: ID of the sentence this applies to
test: boolean from a checked expression
explanation: us... | 78476118ddb073aefc86c4e926b66b9f91e252ec | 653,625 |
def get_url_path(url):
"""Return a list of all actual elements of a url, safely ignoring
double-slashes (//) """
return filter(lambda x: x != '', url.split('/')) | 90f7558f974253f326732d6b4536ad2b3b107748 | 653,626 |
def textblock(text, indent=0):
"""
Indent textblock by specified number of spaces.
.. code-block:: pycon
>>> block = 'one\ntwo'
>>> print(textblock(block))
one
two
>>> print(textblock(block), 4)
one
two
"""
if indent:
return ('\n' + ' ' * indent).join(... | 0364b199b7934f8ec79ffe3d93693a0076706cd3 | 653,629 |
def g2N(T):
"""
Converting gram to Newton
"""
return [0.00980665 * i for i in T] | 648ff44af335d762fa083e1ba1bb62f1474f60a4 | 653,632 |
from typing import Dict
from typing import Any
def get_syntax(selected: Dict[str, Any], cmd: str) -> str:
"""Returns the syntax for a given command
Parameters
----------
selected : Dict[str, Any]
The command object
cmd : str
The command that was attempted
Returns
--------... | 4de2bf50dc3b12a7f20ebbf3e6d8cf8ba1c75d2f | 653,633 |
def predict_model_gen(session, style_dataset, sample_count):
"""Create a generator function that emits style images.
Args:
session: tf.Session, the session that contains subgraph to load the traning
dataset
style_dataset: tf.data.Dataset that contains training style images.
sample_count: int, num... | a781a4f625a961e725ef108d5a8a49799da6ad23 | 653,636 |
def binary_search(array, elem, first, last):
"""
Search for an element in an array using binary search
:param array: array to look for element
:param elem: the lement to look for
:param first: the index of the first position in the array
:param last: the index of the last position in the array
... | 8af4b1cc35dac36f7176c039c37318bf7b54b6e6 | 653,639 |
def string_time_from_ms(time_in_ms: int, hours: bool = False) -> str:
"""
Convert timestamp in millisecond in a string with the format mm:ss.xxx
If hours is true the format will be hh:mm:ss.xx
"""
# if no time time_in_ms is equal to the maximum value of a 32bit int
if time_in_ms == 2147483647 o... | aabcaf1e5e2038f28fb529ee1f83539c8e47b161 | 653,640 |
def format_timedelta(timedelta):
"""Formats a timedelta object to a string by throwing off the microsecond
part from the standard timedelta string representation.
"""
whole_repr = str(timedelta) + '.'
return whole_repr[:whole_repr.find('.')] | 8c71eb5dc7fbbed65eaece1e84351c805011e9d0 | 653,641 |
from typing import List
import math
def calculate_raster_coordinate(longitude: float, latitude: float, origin: List[int], pixel: List[int]):
""" From a given longitude and latitude, calculate the raster coordinate corresponding to the
top left point of the grid surrounding the given geographic coordinate.
... | 7a9f809121afd375fec3628f69a4d830d9f7674a | 653,643 |
def escape(string):
"""Escape strings to be SQL safe"""
if '"' in string:
raise Exception("Can't escape identifier {} because it contains a backtick"
.format(string))
return '"{}"'.format(string) | 054b3b2908d10f82be41bfaa2e587d4e800dea84 | 653,644 |
def _region_to_coords(region):
"""Split GATK region specification (chr1:1-10) into a tuple of chrom, start, end
"""
chrom, coords = region.split(":")
start, end = coords.split("-")
return (chrom, int(start), int(end)) | 5ffb2c0c12541ffe31e648b043b18301969e09a8 | 653,648 |
def edges_iter(G,nbunch=None):
"""Return iterator over edges adjacent to nodes in nbunch.
Return all edges if nbunch is unspecified or nbunch=None.
For digraphs, edges=out_edges
"""
return G.edges_iter(nbunch) | 147c2b1e105453fdabf96a2849b738b5d49b8065 | 653,651 |
def _ConditionHelpText(intro):
"""Get the help text for --condition."""
help_text = """
{intro}
*expression*::: (Required) Expression of the condition which
evaluates to True or False. This uses a subset of Common Expression
Language syntax.
*title*::: (Required) Title for the expression, i.e. a short string
desc... | 3899206fc5bb60c6dec9bc0fc58dcce80cb0799b | 653,663 |
def configsection(config, section):
"""
gets the list of keys in a section
Input:
- config
- section
Output:
- list of keys in the section
"""
try:
ret = config.options(section)
except:
ret = []
return ret | 6850cc0478242364f98864190daaa34704c39569 | 653,664 |
def _py2vim_scalar(value, null, true, false):
"""Return the given Python scalar translated to a Vim value.
None, True, and False are returned as the (Vim) sentinel values 'null',
'true', and 'false', respectively; anything else is returned untouched.
"""
if value is None:
return null
if... | 3fff2543663b695d39e1c56bd728ee4f3a47b0d4 | 653,666 |
def Y_i(i,A,X):
"""
Calculate band `i` of the coordinate rotation described in equation 8 of
Lyzenga 1978.
Parameters
----------
i : int
The band number of `Y` to calculate.
A : np.array
The coordinate system rotation parameters calculated by the method
`Aij` and des... | c0b62a5bb36ecfc86db12e4cb35a03d425e8d524 | 653,667 |
def degree_max_repetition(recpat_bag:list):
"""
Computes the degree of maximal repetition from a bag of
recurring patterns -- a list of ngram tuples.
"""
return max([len(recpat) for recpat in recpat_bag]) | dc5f20123eb56957284a69487b80e37abecdcd87 | 653,668 |
def is_valid_cog(cog):
"""Validates course over ground
Arguments
---------
cog : float
Course over ground
Returns
-------
True if course over ground is greater than zero and less than 360 degrees
"""
return cog >= 0 and cog < 360 | a2aadeb235aa6ab69e3ad6673288703fbce049dc | 653,676 |
def IsGlobalTargetGrpcProxiesRef(target_grpc_proxy_ref):
"""Returns True if the target gRPC proxy reference is global."""
return target_grpc_proxy_ref.Collection() == 'compute.targetGrpcProxies' | 20ea7d0baf818a2435506a7e0a23f7c1a0921f36 | 653,677 |
def divide(num, den):
"""
Divide num by den in a template, returns 'NaN' if denominator is 0.
"""
return (float(num) / float(den)) if float(den)!=0 else 'NaN' | 1c5d8c797a4d2492657f25d8c72b9d060a56db51 | 653,680 |
def _get_all_objects(objs):
"""
Helper function to get all objects of a 'Network' along with their
corresponding ``contained_objects``.
Parameters
----------
objs : Iterable
List or set of objects
Returns
-------
all_objects : set
A set of all Network's objects and ... | df555ffb632bfef1e8aa70fae5588bc311ef5faa | 653,681 |
def is_empty(df):
"""Tests if a pd.DataFrame is empty or not"""
return len(df.index) == 0 | fd204f0824a70cbd0388d02cbaffa49514403ee8 | 653,683 |
def bytes2human(n: int) -> str:
"""Convert `n` bytes into a human readable string.
>>> bytes2human(10000)
'9.8K'
>>> bytes2human(100001221)
'95.4M'
"""
# http://code.activestate.com/recipes/578019
symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y")
prefix = {}
for i, s in enumera... | 6929ad5c3fb865a32e733ba6c0d9fdfed0493efc | 653,693 |
import torch
def extend_batch(batch, dataloader, batch_size):
"""
If the batch size is less than batch_size, extends it with
data from the dataloader until it reaches the required size.
Here batch is a tensor.
Returns the extended batch.
"""
while batch.shape[0] != batch_size:
data... | cbc87d52116c0b4075c3fee3abe7d528d32be56d | 653,695 |
def queue_to_list(queue):
"""Convert a Queue to a list."""
result = []
while queue.qsize() != 0:
result.append(queue.get())
return result | ef40ef32373b81689925dd145842b44033c107e5 | 653,697 |
def get_value(json, attr):
"""Get the value from the json."""
if attr in json:
return json[attr][0]
return "" | df795daca80a4499b58270cd1a5b48ae3e73d5ac | 653,702 |
def run_async(coro):
"""Execute a coroutine until it's done."""
values = []
result = None
while True:
try:
values.append(coro.send(None))
except StopIteration as ex:
result = ex.args[0] if ex.args else None
break
return values, result | f77d62546958dde04c34d788b89ef0a1f7d11e25 | 653,703 |
def get_log_prob_unigram(masked_token_ids, token_ids, mask_idx, lm):
"""
Given a sequence of token ids, with one masked token, return the log probability of the masked token.
"""
model = lm["model"]
tokenizer = lm["tokenizer"]
log_softmax = lm["log_softmax"]
mask_token = lm["mask_token"... | d68dbf996966584c16bbf8ebc13c5c4af079c270 | 653,708 |
def num_region_obs(count_arr, lon_idxs, lat_idxs):
"""
Given lon/lat indices and array of GOSAT counts, determine number of
observations in the region as defined by the indices.
Parameters:
count_arr (np arr) : array of counts (Mx72x46), M num months
lon_idxs (np arr) : array of longit... | 2ca841b003e81637e87f497b628ecea805092fed | 653,709 |
def get_uid_from_action_name(action_name, uid_string=None):
"""
Extract id from action name by splitting at "__", because this marks the start of id in action name.
If uid string is in action name, remove it
:param action_name: full action name of processor (e.g. "{action_type}_{aName}_{id}[uid_string}]... | 01f28bf98ecc390bda02e1a2736c32192abbacf9 | 653,711 |
def metaclass_name_for_class(classname):
"""Return the name of the C++ metaclass for the given class."""
if '::' in classname:
return None
return classname + '::MetaClass' | dda8195475b34aa6dc51f4ce5b4dbe0bd01398ea | 653,713 |
from pathlib import Path
def file_exists(
path,
exception=ValueError,
emsg="`path` is not a file or does not exist",
):
"""
Assert if file exist.
Parameters
----------
path : str or pathlib.Path
The file path.
exception : Exception
The Exceptio... | a9b8c3f633ea9e0ffc906064042ade2a4aa0a1e2 | 653,715 |
import base64
def b64e(b):
"""Base64 encode some bytes.
Uses the url-safe - and _ characters, and doesn't pad with = characters."""
return base64.urlsafe_b64encode(b).rstrip(b"=") | 3c2ce4e5658d2b3ec1f0b0c46464f5baaffbe20c | 653,719 |
import torch
def tensor_abs(inputs):
"""Apply abs function."""
return torch.abs(inputs) | f7c5e0c0a4fa35ade7bae98ceb7236a1f7ccce45 | 653,720 |
from typing import Dict
from typing import Any
def parse_camera_id(metadata: Dict[str, Any]):
"""
Determine the camera the photograph was taken with from its EXIF data.
:param metadata: EXIF data to find the camera from.
:returns: The camera id, if it could be determined. If not, returns ``'Unknown'``.
"""
f... | 1468bac8b6e69d73a021c09c97730e9ae3d25f61 | 653,722 |
def key2freq(n: int) -> float:
"""
Gives the frequency for a given piano key.
Args:
n: The piano key index
Returns:
The Frequency
"""
return 440 * 2 ** ((n - 49) / 12) | aab19e8d4fe592249daef7302895af200ab11486 | 653,724 |
def order(sentence: str) -> str:
"""
Sorts a given string by following rules:
1. Each word in the string will contain a single number.
This number is the position the word should have in the result.
2. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
3. I... | 6d69ed655274c6d0d6dc8ae935217e8b5663c2e4 | 653,726 |
import configparser
def setupcfg_has_metadata(setup_cfg_filename='setup.cfg'):
"""Parse the setup.cfg and return True if it has a metadata section"""
config = configparser.ConfigParser()
config.read(setup_cfg_filename)
if 'metadata' in config.sections():
return True
return False | 8c22cfac3614a43969e0adaa249e7440f83d74dd | 653,729 |
def isnumber(word):
""" Checks if a string is a string of a number.
Parameters
----------
word : string
String of the possible number.
Returns
-------
Boolean.
"""
try:
float(word)
except (ValueError, TypeError):
return False
return True | 3b248a71cb97628bed2f10839e747be49da000f3 | 653,733 |
import hashlib
def md5(filepath, blocksize=65536):
"""Generate MD5 hash for file at `filepath`"""
hasher = hashlib.md5()
fo = open(filepath, 'rb')
buf = fo.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = fo.read(blocksize)
return hasher.hexdigest() | 9906d76de66def0efeaafb2e2d4525bdf218ccb9 | 653,736 |
from pathlib import Path
from typing import Optional
def resolve_absolute_offset(
dataset_path: Path, offset: str, target_path: Optional[Path] = None
) -> str:
"""
Expand a filename (offset) relative to the dataset.
>>> external_metadata_loc = Path('/tmp/target-metadata.yaml')
>>> resolve_absolut... | cbeb2dfb6fea41d5a995ada529d964357c4e9fb9 | 653,737 |
import json
def to_json(data):
"""Return a JSON string representation of data.
If data is a dictionary, None is replaced with 'null' in its keys and,
recursively, in the keys of any dictionary it contains. This is done to
allow the dictionary to be sorted by key before being written to JSON.
"""... | c9c9309ccecbf37c513f18206a9eae495f30095a | 653,738 |
import math
def _calculate_target_load(num_reqs: int, rate: float = 100, baseline: int = 0) -> int:
""" Given the rate and number of URLs in data set, calculate how many URLs to send in this load"""
if baseline:
target_num_reqs = baseline * (rate / 100)
else:
target_num_reqs = num_reqs * (... | 953cbdafa18899f59743932f7edad31d72080ea8 | 653,743 |
def format_name(name: str) -> str:
"""Formats a string for displaying to the user
Examples
--------
>>> format_name("manage_messages")
'Manage Messages'
>>> format_name("some_name")
'Some Name'
Parameters
----------
name : str
the raw name
Returns
-------
s... | 2147183419073f11270cb664df345ced98e44001 | 653,745 |
def string_to_int_list(line) -> list[int]:
"""
Given a line containing integers, return a list of ints.
Return list[int]: A list of integers from the string.
>>> string_to_int_list('22 13 17 11 0')
[22, 13, 17, 11, 0]
>>> string_to_int_list('22,13,17,11,0')
[22, 13, 17, 11, 0]
"""
... | 0a31a7e3b320effb1851d1f37e9fb640c78d0c72 | 653,751 |
def get_push_size(op):
"""Get push side increment for given instruction or register."""
ins = op.lower()
if ins == 'pushq':
return 8
elif ins == 'pushl':
return 4
else:
raise RuntimeError("push size not known for instruction '%s'" % (ins)) | 3381f917647cb5799fb66fb7803e95a570e02b5c | 653,753 |
import requests
def get_number_of_asa_service_groups(asa):
"""
Returns the number of service object-groups the given ASA object has configured.
:param asa: ASA device to count network object-groups.
:return: Integer which describes how many object-groups is found on ASA.
"""
url = asa.url() + ... | a175ea823dfad4bf791da8ad3198ee9c002f0134 | 653,754 |
def zeros(n: int) -> int:
"""Return the number of trailing zeros in the binary representation of n.
Return 0 if n == 0."""
result = 0
while n & 1 == 0:
n = n // 2
result += 1
return result | b215f80dba4aa66ad6cf2baebb24bc6731acfd46 | 653,759 |
import re
def get_nb_query_params(nb_url_search: str) -> dict:
"""
Get the url query parameters from the search string.
Arguments:
nb_url_search {str} -- The URL search string
Returns:
dictionary of the query string parameters.
"""
nb_params = {}
query_string_match = re.... | 123ada462b3c5e29e42f7e66eb9bd5aceeab0419 | 653,760 |
from typing import Callable
from typing import Iterator
def _exponential_backoff(
retries: int = 10,
delay: float = 2,
backoff: float = 2,
max_delay: float = 60) -> Callable:
"""
Customizable exponential backoff strategy.
Args:
retries (int): Maximum number of times... | ba05a44009dcdf4bfb4176fbbc2b0b207b4d8757 | 653,761 |
def find_zeroes_2(f, a, b, epsilon=1e-10):
"""
A formulation of the recursive version of find_zeroes that does not do explicit recursion on the stack.
:param f: The function.
:param a: The lower bound of the interval.
:param b: The upper bound of the interval.
:param epsilon: The stopping toler... | 6ef58e6a32af6eca23bfb734416b9f3d30273b7a | 653,763 |
def find_scenario_string_from_number(scenario):
"""
Find a string to represent a scenario from it's number (or None in the case of baseline).
Args:
scenario: The scenario value or None for baseline
Returns:
The string representing the scenario
"""
if scenario == 0:
retu... | e5c60751506f9e6e79a863426d9ba80bab617bca | 653,768 |
import io
def load_data(dataset_path):
"""
load data from a file
:param dataset_path:
:return: a list of all the items in the file
"""
items = []
with io.open(dataset_path, "r", encoding="utf8") as f:
for line in f:
items.append(line.rstrip())
return items | d3f2f6916ea187cf48e1fc9bb8a5cec12d392ef1 | 653,769 |
from typing import List
def get_clusters_from_labels(texts: List[str], labels: List[int]) -> List[List[str]]:
"""Given a series of texts and their labels (as produced during clustering), reconstructs the clusters"""
return [[text for text, lab in zip(texts, labels) if lab == label] for label in set(labels) i... | fb91c228552d05395f87e508044c324a3784e324 | 653,773 |
def parsing_explore_lines(explore_list, loc_list):
"""
This function parses a list of explore lines into a grouped structure of explore lines.
:param explore_list: the list representing raw explore file.
:type explore_list: list
:param loc_list: the list of dividers, each divider is the number of... | 272d6a2f5f04207a6dd18a78f8cc56967d5ed90f | 653,775 |
def names_to_labels(names, depth=1, sep='.'):
"""
convert names to grouping labels
Parameters
----------
names : [str]
account names in form of 'Foo.Bar.Baz'
depth : int, optional
returned label depth. The default is 1.
sep : char, optional
Separator character. The d... | 230d846ece8e4d054b69bc1bc8f417440c01b5d5 | 653,776 |
def apply_filter(x, W):
"""
Applies a filter on the mixture. Just corresponds to a matrix
multiplication.
Parameters
----------
x: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)]
STFT of the signal on which to apply the filter.
W: np.ndarray [shape=(nb_frames, nb_bins, nb_chan... | 3ff75cc93afe9ac88dfe25022b04d73f266251fd | 653,778 |
import copy
def merge_dict(a, b):
"""Merge the fields of a and b, the latter overriding the former."""
res = copy.deepcopy(a) if a else {}
copyb = copy.deepcopy(b) if b else {}
for key in copyb:
res[key] = copyb[key]
return res | 8913662e3cb229ebbe3e4a2abd54041223dc0def | 653,780 |
import math
def distance_between_points(x, y):
"""
distance between two points with the coordinates (x1, y1) and (x2, y2).
D=√(x2−x1)2+(y2−y1)2
"""
all_distances = []
zipped = zip(x,y)
for z in zipped:
z1, z2 = z
all_distances.append((z1-z2)**2)
return math.sqrt(sum(all... | 1abdf477f7b1045274727b5323b19f4351786459 | 653,783 |
def GetGlueCpp(idl_file):
"""Gets the name of the glue implementation file.
Args:
idl_file: an idl_parser.File, the source IDL file.
Returns:
the name of the implementation file.
"""
if 'npapi_cpp' in idl_file.__dict__:
return idl_file.npapi_cpp
else:
return idl_file.basename + '_glue.cc' | 2aeac9f681389d750866bdd3961cb0e2df569747 | 653,789 |
def register_event(event_type, include_subclasses=False):
"""
Register a method to handle a specific `opsdroid.events.Event` object.
Args:
event_type (Event): The event class this method can handle.
include_subclasses (bool): Allow the function to trigger on subclasses of the registered
... | ab47a895471ae1911e6da30264677a596231de49 | 653,792 |
import random
def CryptRandInt(length=10):
"""Get random integer in range"""
#byte = os.urandom(100)
#rand = int(byte.hex(),16)
r = random.SystemRandom()
rndint = r.randrange( length )
return rndint | e561d923ffcb62d7d456bf855c7be7d7779c9dc8 | 653,794 |
def encode_data(data):
"""Encode sysex data as a list of bytes. A sysex end byte (0xf7)
is appended.
"""
return list(data) + [0xf7] | c3ad4a28f011deec89d3b96445c4dd2d8f6433c6 | 653,799 |
def splitProjectInfo(value: str):
"""Split a comma-separated list of 3 values (hub,group,project)"""
tokens = value.split(",")
if len(tokens) != 3:
raise RuntimeError(f"Invalid project: {value}")
return tokens | df60c85ac4778a6462012db7f9573dca1880ddc6 | 653,800 |
import torch
def num_flat_features(x: torch.Tensor) -> int:
"""
Computes the total number of items except the first dimension.
:param x: input tensor
:return: number of item from the second dimension onward
"""
size = x.size()[1:]
num_features = 1
for ff in size:
num_features ... | 24a8889a070afb3365b60c9afe82cfc0440a3774 | 653,802 |
import re
def parse_role_for_profile(role: str) -> str:
"""Returns a 'safe' profile name for a given role.
Args:
role: The role to generate a profile name for.
Returns:
Formatted profile name.
"""
account_id = "000000000000"
role_name = "Unknown-Role-Name"
account_re = r... | 156624fe49ec033e6c55ef7f41cba1f7281d4c2f | 653,806 |
def datetime_to_str(date_time):
"""
Convert datetime to string. This format is specific to the 42API responses.
Arguments:
date_time: (datetime) the datetime.
Returns:
(str) containing the string equivalent of the datetime object.
"""
return (date_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ")) | 1f190e3d39a78fb63f19abc386da0f288d3d720f | 653,814 |
def verbose_name(obj):
"""Return the object's verbose name."""
try:
return obj._meta.verbose_name
except Exception:
return '' | ae5542404b326be960331632239c11b0ad0411dc | 653,815 |
def unique(s, key=None):
"""
Return unique entries in s
:Returns:
A sequence of unique entries of s.
If `key` is given, return entries whose key(s) is unique.
Order is preserved, and first of duplicate entries is picked.
"""
if key is not None:
keys = (key(x) fo... | 46b69e2ad191cf5cd8e256b669b7158829b5a5ef | 653,816 |
async def index(request):
"""
This is the view handler for the "/" url.
:param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request
:return: context for the template.
"""
# Note: we return a dict not a response because of the @template decorator
... | 254a1a741efb3c7bf3df57b046bacb94294c397f | 653,817 |
import copy
def CountUnique(inputList):
"""
Count the number of unique entries in the supplied list
"""
lInputList = copy.copy(inputList)
lInputList.sort()
count = 0
if len(lInputList) > 0:
count += 1
for i in range(1, len(lInputList)):
if not lInputList[i] == lInputList[i - 1]:
co... | 965610acf91339bd6b6fff93602c3fe5da5ca6d6 | 653,819 |
def simulate(job):
"""Run the minimization, equilibration, and production simulations"""
command = (
"gmx_d grompp -f em.mdp -c system.gro -p system.top -o em && "
"gmx_d mdrun -v -deffnm em -ntmpi 1 -ntomp 1 && "
"gmx_d grompp -f eq.mdp -c em.gro -p system.top -o eq && "
"gmx_d... | 2b4aad3e01f6e826e43114065748470361e7fc9b | 653,820 |
def categories_to_string(categories, queryset=False):
"""
Args:
categories: [{"title": "Business"}, ...] OR
[models.Category] (if queryset=True)
Returns:
['<category.title', ...]
"""
if queryset:
new_categories = [i.title for i in categories]
else:
... | d5e99477b30eb7fed20df837f7dbfb15da52958b | 653,825 |
from typing import Union
def _intermediate_helper(
start_unit: str,
end_unit: str,
quantity: Union[int, float],
imperial: dict,
metric: dict,
) -> Union[int, float]:
"""
Function turns any input quantity into an intermediate value based on dictionary constants. Function
then takes the... | 5d7c378bc39a61e9a271b65485a91ae65f5ae22e | 653,826 |
import six
def _bytes(*args):
"""
Returns a byte array (bytes in py3, str in py2) of chr(b) for
each b in args
"""
if six.PY2:
return "".join(chr(c) for c in args)
# else: Python 3
return bytes(args) | 59fbdc1f10ef1a5e8d3b0f43aae8f18614c5d554 | 653,828 |
import torch
def hat(v: torch.Tensor):
"""Maps a vector to a 3x3 skew symmetric matrix."""
h = torch.zeros((*v.shape, 3), dtype=v.dtype, device=v.device)
h[..., 0, 1] = -v[..., 2]
h[..., 0, 2] = v[..., 1]
h[..., 1, 2] = -v[..., 0]
h = h - h.transpose(-1, -2)
return h | 60876797f76c407c01b0d729bccca5d3ab6f3366 | 653,829 |
import string
def create_character_list(args):
"""Create the list of allowed characters to generate passwords from"""
possible_chars = []
if args.uppercase_ascii:
possible_chars += string.ascii_uppercase
if args.lowercase_ascii:
possible_chars += string.ascii_lowercase
if args.n... | 79f660f48f713296887ec47a899a7b3af84ef75f | 653,830 |
import torch
from typing import Tuple
def _equalize_attributes(actual: torch.Tensor, expected: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Equalizes some attributes of two tensors for value comparison.
If :attr:`actual` and :attr:`expected`
- are not onn the same memory :attr:`~torch.Tensor.de... | 9f69a726d31898489abcb3d6da2d196ea8193056 | 653,832 |
def rightDiagonalProduct(a, diag):
"""
Calculate the product of a matrix and a diagonal matrix, with broadcast.
Parameters
----------
a : 2D ndarray of float
diag : array of float
The diagonal elements of the diagonal matrix.
Returns
2D ndarray of float
Matrix (a @... | e45ba7f6ca950d581396c04cec972ccb7c7d903e | 653,833 |
def bcon(reg, blocks):
"""
Block list converter.
If blocks is a list of integers, convert to a list of blocks using reg.blocks.
Else, do nothing.
Return list of blocks.
"""
## go
if len(blocks)>0 and type(blocks[0])==int:
blocks = [ reg.blocks[blocks[i]] for i in range(len(blocks)) ]
## return
return blocks | b253f83a36cf07f6bda2a4bb3e64826654650f3d | 653,838 |
def _get_vertex_location_name(location):
"""Get the location name from a location that is expected to point to a vertex."""
mark_name, field_name = location.get_location_name()
if field_name is not None:
raise AssertionError(u"Location unexpectedly pointed to a field: {}".format(location))
return mark_name | 26ccd09f7749506e31aa4fb8d02941b3816ea2c0 | 653,839 |
def _generate_manifest(ctx, srcs):
"""Create a `clang_format_manifest` output file
Args:
ctx (ctx): The rule's or aspect's context object
srcs (list): A list of File objects
Returns:
File: The manifest
"""
manifest = ctx.actions.declare_file(ctx.label.name + ".clang_format.... | e6659e3d498f7f3ac2354c664496e1c20a4b9478 | 653,840 |
def to_int16(y1, y2):
"""
Convert two 8 bit bytes to a signed 16 bit integer.
Args:
y1 (int): 8-bit byte
y2 (int): 8-bit byte
Returns:
int: 16-bit integer
"""
x = (y1) | (y2 << 8)
if x >= 32768:
x = -(65536 - x)
return x | 6bed81d20f68725b35498b157204b11ac13e730f | 653,845 |
def any_positive_or_none(*args):
"""Return None if any argument is negative and the list of its argument otherwise"""
for arg in args:
if arg < 0:
return None
return list(args) | c25c90d6743435707dd79b46f5527cea06ebc834 | 653,846 |
import glob
def get_bridges(vnic_dir='/sys/devices/virtual/net'):
"""Return a list of bridges on the system."""
b_regex = "%s/*/bridge" % vnic_dir
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)] | 685ffe3ccae18306c49eb4091c360e966674e606 | 653,850 |
import math
def compute_heading_angle(source_coordinates,
target_coordinates,
radians=True,
apply_r2r_correction=True):
"""Computes heading angle in the xy plane given two xyz coordinates.
Args:
source_coordinates: Source triplet w... | 05de53d86a65ba07e742af6af376b1f2c11de27a | 653,852 |
import torch
def input_2_tensor(input_seq, encoding_space):
"""convert regular sequence of values to one hot encoding tensor"""
input_tensor = torch.zeros((len(input_seq), len(encoding_space)), dtype=torch.float)
for e, element in enumerate(input_seq):
element_tensor = torch.zeros(len(encoding_sp... | 0cb551201d0a321ad5a8ea5aa4a9a54e215b3299 | 653,857 |
import difflib
def get_similar_words(word_with_typo, words):
"""Returns a list of similar words.
The parameters we chose are based on experimenting with
different values of the cutoff parameter for the difflib function
get_close_matches.
Suppose we have the following words:
['cos', 'cosh', '... | b1e37b2f475a59e7ec465316b47dc6ca3b8543ec | 653,859 |
def power_function(context, base, exponent):
"""
The math:power function returns the value of a base expression taken to
a specified power.
"""
base = base.evaluate_as_number(context)
exponent = exponent.evaluate_as_number(context)
return base**exponent | f698691bec21f4bb8f3f306c0989077306b32bf5 | 653,862 |
import re
def multireplace(string, replacements):
"""
Replace multiple matches in a string at once.
:param string: The string to be processed
:param replacements: a dictionary of replacement values {value to find, value to replace}
:return: returns string with all matches replaced.
Credit to b... | af5eef4a211dd5fb82ff07feb75b40fc1ce3e176 | 653,864 |
import torch
def vae_loss(x, recon, mu, logvar, beta):
"""Standard VAE Loss.
Args:
x: input image.
recon: model output as reconstruction of input.
mu: mean of latent.
logvar: logvar of latent distribution.
beta : Hyper-param in loss function.
Returns:
floa... | e79f1f67a9cab255511886154d6bfd5a0109b05d | 653,865 |
def write_float_11e(val: float) -> str:
"""writes a Nastran formatted 11.4 float"""
v2 = '%11.4E' % val
if v2 in (' 0.0000E+00', '-0.0000E+00'):
v2 = ' 0.0'
return v2 | ba6c808f5f8ee986046cc0752b8449d46be1f2fa | 653,868 |
def EgVarshni(E0, VarshniA, VarshniB, tempDet):
"""
This function calculates the bandgap at detector temperature, using the
Varshni equation
Args:
| E0: band gap at room temperature [eV]
| VarshniA: Varshni parameter
| VarshniB: Varshni parameter
| tempDet: detector oper... | a3920d65a7d11a799962b3dc899275f96815651f | 653,869 |
def get_kw_pos_association(kernel):
"""
Returns a tuple of ``(kw_to_pos, pos_to_kw)`` for the arguments in
*kernel*.
"""
kw_to_pos = {}
pos_to_kw = {}
read_count = 0
write_count = -1
for arg in kernel.args:
if not arg.is_output_only:
kw_to_pos[arg.name] = read_c... | a219ea9ffe5eee36d346bd99eb3b2443a91df210 | 653,870 |
from typing import Sequence
def _add_one(s: Sequence[int]) -> Sequence[int]:
"""Adds one to each element in the sequence of integer."""
return [i + 1 for i in s] | 71af45b5f408c86b02eef50fa6c72ffd539649ab | 653,871 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.