content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def generate_bootstrap_correlation_output(borda_count, viz_score, pearson_array,
phenotype_name, feature_name_list, run_parameters):
""" Save final output of correlation
Args:
pearson_array: pearson correlation coefficient array
phenotype_name: name of... | 5,314,300 |
def records2bigwigs(df: pd.DataFrame, prefix: str):
""" Dump dataframe to bigwig files
:param df: records dataframe, contain fields: chrom, start, end.
:param prefix: prefix of output bigwig files.
"""
import pyBigWig
required_fields = ['chrom', 'start', 'end']
assert all((f in df) ... | 5,314,301 |
def preprocess_value(value): # TODO add preprocessing for noise and other stuff
"""
Preprocess value with regex to clear noise and data
Parameters
----------
value: str
string to be preprocessed
Returns
-------
preprocessed: str
value that is already filtered from toke... | 5,314,302 |
def get_molecule(molecule):
"""Call read_xyz for molecule.
Extract symbols and geometry for given molecule from data folder.
Parameters
----------
molecule : string
prefix of the .xyz file
Returns
-------
molecule : `dict`
This output is described in :func:`~molpy.util... | 5,314,303 |
def connect_to_database():
""" Attempt to connect to sqlite database. Return connection object."""
try:
connection = sqlite3.connect('blackjack_terminal')
print("DB Connected!")
except Exception, e:
print e
sys.exit(1)
return connection | 5,314,304 |
def div_up(a, b):
"""Return the upper bound of a divide operation."""
return (a + b - 1) // b | 5,314,305 |
def handle_info():
"""
This function is called when you register your Battlesnake on play.battlesnake.com
See https://docs.battlesnake.com/guides/getting-started#step-4-register-your-battlesnake
It controls your Battlesnake appearance and author permissions.
For customization options, see https://d... | 5,314,306 |
def story_root(story):
"""story_root()
Serves the root page of a story
Accessed at '/story/<story' via a GET request
"""
# Gets the DocumentReference to the story document in Firestore
story_ref = db.collection('stories').document(story)
# Gets the DocumentSnapshot of the story document in... | 5,314,307 |
def get_scons_pkg_build_dir(pkg):
"""Return the build directory for the given package (foo.bar).
The path is relative to the top setup.py"""
from numscons.core.utils import pkg_to_path
return pjoin(get_scons_build_dir(), pkg_to_path(pkg)) | 5,314,308 |
def test_schema_template_subpath(given, expected):
"""Ensure schema_template_subpath makes the right URIs."""
if isinstance(expected, Exception) or issubclass(expected, Exception):
with pytest.raises(expected):
schema_template_subpath(**given)
else:
assert schema_template_subpat... | 5,314,309 |
def oklab_to_linear_srgb(lab):
"""Convert from Oklab to linear sRGB."""
return util.dot(LMS_TO_SRGBL, [c ** 3 for c in util.dot(OKLAB_TO_LMS3, lab)]) | 5,314,310 |
def test_word_cloud_one_string():
"""
word_cloud can be called with an array of single words (e.g. a column
of cells containing single words)
"""
grams = word_cloud(['fun yes Fun perfect fun yes'])
assert grams == [
('fun', 3),
('yes', 2),
('perfect', 1)
] | 5,314,311 |
def rjust(text: str, length: int) -> str:
"""Like str.rjust() but ignore all ANSI controlling characters."""
return " " * (length - len(strip_ansi(text))) + text | 5,314,312 |
def solar_elevation_angle(solar_zenith_angle):
"""Returns Solar Angle in Degrees, with Solar Zenith Angle, solar_zenith_angle."""
solar_elevation_angle = 90 - solar_zenith_angle
return solar_elevation_angle | 5,314,313 |
def vector3d_to_quaternion(x):
"""Convert a tensor of 3D vectors to a quaternion.
Prepends a 0 to the last dimension, i.e. [[1,2,3]] -> [[0,1,2,3]].
Args:
x: A `tf.Tensor` of rank R, the last dimension must be 3.
Returns:
A `Quaternion` of Rank R with the last dimension being 4.
Rais... | 5,314,314 |
def record_read_permission_factory(record=None):
"""Pre-configured record read permission factory."""
PermissionPolicy = get_record_permission_policy()
return PermissionPolicy(action='read', record=record) | 5,314,315 |
def fetch_66_cookie():
"""
获取 cookies
:return:
"""
cookie_url = 'http://www.66ip.cn/'
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Accept-Encoding": "gzip, deflate",
"Accep... | 5,314,316 |
async def test_proxy_binding2():
"""
7
7
----------
sub foo changed 7
sub foo changed 7
"""
# Get ref to JsComponent instantiated by a JsComponent,
# drop that ref, re-get the proxy instance, and verify that its
# a different instance representing the same object in JS
c1, s... | 5,314,317 |
def save_SACvariables(
filename,
rho,
Bx,
By,
Bz,
energy,
option_pars,
physical_constants,
coords,
Nxyz,
... | 5,314,318 |
def drawSlice(r, g, b):
"""
Draws a slice of a specified color.
Parameters:
r (String): The Red component. 2 Hex digits
g (String): The Green component. 2 Hex digits
b (String): The Blue component. 2 Hex digits
"""
turtle.color("#" + r + g + b)
turtle.forward(100) | 5,314,319 |
def query_address(address):
"""
Example: curl localhost:8080/queries/1234
"""
return get_score(address) | 5,314,320 |
def marshal(resp, schema):
"""
prepares the response object with the specified schema
:param resp: the falcon response object
:param schema: the schema class that should be used to validate the response
:return: falcon.Response
"""
data = resp
resp_ = None
if isinstance(data, list):
... | 5,314,321 |
def ethereum_tester(
patch_genesis_gas_limit,
):
"""Returns an instance of an Ethereum tester"""
tester = EthereumTester(PyEVMBackend())
tester.set_fork_block('FORK_BYZANTIUM', 0)
return tester | 5,314,322 |
def get_news():
"""Get all the news"""
global NEWS
NEWS = DATABASE['news'].find_one({}, {'_id': False}) | 5,314,323 |
def fetch_form(formid):
"""
Fetch Ona Form.
"""
headers = {"Authorization": "Token {}".format(ONA_TOKEN)}
url = urljoin(ONA_URI, "/api/v1/forms/{}.json".format(formid))
response = requests.get(url, headers=headers)
return response.json() if response.status_code == 200 else None | 5,314,324 |
def get_token_from_http_header(request):
"""Retrieves the http authorization header from the request"""
token = None
try:
header = request.META.get(HTTP_AUTHORIZATION_HEADER, "")
except AttributeError:
header = ""
try:
prefix, payload = header.split()
except ValueErro... | 5,314,325 |
def choose_line(path_with_lines):
""" Choose one line for each stations in path_with_lines list
Args:
path_with_lines(list): A list of dictionaries of stations and lines
Returns:
final_path(list): A list of dictionaries of station, line, and token
"""
final_path = []
i = ... | 5,314,326 |
def get_multiclass_predictions_and_correctness(probabilities, labels, top_k=1):
"""Returns predicted class, correctness boolean vector."""
_validate_probabilities(probabilities, multiclass=True)
_check_rank_nonempty(rank=1, labels=labels)
_check_rank_nonempty(rank=2, probabilities=probabilities)
if top_k == ... | 5,314,327 |
def download_frappe_assets(verbose=True):
"""Downloads and sets up Frappe assets if they exist based on the current
commit HEAD.
Returns True if correctly setup else returns False.
"""
from subprocess import getoutput
assets_setup = False
frappe_head = getoutput("cd ../apps/frappe && git rev-parse HEAD")
if f... | 5,314,328 |
def compute_gradient_penalty(discriminator, interpolated):
"""Computes the gradient penalty for a discriminator.
According to [https://arxiv.org/abs/1704.00028]
Args:
discriminator: The discriminator to compute the gradient
penalty for.
interpolated: The interpolation between re... | 5,314,329 |
def RevisionFailed(revision_ref):
"""Displays troubleshooting information to the user.
This is the revision-equivalent of DeploymentFailed. It's called when the
revision is determined to be the source of the issue.
Args:
revision_ref: a Revision resource.
"""
messages = blueprints_util.GetMessagesModu... | 5,314,330 |
def build_grid(resolution, device):
"""
Building the grid for linear embedding
:param device: As we create a new tensor, we need to put it on the device as well
:param resolution: tuple of integers (height, width)
:return: Tensor of shape [1, height, height, 4]
"""
ranges = [np.linspace(0., ... | 5,314,331 |
def get_fit_point_data(frame: fitdecode.records.FitDataMessage) -> Optional[Dict[str, Union[float, int, str, datetime]]]:
"""Extract some data from an FIT frame representing a track point
and return it as a dict.
"""
data: Dict[str, Union[float, int, str, datetime]] = {}
if (frame.has_field('posit... | 5,314,332 |
def resp_plot_remove(st, ipre_filt, pre_filt, iplot_response, water_level,
scale_factor, stations, outformat, ifverbose=False):
"""
Remove instrument response. Or plot (but not both)
TODO consider separating the remove and plot functions
"""
print("\nREMOVE INSTRUMENT RESPONSE\... | 5,314,333 |
def read(config_values):
"""Reads an ordered list of configuration values and deep merge the values in reverse order."""
if not config_values:
raise PolyaxonConfigurationError('Cannot read config_value: `{}`'.format(config_values))
config_values = to_list(config_values)
config = {}
for con... | 5,314,334 |
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 omitt... | 5,314,335 |
def makeit_ssa(exprs):
"""
Convert an iterable of Eqs into Static Single Assignment (SSA) form.
"""
# Identify recurring LHSs
seen = {}
for i, e in enumerate(exprs):
seen.setdefault(e.lhs, []).append(i)
# Optimization: don't waste time reconstructing stuff if already in SSA form
... | 5,314,336 |
def get_vocabulary(fobj, threshold):
"""Read text and return dictionary that encodes vocabulary
"""
p_dict = dict()
add_c = 0
for line in fobj:
phrase = line.strip('\r\n ').split(' ||| ')
src_list = phrase[0].split(' ')
trg_list = phrase[1].split(' ')
if len(src_list... | 5,314,337 |
def parse_ucsc_file_index(stream, base_url):
"""Turn a UCSC DCC files.txt index into a dictionary of name-value pairs
"""
file_index = {}
for line in stream:
filename, attribute_line = line.split('\t')
filename = base_url + filename
attributes = {}
for assignment in attr... | 5,314,338 |
def AUC_PR(true_vessel_img, pred_vessel_img, save_fname):
"""
Precision-recall curve
"""
precision, recall, _ = precision_recall_curve(true_vessel_img.flatten(), pred_vessel_img.flatten(), pos_label=1)
save_obj({"precision":precision, "recall":recall}, save_fname)
AUC_prec_rec = auc(recall, pre... | 5,314,339 |
def download_foot_bones():
"""Download foot bones dataset."""
return _download_and_read('fsu/footbones.ply') | 5,314,340 |
def _select_list_subset_schema():
""" schema for select_list_subset type """
return schemas.load(_SELECT_LIST_SUBSET_KEY) | 5,314,341 |
def natural_language_attributes(tagname, attrval_pairs):
"""Yields indices into attrval_pairs where the value is natural language.
For instance, if tagname is 'input' and attrval_pairs is
[('type', 'button'), ('value', 'foo')], then this will yield [1].
We yield the indices in reverse order, so we can ... | 5,314,342 |
def start():
"""
Turn on profiling.
"""
global _profile_start, _profile_setup, _call_stack, _inst_data
if _profile_start is not None:
print("profiling is already active.")
return
if not _profile_setup:
setup() # just do a default setup
_profile_start = etime()
... | 5,314,343 |
def test_delete_user_by_id():
"""Will delete the user with username wdijkerman.
:return: Should return: True
"""
syn = syncope.Syncope(syncope_url="http://192.168.1.145:9080", username="admin", password="password")
user_data = syn.get_user_by_name("wdijkerman")
user_id = int(user_data['id'])
... | 5,314,344 |
def inversion_tasks(gdirs, glen_a=None, fs=None):
"""Shortcut function: run all ice thickness inversion tasks.
Quite useful to deal with calving glaciers as well.
Parameters
----------
gdirs : list of :py:class:`oggm.GlacierDirectory` objects
the glacier directories to process
"""
... | 5,314,345 |
def update_internal_subnets(
self,
ipv4_list: list = [
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"169.254.0.0/16",
"224.0.0.0/4",
],
ipv6_list: list = [],
segment_ipv4_list: list = [],
non_default_routes: bool = False,
) -> bool:
"""Update the l... | 5,314,346 |
def prune_outside_window(boxlist, window, scope=None):
"""Prunes bounding boxes that fall outside a given window.
This function prunes bounding boxes that even partially fall outside the given
window. See also clip_to_window which only prunes bounding boxes that fall
completely outside the window, and clips an... | 5,314,347 |
def test_flowengine_pz_estimate():
"""Test that flow posteriors and flowEng posteriors are the same."""
data = get_galaxy_data().iloc[:10, :]
DS = RailStage.data_store
DS.clear()
handle = DS.add_data('data', data, TableHandle, path='dummy.pd')
bands = ['u','g','r','i','z','y']
rename_dict ... | 5,314,348 |
def main():
"""
Main function executed from console run.
"""
try:
c = cpuFreq()
except CPUFreqErrorInit as err:
print("{}".format(err))
exit()
args = argsparsevalidation(c.available_governors)
if args.info is True:
info(c)
elif args.reset is True... | 5,314,349 |
def cross_section(adjacency_matrices: npt.NDArray[np.int_],
rng: Optional[np.random.Generator] = None):
"""
Parameters
----------
adjacency_matrices :
rng :
Returns
-------
"""
if rng is None:
rng = np.random.default_rng()
masks = rng.choice([0, 1], s... | 5,314,350 |
def get_threshold_otsu(image: npt.ArrayLike, blur_sigma=5):
"""Perform Otsu's thresholding with Gaussian blur."""
skimage_gaussian = get_image_method(image, "skimage.filters.gaussian")
skimage_otsu = get_image_method(image, "skimage.filters.threshold_otsu")
image = skimage_gaussian(image, sigma=blur_sig... | 5,314,351 |
def create_security_group(group_name="mqlibtest"):
"""
Instances are pretty locked down by default. We can assign them to
security groups to give access rights. This group allows us to access
our instances over SSH
"""
ec2 = boto.ec2.connect_to_region(AWS_REGION)
for g in ec2.get_all_securit... | 5,314,352 |
def test_skyview_returns_the_content_sent():
"""Test that the SkyView class returns the received content."""
content = b"I'm a fake FITS file"
responses.add(responses.GET, SKYVIEW_URL, body=content)
dss = SkyView()
fits = dss.load_fits(
"2MASS-K", SkyCoord(ra=0 * u.deg, dec=0 * u.deg), 10 * ... | 5,314,353 |
def mask(batch_tokens, total_token_num, vocab_size, CLS=1, SEP=2, MASK=3):
"""
Add mask for batch_tokens, return out, mask_label, mask_pos;
Note: mask_pos responding the batch_tokens after padded;
"""
max_len = max([len(sent) for sent in batch_tokens])
mask_label = []
mask_pos = []
prob_... | 5,314,354 |
def get_lr_curves(
spark, features_df, cluster_ids, kernel_bandwidth, num_pdf_points, random_seed=None
):
""" Compute the likelihood ratio curves for clustered clients.
Work-flow followed in this function is as follows:
* Access the DataFrame including cluster numbers and features.
* Load same s... | 5,314,355 |
def evaluate(X, yt, cls):
"""Evaluated a classifier on the given labeled data using accuracy."""
from sklearn import metrics, preprocessing
if g.scaling:
X = preprocessing.scale(X, with_mean=False)
yp = cls.predict(X)
acc = metrics.accuracy_score(yt, yp)
print(" Accuracy", acc) | 5,314,356 |
def select(**boolean):
"""Query all the global tags for any tags specified by `boolean`. Yields each address found along with the matching tags as a dictionary.
If `And` contains an iterable then require the returned address contains them.
If `Or` contains an iterable then include any other tags that are s... | 5,314,357 |
def orred_filter_list(prefix, subfilters):
"""Produces Q-object for a list of dicts
Each dict's (key: value) pairs are ANDed together (rows must satisfy all k:v)
List items are ORred together (satisfying any one is enough)
"""
result = Q()
for filter in subfilters:
subresult = Q()
... | 5,314,358 |
def rotate_image(input_file, output_file, angle=90):
"""
:param input_file: str
Path to image to rotate
:param output_file: str
Path to output image
:param angle: float
Angle to rotate
:return: void
Rotates image and saves result
"""
#
cmd = "convert" + "... | 5,314,359 |
def get_unittests():
""" Return all of the unit tests """
directory_of_tests=get_testdirectory()
basic_suite = unittest.TestLoader().discover(directory_of_tests,pattern='basic_tests_*.py')
advanced_suite = unittest.TestLoader().discover(directory_of_tests, pattern='advanced_tests_*.py')
... | 5,314,360 |
def _exec_notebook_nix(path):
"""
Run the ipynb file of path
Raise exception if any error
"""
# http://nbconvert.readthedocs.io/en/latest/execute_api.html
# ijstokes et al, Command line execution of a jupyter notebook fails in default Anaconda 4.1, https://github.com/Anaconda-Platform/nb_conda_k... | 5,314,361 |
def become_mapper_(mapper_idx, map_fun, input_files, n_mappers, n_reducers,
map_begin, map_end, unit_fun, reduce_factory,
load_balancing_scheme, input_files_delimiter, record_terminator,
mapper_output_template, mapper_idx_template):
"""
become mapper
... | 5,314,362 |
def execute_action(arena: ActiveArena, unit: ActiveUnit, act: Dict) -> List[Dict]:
"""
Based on the type of `act`, executes the given action.
Returns a summary of the action's effects, conforming to the action_output_schema.
Mutates the given arena and/or unit and/or their respective derived objects, in... | 5,314,363 |
def has_mutation(gm, example_inputs):
"""Check if the graph module has any form of mutation"""
# TODO - moco gives bad accuracy with Aliasing. gm is getting mutated in a bad way.
new_gm = copy.deepcopy(gm)
ShapeAliasingAndMutationProp(new_gm).run(*example_inputs)
for node in new_gm.graph.nodes:
... | 5,314,364 |
def comment_remove(obj_id, analyst, date):
"""
Remove an existing comment.
:param obj_id: The top-level ObjectId to find the comment to remove.
:type obj_id: str
:param analyst: The user removing the comment.
:type analyst: str
:param date: The date of the comment to remove.
:type date:... | 5,314,365 |
def fibonacci(a=0, b=1):
"""
This function uses a generator to get values of the Fibonacci sequence.
f_{n+2} = f_{n+1} + f_n
General seed (0,1) given as named parameter for the function.
"""
while True:
yield a
a, b = b, a+b | 5,314,366 |
def eul2m_vector(in11, in12, in13, k1, k2, k3):
"""eul2m_vector(ConstSpiceDouble * in11, ConstSpiceDouble * in12, ConstSpiceDouble * in13, SpiceInt k1, SpiceInt k2, SpiceInt k3)"""
return _cspyce0.eul2m_vector(in11, in12, in13, k1, k2, k3) | 5,314,367 |
def clean_board(board: Board, players: list, deck: Deck):
""" Clean the board after every turn.
So, remove used cards from both players hand and board.
All players draw a card.
Args:
board (Board): board game
players (list): players list
"""
# remove cards from hands
for player in players:
player.rem... | 5,314,368 |
def helicsCreateMessageFederateFromConfig(config_file: str) -> HelicsMessageFederate:
"""
Create `helics.HelicsMessageFederate` from a JSON file or JSON string or TOML file.
`helics.HelicsMessageFederate` objects can be used in all functions that take a `helics.HelicsFederate` object as an argument.
**... | 5,314,369 |
def chain_template_as_nx_graph(chain: ChainTemplate):
""" Convert FEDOT chain template into networkx graph object """
graph = nx.DiGraph()
node_labels = {}
for operation in chain.operation_templates:
unique_id, label = operation.operation_id, operation.operation_type
node_labels[unique_i... | 5,314,370 |
def AbsoluteCanonicalPath(*path):
"""Return the most canonical path Python can provide."""
file_path = os.path.join(*path)
return os.path.realpath(os.path.abspath(os.path.expanduser(file_path))) | 5,314,371 |
def skip_if(expr, msg=""):
"""Skip the current substep and set _output to empty. Output
will be removed if already generated."""
if expr:
raise StopInputGroup(msg=msg, keep_output=False)
return 0 | 5,314,372 |
def mergeGuideInfo(seq, startDict, pamPat, otMatches, inputPos, effScores, sortBy=None, org=None):
"""
merges guide information from the sequence, the efficiency scores and the off-targets.
creates rows with too many fields. Probably needs refactoring.
for each pam in startDict, retrieve the guide sequ... | 5,314,373 |
def get_distribution_centers_shipments(dc_id):
"""
Retrieve all shipments originating from the specified distribution center.
:param dc_id: The distribution center's id
:return: [{
"id": "123",
"status": "SHIPPED",
"createdAt": "2015-11-05T22:00:51.692765",
"updatedAt... | 5,314,374 |
def historical_summary(date: Union[None, str, datetime] = None, filter: str = ''):
"""
https://iextrading.com/developer/docs/#historical-summary
Args:
date: fixme
filter: https://iextrading.com/developer/docs/#filter-results
Returns:
dict: result
"""
if date:
if... | 5,314,375 |
def test_session_hostname(mocker):
"""Create a basic IPv4 Session process from hostname"""
mocker.patch('aiobfd.session.log')
mocker.patch.object(aiobfd.session.Session, 'async_tx_packets',
new_callable=AsyncMock)
session = aiobfd.session.Session('localhost', 'localhost')
aio... | 5,314,376 |
def create_latex_file(der, graph_names="", user_input=""):
"""
This function creates a formatted LaTeX document.
INPUTS:
======
der: list of derivatives
grap_names: list of graph_names
user_input: optional user input - string
"""
startJac = r"$J_{ij} = \frac{\partial f_i}{\partial ... | 5,314,377 |
def runIW(before, after, aoi, scl, tScl, ag):
"""
Run the complete iteratively weighted change analysis
Parameters:
before (ee.ImageCollection): images representing the reference landscape
after (ee.ImageCollection): images representing the after condition
aoi: (ee.Geometry): ar... | 5,314,378 |
def normalize_text(text, norm_type="stemming", pos=False, pipeline=None):
"""
Preprocess text data
:param str text:
:param str norm_type: "stemming" or "lemmatization" of None
:param bool pos: Only for lemmatization. If True add tags to tokens like "_NOUN"
:param Pipeline pipeline: for lemm... | 5,314,379 |
def make_field(
name: str,
dimensions: FieldDimensions,
is_temporary: bool = False
) -> Field:
""" Create a Field
:param name: Name of the field
:param dimensions: dimensions of the field (use make_field_dimensions_*)
:param is_temporary: Is it a temporary field?
"""
fie... | 5,314,380 |
def expand_to_point(b1, p1):
"""
Expand bbox b1 to contain p1: [(x,y),(x,y)]
"""
for p in p1:
b1 = add(b1, (p[0], p[1], p[0], p[1]))
return b1 | 5,314,381 |
def get_closing_bracket(string, indice_inicio):
"""Retorna o indice da '}' correspondente a '{' no indice recebido."""
if string[indice_inicio] != '{':
raise ValueError("String invalida")
deque = collections.deque()
for atual in range(indice_inicio, len(string)):
if string[atual] == '}' ... | 5,314,382 |
def read_matrix():
"""Returns a matrix from the input integers, spit by ', '"""
n = int(input())
matrix = []
for _ in range(n):
row = []
for x in input().split(', '):
row.append(int(x))
matrix.append(row)
return matrix | 5,314,383 |
def format_time_trigger_string(timer_instance):
"""
:param timer_instance: either instance of RepeatTimer or EventClock
:return: human-readable and editable string in one of two formats:
- 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM'
- 'every NNN'
"""
if isinstance(timer_instance, Repeat... | 5,314,384 |
def get_class_from_string(class_string: str):
"""Get class or function instance from a string, interpreted as Python module.
:param class_string:
:return:
"""
class_name = class_string.split(".")[-1]
module = class_string.replace(f".{class_name}", "")
lib = importlib.import_module(module)
... | 5,314,385 |
def safe_power(a, b): # pylint: disable=invalid-name
"""a limited exponent/to-the-power-of function, for safety reasons"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise NumberTooHigh("Sorry! I don't want to evaluate {0} ** {1}".format(a, b))
return a**b | 5,314,386 |
def ConcateMatching(vec1, vec2):
"""
ConcateMatching
"""
#TODO: assert shape
return fluid.layers.concat(input=[vec1, vec2], axis=1) | 5,314,387 |
def defaults( d= cli(
cohen = .3
,data = "data/weather.csv"
,far = .9
,k = 1
,m = 2
,mostrest = 3
,p = 2
,seed = 1
,train = .66
,tiny = .6
)):
"""Calling `default` will return a fresh copy of the defaults
(optionally ... | 5,314,388 |
def export_notebooks(app, document, docname):
""""Export the recently resolved document to a Jupyter notebook"""
if not hasattr(app.env, "nbfiles"):
return
if docname not in app.env.nbfiles:
return
docpath = os.path.dirname(docname)
ipynb_path = app.env.nbfiles[docname]
with ope... | 5,314,389 |
def _racemization(compound, max_centers=3, carbon_only=True):
"""Enumerates all possible stereoisomers for unassigned chiral centers.
:param compound: A compound
:type compound: rdMol object
:param max_centers: The maximum number of unspecified stereocenters to
enumerate. Sterioisomers grow... | 5,314,390 |
def stop_gradient(variables):
"""Returns `variables` but with zero gradient with respect to every other
variables.
"""
return KerasSymbol(mx.sym.BlockGrad(variables.symbol)) | 5,314,391 |
def get_repartition_emission_pies(data):
"""
This function will create a figure with 3 pies describing the repartition per building of the emission for electricity / gas / total
"""
fig = make_subplots(
rows=1,
cols=3,
specs=[[{"type": "domain"}, {"type": "domain"}, {"type": "do... | 5,314,392 |
def get_next_video_id(database_session: Session):
"""Returns what the next vid id will be"""
return database_session.query(func.max(models.Video.id)).scalar() + 1 | 5,314,393 |
def system_supports_plotting():
"""
Check if x server is running
Returns
-------
system_supports_plotting : bool
True when on Linux and running an xserver. Returns None when
on a non-linux platform.
"""
try:
if os.environ['ALLOW_PLOTTING'].lower() == 'true':
... | 5,314,394 |
def parse_args():
"""Command-line argument parser for testing."""
# New parser
parser = ArgumentParser(description='Noise2Noise adapted to X-ray microtomography')
# Parameters
parser.add_argument('-d', '--data', help='dataset root path', default='../data')
parser.add_argument('--load-ckpt', he... | 5,314,395 |
def sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value=0):
"""Converts a sparse representation into a dense tensor.
Example::
- sparse_to_dense([[0, 0], [1, 1]], [2, 2], [3, 3], 0) = [[3, 0], [0, 3]]
Parameters
----------
sparse_indices : tvm.te.Tensor
A 0-D, ... | 5,314,396 |
def os_supported():
"""Check if current OS is supported
Returns:
bool
"""
return is_os('Windows') | 5,314,397 |
def put_path_to_db(req_path: ReqPathPutTransact):
"""Put learning path to DynamoDB"""
try:
transact_items = path_input.transact_update_path(path=req_path)
# return transact_items
res = db.client.transact_write_items(
ReturnConsumedCapacity="INDEXES", TransactItems=transact_i... | 5,314,398 |
def get_hash(value, max_hash):
"""Calculate split hash factor"""
return zlib.adler32(str(value).encode()) % max_hash + 1 | 5,314,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.