content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def rgetattr(obj, attr):
"""
Get named attribute from an object, i.e. getattr(obj, 'a.a') is
equivalent to ``obj.a.a''.
- obj: object
- attr: attribute name(s)
>>> class A: pass
>>> a = A()
>>> a.a = A()
>>> a.a.a = 1
>>> rgetattr(a, 'a.a')
1
>>> rgetattr(a, 'a.c')
... | 5,343,500 |
def lambda1_plus_lambda2(lambda1, lambda2):
"""Return the sum of the primary objects tidal deformability and the
secondary objects tidal deformability
"""
return lambda1 + lambda2 | 5,343,501 |
def __create_resource_management_client():
"""
Create a ResourceManagementClient object using the subscription ID from environment variables
"""
subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", None)
if subscription_id is None:
return None
return ResourceManagementClient(
... | 5,343,502 |
def create_cut_sht(stockOutline,array,features,partSpacing,margin):
""" """
numParts = len(array)
basePlanes = generate_base_planes_from_array(array)
targetPlanes = create_cut_sht_targets(stockOutline,array,margin,partSpacing)
if targetPlanes == None:
return None
else:
# converts... | 5,343,503 |
def unicode_is_ascii(u_string):
"""Determine if unicode string only contains ASCII characters.
:param str u_string: unicode string to check. Must be unicode
and not Python 2 `str`.
:rtype: bool
"""
assert isinstance(u_string, str)
try:
u_string.encode('ascii')
return Tru... | 5,343,504 |
def duplicate_item(api_key: str, board_id: str, item_id: str, *args, **kwargs):
"""Duplicate an item.
Parameters
api_key : `str`
The monday.com v2 API user key.
board_id : `str`
The board's unique identifier.
item_id : `str`
... | 5,343,505 |
def hdparm_secure_erase(disk_name, se_option):
"""
Secure erase using hdparm tool
:param disk_name: disk to be erased
:param se_option: secure erase option
:return: a dict includes SE command exitcode and SE message
"""
# enhance_se = ARG_LIST.e
log_file = disk_name.split("/")[-1] + ".lo... | 5,343,506 |
def compute_loss(retriever_logits, retriever_correct, reader_logits,
reader_correct):
"""Compute loss."""
# []
retriever_loss = marginal_log_loss(retriever_logits, retriever_correct)
# []
reader_loss = marginal_log_loss(
tf.reshape(reader_logits, [-1]), tf.reshape(reader_correct, [-1])... | 5,343,507 |
def qa_curveofgrowth(ellipsefit, pipeline_ellipsefit=None, png=None,
plot_sbradii=False, cosmo=None, verbose=True):
"""Plot up the curve of growth versus semi-major axis.
"""
from legacyhalos.ellipse import CogModel
if ellipsefit['success'] is False or np.atleast_1d(ellipsefit['r_... | 5,343,508 |
def is_using_git():
"""True if git checkout is used."""
return os.path.exists(os.path.join(REPO_ROOT, '.git', 'objects')) | 5,343,509 |
def index() -> render_template:
"""
The main part of the code that is ran when the user visits the address.
Parameters:
covid_data: This is a dictionary of the data returned from the API request.
local_last7days_cases: The number of local cases in the last 7 days.
national_last7days_case... | 5,343,510 |
def r(x):
"""
Cartesian radius of a point 'x' in 3D space
Parameters
----------
x : (3,) array_like
1D vector containing the (x, y, z) coordinates of a point.
Returns
-------
r : float
Radius of point 'x' relative to origin of coordinate system
"""
return np.sqr... | 5,343,511 |
def solve(*args):
"""
Crunch the numbers; solve the problem.
solve(IM A, IM b) -> IM
solve(DM A, DM b) -> DM
solve(SX A, SX b) -> SX
solve(MX A, MX b) -> MX
solve(IM A, IM b, str lsolver, dict opts) -> IM
solve(DM A, DM b, str lsolver, dict opts) -> DM
solve(SX A, SX b, str lsolver,... | 5,343,512 |
def NonNegativeInteger(num):
"""
Ensures that the number is non negative
"""
if num < 0:
raise SmiNetValidationError("A non-negative integer is required")
return num | 5,343,513 |
def to_cartesian(r, ang):
"""Returns the cartesian coordinates of a polar point."""
x = r * np.cos(ang)
y = r * np.sin(ang)
return x, y | 5,343,514 |
def plot_seqlogo(ax, seq_1hot, sat_score_ti, pseudo_pct=0.05):
""" Plot a sequence logo for the loss/gain scores.
Args:
ax (Axis): matplotlib axis to plot to.
seq_1hot (Lx4 array): One-hot coding of a sequence.
sat_score_ti (L_sm array): Minimum mutation delta across satmut length.
... | 5,343,515 |
def _get_filtered_partially_learnt_topic_summaries(
topic_summaries, topic_ids):
"""Returns a list of summaries of the partially learnt topic ids and the ids
of topics that are no longer present.
Args:
topic_summaries: list(TopicSummary). The list of topic
summary domain objects... | 5,343,516 |
def build_bar_chart_with_two_bars_per_label(series1, series2, series1_label, series2_label, series1_labels,
series2_labels,
title, x_axis_label, y_axis_label, output_file_name):
"""
This function builds a bar chart that has ... | 5,343,517 |
def calculateDescent():
"""
Calculate descent timestep
"""
global descentTime
global tod
descentTime = myEndTime
line = len(originalTrajectory)
for segment in reversed(originalTrajectory):
flInit = int(segment[SEGMENT_LEVEL_INIT])
flEnd = int(segment[SEGMENT_LEVEL_END])
status = segment[STATUS]
if flIn... | 5,343,518 |
def update_tutorial(request,pk):
"""View function for updating tutorial """
tutorial = get_object_or_404(Tutorial, pk=pk)
form = TutorialForm(request.POST or None, request.FILES or None, instance=tutorial)
if form.is_valid():
form.save()
messages.success(request=request, message="Congra... | 5,343,519 |
def run(_):
"""Run the command. """
source_promusrc()
promusrc() | 5,343,520 |
def download_with_options():
"""
Test if the script is able to download images
with specified characteristics
"""
print('Instantiating crawler')
searcher = crawler()
try:
print('Searching')
for key in options:
for option in options[key]:
pr... | 5,343,521 |
def get_transform_dest_array(output_size):
"""
Returns a destination array of the desired size. This is also used to define the
order of points necessary for cv2.getPerspectiveTransform: the order can change, but
it must remain consistent between these two arrays.
:param output_size: The size to mak... | 5,343,522 |
def fetch(url):
"""
引数urlで与えられたURLのWebページを取得する。
WebページのエンコーディングはContent-Typeヘッダーから取得する。
戻り値:str型のHTML
"""
f = urlopen(url)
# HTTPヘッダーからエンコーディングを取得する(明示されていない場合はutf-8とする)。
encoding = f.info().get_content_charset(failobj="utf-8")
html = f.read().decode(encoding) # 得られたエンコーディングを指定して文字... | 5,343,523 |
def _is_industrial_user():
"""Checking if industrial user is trying to use relion_it.."""
if not grp:
# We're not on a linux/unix system, therefore not at Diamond
return False
not_allowed = ["m10_valid_users", "m10_staff", "m08_valid_users", "m08_staff"]
uid = os.getegid()
fedid = g... | 5,343,524 |
def get_rounded_coordinates(point):
"""Helper to round coordinates for use in permalinks"""
return str(round(point.x, COORDINATE_ROUND)) + '%2C' + str(round(point.y, COORDINATE_ROUND)) | 5,343,525 |
def rgb_to_hls(image: np.ndarray, eps: float = 1e-8) -> np.ndarray:
"""Convert a RGB image to HLS. Image data is assumed to be in the range
of [0.0, 1.0].
Args:
image (np.ndarray[B, 3, H, W]):
RGB image to be converted to HLS.
eps (float):
Epsilon value to avoid div ... | 5,343,526 |
def array_max_dynamic_range(arr):
"""
Returns an array scaled to a minimum value of 0 and a maximum value of 1.
"""
finite_arr = arr[np.isfinite(arr)]
low = np.nanmin(finite_arr)
high = np.nanmax(finite_arr)
return (arr - low)/(high - low) | 5,343,527 |
def production(*args):
"""Creates a production rule or list of rules from the input.
Supports two kinds of input:
A parsed string of form "S->ABC" where S is a single character, and
ABC is a string of characters. S is the input symbol, ABC is the output
symbols.
Neither... | 5,343,528 |
def _unpack_compute(input_place, num, axis):
"""Unpack a tensor into `num` tensors along axis dimension."""
input_shape = get_shape(input_place)
for index, _ in enumerate(input_shape):
input_shape[index] = input_shape[index] if index != axis else 1
output_shape_list = [input_shape for i in ran... | 5,343,529 |
def flatten(items):
"""Convert a sequence of sequences to a single flat sequence.
Works on dictionaries, tuples, lists.
"""
result = []
for item in items:
if isinstance(item, list):
result += flatten(item)
else:
result.append(item)
return result | 5,343,530 |
def _datum_to_cap(datum: Dict) -> float:
"""Cap value of a datum."""
return _cap_str_to_mln_float(datum["cap"]) | 5,343,531 |
def add_eval_to_game(game: chess.pgn.Game, engine: chess.engine.SimpleEngine, analysis_time: float,
should_re_add_analysis: bool = False) -> chess.pgn.Game:
"""
MODIFIES "game" IN PLACE
"""
current_move = game
while len(current_move.variations):
if "eval" in current_move... | 5,343,532 |
def MC_no(a,b,N,pi,mp):
""" Monte Carlo simulation drawn from beta distribution for the uninsured agents
Args:
N (integer): number of draws
a (integer): parameter
b (integer): parameter
Returns:
(numpy float): Monte Carlo integration that computes expe... | 5,343,533 |
def gen_even_tree(fanout):
"""This generalization hierarchy is defined according to even fan-out
(average distribution).For large dataset fanout = 5, for small dataset fanout = 4
"""
treeseed = open('data/treeseed_BMS.txt', 'rU')
treefile = open('data/treefile_BMS.txt', 'w')
for line in ... | 5,343,534 |
def get_conflicting_types(type, tyepdef_dict):
"""Finds typedefs defined in the same class that conflict. General algo
is: Find a type definition that is identical to type but for a
different key. If the type definitions is coming from a different
class, neglect it. This is a pretty slow function for... | 5,343,535 |
def extract_entity_type_and_name_from_uri(uri: str) -> Tuple[str, str]:
"""
从entity uri中提取出其type和name
:param uri: 如 http://www.kg.com/kg/ontoligies/ifa#Firm/百度
:return: ('Firm', '百度')
"""
name_separator = uri.rfind('/')
type_separator = uri.rfind('#')
return uri[type_separator + 1: name_... | 5,343,536 |
def resolve_raw_resource_description(
raw_rd: GenericRawRD, root_path: os.PathLike, nodes_module: typing.Any
) -> GenericResolvedNode:
"""resolve all uris and sources"""
rd = UriNodeTransformer(root_path=root_path).transform(raw_rd)
rd = SourceNodeTransformer().transform(rd)
rd = RawNodeTypeTransfor... | 5,343,537 |
def ret_dict() -> dict:
"""
Returns
-------
"""
# blahs
return {} | 5,343,538 |
def load_rokdoc_well_markers(infile):
"""
Function to load well markers exported from RokDoc in ASCII format.
"""
with open(infile, 'r') as fd:
buf = fd.readlines()
marker = []
well = []
md = []
tvdkb = []
twt = []
tvdss = []
x = []
... | 5,343,539 |
def get_fees():
"""
Returns all information related to fees configured for the institution.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getFees') | 5,343,540 |
async def create_db_pool():
"""Connects to the local PostgreSQL server."""
client.pg_con = await asyncpg.create_pool(database='postgres', user='postgres', password='Mehul09!') | 5,343,541 |
def resample_uv_to_bbox(
predictor_output: DensePoseChartPredictorOutput,
labels: torch.Tensor,
box_xywh_abs: Tuple[int, int, int, int],
) -> torch.Tensor:
"""
Resamples U and V coordinate estimates for the given bounding box
Args:
predictor_output (DensePoseChartPredictorOutput): Dense... | 5,343,542 |
def run(cmd, capture_output=True):
"""
Run command locally with current user privileges
:returns: command output on success
:raises: LocalExecutionFailed if command failed"""
try:
LOG.debug("Running '%s' locally", cmd)
return api.local(cmd, capture=capture_output)
except (SystemE... | 5,343,543 |
def rectangle(ctx, width, height, angle=0):
"""Draws a rectangle at a specified angle.
Parameters
----------
ctx : cairo.Context
Context.
width : float
Width of the rectangle.
height : float
Height of the rectangle.
angle : float, optional
Angle in radians of... | 5,343,544 |
def test_proj2geo():
""" Test Map.proj2geo method """
m = pmk.Map()
m.set_geographic_crs('EPSG:4267') ## NAD84
m.set_projection("EPSG:32023") ## Ohio South FT
## Test singlet integer input
test_coord = (1859916, 728826)
expected = (-83, 40)
actual = m.proj2geo(*test_coord)
assert ex... | 5,343,545 |
def get_error_code(output: int,
program: List[int]
) -> int:
"""
Determine what pair of inputs, "noun" and "verb", produces the output.
The inputs should be provided to the program by replacing the values
at addresses 1 and 2. The value placed in address 1 is calle... | 5,343,546 |
def page(page_id):
"""Gets one page from the database."""
page = Page.objects.get(id=page_id)
return render_template('page.html', page=page) | 5,343,547 |
def compute_Csigma_from_alphaandC(TT,minT,alphaT,CT,ibrav=4):
"""
This function calculate the difference between the constant stress heat capacity
:math:`C_{\sigma}` and the constant strain heat capacity :math:`C_{\epsilon}`
from the *V* (obtained from the input lattice parameters *minT*, the thermal
... | 5,343,548 |
def services(request):
"""
"""
context = {}
services = Service.objects.filter(active=True, hidden=False)
context["services"] = services
context["services_nav"] = True
return render(request, "services.html", context) | 5,343,549 |
def _create_presigned_url(method, object_name, duration_in_seconds=600):
"""
Create presigned S3 URL
"""
s3_client = boto3.client('s3',
endpoint_url=CONFIG.get('s3', 'url'),
aws_access_key_id=CONFIG.get('s3', 'access_key_id'),
... | 5,343,550 |
def read_data(model_parameters, ARGS):
"""Read the data from provided paths and assign it into lists"""
data = pd.read_pickle(ARGS.path_data)
y = pd.read_pickle(ARGS.path_target)['target'].values
data_output = [data['codes'].values]
if model_parameters.numeric_size:
data_output.append(data[... | 5,343,551 |
def _is_src(file):
""" Returns true if the file is a source file
Bazel allows for headers in the srcs attributes, we need to filter them out.
Args:
file (File): The file to check.
"""
if file.extension in ["c", "cc", "cpp", "cxx", "C", "c++", "C++"] and \
file.is_source:
return ... | 5,343,552 |
def constructResponseObject(responsePassed):
"""
constructs an Error response object, even if the
"""
if (not (responsePassed is None)):
temp_resp = Response()
temp_resp.status_code = responsePassed.status_code or 404
if((temp_resp.status_code >= 200) and (temp_resp.status_code ... | 5,343,553 |
async def callback_query_handler(bot: BotAPI, update: Update):
"""Test inline keyboard with callback query and answer_callback_query."""
if update.message is not None and update.message.text is not None:
await bot.send_message(
update.message.chat.id,
'A reply!',
repl... | 5,343,554 |
def calculate_signal_strength(rssi):
# type: (int) -> int
"""Calculate the signal strength of access point."""
signal_strength = 0
if rssi >= -50:
signal_strength = 100
else:
signal_strength = 2 * (rssi + 100)
return signal_strength | 5,343,555 |
async def verify_email(token: str, auth: AuthJWT = Depends()):
"""Verify the user's email with the supplied token"""
# Manually assign the token value
auth._token = token # pylint: disable=protected-access
user = await User.by_email(auth.get_jwt_subject())
if user.email_confirmed_at is not None:
... | 5,343,556 |
def step_select_from_table(context):
"""
Send select from table.
"""
context.cli.sendline('select * from a;') | 5,343,557 |
def main():
""" main body """
# constants
n = 200
# r axis
r_axis = np.linspace(0, 2, n)
# x axis
x_fix = np.array([])
# simulate for different r
for enum in enumerate(r_axis):
# x_fix[200 * enum[0]: 200 * (enum[0] + 1)] = stable_point(enum[1])
x_fix = np.hstack((x_... | 5,343,558 |
def viz_predictions(
input_: np.ndarray,
output: np.ndarray,
target: np.ndarray,
centerlines: np.ndarray,
city_names: np.ndarray,
idx=None,
show: bool = True,
) -> None:
"""Visualize predicted trjectories.
Args:
input_ (numpy array): Input Traject... | 5,343,559 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up a National Weather Service entry."""
hass_data = hass.data.setdefault(DOMAIN, {})
station = entry.data[CONF_STATION]
radar = Nexrad(station)
radar_update = Debouncer(
hass, _LOGGER, cooldown=60, immediate=True,... | 5,343,560 |
def lookAtThisMethod(
first_parameter,
second_paramter=None,
third_parameter=32,
fourth_parameter="a short string as default argument",
**kwargs
):
"""The point of this is see how it reformats parameters
It might be fun to see what goes on
Here I guess it should respect this spacing, since we are in... | 5,343,561 |
def data_incremental_benchmark(
benchmark_instance: GenericCLScenario,
experience_size: int,
shuffle: bool = False,
drop_last: bool = False,
split_streams: Sequence[str] = ("train",),
custom_split_strategy: Callable[
[ClassificationExperience], Sequence[AvalancheDataset]
] = None,
... | 5,343,562 |
def generate_doc_from_endpoints(
routes: typing.List[tornado.web.URLSpec],
*,
api_base_url,
description,
api_version,
title,
contact,
schemes,
security_definitions,
security
):
"""Generate doc based on routes"""
from tornado_swagger.model import export_swagger_models # p... | 5,343,563 |
def _filter_builds(build: Build) -> bool:
"""
Determine if build should be filtered.
:param build: Build to check.
:return: True if build should not be filtered.
"""
if build.display_name.startswith("!"):
return True
return False | 5,343,564 |
def test_compute_free_energy(seq, actions, expected):
"""Tests private method _compute_free_energy()"""
env = Lattice2DEnv(seq)
for action in actions:
env.step(action)
result = env._compute_free_energy(env.state)
assert expected == result | 5,343,565 |
def load_transformers(model_name, skip_model=False):
"""Loads transformers config, tokenizer, and model."""
config = AutoConfig.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(
model_name,
add_prefix_space=True,
additional_special_tokens=('[T]', '[P]'),
)
... | 5,343,566 |
def build_test_data(data):
"""
Generates various features needed to predict
the class of the news.
Input: DataFrame
Returns Array of generated features.
"""
data = process(data)
generators = [
CountFeatureGenerator,
TfidfFeatureGenerator,
... | 5,343,567 |
def set_password_for_sub_account(account_id, password):
"""
Create a message to set the password for a given sub-account.
:param account_id: Integer representing the ID of the account
:param password: String representing the password for the sub-account
:return: Message (dict)
"""
data = san... | 5,343,568 |
def post(req, api):
"""
Append a story to our rpg
Input:
content: string
Output:
string
"""
api.debug(req.body['content'])
return 'Success' | 5,343,569 |
def generate_batch(n, batch_size):
""" Generates a set of batch indices
Args:
n: total number of samples in set
batch_size: size of batch
Returns:
batch_index: a list of length batch_size containing randomly sampled indices
"""
batch_index = a.sample(range... | 5,343,570 |
def assert_(
val: bool,
msg: Tuple[scipy.integrate.tests.test_integrate.CoupledDecay, Literal["bdf"]],
):
"""
usage.scipy: 3
"""
... | 5,343,571 |
def train_model_from_args(args: argparse.Namespace):
"""
Just converts from an `argparse.Namespace` object to string paths.
"""
train_model_from_file(
parameter_filename=args.param_path,
serialization_dir=args.serialization_dir,
overrides=args.overrides,
file_friendly_log... | 5,343,572 |
def solve(si, y, infile):
"""Conducts the solution step, based on the dopri5 integrator in scipy
:param si: the simulation info object
:type si: SimInfo
:param y: the solution vector
:type y: np.ndarray
:param infile: the imported infile module
:type infile: imported module
"""
n = ... | 5,343,573 |
def update_logo(img):
""""this function update the warrior logo"""
try:
with open(img, "rb") as image_file:
encoded_img = base64.b64encode(image_file.read())
img_path = os.path.join(
BASE_DIR, "wui/core/static/core/images/logo.png")
fh = open(img_path, "wb")
... | 5,343,574 |
def test_annotated_field_also_used_in_filter():
"""
Test that when a field also used in filter needs to get annotated, it really annotates only the field.
See issue https://github.com/preply/graphene-federation/issues/50
"""
@key("id")
class B(ObjectType):
id = ID()
@extend("id")
... | 5,343,575 |
def writeOutput(info,prettyPrint=False):
""" Simple method used to print or dump to a file the output, probably will be included inside of class """
if JSON_OUTPUT:
if prettyPrint:
json_dump = json.dumps(info, indent=4, sort_keys=True)
else:
json_dump = json.dumps(info)
... | 5,343,576 |
def test_disable():
"""
Test to disable state run
"""
mock = MagicMock(return_value=["C", "D"])
with patch.dict(state.__salt__, {"grains.get": mock}):
mock = MagicMock(return_value=[])
with patch.dict(state.__salt__, {"grains.setval": mock}):
mock = MagicMock(return_value... | 5,343,577 |
def extend_track(
tator_api: tator.openapi.tator_openapi.api.tator_api.TatorApi,
media_id: int,
state_id: int,
start_localization_id: int,
direction: str,
work_folder: str,
max_coast_frames: int=0,
max_extend_frames: int=None) -> None:
""" Extends the ... | 5,343,578 |
def base(request, format=None):
"""Informational version endpoint."""
message = f"Welcome to {VERSION} of the Cannlytics API. Available endpoints:\n\n"
for endpoint in ENDPOINTS:
message += f"{endpoint}\n"
return Response({ "message": message}, content_type="application/json") | 5,343,579 |
def push(ctx, apikey, url, skill_name):
"""
(topic branch) Reassemble a skill and deploy it as a sandbox
Deploys the files in <project_folder>/waw/<skill_name> as a WA skill named
"<gitbranch>__<skill_name>
"""
Sandbox(apikey, url, skill_name).push() | 5,343,580 |
def discover(discover_system: bool = True) -> Discovery:
"""
Discover Reliably capabilities from this extension.
"""
logger.info("Discovering capabilities from chaostoolkit-reliably")
discovery = initialize_discovery_result(
"chaostoolkit-reliably", __version__, "reliably"
)
discove... | 5,343,581 |
def test_interval_in_seconds() -> None:
"""Tests the interval_in_seconds function"""
interval = interval_in_seconds("13:00")
assert isinstance(interval, int) | 5,343,582 |
def global_search_f(event):
"""
Do global search.
To restore the original appearance of the window, type help.
The per-commander @int fts_max_hits setting controls the maximum hits returned.
"""
c = event['c']
if hasattr(g.app,'_global_search'):
g.app._global_search.fts_max_hits = c... | 5,343,583 |
def frequent_word(message: str) -> str:
"""get frequent word."""
from collections import Counter
words = Counter(message.split())
result = max(words, key=words.get)
print(result)
return result | 5,343,584 |
def test_column_regex_multiindex():
"""Text that column regex works on multi-index column."""
column_schema = Column(
Int,
Check(lambda s: s >= 0),
name=("foo_*", "baz_*"),
regex=True,
)
dataframe_schema = DataFrameSchema(
{
("foo_*", "baz_*"): Column(... | 5,343,585 |
def parse_bjobs_nodes(output):
"""Parse and return the bjobs command run with
options to obtain node list, i.e. with `-w`.
This function parses and returns the nodes of
a job in a list with the duplicates removed.
:param output: output of the `bjobs -w` command
:type output: str
:return: c... | 5,343,586 |
def find_nearest_array(array, array_comparison, tol = 1e-4):
"""
Find nearest array
@ In, array, array-like, the array to compare from
@ In, array_comparison, array-like, the array to compare to
@ In, tol, float, the tolerance
"""
array_comparison = np.asarray(array_comparison)
indeces = np.zero... | 5,343,587 |
def create_bar_filled_line_fusion_chart(fname, frame_data, chart_dir=''):
"""Create the bar filled line fusion chart from window data"""
path_to_image = os.path.join(chart_dir, ChartType.BAR_FLINE_FUSION.value, "%s.png" % fname)
if not os.path.exists(path_to_image):
fig_obj, ax_fline_obj = plt.subpl... | 5,343,588 |
def test_notebooks(nb):
""" Test that notebooks run fine """
if re.match('.*nbconvert.*', nb) is not None:
# nbconvert leaves files like nbconvert.ipynb
# we don't want to run on those
return
# Here I'm trying to determine if the converted nb exists
# if it does not I'll try to ... | 5,343,589 |
def create_block_statistics_on_addition(
block_hash: str,
block_hash_parent: str,
chain_name: str,
deploy_cost_total: int,
deploy_count: int,
deploy_gas_price_avg: int,
era_id: int,
height: int,
is_switch_block: bool,
network: str,
size_bytes: str,
state_root_hash: str,
... | 5,343,590 |
def get_arg():
"""解析参数"""
parser = argparse.ArgumentParser(prog='prcdns', description='google dns proxy.')
parser.add_argument('--debug', help='debug model,default NO', default=False)
parser.add_argument('-l', '--listen', help='listening IP,default 0.0.0.0', default='0.0.0.0')
parser.add_argument('-... | 5,343,591 |
def test___get_flux__f() -> None:
"""
Test for `hsr4hci.photometry._get_flux__f`.
"""
# Case 1
x, y = np.meshgrid(np.arange(33), np.arange(33))
gaussian = models.Gaussian2D(
x_mean=17, x_stddev=1, y_mean=17, y_stddev=1, amplitude=1
)
position, flux = _get_flux__f(
frame=... | 5,343,592 |
def text(title='Text Request', label='', parent=None, **kwargs):
"""
Quick and easy access for getting text input. You do not have to have a
QApplication instance, as this will look for one.
:return: str, or None
"""
# -- Ensure we have a QApplication instance
q_app = qApp()
# -- Get t... | 5,343,593 |
def get_key_score(chroma_vector, keys, key_index):
"""Returns the score of an approximated key, given the index of the key weights to try out"""
chroma_vector = np.rot90(chroma_vector,3)
chroma_vector = chroma_vector[0,:]
key_vector = keys[key_index,:]
score = np.dot(key_vector,chroma_vector)
return score | 5,343,594 |
def as_moderator(mocker):
"""Enforces that the requesting users is treated as a moderator"""
mock_api = mocker.patch("open_discussions.middleware.channel_api.Api").return_value
mock_api.is_moderator.return_value = True | 5,343,595 |
def app():
"""Create the test application."""
return flask_app | 5,343,596 |
def coord_for(n, a=0, b=1):
"""Function that takes 3 parameters or arguments, listed above, and returns a list of the interval division coordinates."""
a=float(a)
b=float(b)
coords = []
inc = (b-a)/ n
for x in range(n+1):
coords.append(a+inc*x)
return coords | 5,343,597 |
def find_indeces_vector(transect_lons, transect_lats, model_lons, model_lats,
tols={
'NEMO': {'tol_lon': 0.104, 'tol_lat': 0.0388},
'GEM2.5': {'tol_lon': 0.016, 'tol_lat': 0.012},
}):
"""Find all indeces for the ... | 5,343,598 |
def _make_prediction_ops(features, hparams, mode, num_output_classes):
"""Returns (predictions, predictions_for_loss)."""
del hparams, mode
logits = tf.layers.dense(
features, num_output_classes, name='logits')
confidences = tf.nn.softmax(logits)
confidence_of_max_prediction = tf.reduce_max(confidences... | 5,343,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.