content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def reshape_to_grid(data_flat, coords, shape):
"""Given a flattened array of data with the corresponding Y and X coordinates and the desired grid shape, return the grid of desired shape with the data given. Assumes flattened array has a time dimension as first dimension.
:arg data_flat: 2d array of data. First... | 56,900 |
def point_mutation(bitstring, mutation_rate):
"""
:param bitstring: '100011...' - 32 bit
:param mutation_rate: 0.08
:return:
"""
child = ""
for bit in bitstring:
if random() < mutation_rate:
child += "0" if bit == "1" else "1"
else:
child += bit
re... | 56,901 |
def test_2():
"""Computational test for mt_ays.check_matchings()."""
store_minimizer = np.array([1, 0, 1])
num_points = 3
counter_matches = 0
for j in range((num_points)):
minimizer_1 = store_minimizer[j]
for k in range(j + 1, num_points):
minimizer_2 = store_minimizer[k]... | 56,902 |
def process_common_arguments(FLAGS) -> None:
""" Processes the common arguments.
Arguments:
FLAGS - The flags that come from parser.parse_args()
Returns:
None
"""
if 'loglevel' in FLAGS:
if FLAGS.loglevel == "critical":
logging.basicConfig(level=logging.CRITICAL,
format="%(levelname)s... | 56,903 |
def coupledHarmonicOscillator_nonlinear( N=500,
dt=0.1,
ICs={ 'y1_0': 0,
'x1_0': 1,
'y2_0': 0,
'x2_0': 0},
args={ 'f1': 45,
'f2': 150,
'm': 1,
'E': 1e5},
plot=False,
verbose=False):
"""
... | 56,904 |
def whos(input_file: str = "ipList.txt",
output_file: str = "rdapIPs.txt",
use_cache: bool = True):
"""Checks RDAP data based on an input file with a list of ip's"""
my_parser: MyParser = MyParser()
my_caching: MyCaching = MyCaching()
my_writer: MyWriter = MyWriter()
rdap_service: ... | 56,905 |
def filter_missing_value(keypoints_list, method='ignore'):
# TODO: impletemd 'interpolate' method.
"""Filter missing value in pose list.
Args:
keypoints_list: Estimate result returned by 2d estimator. Missing value
will be None.
method: 'ignore' -> drop missing value.
Return:
... | 56,906 |
def test_wildcard_search_exact_match(session, query, expected_number_of_hits):
"""
Test different wildcard queries
check that the number of results is exactly as expected
"""
response_json = get_search(session, {'q': query, 'limit': '0'})
compare(response_json['total']['value'], expected_number_... | 56,907 |
def remove_punctuation(line):
"""
去除所有半角全角符号,只留字母、数字、中文
:param line:
:return:
"""
rule = re.compile(u"[^a-zA-Z0-9\u4e00-\u9fa5]")
line = rule.sub('', line)
return line | 56,908 |
def CurrentTimeInSec():
"""Returns current time in fractional seconds."""
return time.time() | 56,909 |
def pair(global_lut: dict, src: str, trace: Trace) -> str:
"""parsers a key value pair, returns the key"""
kv = src.split(Token.VALUE_SEPARATOR)
if len(kv) > 2:
# warn about assigning a value twice
# key = x = y
# in this case only the last value will be used
warn(Warn.MU... | 56,910 |
def env_decode(value):
"""
Decodes an environment variable name or value that was returned by
get_env(for_subprocess=True)
:param value:
On Python 3, a unicode string, on Python 2, a byte string
:return:
A unicode string
"""
if not py2:
if not isinstance(value, str... | 56,911 |
def selection_sort(a):
"""
Sorts a list using the selection sort method.
"""
for n_pass in range(len(a)-1, 0, -1):
i_max = 0
# Search the max. element
for i in range(1, n_pass+1):
if (a[i] > a[i_max]):
i_max = i
# Swap current and max. elemen... | 56,912 |
def disconnect():
"""This handler serves as a global disconnect procedure that will log a
user out no matter which provider they logged in with.
"""
if 'provider' in login_session:
if login_session['provider'] == 'google':
gdisconnect()
del login_session['gplus_id']
... | 56,913 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use',
default=0, type=int)
parser.add_argument('--def', dest='prototxt',
... | 56,914 |
def saveini(inifile, params):
"""Save to a Longbow recovery file.
This method will write a simple ini formatted file.
Required arguments are:
configfile (string): This should be an absolute path to a revovery file.
params (dictionary): This should contain the data structure that should
... | 56,915 |
def DebugViewUrl(breakpoint):
"""Returns a URL to view a breakpoint in the browser.
Given a breakpoint, this transform will return a URL which will open the
snapshot's location in a debug view pointing at the snapshot.
Args:
breakpoint: A breakpoint object with added information on project and
debug t... | 56,916 |
def hyperheader2dic(head):
"""
Convert a hypercomplex block header into a python dictionary.
"""
dic = dict()
dic["s_spare1"] = head[0]
dic["status"] = head[1]
dic["s_spare2"] = head[2]
dic["s_spare3"] = head[3]
dic["l_spare1"] = head[4]
dic["lpval1"] = head[5]
dic["rpva... | 56,917 |
def convert_order_to_href(keystone_id, order_id):
"""Convert the tenant/order IDs to a HATEOS-style href."""
if order_id:
resource = 'orders/' + order_id
else:
resource = 'orders/????'
return utils.hostname_for_refs(keystone_id=keystone_id, resource=resource) | 56,918 |
def pretty_struct(ctx, title, args, kwargs, sep=' :: '):
"""Pretty print a struct."""
kwargs = {f'{k}<<{sep}>>': v
for k, v in kwargs.items()}
return pp.pretty_call_alt(ctx, str(title), args, kwargs) | 56,919 |
def upload_all_emojis(workspace_url: str, email: str, password: str) -> None:
"""Try to upload all emojis from slackmojis.com to a slack workspace."""
# pylint: disable=too-many-locals
# Login to the slack workspace
print("[*] Logging into slack workspace:", workspace_url)
client = SlackClient(work... | 56,920 |
def Gerrity_score(contingency):
"""
Returns Gerrity equitable score given a contingency table
Author: Dougie Squire
Date: 12/05/2018
Parameters
----------
contingency : xarray DataArray
A contingency table of the form output from doppyo.skill.co... | 56,921 |
def parse_args():
"""
Parse and establish the arguments we take in on the CLI
"""
parser = ArgumentParser(description="Mirror a Red Hat mirror.")
# Programmatic Things
parser.add_argument("-b", "--base", dest="base",
help="The remote base URL of the OS you want to "
... | 56,922 |
def test_metrics_on_restart(fake_training_fn, tmpdir):
"""Test that metrics are correctly read on train restart."""
fake_training = fake_training_fn(tmpdir)
assert fake_training()
t1_values = {
metric.name: get_metric_data(metric, tmpdir)
for metric in fake_training.trainer._metrics
... | 56,923 |
def get_course_assignments(course_key, user, include_access=False): # lint-amnesty, pylint: disable=too-many-statements
"""
Returns a list of assignment (at the subsection/sequential level) due dates for the given course.
Each returned object is a namedtuple with fields: title, url, date, contains_gated_c... | 56,924 |
def test_group(client: citric.Client, survey_id: int):
"""Test group methods."""
# Import a group
with open("./examples/group.lsg", "rb") as f:
group_id = client.import_group(f, survey_id)
# Get group properties
group_props = client.get_group_properties(group_id)
assert group_props["gid... | 56,925 |
def ltl_tp(L, out = None):
"""
L.T @ L with a lower triangular matrix.
Parameters
----------
L : (np, ...) ndarray
Lower triangular matrix in packed storage.
out : (np, ...) ndarray
Output buffer. If None, this will be created.
If out = L, then in-place multiplication i... | 56,926 |
def return_dictionary_list(lst_of_tuples):
""" Returns a dictionary of lists if you send in a list of Tuples"""
orDict = defaultdict(list)
# iterating over list of tuples
for key, val in lst_of_tuples:
orDict[key].append(val)
return orDict | 56,927 |
def force_bytes(
s: Any,
encoding: str = 'utf-8',
strings_only: bool = False,
errors: str = 'strict',
) -> bytes:
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (som... | 56,928 |
def delete_content():
"""
DESC : Fonction permettant de supprimer un contenu
"""
try:
compte_id, access = get_jwt_identity().split("+")
content_id = request.get_json().get("content_id")
if compte_id:
try:
CURSOR.execute("""
DEL... | 56,929 |
def collect_nested(expr):
"""
Collect numeric coefficients, trascendental functions, and symbolic powers,
across all levels of the expression tree.
The collection gives precedence to (in order of importance):
1) Trascendental functions,
2) Symbolic powers,
3) Numeric coefficien... | 56,930 |
def euler2(f2p, b, t, h, p):
"""
tuple b = boundary condition (x0, y0, y'0)
float h = step
int t = number of steps
lambda f2p = dy/dx
int p = significant digits after x values
"""
x = b[0]
y = b[1]
yp = b[2]
y2p = f2p(x, y, yp)
ret = [(x, y)] #list of tuples to be returne... | 56,931 |
def Conv2D(in_channels, out_channels, kernel_size, dropout=0, weight_norm=False, **kwargs):
"""Weight-normalized Conv2d layer"""
m = nn.Conv2d(in_channels, out_channels, kernel_size, **kwargs)
nn.init.normal_(m.weight, mean=0, std=0.1)
nn.init.constant_(m.bias, 0)
if weight_norm:
return nn.u... | 56,932 |
def get_profile():
"""Obtain the profile of the logged in user."""
user = util.user_from_jwt(request.get_json().get('token'))
if not user:
return api_error(m.USER_NOT_FOUND), 404
response = {
'username': user.username,
'name': user.name,
}
return api_success(**response... | 56,933 |
def demo_scalar(writer, n_iter):
""" Show how to add_scalar() and add_scalars() to add scalar(s) to tensorboard for NNabla.
:param writer: nnabla_tensorboard summary writer.
:param n_iter: global_step for tensorboard.
:return: nothing.
"""
dummy_s1 = nn.Variable.from_numpy_array(np.random.rand(... | 56,934 |
def check_file_size(origin, temp):
"""Compare the file size of original and re encoded file."""
origin_filesize = os.path.getsize(origin)
filesize = os.path.getsize(temp)
if origin_filesize < filesize:
Logger.info('Encoded movie is bigger than the original movie')
return False, True
... | 56,935 |
def set_validator(
func: Callable[[type], bool],
cls: Union[type, Sequence[type]],
fork_inst: type = StateHolder) -> None:
"""
Set a validator function for the given ``cls``. The function should accept
an instance of the type it should validate and must return ``False`` or
raise ... | 56,936 |
def download_from(url : str, destination_file : str) -> str:
""" Downloads a file to the specified destination.
Keyword arguments:
url -- url of the file to download
destination_file -- path to the file to download to
Returns path to the downloaded file.
"""
try:
... | 56,937 |
def parse_int(text: str) -> int:
"""
Takes in a number in string form and returns that string in integer form
and handles zeroes represented as dashes
"""
text = text.strip()
if text == '-':
return 0
else:
return int(text.replace(',', '')) | 56,938 |
def english_to_french(english_text):
"""
This Function Translates input text from English-French
"""
translate = language_translator.translate(
text = english_text,
model_id = 'en-fr').get_result()
french_text = translate['translations'][0]['translation']
return french_text | 56,939 |
def addCoverageAlpha(patches, coverage, dropThreshold=0.4):
"""Add alpha values to the colors of a polygon collection.
Parameters
----------
patches : 2D mpl mappable
coverage : array
coverage values. Maximum coverage mean no opaqueness.
dropThreshold : float
relative minimum... | 56,940 |
def record_worker_sync(hass):
"""Patch recorder_save_worker for clean thread shutdown for test."""
sync = SaveRecordWorkerSync()
with patch(
"homeassistant.components.stream.recorder.recorder_save_worker",
side_effect=sync.recorder_save_worker,
autospec=True,
):
yield syn... | 56,941 |
def pred_transform(image, target):
"""
:param image: ndarray[H, W, C] RGB
:param target: None
:return: ndarray[H, W, C] RGB 0-255, None"""
image = resize_pad(image, image_size, False, 32, False, 114)[0]
return image, target | 56,942 |
def _get_object_url_for_region(region, uri):
"""Internal function used to get the full URL to the passed PAR URI
for the specified region. This has the format;
https://objectstorage.{region}.oraclecloud.com/{uri}
Args:
region (str): Region for cloud service
uri (str): ... | 56,943 |
def _sx_source_idx_delta(azimuths, radius, dx, dy):
"""Compute indices of pixels that lie at a distance 'radius' from
the target, in the direction of 'azimuths'.
"""
azimuths_rad = np.deg2rad(azimuths)
delta_y_idx = np.rint(radius / dy * np.cos(azimuths_rad))
delta_x_idx = np.rint(radius / dx *... | 56,944 |
async def tests_datadisk_current(coresys: CoreSys):
"""Test current datadisk."""
await coresys.dbus.agent.connect()
await coresys.dbus.agent.update()
assert coresys.os.datadisk.disk_used == PosixPath("/dev/sda") | 56,945 |
def _create_motion_field(input_precip, motion_type):
"""
Create idealized motion fields to be applied to the reference image.
Parameters
----------
input_precip: numpy array (lat, lon)
motion_type : str
The supported motion fields are:
- linear_x: (u=2, v=0)
-... | 56,946 |
def build_walker(concurrency: int) -> Callable[..., Any]:
"""Return a function for waling a graph.
Passed to :class:`runway.cfngin.plan.Plan` for walking the graph.
If concurrency is 1 (no parallelism) this will return a simple topological
walker that doesn't use any multithreading.
If concurrenc... | 56,947 |
def selection_stats(units, margin=0.01, name="test", alpha=0.08, s=0.20, proportion=100.0):
"""Prepare statistics on how many audit units should be selected
in order to be able to reduce the risk of confirming an incorrect
outcome to a given probability.
units = a list of audit units, giving just size o... | 56,948 |
def tts(update, context):
"""Convert text to speech in a given language using Google TTS"""
message = update.message
if not context.args:
try:
args = message.reply_to_message.text or message.reply_to_message.caption
tts = gTTS(args, lang='ja')
message.reply_audio(... | 56,949 |
def calculate_severity_distribution(elt, grid_size=2**14, max_loss_factor=5):
""" This function calculates the severity distribution or the distribution
of the size of losses, given that an event has occurred
----------
elt : pandas dataframe containing ELT
Returns
-------
severity_distribu... | 56,950 |
def MNLI(root, split):
"""MNLI Dataset
For additional details refer to https://cims.nyu.edu/~sbowman/multinli/
Number of lines per split:
- train: 392702
- dev_matched: 9815
- dev_mismatched: 9832
Args:
root: Directory where the datasets are saved. Default: os.path.exp... | 56,951 |
def init(att_trees, data, threshold):
"""
init global variables
"""
global ATT_TREES, DATA_BACKUP, LEN_DATA, QI_LEN, THESHOLD
ATT_TREES = att_trees
DATA_BACKUP = copy.deepcopy(data)
THESHOLD = threshold
QI_LEN = len(data[0]) - 1
LEN_DATA = len(data) | 56,952 |
def full_like(other, nodata=None, lazy=False):
"""Return a full object with the same grid and geospatial attributes as ``other``.
Arguments
---------
other: DataArray
DataArray from which coordinates and attributes are taken
nodata: float, int, optional
Fill value for new DataArray,... | 56,953 |
def run_command_line(command):
"""Runs command in command line, waits for execution to end
Parameters:
command (list(string)): list of commands, for parameters each parameter must be in separate list element i.e.
['ls', '-la']. It will NOT work if you simply use ['ls -la']
Returns:
status ... | 56,954 |
def view_test(path_star="star",
poses_prediction=tf.zeros((1, 72), dtype=tf.float32),
poses_ground_truth=tf.zeros((1, 72), dtype=tf.float32),
betas=tf.zeros((1, 10), dtype=tf.float32),
dt=0.1, fps=10, gender="neutral",
color_prediction=(228, 175, 19,... | 56,955 |
def linear_mcca_resps_only(all_data, new_chans, o_dim):
"""
LINEAR MCCA WITH ONLY THE N SUBJECTS' EEG RESPONSES.
THE COMMON STIMULUS IS NOT CONSIDERED FOR THE MCCA STEP.
ARGUMENTS:
all_data: AN (N+1) ELEMENTS LIST WITH N EEG RESPONSES AND THE ELEMENT AS THE COMMON STIMULI DATA.
... | 56,956 |
def download_evaluated():
"""
Download all evaluated AMVs.
"""
if not PLUGIN.get_setting('username') or not PLUGIN.get_setting('password'):
xbmcgui.Dialog().ok(PLUGIN.name, PLUGIN.get_string(10007))
elif not PLUGIN.get_setting('download_path'):
xbmcgui.Dialog().ok(PLUGIN.name, PLUGIN... | 56,957 |
def _CanCreateRevertForCulprit(parameters, analysis_id):
"""Checks if a culprit can be reverted by a specific analysis.
The culprit can be reverted by the analysis if:
No revert of this culprit is complete or skipped, and
no other pipeline is doing the revert on the same culprit.
"""
culprit = entity_u... | 56,958 |
def read_selection(*args):
"""read_selection(ea_t ea1, ea_t ea2) -> bool"""
return _idaapi.read_selection(*args) | 56,959 |
def losses_and_metrics(num_classes):
"""
Define loss and metrics
Loss: Categorical Crossentropy
Metrics: (Train, Validation) Accuracy, Precision, Recall, F1
Returns:
loss, train loss, train acc, valid loss, valid acc, precision, recall, auc, f1
"""
loss_fn = CategoricalCrossentropy... | 56,960 |
def key_dirs(path, keys):
"""Iterates over a list of keys and returns a list of directories."""
# FIXME: This is CrAzY!
if path.endswith('/'): path = path[:-1]
dirset = set()
for k in keys:
kp = os.path.dirname(k)
if os.path.dirname(kp) == path:
dirset.add(os.path.basenam... | 56,961 |
def get_spans():
"""
Get and flush all spans
:return:
"""
global spans
with span_lock:
r = spans
spans = []
return r | 56,962 |
def sign(message, key):
"""Signs a string 'message' with the private key 'key'"""
if 'p' not in key:
raise Exception("You must use the private key with sign")
return chopstring(message, key['d'], key['p']*key['q'], encrypt_int) | 56,963 |
def NamedTeacherScope():
"""Creates a GPU name scope and CUDA device scope. This function is provided
to reduce `with ...` nesting levels."""
with core.NameScope('teacher'):
yield | 56,964 |
def GTreeGPMutatorOperation(genome, **args):
""" The mutator of GTreeGP, Operation Mutator
.. versionadded:: 0.6
The *GTreeGPMutatorOperation* function
"""
if args["pmut"] <= 0.0:
return 0
elements = len(genome)
mutations = args["pmut"] * elements
ga_engine = args["ga_engine"]
gp_... | 56,965 |
def sgn_inplace(a):
"""sign of `a` (inplace on `a`)""" | 56,966 |
def setup_for_distributed(is_master: bool) -> None:
"""
This function disables printing when not in master process
"""
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop("force", False)
if is_master or force:
buil... | 56,967 |
def test_game_timeout():
"""Test game timeout"""
bot = PrisonersDilemmaBot(strategy.play_tit_for_tat, moves_to_play=2)
bot.play("test_user_1", "@DilemmaBot let's play")
expect_game_state(bot.play("test_user_1", True), [[True, True]], [3, 3], [3, 3])
bot.active_games["test_user_1"]["start_time"] -=... | 56,968 |
def rm(path):
"""Safely remove a file."""
try:
os.unlink(path)
except OSError:
pass | 56,969 |
def register_serializers(app):
"""Register bundle serializers."""
serializers = {}
for bundle in app.bundles:
for name, serializer_class in bundle.serializers:
serializers[name] = serializer_class
app.serializers = serializers | 56,970 |
def sequence_delta(previous_sequence, next_sequence):
""" Check the number of items between two sequence numbers. """
if previous_sequence is None:
return 0
delta = next_sequence - (previous_sequence + 1)
return delta & 0xFFFFFFFF | 56,971 |
def show_providers(country:Optional[str]="")->None:
"""
Show a list of the banks avaliable on Prometeo.
The list can be filtered by a country code.
"""
providers = get_providers()
country = country.strip().upper()
if(country):
providers=[provider for provider in providers if(... | 56,972 |
def interpolate(df, time_series, start, end):
"""Interpolate the time series over the defined period."""
interpolator = time_series.load_dataset("sla", start, end)
mask = (df.index >= start) & (df.index < end)
selected = df.loc[mask, ["lon", "lat"]]
df.loc[mask, ["sla"]] = interpolator.trivariate(
... | 56,973 |
def is_email(email: str) -> bool:
""" Uses regex to check if a incoming string is an email address"""
regex = "^([a-zA-Z0-9]+[\\._-]?[a-zA-Z0-9]+)[@](\\w+[.])+\\w{2,3}$"
return re.search(regex, email) | 56,974 |
def matrix_plot_input(result, kde=False, margins=None):
"""
"""
input_sample = result.input_sample
if margins:
sample = np.zeros(input_sample.shape)
for i, marginal in enumerate(margins):
for j, ui in enumerate(input_sample[:, i]):
sample[j, i] = marginal.com... | 56,975 |
def train_and_predict(k, D_tr, D_te, nontf_X, tfs, genes):
"""Train classifier and predict gene responses.
"""
logger.info('Cross validating fold {}'.format(k))
tf_X_tr, y_tr = D_tr
tf_X_te, y_te = D_te
tfs_tr, tfs_te = tfs
X_tr = np.hstack([tf_X_tr, np.vstack([nontf_X for i in range(len(... | 56,976 |
def hpat_pandas_series_ne(self, other, level=None, fill_value=None, axis=0):
"""
Pandas Series method :meth:`pandas.Series.ne` implementation.
.. only:: developer
Test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_op8
Parameters
----------
self: :class:`pandas.S... | 56,977 |
def _unescape_serialized_class(dct):
# type: (Dict[str, Any]) -> Dict[str, Any]
"""
Unescape serialized '__class__' key.
:param dct: Serialized dictionary.
:return: Unescaped serialized dictionary.
"""
if _ESCAPED_SERIALIZED_CLASS_KEY in dct:
dct = dct.copy()
dct[_SERIALIZED... | 56,978 |
def get_transitions(data_vals, threshold, hysteresis):
"""
Find the high-to-low and low-to-high state transistions
"""
pend_len, time_vals, sens_vals = data_vals
# Get initial state
if sens_vals[0] > threshold:
state = 'high'
else:
state = 'low'
# Find state changes
... | 56,979 |
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# TODO:... | 56,980 |
def check_type(value, ty, value_name="value"):
"""
Verify that the given value has the given type.
value - the value to check
ty - the type to check for, or None to do no checking
(for example, if types come from Python type annotations, and
... | 56,981 |
def load_from_file(filename, key):
"""
Loads an object from a .pkl file or a .py file/module.
If a .pkl file, returns the object.
If a .py file, returns the object named key within that file
"""
#Check for pickle first
if filename[-4:]=='.pkl':
with open(filename,'rb') as file:
... | 56,982 |
def get_our_template(ours):
"""get template in the form of 23 keypoints ours
Args:
-ours: a list of length 92 [x1,y1,z1,c1,x2,y2,z2,c2,......]
Returns:
ours_form: 3 by 13 numpy array
"""
ours_0 = np.asarray(ours).reshape((-1,4)).T[0:3,:] # 3 by 23
ours_head = (ours_0[:,0].copy(... | 56,983 |
def single_number_generalized(nums, k, l):
"""
Given an array of integers, every element appears k times except for one.
Find that single one which appears l times.
We need a array x[i] with size k for saving the bits appears i times.
For every input number a, generate the new counter by
x[j] =... | 56,984 |
def create_ifls(path, inp):
"""Function to create IFLS sheet"""
work_book = load_workbook(path)
work_sheet = work_book.active
input_list = []
faculty_list = []
program_initiative = work_sheet['A1'].value
schedule_month = work_sheet['A4'].value
for cols in range(0, 31):
lead_1 =... | 56,985 |
def force_symlink(target, link):
"""Force a symlink to be created.
:param target: target to link to
:param link: link to create
"""
try:
os.symlink(target, link)
except OSError as e:
if e.errno == errno.EEXIST:
os.remove(link)
os.symlink(target, link)
... | 56,986 |
def variant(name):
"""
:doc: screens
Returns true if a `name` is a screen variant that can be chosen
by Ren'Py. See :ref:`screen-variants` for more details. This function
can be used as the condition in a Python if statement to set up the
appropriate styles for the selected screen variant.
... | 56,987 |
def quat_to_rot(normalized_quat):
"""Convert a normalized quaternion to a rotation matrix."""
rot_tensor = jnp.sum(
np.reshape(QUAT_TO_ROT, (4, 4, 9)) *
normalized_quat[..., :, None, None] *
normalized_quat[..., None, :, None],
axis=(-3, -2))
rot = jnp.moveaxis(rot_tensor, -1, 0) # Unstac... | 56,988 |
def read_tops(path, skip=-999.25000, delimiter='\t', header=0, colnames=[]):
"""
Read well tops file into dataframe
Parameters:
path (string): path to the well tops file
skip (): NaN identifier in the selected file
delimiter (char): character or list of characters used to separate... | 56,989 |
def filename_to_task_id(fname):
"""Map filename to the task id that created it assuming 1k tasks."""
# This matches the order and size in WikisumBase.out_filepaths
fname = os.path.basename(fname)
shard_id_increment = {
"train": 0,
"dev": 800,
"mnist": 900,
}
parts = fname.split("-")
spli... | 56,990 |
async def translateme(trans):
"""For .trt command, translate the given text using Google Translate."""
translator = Translator()
textx = await trans.get_reply_message()
message = trans.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
... | 56,991 |
def guests():
"""
Overview over all non_vip guests.
:return:
"""
class ItemTable(Table):
guest_id = Col('Guest ID')
items = db_helper.get_paying_sessions()
table = ItemTable(items)
return render_template('service.html',
service_description='If you ar... | 56,992 |
def setup_dirs(work_dir,verbose=True):
"""
This sets up the BADASS directory structure for each spectra. It creates
the "MCMC_output_#" folders.
"""
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) ... | 56,993 |
def distribution_generator(num_samples, distribution_type, mean=0, sd=1, interval=1, n=1, p=0.5):
""" Generate random data within a given distribution
:param num_samples: Int The number of samples to be returned
:param distribution_type: String The type of distribution to be used
:param mean: The Mean ... | 56,994 |
def error(msg):
"""Write an error message to stderr"""
stderr.write('ERROR: {}\n'.format(msg)) | 56,995 |
def getrevision(binary):
"""returns the revision string from binary"""
revision = ""
with open(binary, "rb") as rtgt:
stream = rtgt.read()
sppattern = re.compile(r"storpool_revision=[a-z0-9\.]+")
results = set(sppattern.findall(stream))
if results:
assert len(results) == 1, "More... | 56,996 |
def edit(request, id):
"""
Edit contact information. Address, Email and Phone records are provided as inlineformsets.
**Templates:**
* ``rolodex/edit.html``
**Template Variables:**
* person, person_form, email_formset
"""
person = get_object_or_404(Person, id=id)
EmailFormset... | 56,997 |
def gSquared(properFrame):
"""
The gradient squared at each pixel of the image, also known as the convolution
of a Laplacian kernel across the image.
Optimized via `numba`.
Edge values are padded with values of 0.
Parameters
----------
properFrame : np.ndarray[H,W]
An array r... | 56,998 |
def main():
"""main"""
tornado.options.parse_command_line()
reader = nsq.Reader(topic='test', channel='pynsq',
nsqd_tcp_addresses=['127.0.0.1:4150'],
message_handler=handler, heartbeat_interval=10,
tls_v1=True, tls_opti... | 56,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.