content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def comp_ac_fft_middlepad(data):
"""Compute auto-correlations from binned data (without normalization).
Uses FFT after zero-padding the time-series in the middle.
Parameters
-----------
data : nd array
time-series from binned data (numTrials * numBin).
Returns
-------
a... | 54,000 |
def get_sagemaker_resource_config():
"""
Returns JSON for config if training job is running on SageMaker else None
"""
cluster_config = None
sm_config_path = '/opt/ml/input/config/resourceconfig.json'
if os.path.exists(sm_config_path):
with open(sm_config_path) as file:
clust... | 54,001 |
def get_mod_for_key(keycode):
"""
Finds the modifier that is mapped to the given keycode.
This may be useful when analyzing key press events.
:type keycode: int
:return: A modifier identifier.
:rtype: xcb.xproto.ModMask
"""
return __keysmods.get(keycode, 0) | 54,002 |
def remove_delay_fault(virtual_service_name: str,
routes: List[Dict[str, str]],
ns: str = "default",
version: str = "networking.istio.io/v1alpha3",
configuration: Configuration = None,
secrets: Secrets = N... | 54,003 |
def set_lm_labels(dataset, vocab, stm_lex, stm_win=3):
"""
set labels of bi-directional language modeling and sentiment-aware language modeling
:param dataset: dataset
:param vocab: vocabulary
:param stm_lex: sentiment lexicon
:param stm_win: window size (i.e., length) of sentiment context
:... | 54,004 |
def pad_sequences(sequences, pad_func, maxlen = None):
"""
Similar to keras.preprocessing.sequence.pad_sequence but using Sample as higher level
abstraction.
pad_func is a pad class generator.
"""
ret = []
# Determine the maxlen
max_value = max(map(len, sequences))
if maxlen is None... | 54,005 |
def do_downgrade():
"""Downgrade the database's migration level"""
glance.db.sqlalchemy.migration.downgrade(CONF.command.version) | 54,006 |
def update(event, context):
"""
Runs on Stack Update
"""
physical_resource_id = event['PhysicalResourceId']
if event.get('ResourceType') == 'Custom::CWEventPermissions':
cwe = CWEventPermissions(event, logger)
logger.info("Updating CW Event Bus Policy - CR Router")
response =... | 54,007 |
def measure_arbitrary_sequence(qubits, sequence=None, sequence_function=None,
sequence_args=None, drive='timedomain', label=None,
detector_function=None, df_kwargs=None,
sweep_function=awg_swf.SegmentHardSweep,
... | 54,008 |
def LoadAnnotation(
seg_path,
prefix=None,
label_map=None,
reduce_zero_label=False,
imdecode_backend='pillow',
file_client: FileClient = FileClient(backend='disk'),
):
"""Load annotations for semantic segmentation.
**Args**:
- reduce_zero_label (bool): Wh... | 54,009 |
def train_and_sample(config, checkpoint_dir=None):
"""Trains and performs posterior sampling on a single LFADS model
Parameters
----------
config : dict
A dictionary of hyperparameters.
checkpoint_dir : str, optional
UNUSED
"""
# Don't log the TensorFlow info messages on imp... | 54,010 |
def config():
"""called from a high level, e.g. rungeneric, to configure the lower level
modules via modifying parameter settings.
"""
# pprldist.plotRLDistr2 needs to be revised regarding run_length based targets
if genericsettings.runlength_based_targets in (True, 1):
print 'Using bestG... | 54,011 |
def random_translate(img, streering_angle, range_x, range_y):
"""
Randomly shift the image virtially and horizontally (translation).
"""
trans_x = range_x * (np.random.rand() - 0.5)
trans_y = range_y * (np.random.rand() - 0.5)
streering_angle += trans_x * 0.002
trans_m = np.float32([[1, 0, ... | 54,012 |
def read_input_data(filename, arguments):
"""
Reads single input data
:param filename: relative path to file
:param arguments: image resize
:return: left image, right image
"""
cv_image = cv2.imread(filename)
if cv_image is None:
raise RuntimeError(f"Unable to open {filename}"... | 54,013 |
def get_uuid4():
""" make a random UUID
"""
s = uuid.uuid4()
return str(s) | 54,014 |
def test_increase():
"""Tests that ratings increase when appropriate."""
player1 = BaseAgent()
player2 = BaseAgent()
player1.elo = 1619
player2.elo = 1609
player2.elo = elo(player2, player1, 1)
assert player2.elo == 1625 | 54,015 |
def black76_vega(F: float,
K: Union[float, np.ndarray],
vol: Union[float, np.ndarray],
disc: float,
T: float) -> Union[float, np.ndarray]:
"""
Vega(s) for strike(s)
:param F: float, forward price
:param K: float or array, the Strike(s)
... | 54,016 |
def test_data_import_binance_history(rotkehlchen_api_server):
"""Test that the data import endpoint works successfully for binance data"""
rotki = rotkehlchen_api_server.rest_api.rotkehlchen
dir_path = Path(__file__).resolve().parent.parent
filepath = dir_path / 'data' / 'binance_history.csv'
json_... | 54,017 |
def replace_greek_uni(s):
"""Replace Greek spelled out letters with their unicode character."""
for greek_uni, greek_spelled_out in greek_alphabet.items():
s = s.replace(greek_spelled_out, greek_uni)
return s | 54,018 |
def load_GG2_images(images):
"""
Normalizes images and upscales them
"""
images = [fits.open(file, memmap=False)[0].data for file in images]
images = [torch.from_numpy(x.byteswap().newbyteorder()) for x in images]
#Normailze
normalize = [3.5239e+10, 1.5327e+09, 1.8903e+09, 1.2963e+09] #no... | 54,019 |
def index():
"""Main page"""
return render_template('landing.html') | 54,020 |
def run_sas(**kwargs):
"""Run a SAS script"""
try:
run = RunProgramDirective(kwargs)
run.error_check('sas')
# Get option
option = run.option
if not run.option:
if run.osname != 'posix':
option = metadata.default_options['saswin']
# G... | 54,021 |
def train(model, train_inputs, train_labels):
"""
Runs through one epoch - all training examples.
:param model: the initilized model to use for forward and backward pass
:param train_inputs: train inputs (all inputs for training) of shape (num_inputs,)
:param train_labels: train labels (a... | 54,022 |
def active_callback():
"""
A simple callback function for when the navigation action becomes active.
"""
rospy.loginfo('Action is active.') | 54,023 |
def has_computed_fields(context, obj):
"""
Return a boolean value indicating if an object's content type has associated computed fields.
"""
content_type = ContentType.objects.get_for_model(obj)
return ComputedField.objects.filter(content_type=content_type).exists() | 54,024 |
def _prepare_dataframes(
forecast_df: DataFrame,
truth_df: DataFrame,
percentiles: Optional[List[float]] = None,
experiment: Optional[str] = None,
) -> Tuple[DataFrame, DataFrame]:
"""Prepare dataframes for conversion to cubes by: 1) checking
that the expected columns are present, 2) finding the... | 54,025 |
def contour_and_point_distance(point):
"""
A reusable function that preloads a point and then
calculates the distance to a given contour.
:param point: an (x,y) tuple point
:return:
"""
return partial(geometry.distance_between_points, point) | 54,026 |
def main():
"""
the main function, where the magic happens
"""
with open("automator.config") as file:
data = file.readlines()
username = data[0][:-1]
password = data[1][:-1]
anilist = data[2][:-1]
kitsu = data[3][:-1]
global ffmpeg
ffmpeg = data[4]... | 54,027 |
def replace_codepoints(text: str) -> str:
"""
Replaces Unicode codepoints in a string with the corresponding glyphs.
Multiple codepoints can be specified in the same string. Characters
which are not part of codepoint annotation are kept.
@param text: The text with codepoint annotations to be repla... | 54,028 |
def grid2grid1D(f1, boxsize, ngridout, origin=0., originout=0., boxsizeout=None):
"""Remaps a dataset defined on 2D cartesian grid onto a new 2D cartesian grid.
Parameters
----------
f1 : array
The values of the 2D grid pixels.
boxsize : float
Box size.
ngridout : int
Gr... | 54,029 |
def get_all_user_feedback(request):
"""
Returns a list of all the feedbacks for a given user
:param request:
:return: 200 successful
"""
feedbacks = Feedback.objects.filter(user=request.user).order_by('-created')
serializer = FeedbackSerializer(feedbacks, many=True)
return Response(seria... | 54,030 |
def atom(env, args):
"""Atom has the value of 't' or 'f' according to
whether its argument is an atomic symbol. Thus:
(atom t) = t
(atom (quote (t f))) = f
"""
arg = args.car().eval(env)
if isinstance(arg, Symbol) or arg == F:
return T
return F | 54,031 |
def ad_get_user_dn_by_mail(user_mail_addr):
"""
通过mail查询某个用户的完整DN
:param user_mail_addr:
:return: DN
"""
conn = __ad_connect()
conn.search(BASE_DN,
'(&(objectclass=person)(mail=' + user_mail_addr + '))', attributes=['distinguishedName'])
user_dn = conn.entries[0]['disting... | 54,032 |
def safe_load_yaml_with_exceptions(yaml_file: Union[io.FileIO, IO[Any]]) -> Any:
"""Attempts to use ruamel.yaml.safe_load on the specified file. If successful, returns
the output. If not, formats a ruamel.yaml Exception so that the user does not see a traceback
of our internal APIs.
-------------------... | 54,033 |
def get_interface_config_ipv6(ip_address, ip_subnet, ip_gateway):
"""
Return the interface configuration parameters for all IPv6 static
addressing.
"""
parameters = collections.OrderedDict()
parameters['IPV6INIT'] = 'yes'
parameters['IPV6ADDR'] = netaddr.IPNetwork('%s/%u' % (ip_address,
... | 54,034 |
def show_json(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
r=show(i)
if r['return']>0: return r
return... | 54,035 |
def end_test():
"""End the test.
It can be used conditionally to exit a test under certain conditions.
"""
raise EndTest | 54,036 |
def tokenize_jiant_dataset(
tokenizer,
texts: List[str],
span1s: List[List[int]],
span2s: List[List[int]],
labels: List[str],
labels_to_ids: Dict[str, int],
max_seq_length: int=128,
) -> transformers.BatchEncoding:
"""Prepare a jiant dataset for the Da... | 54,037 |
def splitLR(geom: geo.base.BaseGeometry, splitter: String_or_Ring) -> SplitGeometry:
"""Split a geometry into a 'left' and 'right' side using the shapely API"""
left,right = [],[]
split_geom = ops.split(geom, splitter)
if len(split_geom)==1:
raise GeometryError("splitter did not split the geomet... | 54,038 |
def view():
"""Returns the ProteinViewer app view"""
viewer = ProteinViewer()
return viewer.view() | 54,039 |
def schaffer(X, Y):
"""constraints=100, minimum f(0,0)=0"""
numer = np.square(np.sin(X**2 - Y**2)) - 0.5
denom = np.square(1.0 + (0.001*(X**2 + Y**2)))
return 0.5 + (numer*(1.0/denom)) | 54,040 |
def job_install(info):
"""install the package defined in info"""
sentinel_file = Path(
"/anysnake/bioconductor/%s/%s.sentinel" % (info["name"], info["name"])
)
def do():
R_cmd = ["/anysnake/R/bin/R", "--no-save"]
r_build_script = """
lib = "/anysnake/bioconductor/"
... | 54,041 |
async def camera_fixture(
hass: HomeAssistant,
mock_entry: MockEntityFixture,
mock_camera: Camera,
now: datetime,
):
"""Fixture for a single camera for testing the binary_sensor platform."""
# disable pydantic validation so mocking can happen
Camera.__config__.validate_assignment = False
... | 54,042 |
def test_update_password_policy_false():
"""Will update an password policy (Wrong password).
:return: Should return: False
"""
syn = syncope.Syncope(syncope_url="http://192.168.1.145:9080", username="admin", password="passwrd")
assert syn.update_password_policy("json") == False | 54,043 |
def get_producer(): # pragma: no cover
"""Create a Kafka producer."""
producer = Producer({"bootstrap.servers": Config.INSIGHTS_KAFKA_ADDRESS, "message.timeout.ms": 1000})
return producer | 54,044 |
def infer_capture_method(tx, rx):
"""
Infers the capture method from the indices of transmitters and receivers.
Returns: 'hmc', 'fmc', 'unsupported'
Parameters
----------
tx : list
One per timetrace
rx : list
One per timetrace
Returns
-------
capture_method : s... | 54,045 |
def check_function(symbol, forward=None, backward=None, grad_input_vars=None,
shape=None, dtype=None, in_range=None, values=None,
exclude_targets=None, only_targets=None,
additional_params=None,
numerical_grads=None, numerical_grads_params=None... | 54,046 |
def SieveFilter(*args, **kwargs):
"""
SieveFilter(Band srcBand, Band maskBand, Band dstBand, int threshold, int connectedness=4, char ** options=None,
GDALProgressFunc callback=0, void * callback_data=None) -> int
"""
return _gdal.SieveFilter(*args, **kwargs) | 54,047 |
def rounded_corner_path(start_x, end_x, min_y, max_y):
"""creates a U shaped path between the start and end points."""
if start_x > end_x:
return rounded_corner_path(end_x, start_x, min_y, max_y).reversed()
radius = min(max_y - min_y, (end_x - start_x)/2)
paths = []
#first curve
paths.ap... | 54,048 |
def desc(col):
"""Sort by `col` descending."""
return Descending(col) | 54,049 |
def compare_names(tag, name, tagname=None):
"""Compare a tag against a filename and return if they're the same
Common substitutions will be tried.
Dates will only require the minimum provided data to match
"""
if tagname in DATE_TAGS:
return Date.parse(tag) == Date.parse(name) is not None
... | 54,050 |
def clean_text(text: str, remove_punctuation=False) -> str:
"""Cleans the inputted text based on the rules given in the comments.
Code taken from: https://github.com/kk7nc/Text_Classification/
Args:
text (str): the text to be cleaned
remove_punctuation (bool): whether to remove punctuation ... | 54,051 |
def dont_quit_when_last_window_closed(qt_app):
"""
Suppress exit of the application when the last window is closed.
"""
flag = qt_app.quitOnLastWindowClosed()
qt_app.setQuitOnLastWindowClosed(False)
try:
yield
finally:
qt_app.setQuitOnLastWindowClosed(flag) | 54,052 |
def doc(obj=None, itm=None, docs=None, prefix=None):
"""Python IVI documentation generator"""
st = ""
# add a dot to prefix when needed
if prefix is None or len(prefix) == 0:
prefix = ''
elif not prefix[-1] == '.':
prefix += '.'
# if something passed in docs, iterate ov... | 54,053 |
def buscaNumQueries():
"""
Pela leitura do arquivo de configuração config.ini, retorna o número de queries configuradas.
:return número de consultas cadastradas no arquivo de configuração
"""
# Cria um set com as queries registradas no arquivo de configuração
queries = set()
contador... | 54,054 |
def add_folder():
""""This function is to enable the user add folders to be accessed"""
# some highlighted variables are for test purposes only
""" I was finally able to make it default to HOME anytime by using 'tilde' '~' in 'initial dir'"""
folder_variable = filedialog.askdirectory(parent=wi... | 54,055 |
def openURL(url):
"""Opens a URL."""
webbrowser.open_new(url)
return True | 54,056 |
def plasticmodel_error(bedfunction, tau_val, Bfunction, startpoint, hinit, endpoint, Npoints, obsheightfunction, allow_upstream_breakage=True):
"""Arguments used:
bedfunction should be function of arclength returning bed elevation of the glacier.
Bfunction is nondim yield strength. Should be functi... | 54,057 |
def lisp_parens_with_stack(parens):
"""Output with stack to see whether parens are open(1), broken(-1), or balanced(0)."""
open_stack = []
for par in parens:
if par == '(':
open_stack.append(par)
if par == ')':
try:
open_stack.pop()
except ... | 54,058 |
def attention_resnet56(**kwargs):
"""Constructs a ResNet-34 model.
"""
model = CifarAttentionResNet(CifarAttentionBasicBlock, 9, **kwargs)
return model | 54,059 |
def test_copy_tree(result, slink):
"""
Tests copy_tree function
"""
src = tempfile.mkdtemp()
dest = tempfile.mkdtemp()
try:
if result == 'success':
add_data(src)
copy_tree(src, dest, symlink=slink)
for root, dirs, files in os.walk(dest):
if root... | 54,060 |
def deploy(remote='origin', reload=False):
"""
Deploy the latest app to S3 and, if configured, to our servers.
"""
require('settings', provided_by=[production, staging])
if app_config.DEPLOY_TO_SERVERS:
require('branch', provided_by=[stable, master, branch])
servers.checkout_latest... | 54,061 |
def index(request):
"""View-func for '' request.
Displays ten posts per page, sorted by date added.
Returns 'posts/index.html' template.
"""
post_list = Post.objects.all()
page_obj = paginator_page(request, post_list)
context = {
'page_obj': page_obj,
}
cache.clear()
ret... | 54,062 |
def download_file(directory: str, source_url: str, decompress: bool = False) -> None:
"""Download data from source_ulr inside directory.
Parameters
----------
directory: str, Path
Custom directory where data will be downloaded.
source_url: str
URL where data is hosted.
decompres... | 54,063 |
def generate_cyclic_group(order, identity_name="e", elem_name="a", name=None, description=None):
"""Generates a cyclic group with the given order."""
if name:
nm = name
else:
nm = "Z" + str(order)
if description:
desc = description
else:
desc = f"Autogenerated cyclic ... | 54,064 |
def format_data(statistics: List = [], group_data_by: str = None):
"""
Format data to be displayed in the carts.
Arguments:
statistics {List} -- All device statistics.
group_data_by {str} -- User selected aggregation option.
"""
reports, alerts = {}, {}
for statistic in statist... | 54,065 |
def each_side(token):
"""Count the found embryo."""
trait = Trait(start=token.start, end=token.end)
if token.group.get("subcount"):
count = to_positive_int(token.group["subcount"])
trait.value = count + count
trait.left = count
trait.right = count
return trait | 54,066 |
def test__linter__linting_result__sum_dicts():
"""Test the summing of dictionaries in the linter."""
lr = LintingResult()
i = {}
a = dict(a=3, b=123, f=876.321)
b = dict(a=19, b=321.0, g=23478)
r = dict(a=22, b=444.0, f=876.321, g=23478)
assert lr.sum_dicts(a, b) == r
# Check the identit... | 54,067 |
def get_match_data_by_uid(uid):
"""
通过用户id获取mysql匹配场数据
:param: uid
:return:dict
"""
# TODO 获取匹配场数据
return mj_hall_bridge.get_match_data_by_uid(uid) | 54,068 |
def add_image(db, filename, usernick):
"""Add this image to the database for the given user"""
flowTowCursor = db.cursor()
SQL = """INSERT INTO images(filename, timestamp, usernick) VALUES (?, datetime('now'), ?)"""
flowTowCursor.execute(SQL, [filename, usernick])
db.commit() | 54,069 |
def str_format_env(value):
"""
Substitute values with environment variables in a string
Parameters
----------
value : str
The string object to be formatted and converted into a list
Returns
-------
str
With env variable values substituded
"""
template = Template... | 54,070 |
def render_output_preview(output_preview, filename, region):
"""
We get the exact number of preview lines we want, but some of them might be too long
and get wrapped. In this case, the extra lines overflow at the bottom, but we want
overflow at the top (and there seems to be no way to fix this natively ... | 54,071 |
def main():
"""Main method."""
options = parse_args()
# set logging based on log_level option
log_level_mapping = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR}
logging.basicConfig(
leve... | 54,072 |
def update_quantization_param(bits, rmin, rmax, dtype, scheme):
"""
calculate the `zero_point` and `scale`.
Parameters
----------
bits : int
quantization bits length
rmin : Tensor
min value of real value
rmax : Tensor
max value of real value
dtype : QuantDtype
... | 54,073 |
def process_correct_phidp0(procstatus, dscfg, radar_list=None):
"""
corrects phidp of the system phase
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
2 post-processing
dscfg : dictionary of dictionaries
data set configurati... | 54,074 |
def create_summary_tear_sheet(factor_data, long_short=True):
"""
Creates a small summary tear sheet with returns, information, and turnover
analysis.
Parameters
----------
factor_data : pd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1),
... | 54,075 |
def largest_nonadjacent_sum(arr):
"""
Find the largest sum of non-adjacent numbers
"""
before_last = 0
last = 0
for elt in arr:
cur = before_last + elt
before_last = max(before_last, last)
last = max(cur, last)
return last | 54,076 |
def test_functional():
"""Functional tests"""
# Types of recipes we are targeting for testing. (Recommend "download" and "pkg" only.)
recipe_types = ("download", "pkg")
# Walk our repo and collect each recipe matching the above types.
recipe_paths = []
for root, dirs, files in os.walk("."):
... | 54,077 |
def _flip_boxes_up_down(boxes):
"""Up-down flip the boxes.
Args:
boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
Each row is in the form of [ymin, xmin, ymax, xmax].
Returns:
... | 54,078 |
def test_info_alert_height_problem():
"""## test_info_alert_height_problem
We saw that the height of InfoAlert Div was much greater than it needed to be.
See [Issue 829](https://github.com/holoviz/panel/issues/829)
"""
pn.config.raw_css.append(pnx.InfoAlert.raw_css)
text = """\
Navigate to the ... | 54,079 |
def mode(ctx, mode, touch_eject, autoeject_timeout, chalresp_timeout, force):
"""
Manage connection modes (USB Interfaces).
Get the current connection mode of the YubiKey, or set it to MODE.
MODE can be a string, such as "OTP+FIDO+CCID", or a shortened form: "o+f+c".
It can also be a mode number.
... | 54,080 |
def get_image_id() -> list:
"""
Returns:
[list]: [Return a list with all Image id content in the storage]
"""
storage_folder = settings.STORAGE_DIR+'/image'
list_id = []
i=0
for f in os.listdir(storage_folder):
if os.path.isfile(os.path.join(storage_folder, f)):
... | 54,081 |
def parse_replays(
game_filter: Callable,
unparsed_folder: Path,
events_folder: Path,
pickle_folder: Path,
json_folder: Path,
screenshot_iterator: Callable,
limit=None,
): # pylint: disable=too-many-arguments
"""
game filter must be a function that takes a game and returns boolean, ... | 54,082 |
def any_state(message):
"""
Cancel state
"""
bot.send_message(message.chat.id, "Your state was cancelled.")
bot.delete_state(message.from_user.id, message.chat.id) | 54,083 |
def openTypeOS2WinAscentFallback(info):
"""
Fallback to the maximum y value of the font's bounding box.
If that is not available, fallback to *ascender*.
if the maximum y value is negative, fallback to 0 (zero).
"""
font = info.getParent()
if font is None:
yMax = getAttrWithFallback(... | 54,084 |
def test_init():
"""
"""
runner = CliRunner()
result = runner.invoke(cli, ['init'])
assert result.exit_code == 0
assert result.output == 'Initialize Python project in given directory\n' | 54,085 |
def get_updates_and_outputs(ls):
"""
Parses the list ``ls`` into outputs and updates. The semantics
of ``ls`` is defined by the constructive function of scan.
The elemets of ``ls`` are either a list of expressions representing the
outputs/states, a dictionary of updates or a condition.
"""
d... | 54,086 |
def get_regularized_cost(dims, theta, num_samples, lambd):
""" Calculates L2 Regularization cost using hyper parameter lambd
Preconditions:
dims: list of int length >= 2
theta: dict
num_samples: int
Parameters:
dims: dimensions of the neural network model
theta: learned parameters
... | 54,087 |
def eval_with_import(path: str) -> Any:
"""Evaluate the string as Python script.
Args:
path (str): The path to evaluate.
Returns:
Any: The result of evaluation.
"""
split_path = path.split('.')
for i in range(len(split_path), 0, -1):
try:
exec('import {}'.fo... | 54,088 |
def get_labeled_measurements(data: DataRowsSet_t, correct_channels: WorkingChannels_t,
functionalisations: Functionalisations_t, start_offset: Union[int, Iterable[int]] = 0,
debug=False) \
-> List[Measurement]:
"""
Extracts the individual Measure... | 54,089 |
def GDL(input, target, weights):
"""
Generalized Dice Loss
:param input: input is a torch variable of size Batch x nclasses x H x W representing the predictions for each class
:param target: target is a 1-hot representation of the groundtruth, shoud have same size as the input
:return: Generalize... | 54,090 |
def eval_class(gt_annos,
dt_annos,
current_class,
difficulty,
metric,
min_overlap,
num_parts=50):
"""Kitti eval. Only support 2d/bev/3d eval for now.
Args:
gt_annos: dict, must from get_label_annos() in kitti_commo... | 54,091 |
def displaying_dairy():
"""This function displays all the items in the category [dairy]"""
global name_dairy
global cost_dairy
global quantity_dairy
global users_cart_category
# displaying Dairy
for i in range(0, len(name_dairy)):
print(f"{i+1}.{bcolors.OKBLUE}{quantity_dai... | 54,092 |
def integral_curve(h, hstar, hustar, wave_family, g=1., y_axis='u'):
"""
Return u or hu as a function of h for integral curves through
(hstar, hustar).
"""
ustar = hustar / pospart(hstar)
if wave_family == 1:
if y_axis == 'u':
return ustar + 2*(np.sqrt(g*hstar) - np.sqrt(g*h)... | 54,093 |
def dev_guide(request):
"""
开发指引
"""
return render_mako_context(request, '/home_application/dev_guide.html', {"ssssss": "11111111",
"AAA": [{'QQQ': "22222"}]
... | 54,094 |
def _run_calculations(
data_set: "PhysicalPropertyDataSet",
force_field: "ForceField",
polling_interval: int,
request_options: "RequestOptions",
server_config: EvaluatorServerConfig,
) -> "RequestResult":
"""Attempt to estimate the data set using the specified force field.
Parameters
--... | 54,095 |
def test_produce_string_records_multiple_partitions(sdc_builder, sdc_executor, cluster, port):
"""Write simple text messages into Kafka multiple partitions and confirm that Kafka successfully reads them.
Because cluster mode pipelines don't support wiretap as destination, we do this verification using a
sec... | 54,096 |
def NewtonRaphson(funcion, derivada, x_inicial, num_iteraciones, error):
"""
La x inicial determinara el numero de iteraciones necesarias
para alcanzar el resultado.
:param funcion: Nombre de la funcion a utilizar sin parentesis.
:param derivada: Nombre de la derivada de la funcion sin parentesis.
... | 54,097 |
def readoptions(fname):
"""
Read `markowik` options from a file, one per line.
"""
if os.path.exists(fname):
with codecs.open(fname, 'r', 'UTF8') as fp:
cfg = fp.read()
options = [x.strip() for x in cfg.split("\n") if x.strip()]
else:
options = []
return opt... | 54,098 |
def get_train_random_forest_pai_cmd(model_name, data_table, model_attrs,
feature_column_names, label_name):
"""Get a command to submit a KMeans training task to PAI
Args:
model_name: model name on PAI
data_table: input data table name
model_attrs: mod... | 54,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.