content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def setxlabels(dreameqsys, ax=None):
"""
Set x labels of current plot based on the given DREAMEqsys object.
"""
if ax is None:
ax = plt.gca()
ax.set_xticks(dreameqsys.getoffsets())
ax.set_xticklabels(dreameqsys.getnames())
plt.gcf().canvas.draw() | 15,800 |
def is_docker_reachable(docker_client):
"""
Checks if Docker daemon is running.
:param docker_client : docker.from_env() - docker client object
:returns True, if Docker is available, False otherwise.
"""
errors = (
docker.errors.APIError,
requests.exceptions.ConnectionError,
... | 15,801 |
def get_string(entry):
"""
This function ...
:param entry:
:return:
"""
value = entry.split(" / ")[0].rstrip()
return value | 15,802 |
def data_getfilenode(ctx, all, filespec):
"""Retrieve file(s) from a compute node"""
ctx.initialize_for_batch()
convoy.fleet.action_data_getfilenode(
ctx.batch_client, ctx.config, all, filespec) | 15,803 |
def tabtagged(files = 'chunked', basedir= None):
"""
@param files: One or more treebank files to be processed
@type files: L{string} or L{tuple(string)}
@return: iterator over lines in Malt-TAB input format
"""
if type(files) is str: files = (files,)
if not basedir: basedir = os.envi... | 15,804 |
def read_yaml_env(fname: str) -> Any:
"""Parse YAML file with environment variable substitution.
Parameters
----------
fname : str
yaml file name.
Returns
-------
table : Any
the object returned by YAML.
"""
content = read_file(fname)
# substitute environment va... | 15,805 |
def get_top_words(words):
"""
Получить список наиболее часто встречающихся слов, с указанием частоты
:param words: список слов для анализа
:return: [(слово1, количество повторений слова1), ..]
"""
return collections.Counter(words).most_common() | 15,806 |
def get_slope(x, y, L):
"""
Funcao que retorna o slope da serie temporal dos dados
"""
try:
x=np.array(x).reshape(-1, 1)
y=np.array(y).reshape(-1, 1)
lr=LinearRegression()
lr.fit (x[:L],y[:L])
return lr.coef_[0][0]
except:
return 0 | 15,807 |
def _minimize_price(price: Dict[str, Any]) -> Price:
"""
Return only the keys and values of a price the end user would be interested in.
"""
keys = ['id', 'recurring', 'type', 'currency', 'unit_amount', 'unit_amount_decimal', 'nickname',
'product', 'metadata']
return {k: price[k] for k i... | 15,808 |
def test_workflow(workflow_files, monkeypatch):
"""Given a list of input files (ini_file, jsonfile, bodyfile,
renderedfile) that are a record for the interaction with a for a particular
cluster, check that replay of that interaction yields the same
communication with the cluster (without actually connec... | 15,809 |
def project(signals, q_matrix):
"""
Project the given signals on the given space.
Parameters
----------
signals : array_like
Matrix with the signals in its rows
q_matrix : array_like
Matrix with an orthonormal basis of the space in its rows
Returns
-------
proj_sig... | 15,810 |
def all_movies():
"""
Returns all movie in the database for Movies
service
"""
movies = ut.get_movies()
if len(movies) == 0:
abort(404)
return make_response(jsonify({"movies":movies}),200) | 15,811 |
def test():
"""Test with sample inputs.
"""
u = Universe()
world = [
[Cell(AliveState()), Cell(AliveState())],
[Cell(AliveState()), Cell(AliveState())],
]
u.seed(world)
print 'INPUT (Block Pattern)'
print u
u.nextGeneration()
print 'OUTPUT'
print u, '\n'
... | 15,812 |
def remove_condition(self, node=None):
"""Check that user is able to see the table after row policy condition has been removed."""
table_name = f"table_{getuid()}"
pol_name = f"pol_{getuid()}"
if node is None:
node = self.context.node
with table(node, table_name):
with Given("I h... | 15,813 |
def format_map(mapping, st):
"""
Format string st with given map.
"""
return st.format_map(mapping) | 15,814 |
def communities_greedy_modularity(G,f):
"""
Adds a column to the dataframe f with the community of each node.
The communitys are detected using greedy modularity.
G: a networkx graph.
f: a pandas dataframe.
It works with networkx vesion: '2.4rc1.dev_20190610203526'
"""
if not(set(f.name... | 15,815 |
def load_loglin_stats(infile_path):
"""read in data in json format"""
# convert all 'stats' to pandas data frames
with open(infile_path) as infile:
data = json.load(infile)
new_data = {}
for position_set in data:
try:
new_key = eval(position_set)
except NameError... | 15,816 |
def _simple_logistic_regression(x,y,beta_start=None,verbose=False,
CONV_THRESH=1.e-3,MAXIT=500):
"""
Faster than logistic_regression when there is only one predictor.
"""
if len(x) != len(y):
raise ValueError, "x and y should be the same length!"
if beta_start is ... | 15,817 |
def preemphasis(signal,coeff=0.95):
"""perform preemphasis on the input signal.
:param signal: The signal to filter.
:param coeff: The preemphasis coefficient. 0 is no filter, default is 0.95.
:returns: the filtered signal.
"""
return np.append(signal[0],signal[1:]-coeff*signal[:-1]) | 15,818 |
def build_moses_tokenizer(tokenizer: MosesTokenizerSpans,
normalizer: MosesPunctNormalizer = None) -> Callable[[str], List[Token]]:
"""
Wrap Spacy model to build a tokenizer for the Sentence class.
:param model a Moses tokenizer instance
:return a tokenizer function to provide ... | 15,819 |
def setup_lithops_logger(log_level=constants.LOGGER_LEVEL,
log_format=constants.LOGGER_FORMAT,
stream=None, filename=None):
"""Setup logging for lithops."""
if log_level is None or str(log_level).lower() == 'none':
return
if stream is None:
... | 15,820 |
def callback_query_stats(update: Update, context: CallbackContext):
"""
generate json file and send it back to poll's owner.
"""
query: CallbackQuery = update.callback_query
poll_id = int(context.match.groups()[0])
poll = Poll.load(poll_id)
if poll.owner.id != query.from_user.id:
l... | 15,821 |
def print_n(s: str, n: int):
"""Exibe na tela 'n' vezes a string 's'.
Args:
s (str): String fornecida pelo usuário.
n (int): Número de vezes que string será exibida.
"""
if n <= 0:
return # nota: se não dermos um valor para a instrução return, a função retorna None
else:
... | 15,822 |
def horizontal_block_reduce(
obj: T_DataArray_or_Dataset,
coarsening_factor: int,
reduction_function: Callable,
x_dim: Hashable = "xaxis_1",
y_dim: Hashable = "yaxis_1",
coord_func: Union[str, CoordFunc] = coarsen_coords_coord_func,
) -> T_DataArray_or_Dataset:
"""A generic horizontal block ... | 15,823 |
def statements_api(context, request):
"""List all the statements for a period."""
dbsession = request.dbsession
owner = request.owner
owner_id = owner.id
period = context.period
inc_case = case([(AccountEntry.delta > 0, AccountEntry.delta)], else_=None)
dec_case = case([(AccountEntry.delta ... | 15,824 |
def fp(x):
"""Function used in **v(a, b, th, nu, dimh, k)** for **analytic_solution_slope()**
:param x: real number
:type x: list
:return: fp value
:rtype: list
"""
rx = np.sqrt(x * 2 / np.pi)
s_fresnel, c_fresnel = sp.fresnel(rx)
return - 2 * 1j * np.sqrt(x) * np.exp(-1j * ... | 15,825 |
def get_truck_locations(given_address):
"""
Get the location of the food trucks in Boston TODAY within 1 mile
of a given_address
:param given_address: a pair of coordinates
:return: a list of features with unique food truck locations
"""
formatted_address = '{x_coordinate}, {y_coordinate}'.... | 15,826 |
def _getRelevantKwds(method, kwds):
"""return kwd args for the given method, and remove them from the given kwds"""
import inspect
argspec = inspect.getargspec(method)
d = dict()
for a in kwds:
if a not in argspec.args:
warnings.warn("Unrecognized kwd: {!r}".format(a))
for a ... | 15,827 |
def heatmap_contingency_triggers_01(df_devs=None, df_acts=None, df_con_tab_01=None, figsize=None,
idle=True, z_scale=None, numbers=None, file_path=None
):
"""
Plot the device on and off triggers against the activities
Parameters
--... | 15,828 |
def find_overview_details(park_code):
""" Find overview details from park code """
global API_KEY
fields = "&fields=images,entranceFees,entrancePasses,operatingHours,exceptions"
url = "https://developer.nps.gov/api/v1/parks?parkCode=" + park_code + "&api_key=" + API_KEY + fields
response = request... | 15,829 |
def test_command_line_with_vowel_preserve_case():
""" foo -> fii """
out = getoutput(f'{prg} "APPLES AND BANANAS" --vowel i')
assert out.strip() == 'IPPLIS IND BININIS' | 15,830 |
def p_expression_ID(p):
"""expression : FIELD operation value
"""
lookup = compa2lookup[p[2]]
try:
field = get_shortcut(p[1])
except KeyError:
field = p[1]
if lookup:
field = '%s__%s' % (field, lookup)
# In some situations (which ones?), python
# refuses unicod... | 15,831 |
def embed_nomenclature(
D,
embedding_dimension,
loss="rank",
n_steps=1000,
lr=10,
momentum=0.9,
weight_decay=1e-4,
ignore_index=None,
):
"""
Embed a finite metric into a target embedding space
Args:
D (tensor): 2D-cost matrix of the finite metric
embedding_dim... | 15,832 |
def blitLevelData(playerList, level, goldCount, time, animate=False):
"""Draw the level data to the screen.
This includes the time remaining, gold remaining, players' lives, black hole sprites, and the level image.
Black hole sprites are included, as they are the only sprites drawn before the level begins.... | 15,833 |
def raw_env():
"""
To support the AEC API, the raw_env() function just uses the from_parallel
function to convert from a ParallelEnv to an AEC env
"""
env = parallel_env()
env = parallel_to_aec(env)
return env | 15,834 |
def cmd_line(preprocessor: Preprocessor, args: str) -> str:
"""the line command - prints the current line number"""
if args.strip() != "":
preprocessor.send_warning("extra-arguments", "the line command takes no arguments")
context = preprocessor.context.top
pos = context.true_position(preprocessor.current_positio... | 15,835 |
def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False):
"""Install plugin from zipfile."""
logger.debug("%s is a file, attempting to load zip", pkgpath)
pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_")
try:
with zipfile.ZipFile(pkgpath) as pkgzip:
pk... | 15,836 |
def parse(file, parser=None, bufsize=None):
"""Parse a file into a DOM by filename or file object."""
if parser is None and not bufsize:
from xml.dom import expatbuilder
return expatbuilder.parse(file)
else:
from xml.dom import pulldom
return _do_pulldom_parse(pulldom.parse, ... | 15,837 |
def create_hash256(max_length=None):
"""
Generate a hash that can be used as an application secret
Warning: this is not sufficiently secure for tasks like encription
Currently, this is just meant to create sufficiently random tokens
"""
hash_object = hashlib.sha256(force_bytes(get_random_string(... | 15,838 |
def _getbundlelistkeysparts(bundler, repo, source, bundlecaps=None,
b2caps=None, **kwargs):
"""add parts containing listkeys namespaces to the requested bundle"""
listkeys = kwargs.get('listkeys', ())
for namespace in listkeys:
part = bundler.newpart('listkeys')
p... | 15,839 |
def test_get_exectype_from_xmlfile_with_unsupported_type():
"""Gets the exectype values for testcases from the testsuite.xml file """
filepath = os.path.join(os.path.split(__file__)[0], "exmp_suite_file.xml")
exectype = xml_Utils.getChildAttributebyParentTag = MagicMock(return_value='junk_value')
resul... | 15,840 |
def assert_content_in_file(file_name, expected_content):
"""
Fabric assertion: Check if some text is in the specified file (result of installing a test product)
Provision dir: PROVISION_ROOT_PATH
:param file_name: File name
:param expected_content: String to be found in file
:return: True if giv... | 15,841 |
def generate_substrate_fasta(df):
""" gemerates fasta sequence files containing sequences of
all proteins that contain phosphosites that do not have kinase
annotations in PSP or Networkin. The outputs of the function
will be used as input to run Networkin locally and predict kinases
Parameters
... | 15,842 |
def _calculate_hwp_storage_fut(
hwp_shapes, base_dataset_uri, c_hwp_uri, bio_hwp_uri, vol_hwp_uri,
yr_cur, yr_fut, process_pool=None):
"""Calculates carbon storage, hwp biomassPerPixel and volumePerPixel due to
harvested wood products in parcels on current landscape.
hwp_shapes - a dictiona... | 15,843 |
def draw_boxes(
img, bbox_tlbr, class_prob=None, class_idx=None, class_names=None
):
"""
Draw bboxes (and class names or indices for each bbox) on an image.
Bboxes are drawn in-place on the original image.
If `class_prob` is provided, the prediction probability for each bbox
will be displayed a... | 15,844 |
def test_function(client: MsGraphClient, args):
"""
Performs basic GET request to check if the API is reachable and authentication is successful.
Returns ok if successful.
"""
response = client.ms_client.http_request(
method='GET', url_suffix='security/alerts', params={'$top': 1}, r... | 15,845 |
def load(path='db'):
"""Recursivly load a db directory"""
if not os.path.isabs(path):
path = os.path.abspath(path)
env["datastore"].update({
"type": "yamldir",
"path": path,
})
return loaddir(path) | 15,846 |
def wcxf2arrays_symmetrized(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values.
In contrast to `wcxf2arrays`, here the numpy ... | 15,847 |
def main(port, dir):
"""Load [Fog of World] data from DIR.
DIR is the path to the [Fog of World] folder, the given folder should contain a subfolder [Sync].
"""
fog_map = parser.FogMap(dir)
tmp_folder = tempfile.TemporaryDirectory()
def exit_handler():
tmp_folder.cleanup()
atexit.... | 15,848 |
def prepare_storage_paths(): # pragma: no cover
"""Ensures that the folder structure exists."""
if not os.path.exists(HELHEIMR_LOG_DIR):
_logger.info(f'Creating log folder {HELHEIMR_LOG_DIR}.')
os.makedirs(HELHEIMR_LOG_DIR)
else:
_logger.info(f'All logs will be stored to {HELHEIMR_L... | 15,849 |
async def test_pydelijn():
"""Example usage of pydelijn."""
subscriptionkey = "<put your data.delijn.be subscriptionkey here>"
stopid = 200551
maxpassages = 10
custom_session = aiohttp.ClientSession()
delijndata = Passages(
LOOP, stopid, maxpassages, subscriptionkey, custom_session, True... | 15,850 |
def gather_inputs(headers, test_suites, inputs_class=Inputs):
"""Read the list of inputs to test psa_constant_names with."""
inputs = inputs_class()
for header in headers:
inputs.parse_header(header)
for test_cases in test_suites:
inputs.parse_test_cases(test_cases)
inputs.gather_arg... | 15,851 |
def load_institute(adapter, internal_id, display_name, sanger_recipients=None, loqusdb_id=None):
"""Load a institute into the database
Args:
adapter(MongoAdapter)
internal_id(str)
display_name(str)
sanger_recipients(list(email))
loqusdb_id(str)
"""
institute_obj... | 15,852 |
def key_create(adapter_id):
"""Creates a key using a certain adapter."""
adapter = get_adapter(adapter_id)
if not adapter:
return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501)
if not adapter.do_verify(request.headers):
return outp... | 15,853 |
def run_jsonhook(hook, spec, res, dsarg=None):
"""Execute a hook on a given result
A hook definition's 'call' specification may contain placeholders that
will be expanded using matching values in the given result record. In
addition to keys in the result a '{dsarg}' placeholder is supported.
The ch... | 15,854 |
def is_right(side1, side2, side3):
"""
Takes three side lengths and returns true if triangle is right
:param side1: int or float
:param side2: int or float
:param side3: int or float
:return: bool
"""
return False | 15,855 |
def parser_electron_number(electron_line):
"""
function of parser for electron information
Args:
electron_line (str): line
Returns:
list: electron information
"""
electron_list = parser_split_line_by_length(electron_line.rstrip(), CPF_FORMAT["ELECTRON"]["length"], "int")
return electron_list | 15,856 |
def summary(t, rtol=1e-5, atol=1e-8):
"""
Parameters
----------
t
rtol
atol
Returns
-------
"""
deltas = np.diff(t)
if np.allclose(deltas, deltas[0], rtol, atol):
# constant time steps
return deltas[0], deltas, ''
# non-constant time steps!
unq... | 15,857 |
def download(local_qanta_prefix, retrieve_paragraphs):
"""
Run once to download qanta data to data/. Runs inside the docker container, but results save to host machine
"""
#print("\n\n\tLocal Qanta Prefix: %s" %local_qanta_prefix)
#print("\n\n\tRetrieve Paragraphs: %s" %retrieve_paragraphs)
... | 15,858 |
def test_assert_correct_version():
"""
yep. update it every time.
This is a dumb test, but I want it here to remind future committers that if
you make a change to the package, your change should probably include a
test which verifies why the change was made.
If you want your changes to be seen... | 15,859 |
def masked_huber(input, target, lengths):
"""
Always mask the first (non-batch dimension) -> usually time
:param input:
:param target:
:param lengths:
:return:
"""
m = mask(input.shape, lengths, dim=1).float().to(input.device)
return F.smooth_l1_loss(input * m, target * m, reduction... | 15,860 |
def calcProbabilisticResiduals(
coords_actual,
coords_desired,
covariances_actual
):
"""
Calculate the probabilistic residual.
Parameters
----------
coords_actual : `~numpy.ndarray` (N, M)
Actual N coordinates in M dimensions.
coords_desired : `~numpy... | 15,861 |
def split_words_and_quoted_text(text):
"""Split string text by space unless it is
wrapped inside double quotes, returning a list
of the elements.
For example
if text =
'Should give "3 elements only"'
the resulting list would be:
['Should', 'give', '3 elements only'... | 15,862 |
def scheduler(epoch):
"""Generating learning rate value for a given epoch.
inputs:
epoch = number of current epoch
outputs:
learning_rate = float learning rate value
"""
if epoch < 100:
return 1e-3
elif epoch < 125:
return 1e-4
else:
return 1e-5 | 15,863 |
def plot_predictions(device, test_loader, net):
"""Plot the predictions of 1D regression tasks.
Args:
(....): See docstring of function :func:`main.test`.
"""
net.eval()
data = test_loader.dataset
assert(data.inputs.shape[1] == 1 and data.outputs.shape[1] == 1)
inputs = data.inpu... | 15,864 |
def external_search(query, feature_type, url):
""" Makes an external search request to a specified URL. The url will have the search
text appended to it. Returns geojson matches with extra data for the geocoder.
"""
logger.info("using external API for feature lookup: %s", url + query)
req = E... | 15,865 |
def has_supervisor() -> bool:
"""Return true if supervisor is available."""
return "SUPERVISOR" in os.environ | 15,866 |
def setup(*args, **kwds):
"""
Compatibility wrapper.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
return setup(*args, **kwds) | 15,867 |
def joinpath(base, end):
"""Like Path.joinpath(), but ensures the result is inside `base`.
Should be used for user-supplied `end`.
"""
result = (base / end).resolve()
if base not in result.parents:
print(base, end, result)
raise ValueError(end)
return result | 15,868 |
def multicolored_line_collection(x, y, z, colors):
""" Color a 2D line based on which state it is in
:param x: data x-axis values
:param y: data y-axis values
:param z: values that determine the color of each (x, y) pair
"""
nstates = colors.shape[0]
# come up with color map and normalizat... | 15,869 |
def foldr(fn,
elems,
initializer=None,
parallel_iterations=10,
back_prop=True,
swap_memory=False,
name=None):
"""foldr on the list of tensors unpacked from `elems` on dimension 0.
This foldr operator repeatedly applies the callable `fn` to a sequence
of... | 15,870 |
def featurise_distances(diagram):
"""Create feature vector by distance-to-diagonal calculation.
Creates a feature vector by calculating distances to the diagonal
for every point in the diagram and returning a sorted vector. The
representation is *stable* but might not be discriminative.
Parameters... | 15,871 |
def resize(source, width=None, height=None, filter=None, radius=1,
wrapx=False, wrapy=False):
"""Create a new numpy image with the desired size.
Either width or height can be null, in which case its value
is inferred from the aspect ratio of the source image.
Filter can be HERMITE, TRIANGLE... | 15,872 |
def load_and_classify_payload(config, service, entity, raw_record):
"""Return a loaded and classified payload."""
# prepare the payloads
payload = load_stream_payload(service, entity, raw_record)
payload = list(payload.pre_parse())[0]
classifier = StreamClassifier(config=config)
classifier.load... | 15,873 |
def Mode():
"""Take mode of cryptography."""
if mode.get() == 'e':
Result.set(Encode(private_key.get(), Text.get()))
elif mode.get() == 'd':
Result.set(Decode(private_key.get(), Text.get()))
else:
Result.set('Invalid Mode') | 15,874 |
def render_text(self, block: str, block_type: str, y: int) -> int:
"""
:param self: MarkdownRenderer
:param block: string of text
:param block_type: type of the text (e.g. headers, ordered/unordered lists, blockquotes, code etc)
:param y: y-coordinate to start rendering on
:return: y-coordina... | 15,875 |
def tvadam_reconstructor(dataset='ellipses', name=None):
"""
:param dataset: Can be 'ellipses' or 'lodopab'
:return: TV reconstructor for the specified dataset
"""
try:
params = Params.load('{}_tvadam'.format(dataset))
standard_dataset = load_standard_dataset(dataset)
if name... | 15,876 |
def process_spf_data(res, data):
"""
This function will take the text info of a TXT or SPF record, extract the
IPv4, IPv6 addresses and ranges, request process include records and return
a list of IP Addresses for the records specified in the SPF Record.
"""
# Declare lists that will be used in ... | 15,877 |
def label_attack(dataset, index_start, index_end, components):
"""Label one attack on a dataset
Parameters
----------
dataset: dataset, the dataset to label the attacks on
index_start: int, the first index of the attack
index_end: int, the last index of the attac... | 15,878 |
def create_knight():
"""
Creates a new knight according to player input.
Checks the knights module for how many points are to spend,
and which attributes are available. It then asks the player
for a name for the knight and to spend their points on the
available attributes.
Returns:
... | 15,879 |
async def get_bank_name(guild: discord.Guild = None) -> str:
"""Get the current bank name.
Parameters
----------
guild : `discord.Guild`, optional
The guild to get the bank name for (required if bank is
guild-specific).
Returns
-------
str
The bank's name.
Raises
... | 15,880 |
def main():
"""
Execute the nose test runner.
Drop privileges and alter the system argument to remove the
userid and group id arguments that are only required for the test.
"""
if len(sys.argv) < 2:
print (
u'Run the test suite using drop privileges username as first '
... | 15,881 |
def build_cli_lib(to_save_location: Optional[str] = None, render_kwargs: Optional[Dict[str, Any]] = None) -> str:
"""Create project-specific cli.fif lib"""
if not to_save_location:
to_save_location: str = tempfile.mkstemp(suffix='.fif')[1]
logger.info(f"👽 Save ton-cli to {to_save_location}")
... | 15,882 |
def match(A, S, trueS):
"""Rearranges columns of S to best fit the components they likely represent (maximizes sum of correlations)"""
cov = np.cov(trueS, S)
k = S.shape[0]
corr = np.zeros([k, k])
for i in range(k):
for j in range(k):
corr[i][j] = cov[i + k][j] / np.sqrt(c... | 15,883 |
def test_check_time_data(times):
""" Tests the function "check_time_data" from heartRateMonitor.py
:param times: List of time data
:returns: passes if exceptions raised when necessary, fails
otherwise
"""
from heartRateMonitor import check_time_data
with pytest.raises(ValueError):
c... | 15,884 |
def image_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all images.
Generates a sorted list of images available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the f... | 15,885 |
def plot_education_against_tv(adult_data: pd.DataFrame) -> None:
"""PLots combined barchart of the pop count and the mean tv in the sample
Source for combined barchart for sns:
https://python.tutorialink.com/how-can-i-plot-a-secondary-y-axis-with-seaborns-barplot/
* Notice how I link the stackoverflo... | 15,886 |
def _retry_for_entity_delay(func, timeout=60):
"""
Retry the given function a few times if it raises a DoesNotExistAWSError
with an increasing delay.
It sometimes takes AWS a bit for new entities to be available, so this
helper retries an AWS call a few times allowing for any of the errors
that... | 15,887 |
def posts_completed(scraped_posts, limit):
"""Returns true if the amount of posts scraped from
profile has reached its limit.
"""
if len(scraped_posts) == limit:
return True
else:
return False | 15,888 |
def mag(x):
"""Returns the absolute value squared of the input"""
return np.abs(x)**2 | 15,889 |
def get_zero_columns(matrix):
""" Returns a list of the columns which are all 0 """
rows = matrix.shape[0]
columns = matrix.shape[1]
result = []
for j in range(columns):
is_zero_column = True
for i in range(rows):
is_zero_column = is_zero_column and matrix[i, j] == 0.0
... | 15,890 |
def traditional_constants_icr_equation_empty_fixed(fixed_params, X_col):
""" Traditional ICR equation with constants from ACE consensus """
a = 450
tdd = X_col[0]
return a / tdd | 15,891 |
def sort_completions_key(completion):
"""
sort completions according to their type
Args:
completion (jedi.api.classes.Completion): completion
Returns:
int: sorting order
"""
if completion.type == "function":
return 2
elif completion.type == "instance":
retur... | 15,892 |
def _is_git_url_mismatch(mismatch_item):
"""Returns whether the given mismatch item is for a GitHub URL."""
_, (required, _) = mismatch_item
return required.startswith('git') | 15,893 |
def from_url(url, output_path=None, options=None):
"""
Convert file of files from URLs to PDF document
:param url: URL or list of URLs to be saved
:param output_path: (optional) path to output PDF file. If not provided, PDF will be returned as string
:param options: (optional) dict to configure pyp... | 15,894 |
def parse_wmic_output(wmic_output: str) -> Dict[str, str]:
"""Parse output of wmic query
See test cases.
@param wmic_output: Output from wmic tool
@return Dictionary with key/value from wmic"""
try:
non_blank_lines = [s for s in wmic_output.splitlines() if s]
parsed = {non_blank_li... | 15,895 |
def parse_identifier(stream: TokenStream) -> expression.Identifier:
"""Read an identifier from the token stream.
<ident>.<ident>
<ident>["<ident>"]
<ident>["<ident>"].<ident>
<ident>[<ident --> int/str>]
<ident>[<ident>.<ident --> int/str>]
<ident>[<int>]
<ident>[<int>].<ident>
"""
... | 15,896 |
def generate(json_file):
"""Read the JSON_FILE and write the PBS files"""
json_file = click.format_filename(json_file)
settings = read_jsonfile(json_file)
simulation = Simulation(settings)
click.echo('Job length = {}'.format(simulation.job_length))
simulation.writeSimulationFiles() | 15,897 |
def cubemap_projection_matrices(from_point: Vector3D, far_plane: float) -> List[np.ndarray]:
"""
Create the required Cubemap projection matrices.
This method is suitable for generating a Shadow Map.
Simply speaking, this method generates 6 different camera matrices from the center of
an imaginary ... | 15,898 |
def loadOptionsFile():
"""Find the .buildbot/FILENAME file. Crawl from the current directory up
towards the root, and also look in ~/.buildbot . The first directory
that's owned by the user and has the file we're looking for wins. Windows
skips the owned-by-user test.
@rtype: dict
@return:... | 15,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.