content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def post_to_conf(post_grid, cell_size):
"""
Converts a N-dimensional grid of posterior values into a grid of confidence levels. The posterior values do not need
to be normalised, i.e. their distribution need not integrate to 1. Works with likelihood values (not log-likelihood)
instead of posteriors, ass... | b4bcb8dddeceb7a4e1bb0914e503868e443ecb09 | 3,651,800 |
def get_fuzzer_display(testcase):
"""Return FuzzerDisplay tuple."""
if (testcase.overridden_fuzzer_name == testcase.fuzzer_name or
not testcase.overridden_fuzzer_name):
return FuzzerDisplay(
engine=None,
target=None,
name=testcase.fuzzer_name,
fully_qualified_name=testcase.... | 273e0a2f92a4e24606908586111f1bad17e50b4c | 3,651,801 |
def process_articles_results(articles_list):
"""
Function that processes the articles result and transform them to a list of Objects
Args:
articles_list: A list of dictionaries that contain sources details
Returns :
articles_results: A list of source objects
"""
articles_... | 7b4e540474757b2e0e9b93f66f5bee926992a782 | 3,651,802 |
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:r... | 19bcc6751e4805adcbfde54656ff83ef52ef02b8 | 3,651,803 |
def handle_td(element, box, _get_image_from_uri):
"""Handle the ``colspan``, ``rowspan`` attributes."""
if isinstance(box, boxes.TableCellBox):
# HTML 4.01 gives special meaning to colspan=0
# http://www.w3.org/TR/html401/struct/tables.html#adef-rowspan
# but HTML 5 removed it
# ... | d3a2669ffc8ccac27d3b40c4f693751239b9c135 | 3,651,804 |
import pipes
def login_flags(db, host, port, user, db_prefix=True):
"""
returns a list of connection argument strings each prefixed
with a space and quoted where necessary to later be combined
in a single shell string with `"".join(rv)`
db_prefix determines if "--dbname" is prefixed to the db arg... | 2c844def8e6f1154a9962d43c858b39b9a7adf2a | 3,651,805 |
def glplot(ncfile, times, colora, label):
"""
add a plot of grounding line points to current axes.
makes use of the numpy.ma.MaskedArray when reading xGL,yGL
"""
try:
ncid = Dataset(ncfile, 'r')
except:
print("Failed to open file: {}. Skipping.".format(ncfile))
return 350.0,... | 149836ceb0f6b65ba792bffcbdafad6fe8702f62 | 3,651,806 |
def roi_intersect(a, b):
"""
Compute intersection of two ROIs.
.. rubric:: Examples
.. code-block::
s_[1:30], s_[20:40] => s_[20:30]
s_[1:10], s_[20:40] => s_[10:10]
# works for N dimensions
s_[1:10, 11:21], s_[8:12, 10:30] => s_[8:10, 11:21]
"""
def slice_inter... | d1070c8ec0c493296dfee6bdc54b7430e703bda8 | 3,651,807 |
def _flows_finished(pgen_grammar, stack):
"""
if, while, for and try might not be finished, because another part might
still be parsed.
"""
for stack_node in stack:
if stack_node.nonterminal in ('if_stmt', 'while_stmt', 'for_stmt', 'try_stmt'):
return False
return True | dd0fe435d1328b3ae83ba2507006b6825ca23087 | 3,651,808 |
def PositionToPercentile(position, field_size):
"""Converts from position in the field to percentile.
position: int
field_size: int
"""
beat = field_size - position + 1
percentile = 100.0 * beat / field_size
return percentile | c75869f3d7f8437f28d3463fcf12b2b446fe930a | 3,651,809 |
def grid(num, ndim, large=False):
"""Build a uniform grid with num points along each of ndim axes."""
if not large:
_check_not_too_large(np.power(num, ndim) * ndim)
x = np.linspace(0, 1, num, dtype='float64')
w = 1 / (num - 1)
points = np.stack(
np.meshgrid(*[x for _ in range(ndim)], indexing='ij'),... | 51a3ef70da4581a774d76839d05a14042e7bf78c | 3,651,810 |
def rolling_outlier_quantile(x, width, q, m):
"""Detect outliers by multiples of a quantile in a window.
Outliers are the array elements outside `m` times the `q`'th
quantile of deviations from the smoothed trend line, as calculated from
the trend line residuals. (For example, take the magnitude of the... | 3c28fa245c8dfce03958dee33c47828eb38ac979 | 3,651,811 |
def compute_region_classification_len(dataset_output,
dataset_type: str):
"""
Compute the number of points per class and return a dictionary (dataset_type specifies the keys) with the results
"""
stable_region_indices, marginal_stable_region_indices, marginal_regio... | ba78d7d000b97cfcefa2acac263612ebd4aff377 | 3,651,812 |
def set_world_properties(world_uid, world_name=None, owner=None, config=None):
""" Set the properties of the given world """
return runtime.set_world_properties(world_uid, world_name, owner, config) | 4c063554390c0fb33ec74394a5a7cc967d55211d | 3,651,813 |
def _resize_and_pad(img, desired_size):
"""
Resize an image to the desired width and height
:param img:
:param desired_size:
:return:
"""
old_size = img.shape[:2] # old_size is in (height, width) format
ratio = float(desired_size) / max(old_size)
new_size = tuple([int(x * ratio) fo... | 1053748c0a303e3b5b3712623a089e42ba822301 | 3,651,814 |
from typing import Tuple
import os
from typing import cast
def _terminal_size(fallback: Tuple[int, int]) -> Tuple[int, int]:
"""
Try to get the size of the terminal window.
If it fails, the passed fallback will be returned.
"""
for i in (0, 1):
try:
window_width = os.get_termin... | 3254068444167bad0b87479001b0c22887b32a60 | 3,651,815 |
from cntk.ops.cntk2 import Dropout
def dropout(x, name=None):
"""
Compute a new tensor with `dropoutRate` perecent set to zero. The values
that are set to zero are randomly chosen. This is commonly used to prevent
overfitting during the training process.
The output tensor has the same shape as ... | ae688aa478842ba451b92de2bc0503e42f1a9363 | 3,651,816 |
def mol2graph(crystal_batch: CrystalDataset, args: Namespace) -> BatchMolGraph:
"""
Converts a list of SMILES strings to a BatchMolGraph containing the batch of molecular graphs.
:param crystal_batch: a list of CrystalDataset
:param args: Arguments.
:return: A BatchMolGraph containing the combined ... | 604351ad5ae6c1ccfa6ce01a1e7b03c5e80ff2a4 | 3,651,817 |
import ast
def _compile(s: str):
"""compiles string into AST.
:param s: string to be compiled into AST.
:type s: str
"""
return compile(
source = s,
filename = '<unknown>',
mode = 'eval',
flags = ast.PyCF_ONLY_AST,
) | 4709cfa84ab6e5d7210924cf3aa206a1d297b7bd | 3,651,818 |
def temp_get_users_with_permission_form(self):
"""Used to test that swapping the Form method works"""
# Search string: ABC
return () | 72390791304d62fc5d78720aac4e2807e918587c | 3,651,819 |
def create_resource_types(raml_data, root):
"""
Parse resourceTypes into ``ResourceTypeNode`` objects.
:param dict raml_data: Raw RAML data
:param RootNode root: Root Node
:returns: list of :py:class:`.raml.ResourceTypeNode` objects
"""
# TODO: move this outside somewhere - config?
acce... | e3858924b842b3d3d6a7bbd3b0a2783a0b054a06 | 3,651,820 |
def permute_images(images, permutation_index):
"""
Permute pixels in all images.
:param images: numpy array of images
:param permutation_index: index of the permutation (#permutations = #tasks - 1)
:return: numpy array of permuted images (of the same size)
"""
# seed = np.random.randint(low... | 5742c9c2bce5012b0c17b60eb5e66328b91e53b4 | 3,651,821 |
def new_user(request, id):
"""
Page for creating users after registering a person.
person must be either volunteer, NGO employee or Government
"""
msg = ''
password = ''
try:
person_id = int(id)
# Get Name
user = RegPerson.objects.get(pk=person_id)
personfna... | 26ff9e3fa289915218a6f60e138a3491955c0228 | 3,651,822 |
def multi_conv(func=None, options=None):
"""A function decorator for generating multi-convolution operations.
Multi-convolutions allow for a set of data-independent convolutions to be
executed in parallel. Executing convolutions in parallel can lead to an
increase in the data throughput.
The ``multi_conv`` f... | d1c9a69fbcec7b374142bc7568fc89ba8dddb0b9 | 3,651,823 |
def hi_joseangel():
""" Hi Jose Angel Function """
return "hi joseangel!" | 5889a51977d3ec2269040a9a7e7968801209ff25 | 3,651,824 |
import time
def received_date_date(soup):
"""
Find the received date received_date_date in human readable form
"""
received_date = get_history_date(soup, date_type = "received")
date_string = None
try:
date_string = time.strftime("%B %d, %Y", received_date)
except(TypeError):
# Date did not convert
pass
... | 3963d846a64e06ed0d2e60b7ecba26efcd4d9e6e | 3,651,825 |
def is_on(hass, entity_id):
""" Returns if the group state is in its ON-state. """
state = hass.states.get(entity_id)
if state:
group_type = _get_group_type(state.state)
# If we found a group_type, compare to ON-state
return group_type and state.state == _GROUP_TYPES[group_type][0]... | 8e77a7a3f4a09d68d92d58105b3d5a36c830cd0c | 3,651,826 |
def pytest_report_header(config, startdir):
"""return a string to be displayed as header info for terminal reporting."""
capabilities = config.getoption('capabilities')
if capabilities:
return 'capabilities: {0}'.format(capabilities) | 4e6ada67f5f08c1db8f5b6206089db4e3ee84f46 | 3,651,827 |
def chessboard_distance(x_a, y_a, x_b, y_b):
"""
Compute the rectilinear distance between
point (x_a,y_a) and (x_b, y_b)
"""
return max(abs(x_b-x_a),abs(y_b-y_a)) | 9b11bf328faf3b231df23585914f20c2efd02bf9 | 3,651,828 |
from pgmpy.factors import TabularCPD
from pgmpy.models import BayesianModel
import pandas as pd
from pgmpy.inference import VariableElimination # NOQA
from pgmpy.factors import TabularCPD
import pgmpy
import plottool as pt
import networkx as netx
def bayesnet():
"""
References:
https://class.coursera... | 05853fb3a7e84a1864399588af4b27390a1c8d31 | 3,651,829 |
def sigma_R(sim, Pk=None, z=None, non_lin=False):
""" return amplitude of density fluctuations
if given Pk -- C++ class Extrap_Pk or Extrap_Pk_Nl -- computes its sigma_R.
if given redshift, computes linear or non-linear (emulator) amplitude of density fluctuations """
sigma = fs.Data_Vec_2()
if Pk:... | 956a4ca092ce56c1d8120c3b9047280306005326 | 3,651,830 |
def session_ended_request_handler(handler_input):
"""Handler for Session End."""
# type: (HandlerInput) -> Response
logger.info("Entering AMAZON.SessionEndedRequest")
save_data(handler_input)
return handler_input.response_builder.response | a3bd1c38699a69da0cdce0203ee0549e9132b1c1 | 3,651,831 |
import unittest
def _getTestSuite(testFiles):
"""
Loads unit tests recursively from beneath the current directory.
Inputs: testFiles - If non-empty, a list of unit tests to selectively run.
Outputs: A unittest.TestSuite object containing the unit tests to run.
"""
loader = unittest.TestLoad... | 786baa4d70161e1ae6c60160460f379c66ea465c | 3,651,832 |
def stratifiedsmooth2stratifiedwavy_c(rho_gas, rho_liq, vel_gas, d_m, beta, mu_liq, mu_gas):
"""
function for construction of boundary transition from stratified-smooth to stratified-wavy structure
resulting from the "wind" effect
:param rho_gas: gas density
:param rho_liq: liquid density
:para... | a80c1b5f400d4db36979960a26f5b914047abe8d | 3,651,833 |
def box(
data_frame=None,
x=None,
y=None,
color=None,
facet_row=None,
facet_row_weights=None,
facet_col=None,
facet_col_weights=None,
facet_col_wrap=0,
facet_row_spacing=None,
facet_col_spacing=None,
hover_name=None,
hover_data=None,
custom_data=None,
animatio... | 2e5a22fd4fa875b4cb506c7d21ff91e56908ed65 | 3,651,834 |
def _infer_main_columns(df, index_level='Column Name', numeric_dtypes=_numeric_dtypes):
"""
All numeric columns up-until the first non-numeric column are considered main columns.
:param df: The pd.DataFrame
:param index_level: Name of the index level of the column names. Default 'Column Name'
:param... | 3eae67b765ca7a1a048047e12511c1a9721f9fea | 3,651,835 |
def index():
"""
显示首页
:return:
"""
return render_template('index.html') | 8965ff54f131a0250f1a05183ceb79d6d677883c | 3,651,836 |
def two_phase(model, config):
"""Two-phase simulation workflow."""
wea_path, datetime_stamps = get_wea(config)
smx = gen_smx(wea_path, config.smx_basis, config.mtxdir)
pdsmx = prep_2phase_pt(model, config)
vdsmx = prep_2phase_vu(model, config)
if not config.no_multiply:
calc_2phase_pt(mo... | 0f2eb619dcfea233446e90565bc1310ee1a3bc3f | 3,651,837 |
def str_with_tab(indent: int, text: str, uppercase: bool = True) -> str:
"""Create a string with ``indent`` spaces followed by ``text``."""
if uppercase:
text = text.upper()
return " " * indent + text | 3306ba86781d272a19b0e02ff8d06da0976d7282 | 3,651,838 |
def delete(card, files=None):
"""Delete individual notefiles and their contents.
Args:
card (Notecard): The current Notecard object.
files (array): A list of Notefiles to delete.
Returns:
string: The result of the Notecard request.
"""
req = {"req": "file.delete"}
if fi... | 2acfa67b7531244e44a183286a9d87b9ac849c83 | 3,651,839 |
def test_timed_info():
"""Test timed_info decorator"""
@timed_info
def target():
return "hello world"
result = target()
assert result == "hello world" | 4deb25b542bcc1a3ad2fc5859c2c3f243060b6d9 | 3,651,840 |
from typing import Set
def get_doc_word_token_set(doc: Doc, use_lemma=False) -> Set[Token]:
"""Return the set of tokens in a document (no repetition)."""
return set([token.lemma_ if use_lemma else token.text for token in get_word_tokens(doc)]) | 56e1d8bfcad363049b4dd455e728d5c4dd3754f5 | 3,651,841 |
from typing import List
def finding_the_percentage(n: int, arr: List[str], query_name: str) -> str:
"""
>>> finding_the_percentage(3, ['Krishna 67 68 69', 'Arjun 70 98 63',
... 'Malika 52 56 60'], 'Malika')
'56.00'
>>> finding_the_percentage(2, ['Harsh 25 26.5 28', 'Anurag 26 28 30'],
... 'Har... | 86c2ad777c667f9ba424bc2b707f46465a10accc | 3,651,842 |
def mvg_logpdf_fixedcov(x, mean, inv_cov):
"""
Log-pdf of the multivariate Gaussian distribution where the determinant and inverse of the covariance matrix are
precomputed and fixed.
Note that this neglects the additive constant: -0.5 * (len(x) * log(2 * pi) + log_det_cov), because it is
irrelevant ... | 648d1925ed4b4793e8e1ce1cec8c7ccd0efb9f6b | 3,651,843 |
from pathlib import Path
import sys
def app_dir(app_name: str = APP_NAME) -> Path:
"""Finds the application data directory for the current platform.
If it does not exists, it creates the required directory tree.
Returns:
The path to the root app directory.
"""
if sys.platform == "win32":... | 9ed4ae1ec1113a806ac2fc9c2488a12ace338c2a | 3,651,844 |
def make_frac_grid(frac_spacing, numrows=50, numcols=50, model_grid=None,
seed=0):
"""Create a grid that contains a network of random fractures.
Creates and returns a grid containing a network of random fractures, which
are represented as 1's embedded in a grid of 0's.
Parameters
... | 2e1ffc1bab30726dcbbe1b022c6cf92920c2dcc2 | 3,651,845 |
import colorsys
def generate_colors():
"""
Generate random colors.
To get visually distinct colors, generate them in HSV space then
convert to RGB.
"""
N = 30
brightness = 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
perm = [15, 13... | ee8951d66972190e6d1dcd5dc5c211d5631f6841 | 3,651,846 |
def secant_method(f, x0, x1, iterations):
"""Return the root calculated using the secant method."""
for i in range(iterations):
f_x1 = f(x1)
x2 = x1 - f_x1 * (x1 - x0) / (f_x1 - f(x0) + 1e-9).float()
x0, x1 = x1, x2
return x2 | 081522ae8e68ad14cb67f8afc03989c46f3999d5 | 3,651,847 |
def to_skopt_space(x):
"""converts the space x into skopt compatible space"""
if isinstance(x, list):
if all([isinstance(s, Dimension) for s in x]):
_space = Space(x)
elif len(x) == 1 and isinstance(x[0], tuple):
if len(x[0]) == 2:
if 'int' in x[0][0].__cl... | c5f4afdf2f3f3e36abe6cf8a8e12e20992aa13f7 | 3,651,848 |
import requests
def build_response(status=OK, etag='etag', modified='modified', max_age=None):
"""Make a requests.Response object suitable for testing.
Args:
status: HTTP status
exp-time: cache expire time (set to future for fresh cache, past for
stale cache (defaults to stale))
... | f9a97da74b7802511180f30dc45e9df5d5e87f51 | 3,651,849 |
from typing import List
from re import T
def split_list(big_list: List[T], delimiter: T) -> List[List[T]]:
"""Like string.split(foo), except for lists."""
cur_list: List[T] = []
parts: List[List[T]] = []
for item in big_list:
if item == delimiter:
if cur_list:
parts... | c56dd88a7376f002ae6b91c3b227c8a16991ca31 | 3,651,850 |
def generate_partitions(data):
"""
Generates a random nested partition for an array of integers
:param data:
:return:
"""
if len(data) == 1:
return data
else:
mask1 = np.random.choice(len(data), np.floor(len(data)/2), replace=False)
par1 = [data[i] for i in range(le... | 164749c135de1cf690bb209a18270a5550cdefc8 | 3,651,851 |
import os
import shutil
def adjust_shapefile_to_aoi(data_uri, aoi_uri, output_uri, \
empty_raster_allowed = False):
"""Adjust the shapefile's data to the aoi, i.e.reproject & clip data points.
Inputs:
- data_uri: uri to the shapefile to adjust
- aoi_uri: uir to a single polygo... | 83fcefaebf2adff02a360a5186fbf219de5579a2 | 3,651,852 |
def randomRectangularCluster(nRow, nCol, minL, maxL, mask=None):
"""
Create a random rectangular cluster neutral landscape model with
values ranging 0-1.
Parameters
----------
nRow : int
The number of rows in the array.
nCol : int
The number of columns in the array.
... | b53db06114ac3a465c1e0444bed59aa7403bba83 | 3,651,853 |
import os
import pickle
def auth(credentials_file_path):
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes f... | b9b65c1976ec5574f9ec2bc56b3c5d0e827cd4a6 | 3,651,854 |
def add_arc():
"""
:return: arc object
"""
l_hand = GArc(200, 200, 60, 150, x=480, y=270)
l_hand.filled = True
l_hand.fill_color = "#8eded9"
r_hand = GArc(200, 200, -30, 120, x=650, y=300)
r_hand.filled = True
r_hand.fill_color = "#8eded9"
return l_hand, r_hand | 667004d534d58ab11e9b41ca42572dc445ffcf7d | 3,651,855 |
def get_data_item_or_add(results_dic, name, n_hid, epochs, horizon, timesteps):
""" Return or create a new DataItem in `results_dic` with the corresponding
metadata.
"""
if name not in results_dic:
results_dic[name] = []
found = False
for item in results_dic[name]:
if item.is_me... | e6c713cd89b7a9816f52be11a4730f1cef60355c | 3,651,856 |
def midcurve_atm_fwd_rate(asset: Asset, expiration_tenor: str, forward_tenor: str, termination_tenor: str,
benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None, *, source: s... | e77ba9ef705c2eefe0f46431862697b6a840d6fd | 3,651,857 |
def extrode_multiple_urls(urls):
""" Return the last (right) url value """
if urls:
return urls.split(',')[-1]
return urls | 34ec560183e73100a62bf40b34108bb39f2b04b4 | 3,651,858 |
def build_header(cp: Config) -> str:
"""Build the email header for a SMTP email message"""
header = '\n'.join([
'From: {}'.format(cp.sender),
'To: {}'.format(''.join(cp.receiver)),
'Subject: {}\n\n'.format(cp.subject)
])
return header | a0c9fdc820d4a454c0384c46775d3e1359710fad | 3,651,859 |
def apex_distance(r0, rc, Rc, uvec):
"""
Implements equation (E4) of TYH18
"""
R0 = rc + Rc * uvec - r0
return np.hypot(*R0) | f88d59727fce25306ae6ef0856941efdbb80a712 | 3,651,860 |
def pixel2phase(data):
"""
converts each channel of images in the data to phase component of its 2-dimensional discrete Fourier transform.
:param data: numpy array with shape (nb_images, img_rows, img_cols, nb_channels)
:return: numpy array with same shape as data
"""
channels = data.shape[-1]
... | 1b6b2c513cc20fe9642dd375dd17ee2205692912 | 3,651,861 |
def take_last_while(predicate, list):
"""Returns a new list containing the last n elements of a given list, passing
each value to the supplied predicate function, and terminating when the
predicate function returns false. Excludes the element that caused the
predicate function to fail. The predicate fun... | 19468c9130e9ab563eebd97c30c0e2c74211e44b | 3,651,862 |
import re
from bs4 import BeautifulSoup
def get_notes() -> str:
"""Scrape notes and disclaimers from dashboard."""
# As of 6/5/20, the only disclaimer is "Data update weekdays at 4:30pm"
with get_firefox() as driver:
notes = []
match = re.compile('disclaimers?', re.IGNORECASE)
driv... | 7ec0efab1c5ed17c1878ece751bffe82d77f0105 | 3,651,863 |
def signup_logout(request):
"""
Just wrapping the built in
"""
return logout_view(request, template_name='logged_out.html') | 14c403720c396aa8bbb37752ce304bb2804dd46b | 3,651,864 |
def stress_rotation(stress, angle):
"""
Rotates a stress vector against a given angle.
This rotates the stress from local to the global axis sytem.
Use a negative angle to rotate from global to local system.
The stress vector must be in Voigt notation and engineering stress is used.
Parameters... | 96ae75ae61fdbee0cf120e6d705cadc265452e7d | 3,651,865 |
def blue_noise(x=None, hue=None, data=None, dodge=False, orient='v', plot_width=None,
color='black', palette='tab10', size=3, centralized=False,
filename='', scaling=10):
""" Renders a *Blue Noise Plot* from the given data.
Args:
x (str in data): Variables that specify pos... | 8743dacba9ddac1b1e73e676962d850876c5b2f3 | 3,651,866 |
def get_repository(auth_user: check_auth, repository_id: hug.types.text):
"""
GET: /repository/{repository_id}
Returns the CLA repository requested by UUID.
"""
return cla.controllers.repository.get_repository(repository_id) | ad9bb45a4d4526b790abb7f89d72a3deafb2d10f | 3,651,867 |
def _isDebug():
"""*bool* = "--debug" or "--debugger" """
return options is not None and (options.debug or options.debugger) | f6670a5c5711e2f5e4c29b6b4d5356813b302ee9 | 3,651,868 |
def _and(mat,other,obj,m):
"""
Can only be used with '&' operator not with 'and'
Multi-column boolean matrices' values are compared with 'and' operator, meaning that 1 false value
causes whole row to be reduced to a false value
"""
if mat.BOOL_MAT:
if isinstance(other,obj):
... | ac4e4d5f205c6aeb068d9fb427839e4e8f85f0ea | 3,651,869 |
import copy
def MAP (request, resource, optimize_already_mapped_nfs=True,
migration_handler_name=None, migration_coeff=None,
load_balance_coeff=None, edge_cost_coeff=None,
time_limit=None, mip_gap_limit=None, node_limit=None, logger=None,
**migration_handler_kwargs):
"""
Starts... | 28d74396d14e75fc3c2865461de40aa9cf2586e7 | 3,651,870 |
def _parcel_profile_helper(pressure, temperature, dewpt):
"""Help calculate parcel profiles.
Returns the temperature and pressure, above, below, and including the LCL. The
other calculation functions decide what to do with the pieces.
"""
# Find the LCL
press_lcl, temp_lcl = lcl(pressure[0], t... | 2e9abd03dbf4617e53ea19ac7a415025567195e8 | 3,651,871 |
import os
import glob
import hashlib
def extract_subject(subj, mask_name, summary_func=np.mean,
residual=False, exp_name=None):
"""Extract timeseries from within a mask, summarizing flexibly.
Parameters
----------
subj : string
subject name
mask_name : string
n... | be9759e6cde757fc55bd70d10cb8b784e312b0d2 | 3,651,872 |
def best_param_search(low=1, margin=1, func=None):
"""
Perform a binary search to determine the best parameter value.
In this specific context, the best
parameter is (the highest) value of the parameter (e.g. batch size)
that can be used to run a func(tion)
(e.g., training) successfully. Beyond ... | 6392d8c019ebb50a49c46e724e62fd63671a00df | 3,651,873 |
def configure_plugins_plugin_uninstall(request, pk):
"""
Disables a plugin from the system
:param request:
:param pk: The primary key of the plugin to be disabled
:return:
"""
# TODO: See about pulling this out into a common methods
plugin = get_object_or_404(Plugin, pk=pk)
action = ... | f6c849a2dc4fe63ec43119e9e135c4c6385accd0 | 3,651,874 |
def get_supervised_timeseries_data_set(data, input_steps):
"""This function transforms a univariate timeseries into a supervised learning problem where the input consists
of sequences of length input_steps and the output is the prediction of the next step
"""
series = pd.Series(data)
data_set = pd.D... | 0fce866ea266c15e83e57795f86fcfe4fee4a54e | 3,651,875 |
import os
def load_df(name):
"""Load a pandas dataframe from csv file at results/name."""
load_name = os.path.join(here, "..", "results", name)
df = pd.read_csv(load_name)
return df | 6b96b8368c2afcfa552b98ee65d0ee9d889ee0bc | 3,651,876 |
def load_template_spectra_from_folder(parent_folder,
spectrum_identifier,
normalization=None):
"""
Load template spectrum data into a dictionary. This allows templates from
different folders to be loaded into different dictionaries.... | 466d0eb74de197ddb18e289f072d9451bc7ea2d8 | 3,651,877 |
import json
def remove_screenshot_from_object(request):
"""
Removes the screenshot from being associated with a top-level object.
:param request: The Django request.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
analyst = request.user.use... | 36836120c79dc8d825c91370074da09fd2255c6d | 3,651,878 |
import csv
import json
def read_csv_as_dicts(
filename,
newline="",
delimiter=",",
quotechar='"',
encoding="utf-8",
remove_prefix=True,
prefix="dv.",
json_cols=CSV_JSON_COLS,
false_values=["FALSE"],
true_values=["TRUE"],
):
"""Read in CSV file into a list of :class:`dict`.
... | bf15b684120445adf7e6ba8ae18befd64ad6a99f | 3,651,879 |
from typing import Dict
from typing import Union
from typing import Tuple
from typing import List
import torch
from typing import Any
def get_rewrite_outputs(wrapped_model: nn.Module,
model_inputs: Dict[str, Union[Tuple, List,
torch.Tensor]... | 147276df37fcb7df604ec14454638605266fbdc1 | 3,651,880 |
import tempfile
import os
def _get_implied_dependencies(path: str) -> list:
""" Attempt to replace _get_requirements_from_file
Extracts import statements via regex.
Does not catch all import statements and its
use was rolled back.
Might still be overhauled and integrated again.
"""
_pyth... | 5ddd0b00e769f5d529053f00114ef3e5fb33e6da | 3,651,881 |
def get_interface_breakout_param(dut,**kwargs):
"""
Author: Naveen Nag
email : [email protected]
:param dut:
:param interface:
:param fields:
:return: interface breakout speed
Usage:
port.get_interface_breakout_param(dut1, 'Ethernet4')
:return - ['4x10G', 'Completed... | 43286c8dbc29fef096d34c567f3f7c4ff2a06691 | 3,651,882 |
def get_process_basic_window_enriched(cb, print_detail, window):
"""
Text
Args:
cb (CBCloudAPI): API object
print_detail (bool): whether to print full info to the console, useful for debugging
window (str): period to search
Returns:
process_guid of the first process in ... | 97a9a3df0570ee4f1777faa6385c7ddd8a013594 | 3,651,883 |
def home():
"""Home view"""
if flask.session.get('userid'):
leaderboard_players = rankedlist(
member=db.web.session.query(
models.Member).get(
flask.session['userid']))
member = db.web.session.query(
models.Member).get(
flask.se... | 89211f6b79eae71b757201a2d8b234000a3e42bf | 3,651,884 |
def is_number(string):
""" Tests if a string is valid float. """
try:
float(string)
return True
except ValueError:
return False | 1c46820de59b932ec565af55c565d175eef58c3c | 3,651,885 |
import os
def recursive_load_gfx(path, accept=(".png", ".bmp", ".svg")):
"""
Load graphics files.
This operates on a one folder at a time basis.
Note: An empty string doesn't count as invalid,
since that represents a folder name.
"""
colorkey = c.UGLY_PURPLE
graphics = {}
for pic... | 5daff8707aeeb2837e0a00be7a54b3d70ec3f917 | 3,651,886 |
def inputs(filename, batch_size, n_read_threads = 3, num_epochs = None, image_width = 200, image_height=290):
"""
reads the paired images for comparison
input: name of the file to load from, parameters of the loading process
output: the two images and the label (a logit classifier for 2 class - yes or no)
"""... | 1b22a3f5b28513a2f65312981205b2df40acd2b3 | 3,651,887 |
import logging
import os
def combinedlogger(
log_name,
log_level=logging.WARN,
syslogger_format="%(levelname)s %(message)s",
consolelogger_format="%(asctime)s %(levelname)s %(message)s",
):
"""
Returns a combined SysLogHandler/StreamHandler logging instance
with formatters
"""
if "... | 45b6b63c1912f115a57afbf7ad2ba5478f12d548 | 3,651,888 |
def abs_p_diff(predict_table, categA='sandwich', categB='sushi'):
"""Calculates the absolute distance between two category predictions
:param predict_table: as returned by `predict_table`
:param categA: the first of two categories to compare
:param categB: the second of two categoreis to compare
:r... | 235bfc7df29ac4a2b67baff9dfa3ee62204a9aed | 3,651,889 |
def _is_target_feature(column_names, column_mapping):
"""Assert that a feature only contains target columns if it contains any."""
column_names_set = set(column_names)
column_types = set(column['type']
for column_name, column in column_mapping.iteritems()
if column_name i... | 098af45938c616dd0ff2483a27131f15ba50797b | 3,651,890 |
import typing
import json
import requests
def server_upload_document(path: str, title: str, peer: int, document_type: str = "doc") -> \
typing.Tuple[bool, typing.Union[str, typing.Any]]:
""" Uploads document to the server and returns it (as document string). """
try:
# Trying to upload docume... | 2387dabd84c590a0eb3f6406d0b6742ccad4cb14 | 3,651,891 |
def _default_mono_text_dataset_hparams():
"""Returns hyperparameters of a mono text dataset with default values.
See :meth:`texar.MonoTextData.default_hparams` for details.
"""
return {
"files": [],
"compression_type": None,
"vocab_file": "",
"embedding_init": Embedding.... | bfd015cc93bd974b6486cf07cf72f1dfb7443b61 | 3,651,892 |
def validate_engine_mode(engine_mode):
"""
Validate database EngineMode for DBCluster
Property: DBCluster.EngineMode
"""
VALID_DB_ENGINE_MODES = (
"provisioned",
"serverless",
"parallelquery",
"global",
"multimaster",
)
if engine_mode not in VALID_DB... | 69f7952a998b6ca593106c92710909104e21f55f | 3,651,893 |
import logging
def GetBlameListForV2Build(build):
""" Uses gitiles_commit from the previous build and current build to get
blame_list.
Args:
build (build_pb2.Build): All info about the build.
Returns:
(list of str): Blame_list of the build.
"""
search_builds_response = buildbucket_client.Sea... | 622fb540d4cce2dc2f57c7a7276ebef546ebc766 | 3,651,894 |
from datetime import datetime
def run_command(cmd, log_method=log.info):
"""Subprocess wrapper for capturing output of processes to logs
"""
if isinstance(cmd, str):
cmd = cmd.split(" ")
start = datetime.utcnow()
log_method("Starting run_command for: {}".format(" ".join([str(x) for x in cm... | 8366c9306810d927daf82b473db86dc67b0d84c6 | 3,651,895 |
def jar(state: State, fail: Fail):
"""
Store a function by a name
"""
(identifier, (code, rest)) = state.infinite_stack()
if identifier.tag != "atom":
fail(f"{identifier} is not an atom")
if code.tag not in ["code", "native"]:
fail(f"{code} is not code")
if code.tag == "cod... | 5f60a30ff7bed1a453bfe6ff354dc34a6fabee4f | 3,651,896 |
import os
import argparse
def existant_file(filepath:str):
"""Argparse type, raising an error if given file does not exists"""
if not os.path.exists(filepath):
raise argparse.ArgumentTypeError(
" file {} doesn't exists".format(C_FILE + filepath + C_ENDC)
)
return filepath | dacf94aaeccb6b70974eafc87dff96609408ccb6 | 3,651,897 |
import requests
import json
def get_daily_activity(p_sap_date: str) -> dict:
""" Returns activities on the given date """
fiori_url = config.CONSTANTS["ECZ_DAHA_DAILY_URL"] + "?date=" + p_sap_date
resp = requests.get(
fiori_url,
auth=HTTPBasicAuth(
config.CONSTANTS["ECZ_DAHA_US... | 68da0af50b0fc828d6eae3d1685911f039bd9732 | 3,651,898 |
import random
from typing import Optional
def load_example_abc(title: Optional[str] = None) -> str:
"""Load a random example ABC if `title` not provided.
Case ignored in the title.
"""
if title is None:
k = random.choice(list(examples))
else:
k = title.lower()
abc = examples.... | d1deba6a03814da68c5d47a7018a6768059fef62 | 3,651,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.