content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def sequential_colors(n):
"""
Between 3 and 9 sequential colors.
.. seealso:: `<https://personal.sron.nl/~pault/#sec:sequential>`_
"""
# https://personal.sron.nl/~pault/
# as implemented by drmccloy here https://github.com/drammock/colorblind
assert 3 <= n <= 9
cols = ['#FFFFE5', '#FFFB... | d2ad5f8993f8c7dac99a577b6115a8452ad30024 | 703,657 |
def get_king_moves():
"""Generate the king's movement range."""
return [(1, 0), (1, -1), (-1, 0), (-1, -1),
(0, 1), (0, -1), (-1, 1), (1, 1)] | 5e6f5fcb8c57846b9b2ab112c27f90fc13a6d6b4 | 703,659 |
def _unpack_topk(topk, lp, hists, attn=None):
"""unpack the decoder output"""
beam, _ = topk.size()
topks = [t for t in topk]
lps = [l for l in lp]
k_hists = [(hists[0][:, i, :], hists[1][:, i, :], hists[2][i, :])
for i in range(beam)]
if attn is None:
return topks, lps, ... | 7e9012b62f25ec7f4a09387235a0161143ec5029 | 703,660 |
def box2start_row_col(box_num):
"""
Converts the box number to the corresponding row and column number of the square in the upper left corner of the box
:param box_num: Int
:return: len(2) tuple
[0] start_row_num: Int
[1] start_col_num: Int
"""
start_row_num = 3 * (box_num // 3... | b11e7d4317e1dd32e896f1541b8a0cf05a342487 | 703,661 |
import re
def create_title(chunk, sep, tags):
"""Helper function to allow doconce jupyterbook to automatically assign titles in the TOC
If a chunk of text starts with the section specified in sep, lift it up
to a chapter section. This allows doconce jupyterbook to automatically use the
section's text... | 67bd80c10733d79f84ba38cd44155e73bb2a2efd | 703,662 |
import uuid
def get_uuid():
"""
Returns a uuid4 (random UUID) specified by RFC 4122 as a
32-character hexadecimal string
"""
return uuid.uuid4().hex | ce3f00569c3fa12aa203246bd5d3ae098f2dab2a | 703,664 |
import re
def hashtag(phrase, plain=False):
"""
Generate hashtags from phrases. Camelcase the resulting hashtag, strip punct.
Allow suppression of style changes, e.g. for two-letter state codes.
"""
words = phrase.split(' ')
if not plain:
for i in range(len(words)):
try:
if not words[i]:
del word... | b6e7ab647330a42cf9b7417469565ce5198edd4f | 703,665 |
def gather_data_to_plot(wells, df):
"""
Given a well ID, plot the associated data, pull out treatments.
Pull in dataframe of all the data.
"""
data_to_plot = []
error_to_plot = []
legend = []
for well in wells:
data_to_plot.append(df.loc[well, '600_averaged'])
error_to_pl... | 1870384b94c2cf3a8a5da84b848586e0a95d1713 | 703,667 |
import re
def is_ignored(filename, ignores):
"""
Checks if the filename matches any of the ignored keywords
:param filename:
The filename to check
:type filename:
`str`
:param ignores:
List of regex paths to ignore. Can be none
:type ignores:
`list` of `str` or... | 3d5016d5ac86efdf9f67a251d5d544b06347a3bf | 703,668 |
import hashlib
import os
def ftp_file_hash(con):
""" Get the file hashes inside the FTP server
Assumes that the FTP connection is already in the wordpress dir.
"""
# Function to get MD5 Hash inside the FTP server
def get_md5(fpath):
""" Returns the md5 hash string of a file """
... | fac1d9ee558a7339135ccf5f1a25191fef2aac4f | 703,669 |
def stop_program():
"""Small function to ask for input and stop if needed
"""
ok = input("Press S to Stop, and any other key to continue...\n")
if ok in ["S", "s"]:
return True
return False | c076d4a443331d64ef5855f0d20f7db2adb0cf11 | 703,670 |
def rotate(n):
"""
Rotate 180 the binary bit string of n and convert to integer
"""
bits = "{0:b}".format(n)
return int(bits[::-1], 2) | 23fa595ee66c126ad7eae0fa1ca510cf0cebdfbd | 703,671 |
def flip_thetas(thetas, theta_pairs):
"""Flip thetas.
Parameters
----------
thetas : numpy.ndarray
Joints in shape (num_thetas, 3)
theta_pairs : list
List of theta pairs.
Returns
-------
numpy.ndarray
Flipped thetas with shape (num_thetas, 3)
"""
thetas... | e19a274953a94c3fb4768bcd6ede2d7556020ab2 | 703,672 |
def surface_analysis_function_for_tests(surface, a=1, c="bar"):
"""This function can be registered for tests."""
return {'name': 'Test result for test function called for surface {}.'.format(surface),
'xunit': 'm',
'yunit': 'm',
'xlabel': 'x',
'ylabel': 'y',
... | e6e58c172687ce3e0782abb07b9154afae9356cb | 703,673 |
def from_time (year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None):
"""
Convenience wrapper to take a series of date/time elements and return a WMI time
of the form yyyymmddHHMMSS.mmmmmm+UUU. All elements may be int, string or
omitted altogether. If omitted... | 61d2bf9fb36225990ac0ac9d575c3931ef66e9f6 | 703,674 |
def plural(num, one, many):
"""Convenience function for displaying a numeric value, where the attached noun
may be both in singular and in plural form."""
return "%i %s" % (num, one if num == 1 else many) | f29753d25e77bcda2fb62440d8eb19d9bd332d1e | 703,675 |
import math
import time
def test_query_retry_maxed_out(
mini_sentry, relay_with_processing, outcomes_consumer, events_consumer
):
"""
Assert that a query is not retried an infinite amount of times.
This is not specific to processing or store, but here we have the outcomes
consumer which we can us... | 9339078c432cd087dcdbf799cad8d881defb41c2 | 703,676 |
def dollo_parsimony(phylo_tree, traitLossSpecies):
""" simple dollo parsimony implementation
Given a set of species that don't have a trait (in our hash), we do a bottom up pass through the tree.
If two sister species have lost the trait, then the ancestor of both also lost it. Otherwise, the ancestor has the trait.... | 7929006e1625ba502642fcbd44c0dfff44569777 | 703,677 |
def _to_bytes(str_bytes):
"""Takes UTF-8 string or bytes and safely spits out bytes"""
try:
bytes = str_bytes.encode('utf8')
except AttributeError:
return str_bytes
return bytes | fd16c24e80bdde7d575e430f146c628c0000bf9a | 703,678 |
import os
def tile_num(fname):
""" extract tile number from file name. """
l = os.path.splitext(fname)[0].split('_') # fname -> list
i = l.index('tile') # i is the index in the list
return int(l[i+1]) | 9f86598d5614fc986676491ad8b238960609148a | 703,679 |
def determine_host(environ):
"""
Extract the current HTTP host from the environment.
Return that plus the server_host from config. This is
used to help calculate what space we are in when HTTP
requests are made.
"""
server_host = environ['tiddlyweb.config']['server_host']
port = int(serv... | 6e91f93d5854600fe4942f093de593e53aaf2aa0 | 703,680 |
def read_messages(message_file):
""" (file open for reading) -> list of str
Read and return the contents of the file as a list of messages, in the
order in which they appear in the file. Strip the newline from each line.
"""
# Store the message_file into the lst as a list of messages... | 0e4b1a6995a6dd25ab3783b53e730d0dd446747c | 703,681 |
import os
def _ToGypPath(path):
"""Converts a path to the format used by gyp."""
if os.sep == '\\' and os.altsep == '/':
return path.replace('\\', '/')
return path | a2f4864c7a2cc844716ef17fffcd088843f23b3a | 703,682 |
def hello_world1():
"""
Flask endpoint
:return: TXT
"""
return "Hello World From App 1!" | fed4dcf04234ca8c47885d0702f284c13136f52f | 703,683 |
def cradmin_titletext_for_role(context, role):
"""
Template tag implementation of
:meth:`django_cradmin.crinstance.BaseCrAdminInstance.get_titletext_for_role`.
"""
request = context['request']
cradmin_instance = request.cradmin_instance
return cradmin_instance.get_titletext_for_role(role) | 8e6a29c369c5ae407701c12dc541e82dda31f193 | 703,684 |
import sys
import traceback
def get_raising_file_and_line(tb=None):
"""Return the file and line number of the statement that raised the tb
Returns: (filename, lineno) tuple
"""
if not tb:
tb = sys.exc_info()[2]
filename, lineno, _context, _line = traceback.extract_tb(tb)[-1]
return f... | f6b0b7878f0a4a322eb4d1ea3f6bdbf1b6ee7530 | 703,685 |
def compute_average_oxidation_state(site):
"""
Calculates the average oxidation state of a site
Args:
site:
Site to compute average oxidation state
Returns:
Average oxidation state of site.
"""
try:
avg_oxi = sum([sp.oxi_state * occu
f... | 8ea8611984f171a84a2bac17c0b49b70c85bfba4 | 703,687 |
import math
def cos(x, offset=0, period=1, minn=0, maxx=1):
"""A cosine curve scaled to fit in a 0-1 range and 0-1 domain by default.
offset: how much to slide the curve across the domain (should be 0-1)
period: the length of one wave
minn, maxx: the output range
"""
value = math.cos((x/peri... | e3119dc71c1b6c6160a29dca37b51b0550479a83 | 703,688 |
from os import access,W_OK
def iswritable(pathname):
"""Is file or folder writable?"""
return access(pathname,W_OK) | 705c8ecb9c5d2d3b7aeef6e6e99838ff72ed27f1 | 703,689 |
def mean_of_list(list_in):
"""Returns the mean of a list
Parameters
----------
list_in : list
data for analysis
Returns
-------
mean : float
result of calculation
"""
mean = sum(list_in) / len(list_in)
return(mean) | fac8f40b86e7fa37f96a46b56de722c282ffc79c | 703,691 |
from collections import OrderedDict
def read_markers_gmt(filepath):
"""
Read a marker file from a gmt.
"""
ct_dict = OrderedDict()
with open(filepath) as file_gmt:
for line in file_gmt:
values = line.strip().split('\t')
ct_dict[values[0]] = values[2:]
return ct_... | a45ed9da13c9ba4110bb4e392338036a32a58e60 | 703,692 |
import logging
def get_all_annots(annotations):
"""
All annotations
"""
all_annots = set()
for genome in annotations.keys():
for annot_name in annotations[genome].keys():
all_annots.add(annot_name)
logging.info(' No. of annotation columns: {}'.format(len(all_annots)))
... | 98270d18fbc8ded648a16178087037b1319263d4 | 703,693 |
def construct_select_bijlagen_query(bericht_uri):
"""
Construct a SPARQL query for retrieving all bijlages for a given bericht.
:param bericht_uri: URI of the bericht for which we want to retrieve bijlagen.
:returns: string containing SPARQL query
"""
q = """
PREFIX schema: <http://sche... | 56e9868ddc38c703ac383508cce4e446f0f566a4 | 703,694 |
def check_convergence(x):
""" Check for convergence of the sampler
"""
return False | 989d94991eeecd414c3f6ff85b2d2bc2801d5cbc | 703,695 |
def add_to_leftmost(branch, val):
"""adds value to the leftmost part of the branch and returns the modified branch and 0.
OR returns unchanged change and val if the val cannot be added"""
if val == 0:
return branch, val
if type(branch) is int:
return branch + val, 0
# add to children... | 1c2c3bdccfcb6f4966b9bf9228f092ee17ca49f9 | 703,696 |
def normalize_list_of_dict_into_dict(alist):
"""
Info is generated as a list of dict
objects with a single key.
@alist - the list in question.
@return - normalized dict with multiple keys
"""
result = {}
for element in alist:
for key in element.keys():
... | 8de00b0923d07b99085ca3b4d694960aae9fc7f5 | 703,697 |
import argparse
def get_args():
"""Get our arguments"""
parser = argparse.ArgumentParser()
parser.add_argument('filename', metavar='F', type=str, nargs=1,
help='File to load')
parser.add_argument('-a', '--annealing', action='store_true',
default=False,
... | 33e82867f37b1934f9622076459402beb2cb3214 | 703,699 |
import logging
def make_error_logger(name, level, filename):
"""
Création d'un Logger d'erreur
:param name: nom du logger
:param level: niveau de logging
:param filename: nom du fichier d'erreur
:return: logger
"""
formatter = logging.Formatter("%(asctime)s %(levelname)s - %(messa... | 0d78faa4657af348c06755298c2e1d3f717cd092 | 703,700 |
from typing import Dict
from typing import Any
from typing import Iterable
from typing import Optional
from typing import Tuple
def kwargs_from_config(
config: Dict[str, Any],
required_keys: Iterable[str],
optional_keys: Iterable[str],
renames: Optional[Iterable[Tuple[str, str]]] = None,
) -> Dict[str... | b3acef60b87dc8bb4c00157c169d1968c8751100 | 703,701 |
import os
import os.path as op
from glob import glob
from warnings import warn
def bids_scan_file_walker(dataset=".", include_types=None, warn_no_files=False):
"""
Traverse a BIDS dataset and provide a generator interface
to the imaging files contained within.
:author: @chrisfilo
https://github.... | f3a4f3e1c96073e89fd69ff2768570c1f0667f9f | 703,703 |
def insert_dim(arg, pos=-1):
"""insert 1 fake dimension inside the arg before pos'th dimension"""
shape = [i for i in arg.shape]
shape.insert(pos, 1)
return arg.reshape(shape) | 921cd27894df9910dbc12b31db6eb1f73d47f180 | 703,704 |
def encode_captions(captions):
"""
Convert all captions' words into indices.
Input:
- captions: dictionary containing image names and list of corresponding captions
Returns:
- word_to_idx: dictionary of indices for all words
- idx_to_word: list containing all words
- vocab_size... | 2ba216c844723b0925b46d0db7bc8afd6ce0f5b4 | 703,705 |
def load_stop_words(stop_word_file):
"""
Utility function to load stop words from a file and return as a list of words
@param stop_word_file Path and file name of a file containing stop words.
@return list A list of stop words.
"""
stop_words = []
for line in open(stop_word_file):
if... | 8127aeec8db8f7bc87130ea0d1e5faa4998ac86f | 703,706 |
def NullFlagHandler(feature):
""" This handler always returns False """
return False | 7d37ecc8518144b27b43580b7273adf5f68dfdfb | 703,707 |
import copy
def find_paths(orbital_graph, starting_node, ending_node, visited_nodes=None):
"""Recursively find all the paths from starting_node to ending_node in the graph
Paths are returned as a list of paths, where paths are a list of nodes.
An empty list means that no valid path exists.
"""
pat... | 55a47542c3d70bbc1f5c722c1e87908e10b3d0e5 | 703,708 |
def find_matching_nodes(search_for, search_in, matches=[]):
"""
Search Vertex tree 'search_in' for the first isomorphic occurance of the
Vertex tree search_for
Return a list of [(x,y)...] for node in search_for (x) matched with
a pair (y) from search in, such as the two graphs preserve their ... | 9e6696533f7b5e313075fadade8b42fe6f09f0cf | 703,709 |
def distance_between_points(p1, p2):
""" Function that computes the euclidean distance between to points.
Returns:
float: distance value
"""
return ((p1['x']-p2['x']) * (p1['x'] - p2['x']) + (p1['y']-p2['y']) * (p1['y']-p2['y'])) ** 0.5 | b8cb563f13f64f0511525e5428d47d9228220915 | 703,711 |
def _get(pseudodict, key, single=True):
"""Helper method for getting values from "multi-dict"s"""
matches = [item[1] for item in pseudodict if item[0] == key]
if single:
return matches[0]
else:
return matches | f68156535d897dd719b05d675e66cadc284ce1a3 | 703,712 |
import glob
def datedfile(filename,date):
""" select file based on observation date and latest version
Parameters
----------
filename: text file name pattern, including "yyyymmdd_vnn" place holder for date and version
date: yyyymmdd of observation
Returns: file name
"""
filelist = ... | 203cf848e351ef9b8b77bda62d5850b35485762a | 703,713 |
import random
import string
def random_user(n):
"""generate a random user id of size n"""
chars = []
for i in range(n):
chars.append(random.choice(string.ascii_lowercase))
return ''.join(chars) | 21d8ec2ef8b275ffca481e4553ec396ff4010653 | 703,714 |
def _get_parse_input(parse_args, args_in, dict_in):
"""Return default for parse_input.
This is to decide if context_parser should run or not.
To make it easy on an API consumer, default behavior is ALWAYS to run
parser UNLESS dict_in initializes context and there is no args_in.
If dict_in specifi... | 64dcfd32a3d9f66749a27d4b26bd5fb3a66edf28 | 703,715 |
import argparse
def get_parser():
"""
Creates and returns the argument parser for jExam
Returns:
``argparse.ArgumentParser``: the argument parser for jExam
"""
parser = argparse.ArgumentParser()
parser.add_argument("master", type=str, help="Path to exam master notebook")
parse... | 03e433f3b3cdb371dff74489f619f0e65311f5dd | 703,716 |
import os
def find_source_filename(source_name, dir_path):
"""Find the filename matching the source/module name
in the specified path. For example searching for "queue"
might return "queue.py" or "queue.pyc"
"""
source_filenames = [
os.path.join(dir_path, source_name + ext) for
... | 0360e57d4071c389d28768946551ad041236e6e3 | 703,717 |
def MergeDictsRecursively(original_dict, merging_dict):
"""
Merges two dictionaries by iterating over both of their keys and returning the merge
of each dict contained within both dictionaries.
The outer dict is also merged.
ATTENTION: The :param(merging_dict) is modified in the process!
:para... | 43174a7f5163a36eb850bc2c4d0f557790920189 | 703,718 |
import argparse
def parse_args():
"""
Parse command line arguments for CLI
:return: namespace containing the arguments passed.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--login',
type=str,
required=True,
help="Full path to file containing JSO... | 0982407f808c9af9996bae0a36e8ae252cae0df6 | 703,720 |
def _split_hdf5_path(path):
"""Return the group and dataset of the path."""
# Make sure the path starts with a leading slash.
if not path.startswith('/'):
raise ValueError(("The HDF5 path '{0:s}' should start with a "
"leading slash '/'.").format(path))
if '//' in path:... | f0f8bba67254e3616a80c26b58fdcb91db00a49b | 703,721 |
def rebuildEventList(events, eventList = None):
"""
Add all events (top and nested) from event trees to a list.
"""
if eventList == None:
eventList = []
for event in events:
if event not in eventList:
eventList.append(event)
for arg in event.arguments:
... | 404ac02e6807214c82d30e465766a4e7af89016b | 703,722 |
def _pack_64b_int_arg(arg):
"""Helper function to pack a 64-bit integer argument."""
return ((arg >> 56) & 0xff), ((arg >> 48) & 0xff), ((arg >> 40) & 0xff), ((arg >> 32) & 0xff), \
((arg >> 24) & 0xff), ((arg >> 16) & 0xff), ((arg >> 8) & 0xff), (arg & 0xff) | 274fadb627de9ac47bff34c8e55db545b8e6cf0a | 703,723 |
def list_array_paths(path, array_dict):
"""
Given a dictionary containing each directory (experiment folder) as a
key and a list of array data files (analysis of array containing Log2Ratio
data) as its value (i.e., the output of 'find_arrays'), returns a list of
full paths to array files.
"""
... | 79d5f58a97005fb915de290ae8ccc480fbacd3c0 | 703,724 |
def log_simple(n, k):
"""
A function that simply finds how many k's does n have.
For example 28 = 2 * 2 * 7, so log_simple(28, 2) will return 2
and log_simple(28, 7) will return 1
"""
log_result = 0
while (n % k == 0):
log_result += 1
n /= k
return n, log_resu... | 22bda2911aa14a5866759cc0e5d8bf377b372bd7 | 703,725 |
def fitparams_for_update(fitparams):
"""
Extracts a dictionary of fitparameters from
modelmiezelb.io.ContrastData.fitparams for updating e.g. a sqe model
via modelmiezelb.sqe_model.SqE.update_params
Parameters
----------
fitparams : modelmiezelb.io.ContrastData.fitparam
Return
-... | b4f2ddf26dbdcb37105da4dcf23602fec19bf4e1 | 703,726 |
def spinChainProductSum(spins):
"""
Calculate the Ising nearest neighbor interactions of a spin chain, periodic boundary condition(PBC).
Parameters
----------
spins : list of ints or floats
The given spin under PBC.
Returns
float
The nearest neighbor interactions(products).... | 0f115c3284f5680b28d1648140c8618de873e16c | 703,728 |
def has_ext_state(section: str, key: str) -> bool:
"""
Return whether extended state exists for given section and key.
Parameters
----------
section : str
Extended state section.
key : str
Extended state key.
Returns
-------
has_ext_state : bool
"""
has_ext_... | 2483763cbe05f404331d8dfe8a1112fc15b70029 | 703,729 |
import re
def _escape_for_regex(text):
"""Escape ``text`` to allow literal matching using egrep"""
regex = re.escape(text)
# Seems like double escaping is needed for \
regex = regex.replace("\\\\", "\\\\\\")
# Triple-escaping seems to be required for $ signs
regex = regex.replace(r"\$", r"\\\$... | c7d9866dfe4b9c96e500a43d3726db8e7ea73532 | 703,730 |
def color_to_256(color):
"""Convert color into ANSI 8-bit color format.
Red is converted to 196
This converter emits the 216 RGB colors and the 24 grayscale colors.
It does not use the 16 named colors.
"""
output = 0
if color.r == color.g == color.b:
# grayscale case
if color... | 3fc747404f393d1adc04de06f59903593979a2a1 | 703,731 |
def breadcrumb(*args):
""""Render a breadcrumb trail
Args:
args (list) : list of urls and url name followed by the final name
Example: url1, name1, url2, name2, name3
"""
def pairs(l):
a = iter(l)
return list(zip(a,a))
return {
'urls': pairs(ar... | dd4fbd6c130da497a1f38c876685dc3f17298efb | 703,732 |
def translate(value, leftMin, leftMax, rightMin, rightMax):
"""
Normalize the data in range rightMin and rightMax
:param value: Value to be normalize
:param leftMin: original min value
:param leftMax: original max value
:param rightMin: final min value
:param rightMax: final max value
:r... | 2cc02618edaec4112d30a4f61de9c95d5e8a0f8b | 703,734 |
import os
def get_html_theme_path():
"""Return the html theme path for this template library.
:returns: List of directories to find template files in
"""
curdir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
return [curdir] | f37e9b99cff0b4c87f78dd4fc5a9612908eb97d3 | 703,735 |
def get_sqrt_2():
"""Returns an approximation for the square root of 2"""
return 1.41421356 | 56c24f16bc27b9b40b771ed545cc553b817f8260 | 703,736 |
from typing import Dict
from typing import Optional
def get_gsx_entry_value(entry: Dict[str, Dict[str, str]], field: str) -> Optional[str]:
"""Returns the `entry` value for the given `field`."""
if not entry or not field:
return None
field = f"gsx${field}"
if field not in entry:
retur... | 788c0a3e99691bfa81386c6fc2b5ea05332c06fd | 703,737 |
from typing import Sequence
import re
def parse_fvalues(fvalues: Sequence) -> frozenset:
"""
Parse a sequence of fvalues as a frozenset.
This function is mostly used for parsing string provided by the user,
splitting them accordingly, but accepts any sequence type. If a string is
passed, it will ... | 7c6356b5320e6a7056f615bf5a324edbe7c66e47 | 703,738 |
def get_resume(text):
"""
:param text: text to resume
:return: first paragraphe in the text
"""
# regex = re.compile(r"^(.*?)\n")
# return regex.match(text).group(1)
return text[:500] | f247222de19cc131ecdb99400be2a8957cc5ea56 | 703,739 |
def compute_q10_correction(q10, T1, T2):
"""Compute the Q10 temperature coefficient.
As explained in [1]_, the time course of voltage clamp recordings are
strongly affected by temperature: the rates of activation and inactivation
increase with increasing temperature. The :math:`Q_{10}` temperature
... | eed7d7f38c1f9d98b1a6a89a28eb4f1a6656b6c7 | 703,740 |
def without(array, *values):
"""Creates an array with all occurrences of the passed values removed.
Args:
array (list): List to filter.
values (mixed): Values to remove.
Returns:
list: Filtered list.
Example:
>>> without([1, 2, 3, 2, 4, 4], 2, 4)
[1, 3]
.... | 21bddf5244a591a261f704557fb8017a2401ef77 | 703,741 |
def get_total_mnsp_ramp_rate_violation(model):
"""Get total MNSP ramp rate violation"""
ramp_up = sum(v.value for v in model.V_CV_MNSP_RAMP_UP.values())
ramp_down = sum(v.value for v in model.V_CV_MNSP_RAMP_DOWN.values())
return ramp_up + ramp_down | 9e326a70966edce51f82036977fcec1b26991c21 | 703,742 |
import re
def parse_traceroute(raw_result):
"""
Parse the 'traceroute' command raw output.
:param str raw_result: traceroute raw result string.
:rtype: dict
:return: The parsed result of the traceroute command in a \
dictionary of the form:
::
{1: {'time_stamp2': '0.189',
... | 2a12d72a4e2e9a64287c65525b7eca6997849f97 | 703,743 |
import math
def ecliptic_obliquity_radians(time):
"""Returns ecliptic obliquity radians at time."""
return math.radians(23.439 - 0.0000004 * time) | 384199a506d29cb14b2a42facf2d6c46bf44f111 | 703,745 |
def equations_to_matrix() -> list:
"""
:return: augmented matrix formed from user input (user inputs = linear equations)
:rtype: list
"""
n = int(input("input number of rows "))
m = int(input("input number of columns "))
A = []
for row_space in range(n):
print("input row ", row_... | 702c252fed2d7127e4e5f9e5433ca4c29867138c | 703,746 |
def same_origin(origin1, origin2):
"""
Return True if these two origins have at least one common ASN.
"""
if isinstance(origin1, int):
if isinstance(origin2, int):
return origin1 == origin2
return origin1 in origin2
if isinstance(origin2, int):
return origin2 in o... | 1fbc55d9dcfb928c173128a5b386cc6375ec0cde | 703,747 |
def format_outcome_results(outcome_results):
"""
Cleans up formatting of outcome_results DataFrame
:param outcome_results: outcome_results DataFrame
:return: Reformatted outcomes DataFrame
"""
new_col_names = {"links.learning_outcome": "outcome_id"}
outcome_results = outcome_results.rename(c... | 9c22481725f2782d614b48582edfcd60db284c13 | 703,748 |
from win32api import GetSystemMetrics
def _get_max_width():
"""Hamta information om total skarmbredd och -hojd
"""
#Hamta information om total skarmbredd over alla anslutna skarmar
width = GetSystemMetrics(78)
#Hamta information om total skarmhojd over alla anslutna skarmar
height = GetSystemM... | e2382eab98faecd7d8cf9ba2689897d2512c39db | 703,750 |
from datetime import datetime
import functools
import time
def function_timer(func):
"""This is a timer decorator when defining a function if you want that function to
be timed then add `@function_timer` before the `def` statement and it'll time the
function
Arguments:
func {function} -- it t... | 6ddcca82ae60aafb2c072e62497f8b27d557ccdc | 703,752 |
def breadcrumbs(category):
"""
Renders a category tree path using a customizable delimiter.
Usage::
{% breadcrumbs <category> %}
Example::
{% breadcrumbs category %}
"""
return {'ancestors': category.get_ancestors()} | 3c83a7ad7e8ae30ad297fd9d3d7aa5ffa5631449 | 703,753 |
from typing import List
def combine_results_dicts(results_summaries: List[dict]) -> dict:
"""For a list of dictionaries, each with keys 0..n-1,
combine into a single dictionary with keys 0..ntot-1"""
combined_summary = {}
n_overall = 0
for d in results_summaries:
n_this = len(d)
fo... | 67e5654b3f4b045526bc181ddb9b05eb9f7ce018 | 703,754 |
def StringToId(peg_positions):
""" input a list of strings representing peg positions
returns the game bitfield as integer number
"""
my_string = [''] * 36
cur_pos = 0
cur_bitfield = 0
for row in ['A', 'B', 'C', 'D', 'E', 'F']:
for col in ['1', '2', '3', '4', '5', '6']:
... | 71845dd2a9166bf1e43fc68040de81f93806b322 | 703,755 |
import sys
def notebook_is_active() -> bool:
"""Return if script is executing in a IPython notebook (e.g. Jupyter notebook)"""
for x in sys.modules:
if x.lower() == 'ipykernel':
return True
return False | 200962d831c75d636b310aafa0c8cc4e664e0b4a | 703,758 |
import argparse
def build_parser():
"""Parser to grab and store command line arguments"""
MINIMUM = 200000
SAVEPATH = "data/raw/"
parser = argparse.ArgumentParser()
parser.add_argument(
"subreddit", help="Specify the subreddit to scrape from")
parser.add_argument("-m", "--minimum",
... | d4f3eb484423416d3cb83ad64784747a8f453d98 | 703,759 |
def lzip(*args):
"""
this function emulates the python2 behavior of zip (saving parentheses in py3)
"""
return list(zip(*args)) | 92aa6dea9d4058e68764b24eb63737a2ec59a835 | 703,760 |
def sanitize_url(url: str) -> str:
"""
This function strips to the protocol, e.g., http, from urls.
This ensures that URLs can be compared, even with different protocols, for example, if both http and https are used.
"""
prefixes = ["https", "http", "ftp"]
for prefix in prefixes:
if url... | 9c61a9844cfd6f96e158a9f663357a7a3056abf0 | 703,761 |
def image_to_world(bbox, size):
"""Function generator to create functions for converting from image coordinates to world coordinates"""
px_per_unit = (float(size[0])/bbox.width, float(size[1]/bbox.height))
return lambda x,y: (x/px_per_unit[0] + bbox.xmin, (size[1]-y)/px_per_unit[1] + bbox.ymin) | 35fcfbf8e76e0ec627da9bf32a797afdae11fe17 | 703,762 |
def find_kern_timing(df_trace):
"""
find the h2d start and end for the current stream
"""
kern_begin = 0
kern_end = 0
for index, row in df_trace.iterrows():
if row['api_type'] == 'kern':
kern_begin = row.start
kern_end = row.end
break;
return kern... | 2e121e7a9f7ae19f7f9588b0105f282c59f125ba | 703,763 |
def overlap_branches(targetbranch: dict, sourcebranch: dict) -> dict:
"""
Overlaps to dictionaries with each other. This method does apply changes
to the given dictionary instances.
Examples:
>>> overlap_branches(
... {"a": 1, "b": {"de": "ep"}},
... {"b": {"de": {"eper"... | a11b54b72d4a7d79d0bfaa13ed6c351dd84ce45f | 703,764 |
def make_legend_labels(dskeys=[], tbkeys=[], sckeys=[], bmkeys=[], plkeys=[],
dskey=None, tbkey=None, sckey=None, bmkey=None, plkey=None):
"""
@param dskeys : all datafile or examiner keys
@param tbkeys : all table keys
@param sckeys : all subchannel keys
@param bmkeys : all beam keys
@pa... | a8b17916f896b7d8526c5ab7ae3cf4a7435627e2 | 703,765 |
import collections
def get_interface_config_vlan():
"""
Return the interface configuration parameters for all IP static
addressing.
"""
parameters = collections.OrderedDict()
parameters['VLAN'] = 'yes'
return parameters | 61ef6affba231af19e4030c54bfcaaaa15a6438f | 703,766 |
def normalize_string(value):
""" Normalize a string value. """
if isinstance(value, bytes):
value = value.decode()
if isinstance(value, str):
return value.strip()
raise ValueError("Cannot convert {} to string".format(value)) | 86d8134f8f83384d83da45ed6cb82841301e2e52 | 703,767 |
from distutils.version import StrictVersion
from distutils.spawn import find_executable
import re
import os
def get_versions():
""" Try to find out the versions of gcc and ld.
If not possible it returns None for it.
"""
gcc_exe = find_executable('gcc')
if gcc_exe:
out = os.popen(gcc_e... | 3774f0fe270733512b3a6c1cb3e361a1cb90a362 | 703,768 |
def mapAddress(name):
"""Given a register name, return the address of that register.
Passes integers through unaffected.
"""
if type(name) == type(''):
return globals()['RCPOD_REG_' + name.upper()]
return name | 21f2f9a085d259d5fd46b258cc3ee0298fdda158 | 703,769 |
def list_index(ls, indices):
"""numpy-style creation of new list based on a list of elements and another
list of indices
Parameters
----------
ls: list
List of elements
indices: list
List of indices
Returns
-------
list
"""
return [ls[i] for i in indices] | 7e5e35674f48208ae3e0befbf05b2a2e608bcdf0 | 703,770 |
import io
import re
def copyright_present(f):
"""
Check if file already has copyright header.
Args:
f - Path to file
"""
with io.open(f, "r", encoding="utf-8") as fh:
return re.search('Copyright', fh.read()) | afbffde0ab51984dab40d296f8ad9ca29829aef1 | 703,771 |
import math
def calc_LFC(in_file_2, bin_list):
"""
Mods the count to L2FC in each bin
"""
#for itereating through the bin list
bin_no=0
header_line = True
with open(in_file_2, 'r') as f:
for bin_count in f:
if header_line:
header_line = False
... | 379035fa4972c956d9734b958f3e81a3792c96d6 | 703,772 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.