repo_name stringlengths 2 55 | dataset stringclasses 1
value | owner stringlengths 3 31 | lang stringclasses 10
values | func_name stringlengths 1 104 | code stringlengths 20 96.7k | docstring stringlengths 1 4.92k | url stringlengths 94 241 | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
OpenComplex | github_2023 | baaihealth | python | between_residue_clash_loss | def between_residue_clash_loss(
atom23_pred_positions: torch.Tensor,
atom23_atom_exists: torch.Tensor,
atom23_atom_radius: torch.Tensor,
residue_index: torch.Tensor,
overlap_tolerance_soft=1.5,
overlap_tolerance_hard=1.5,
eps=1e-10,
) -> Dict[str, torch.Tensor]:
"""Loss to penalize steri... | """Loss to penalize steric clashes between residues.
This is a loss penalizing any steric clashes due to non bonded atoms in
different peptides coming too close. This loss corresponds to the part with
different residues of
Jumper et al. (2021) Suppl. Sec. 1.9.11, eq 46.
Args:
atom14_pred_pos... | https://github.com/baaihealth/OpenComplex/blob/ce0d5b97b154e992b7abb10403b2ad49f850ea6f/opencomplex/loss/loss_fns_rna.py#L180-L310 | ce0d5b97b154e992b7abb10403b2ad49f850ea6f |
opshin | github_2023 | OpShin | python | apply_parameter | def apply_parameter(self, *args: pycardano.Datum):
"""
Returns a new OpShin Contract with the applied parameters
"""
# update the parameters in the blueprint (remove applied parameters)
assert len(self.parameter_types) >= len(
args
), f"Applying too many param... | """
Returns a new OpShin Contract with the applied parameters
""" | https://github.com/OpShin/opshin/blob/d657a227f02670e6b6eed9cac77c0f8a25d51423/opshin/builder.py#L146-L169 | d657a227f02670e6b6eed9cac77c0f8a25d51423 |
NeMo-Framework-Launcher | github_2023 | NVIDIA | python | LM.loglikelihood_rolling | @abc.abstractmethod
def loglikelihood_rolling(self, requests):
"""Compute full log-likelihood of a string, with no truncation, for perplexity computation
- We will use the full max context length of the model.
- For inputs that exceed the max context length, we divide the tokenized string in... | """Compute full log-likelihood of a string, with no truncation, for perplexity computation
- We will use the full max context length of the model.
- For inputs that exceed the max context length, we divide the tokenized string into chunks of up to
the max context length.
- IMPORTANT: Eac... | https://github.com/NVIDIA/NeMo-Framework-Launcher/blob/4abd481402adc8a061942c486eda6d71f19de718/launcher_scripts/nemo_launcher/collections/eval_harness/lm_eval/base.py#L64-L104 | 4abd481402adc8a061942c486eda6d71f19de718 |
kaizenflow | github_2023 | causify-ai | python | Backtest_TestCase._test | @abc.abstractmethod
def _test(self, *args: Any, **kwargs: Any) -> None:
"""
Run the entire flow.
""" | """
Run the entire flow.
""" | https://github.com/causify-ai/kaizenflow/blob/545f66ef6e6b0e5109602dbf1938ef668c55750d/dataflow/backtest/backtest_test_case.py#L123-L127 | 545f66ef6e6b0e5109602dbf1938ef668c55750d |
kaizenflow | github_2023 | causify-ai | python | get_forecast_evaluator | def get_forecast_evaluator(
forecast_evaluator_class_name: str, **kwargs: Dict[str, Any]
) -> dtfmabfoev.AbstractForecastEvaluator:
"""
Get the forecast evaluator for the backtest analysis.
:param forecast_evaluator_class_name: name of the ForecastEvaluator
as str, e.g. "ForecastEvaluatorFromPr... | """
Get the forecast evaluator for the backtest analysis.
:param forecast_evaluator_class_name: name of the ForecastEvaluator
as str, e.g. "ForecastEvaluatorFromPrices",
"ForecastEvaluatorWithOptimizer" :param **kwargs: kwargs for
ctor of the provided ForecastEvaluator class
:return... | https://github.com/causify-ai/kaizenflow/blob/545f66ef6e6b0e5109602dbf1938ef668c55750d/dataflow/model/backtest_notebook_utils.py#L138-L163 | 545f66ef6e6b0e5109602dbf1938ef668c55750d |
kaizenflow | github_2023 | causify-ai | python | to_typed_csv | def to_typed_csv(df: pd.DataFrame, file_name: str) -> str:
"""
Convert df into CSV and creates a file with the dtypes of columns.
This function creates a file containing the types with the same name
and suffix e.g., `foobar.csv.types`.
"""
# Save the types.
dtypes_filename = file_name + ".t... | """
Convert df into CSV and creates a file with the dtypes of columns.
This function creates a file containing the types with the same name
and suffix e.g., `foobar.csv.types`.
""" | https://github.com/causify-ai/kaizenflow/blob/545f66ef6e6b0e5109602dbf1938ef668c55750d/helpers/hcsv.py#L350-L365 | 545f66ef6e6b0e5109602dbf1938ef668c55750d |
kaizenflow | github_2023 | causify-ai | python | purify_from_environment | def purify_from_environment(txt: str) -> str:
"""
Replace environment variables with placeholders.
The performed transformations are:
1. Replace the Git path with `$GIT_ROOT`
2. Replace the path of current working dir with `$PWD`
3. Replace the current user name with `$USER_NAME`
"""
# ... | """
Replace environment variables with placeholders.
The performed transformations are:
1. Replace the Git path with `$GIT_ROOT`
2. Replace the path of current working dir with `$PWD`
3. Replace the current user name with `$USER_NAME`
""" | https://github.com/causify-ai/kaizenflow/blob/545f66ef6e6b0e5109602dbf1938ef668c55750d/helpers/hunit_test.py#L372-L409 | 545f66ef6e6b0e5109602dbf1938ef668c55750d |
kaizenflow | github_2023 | causify-ai | python | _get_docker_compose_cmd | def _get_docker_compose_cmd(
base_image: str,
stage: str,
version: str,
cmd: str,
*,
# TODO(gp): make these params mandatory.
extra_env_vars: Optional[List[str]] = None,
extra_docker_compose_files: Optional[List[str]] = None,
extra_docker_run_opts: Optional[List[str]] = None,
ser... | """
Get `docker-compose` run command.
E.g.,
```
IMAGE=*****..dkr.ecr.us-east-1.amazonaws.com/amp:dev \
docker-compose \
--file /amp/devops/compose/docker-compose.yml \
--env-file devops/env/default.env \
run \
--rm \
--name grisha.cmamp.app.cmamp1.2022031... | https://github.com/causify-ai/kaizenflow/blob/545f66ef6e6b0e5109602dbf1938ef668c55750d/helpers/lib_tasks_docker.py#L1133-L1254 | 545f66ef6e6b0e5109602dbf1938ef668c55750d |
kaizenflow | github_2023 | causify-ai | python | _apply_trimming | def _apply_trimming(self, df: pd.DataFrame) -> pd.DataFrame:
"""
Trim `df` according to ATH, weekends, missing data.
:param df: as in `compute_portfolio()`
:return: `df` trimmed down to:
- required and possibly optional columns
- "active" bars (bars where at least on... | """
Trim `df` according to ATH, weekends, missing data.
:param df: as in `compute_portfolio()`
:return: `df` trimmed down to:
- required and possibly optional columns
- "active" bars (bars where at least one instrument has an end-of-bar
price)
- first i... | https://github.com/causify-ai/kaizenflow/blob/545f66ef6e6b0e5109602dbf1938ef668c55750d/optimizer/forecast_evaluator_with_optimizer.py#L285-L325 | 545f66ef6e6b0e5109602dbf1938ef668c55750d |
kaizenflow | github_2023 | causify-ai | python | get_github_create_issues_table_query | def get_github_create_issues_table_query() -> str:
"""
Get SQL query to create github_issues table.
This table contains the data as it is downloaded.
"""
query = """
CREATE TABLE IF NOT EXISTS github_issues(
id SERIAL PRIMARY KEY,
number NUMERIC,
title V... | """
Get SQL query to create github_issues table.
This table contains the data as it is downloaded.
""" | https://github.com/causify-ai/kaizenflow/blob/545f66ef6e6b0e5109602dbf1938ef668c55750d/sorrentum_sandbox/spring2023/ml_projects/SorrIssue21_Team2_Implement_sandbox_for_GitHub_2/db_team2.py#L52-L76 | 545f66ef6e6b0e5109602dbf1938ef668c55750d |
gyre | github_2023 | stablecabal | python | sample_dpmpp_2m | @torch.no_grad()
def sample_dpmpp_2m(
model,
x,
sigmas,
extra_args=None,
callback=None,
disable=None,
warmup_lms=False,
ddim_cutoff=0.0,
):
"""DPM-Solver++(2M)."""
extra_args = {} if extra_args is None else extra_args
s_in = x.new_ones([x.shape[0]])
sigma_fn = lambda t: t... | """DPM-Solver++(2M).""" | https://github.com/stablecabal/gyre/blob/9cba9781cd458acb8b821f5dc584299cab1ed2f3/gyre/pipeline/schedulers/sample_dpmpp_2m.py#L5-L50 | 9cba9781cd458acb8b821f5dc584299cab1ed2f3 |
BigWorld-Engine-14.4.1 | github_2023 | v2v3v4 | python | Select.froms | @property
def froms(self):
"""Return the displayed list of FromClause elements."""
return self._get_display_froms() | """Return the displayed list of FromClause elements.""" | https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/build/bw_internal/perf/sqlalchemy/sql/expression.py#L4842-L4846 | 4389085c8ce35cff887a4cc18fc47d1133d89ffb |
BigWorld-Engine-14.4.1 | github_2023 | v2v3v4 | python | Complex.__truediv__ | @abstractmethod
def __truediv__(self, other):
"""self / other with __future__ division.
Should promote to float when necessary.
"""
raise NotImplementedError | """self / other with __future__ division.
Should promote to float when necessary.
""" | https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/python/Lib/numbers.py#L123-L129 | 4389085c8ce35cff887a4cc18fc47d1133d89ffb |
BigWorld-Engine-14.4.1 | github_2023 | v2v3v4 | python | is_namespace | def is_namespace(self):
"""Returns true if name binding introduces new namespace.
If the name is used as the target of a function or class
statement, this will be true.
Note that a single name can be bound to multiple objects. If
is_namespace() is true, the name may also be bo... | """Returns true if name binding introduces new namespace.
If the name is used as the target of a function or class
statement, this will be true.
Note that a single name can be bound to multiple objects. If
is_namespace() is true, the name may also be bound to other
objects, li... | https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/python/Lib/symtable.py#L207-L218 | 4389085c8ce35cff887a4cc18fc47d1133d89ffb |
BigWorld-Engine-14.4.1 | github_2023 | v2v3v4 | python | create_arc | def create_arc(self, *args, **kw):
"""Create arc shaped region with coordinates x1,y1,x2,y2."""
return self._create('arc', args, kw) | """Create arc shaped region with coordinates x1,y1,x2,y2.""" | https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/python/Lib/lib-tk/Tkinter.py#L2271-L2273 | 4389085c8ce35cff887a4cc18fc47d1133d89ffb |
BigWorld-Engine-14.4.1 | github_2023 | v2v3v4 | python | clearstamp | def clearstamp(self, stampid):
"""Delete stamp with given stampid
Argument:
stampid - an integer, must be return value of previous stamp() call.
Example (for a Turtle instance named turtle):
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
... | """Delete stamp with given stampid
Argument:
stampid - an integer, must be return value of previous stamp() call.
Example (for a Turtle instance named turtle):
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.clearstamp(astamp)
... | https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/python/Lib/lib-tk/turtle.py#L2933-L2946 | 4389085c8ce35cff887a4cc18fc47d1133d89ffb |
BigWorld-Engine-14.4.1 | github_2023 | v2v3v4 | python | getEventCategory | def getEventCategory(self, record):
"""
Return the event category for the record.
Override this if you want to specify your own categories. This version
returns 0.
"""
return 0 | """
Return the event category for the record.
Override this if you want to specify your own categories. This version
returns 0.
""" | https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/python/Lib/logging/handlers.py#L994-L1001 | 4389085c8ce35cff887a4cc18fc47d1133d89ffb |
BigWorld-Engine-14.4.1 | github_2023 | v2v3v4 | python | errorCheck | def errorCheck(self):
"""Check for an error if necessary.
This only generates code if the variable's mode is ErrorMode.
"""
if self.flags == ErrorMode:
self.type.errorCheck(self.name) | """Check for an error if necessary.
This only generates code if the variable's mode is ErrorMode.
""" | https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/python/Tools/bgen/bgen/bgenVariable.py#L91-L97 | 4389085c8ce35cff887a4cc18fc47d1133d89ffb |
griptape | github_2023 | griptape-ai | python | get_mime_type | def get_mime_type(file_path_or_bytes: str | bytes) -> str:
"""Attempt to determine the MIME type of a file or bytes.
If the input is a file path, we use the built-in `mimetypes` package to guess the MIME type.
If the input is bytes, we use the `filetype` library to determine the MIME type.
If the libr... | """Attempt to determine the MIME type of a file or bytes.
If the input is a file path, we use the built-in `mimetypes` package to guess the MIME type.
If the input is bytes, we use the `filetype` library to determine the MIME type.
If the library cannot determine the MIME type (data missing magic bytes), ... | https://github.com/griptape-ai/griptape/blob/f9ac289715eeb24cb15cbb31e8e32c0e9fb00d45/griptape/utils/file_utils.py#L11-L43 | f9ac289715eeb24cb15cbb31e8e32c0e9fb00d45 |
f2 | github_2023 | Johnserf-Seed | python | fetch_play_list | async def fetch_play_list(
self,
secUid: str,
cursor: int,
page_counts: int,
) -> UserPlayListFilter:
"""
用于获取指定用户的作品合集列表
(Used to get video mix list of specified user)
Args:
secUid: str: 用户ID (User ID)
cursor: int: 分页游标 (Page ... | """
用于获取指定用户的作品合集列表
(Used to get video mix list of specified user)
Args:
secUid: str: 用户ID (User ID)
cursor: int: 分页游标 (Page cursor)
page_counts: int: 分页数量 (Page counts)
Return:
playlist: UserPlayListFilter: 作品合集列表 (Video mix list)
... | https://github.com/Johnserf-Seed/f2/blob/c80eeabf0622b34549e3316f4f711c3f01109bc1/f2/apps/tiktok/handler.py#L688-L724 | c80eeabf0622b34549e3316f4f711c3f01109bc1 |
DSVT | github_2023 | Haiyang-W | python | bilinear_interpolate_torch | def bilinear_interpolate_torch(im, x, y):
"""
Args:
im: (H, W, C) [y, x]
x: (N)
y: (N)
Returns:
"""
x0 = torch.floor(x).long()
x1 = x0 + 1
y0 = torch.floor(y).long()
y1 = y0 + 1
x0 = torch.clamp(x0, 0, im.shape[1] - 1)
x1 = torch.clamp(x1, 0, im.shape[... | """
Args:
im: (H, W, C) [y, x]
x: (N)
y: (N)
Returns:
""" | https://github.com/Haiyang-W/DSVT/blob/8cfc2a6f23eed0b10aabcdc4768c60b184357061/pcdet/models/backbones_3d/pfe/voxel_set_abstraction.py#L11-L42 | 8cfc2a6f23eed0b10aabcdc4768c60b184357061 |
OnePose_Plus_Plus | github_2023 | zju3dv | python | merge_train_core | def merge_train_core(
anno_2d_file,
avg_anno_3d_file,
idxs_file,
img_id,
ann_id,
images,
annotations,
):
""" Merge training annotations of different objects"""
with open(anno_2d_file, "r") as f:
annos_2d = json.load(f)
for anno_2d in annos_2d:
img_id += 1
... | """ Merge training annotations of different objects""" | https://github.com/zju3dv/OnePose_Plus_Plus/blob/fc660efb1f594468642d681e35e4843928f16f3e/merge.py#L13-L46 | fc660efb1f594468642d681e35e4843928f16f3e |
RDM-Region-Aware-Diffusion-Model | github_2023 | haha-lisa | python | get_named_beta_schedule | def get_named_beta_schedule(schedule_name, num_diffusion_timesteps):
"""
Get a pre-defined beta schedule for the given name.
The beta schedule library consists of beta schedules which remain similar
in the limit of num_diffusion_timesteps.
Beta schedules may be added, but should not be removed or c... | """
Get a pre-defined beta schedule for the given name.
The beta schedule library consists of beta schedules which remain similar
in the limit of num_diffusion_timesteps.
Beta schedules may be added, but should not be removed or changed once
they are committed to maintain backwards compatibility.
... | https://github.com/haha-lisa/RDM-Region-Aware-Diffusion-Model/blob/be0c767f05af74021530962218106c9c20cad3f0/guided_diffusion/gaussian_diffusion.py#L20-L49 | be0c767f05af74021530962218106c9c20cad3f0 |
CFScanner | github_2023 | MortezaBashsiz | python | CloudflareSolver._parse_proxy | @staticmethod
def _parse_proxy(proxy: str) -> Dict[str, str]:
"""
Parse a proxy URL string into a dictionary of proxy parameters for the Playwright browser.
Parameters
----------
proxy : str
Proxy URL string.
Returns
-------
Dict[str, str... | """
Parse a proxy URL string into a dictionary of proxy parameters for the Playwright browser.
Parameters
----------
proxy : str
Proxy URL string.
Returns
-------
Dict[str, str]
Dictionary of proxy parameters.
""" | https://github.com/MortezaBashsiz/CFScanner/blob/bcb96dd437e9cf90350ee5581df613b92380827f/other/gist/cfchallenger.py#L96-L123 | bcb96dd437e9cf90350ee5581df613b92380827f |
temporian | github_2023 | google | python | test_correct_or | def test_correct_or(self) -> None:
"""Test correct OR operator."""
expected = event_set(
timestamps=[1, 2, 3, 4],
features={"x": [True, False, True, True]},
same_sampling_as=self.evset_1,
)
assertOperatorResult(self, self.evset_1 | self.evset_2, expect... | """Test correct OR operator.""" | https://github.com/google/temporian/blob/1e33b75b9fadfaf1c30bc20725cba9753105e4f9/temporian/core/operators/test/test_logical.py#L43-L50 | 1e33b75b9fadfaf1c30bc20725cba9753105e4f9 |
temporian | github_2023 | google | python | PlotterBackend.finalize_subplot | @abstractmethod
def finalize_subplot(
self,
):
"""Finalizes a previously added sub plot."""
raise NotImplementedError | """Finalizes a previously added sub plot.""" | https://github.com/google/temporian/blob/1e33b75b9fadfaf1c30bc20725cba9753105e4f9/temporian/implementation/numpy/data/plotter_base.py#L77-L83 | 1e33b75b9fadfaf1c30bc20725cba9753105e4f9 |
cloudfoxable | github_2023 | BishopFox | python | Pack | def Pack(self, msg, type_url_prefix='type.googleapis.com/',
deterministic=None):
"""Packs the specified message into current Any message."""
if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
else:
self.type... | """Packs the specified message into current Any message.""" | https://github.com/BishopFox/cloudfoxable/blob/b7f028ebf2c9d9489e19736942b99fb07b0d0251/aws/challenges/Variable/data/lambda-src-backup/protobuf/internal/well_known_types.py#L64-L71 | b7f028ebf2c9d9489e19736942b99fb07b0d0251 |
cloudfoxable | github_2023 | BishopFox | python | _path_get | def _path_get(self, data, path):
"""Return the nested data at the given path.
For instance:
data = {'foo': ['bar', 'baz']}
path = ['foo', 0]
==> 'bar'
"""
# jmespath isn't used here because it would be difficult to actually
# create the jmespa... | """Return the nested data at the given path.
For instance:
data = {'foo': ['bar', 'baz']}
path = ['foo', 0]
==> 'bar'
""" | https://github.com/BishopFox/cloudfoxable/blob/b7f028ebf2c9d9489e19736942b99fb07b0d0251/aws/challenges/Variable/data/lambda-src/botocore/paginate.py#L143-L158 | b7f028ebf2c9d9489e19736942b99fb07b0d0251 |
cloudfoxable | github_2023 | BishopFox | python | create_client | def create_client(
self,
service_name,
region_name=None,
api_version=None,
use_ssl=True,
verify=None,
endpoint_url=None,
aws_access_key_id=None,
aws_secret_access_key=None,
aws_session_token=None,
config=None,
):
"""Crea... | """Create a botocore client.
:type service_name: string
:param service_name: The name of the service for which a client will
be created. You can use the ``Session.get_available_services()``
method to get a list of all available service names.
:type region_name: string
... | https://github.com/BishopFox/cloudfoxable/blob/b7f028ebf2c9d9489e19736942b99fb07b0d0251/aws/challenges/Variable/data/lambda-src/botocore/session.py#L826-L991 | b7f028ebf2c9d9489e19736942b99fb07b0d0251 |
Diffusion-SDF | github_2023 | princeton-computational-imaging | python | __init__ | def __init__(self, num_classes, in_channels=3, depth=5,
start_filts=64, up_mode='transpose', same_channels=False,
merge_mode='concat', **kwargs):
"""
Arguments:
in_channels: int, number of channels in the input tensor.
Default is 3 for RGB i... | """
Arguments:
in_channels: int, number of channels in the input tensor.
Default is 3 for RGB images.
depth: int, number of MaxPools in the U-Net.
start_filts: int, number of convolutional filters for the
first conv.
up_mode: strin... | https://github.com/princeton-computational-imaging/Diffusion-SDF/blob/7eb2d6786b8864dc45cd180be8ad5c5b2f8c1f8f/models/archs/encoders/conv_pointnet.py#L389-L462 | 7eb2d6786b8864dc45cd180be8ad5c5b2f8c1f8f |
UniPC | github_2023 | wl-zhao | python | marginal_lambda | def marginal_lambda(self, t):
"""
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
"""
log_mean_coeff = self.marginal_log_mean_coeff(t)
log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
return log_mean_coeff - log_s... | """
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
""" | https://github.com/wl-zhao/UniPC/blob/cf9de85bf2ed68137e6fba5f165f451677b174c4/example/score_sde_pytorch/uni_pc.py#L128-L134 | cf9de85bf2ed68137e6fba5f165f451677b174c4 |
modulus | github_2023 | NVIDIA | python | build_fno | def build_fno(self, num_fno_modes: List[int]) -> None:
"""construct FNO block.
Parameters
----------
num_fno_modes : List[int]
Number of Fourier modes kept in spectral convolutions
"""
# Build Neural Fourier Operators
self.spconv_layers = nn.ModuleLis... | """construct FNO block.
Parameters
----------
num_fno_modes : List[int]
Number of Fourier modes kept in spectral convolutions
""" | https://github.com/NVIDIA/modulus/blob/e6d7b02fb19ab9cdb3138de228ca3d6f0c99e7d1/modulus/models/fno/fno.py#L463-L484 | e6d7b02fb19ab9cdb3138de228ca3d6f0c99e7d1 |
modulus | github_2023 | NVIDIA | python | is_ignored | def is_ignored(path, working_path, ignore_patterns):
"""
Check if the path needs to be ignored
"""
# Get the git root path to stop the search
git_root_path = Path(__file__) / Path(working_path)
git_root_path = git_root_path.resolve()
for pattern in ignore_patterns:
normalized_patter... | """
Check if the path needs to be ignored
""" | https://github.com/NVIDIA/modulus/blob/e6d7b02fb19ab9cdb3138de228ca3d6f0c99e7d1/test/ci_tests/header_check.py#L42-L74 | e6d7b02fb19ab9cdb3138de228ca3d6f0c99e7d1 |
modulus | github_2023 | NVIDIA | python | test_irfft_ort_op | @check_ort_version()
@pytest.mark.parametrize("dft_dim", [-1, 1])
def test_irfft_ort_op(
test_data: Tensor, norm: str, dft_dim: int, rtol: float = 1e-5, atol: float = 1e-5
):
"""Test IRFFT onnx runtime operation is consistent with torch irfft"""
x = test_data.transpose(-1, dft_dim)
x = fft.rfft(x, dim=d... | """Test IRFFT onnx runtime operation is consistent with torch irfft""" | https://github.com/NVIDIA/modulus/blob/e6d7b02fb19ab9cdb3138de228ca3d6f0c99e7d1/test/deploy/test_onnx_fft.py#L168-L190 | e6d7b02fb19ab9cdb3138de228ca3d6f0c99e7d1 |
safety-gymnasium | github_2023 | PKU-Alignment | python | build_sensor_observation_space | def build_sensor_observation_space(self) -> gymnasium.spaces.Dict:
"""Build observation space for all sensor types.
Returns:
gymnasium.spaces.Dict: The observation space generated by sensors bound with agent.
"""
obs_space_dict = {}
for sensor in self.sensor_conf.se... | """Build observation space for all sensor types.
Returns:
gymnasium.spaces.Dict: The observation space generated by sensors bound with agent.
""" | https://github.com/PKU-Alignment/safety-gymnasium/blob/3b117c1ee896b62cd47a527d201d1117fd36ef3d/safety_gymnasium/tasks/safe_multi_agent/bases/base_agent.py#L345-L429 | 3b117c1ee896b62cd47a527d201d1117fd36ef3d |
DDPM-IP | github_2023 | forever208 | python | update_ema | def update_ema(target_params, source_params, rate=0.99):
"""
Update target parameters to be closer to those of source parameters using
an exponential moving average.
:param target_params: the target parameter sequence.
:param source_params: the source parameter sequence.
:param rate: the EMA ra... | """
Update target parameters to be closer to those of source parameters using
an exponential moving average.
:param target_params: the target parameter sequence.
:param source_params: the source parameter sequence.
:param rate: the EMA rate (closer to 1 means slower).
""" | https://github.com/forever208/DDPM-IP/blob/1f767192e8b60e1694c670672d5adfd8b42256f5/guided_diffusion/nn.py#L55-L65 | 1f767192e8b60e1694c670672d5adfd8b42256f5 |
ControlNet | github_2023 | lllyasviel | python | forward | def forward(self, query_feats, key_feats):
"""Forward function."""
context = super(ObjectAttentionBlock,
self).forward(query_feats, key_feats)
output = self.bottleneck(torch.cat([context, query_feats], dim=1))
if self.query_downsample is not None:
outp... | """Forward function.""" | https://github.com/lllyasviel/ControlNet/blob/ed85cd1e25a5ed592f7d8178495b4483de0331bf/annotator/uniformer/mmseg/models/decode_heads/ocr_head.py#L73-L81 | ed85cd1e25a5ed592f7d8178495b4483de0331bf |
llama-hub | github_2023 | run-llama | python | load_data | def load_data(
self,
state: Optional[IssueState] = IssueState.OPEN,
labelFilters: Optional[List[Tuple[str, FilterType]]] = None,
) -> List[Document]:
"""
Load issues from a repository and converts them to documents.
Each issue is converted to a document by doing the ... | """
Load issues from a repository and converts them to documents.
Each issue is converted to a document by doing the following:
- The text of the document is the concatenation of the title and the body of the issue.
- The title of the document is the title of the issue.
- The d... | https://github.com/run-llama/llama-hub/blob/b476d3bd2c963cad9dfe2944de7d6ce408aac65a/llama_hub/github_repo_issues/base.py#L118-L196 | b476d3bd2c963cad9dfe2944de7d6ce408aac65a |
llama-hub | github_2023 | run-llama | python | read_page | def read_page(self, page_id: str) -> str:
"""Read a page."""
return self._read_block(page_id) | """Read a page.""" | https://github.com/run-llama/llama-hub/blob/b476d3bd2c963cad9dfe2944de7d6ce408aac65a/llama_hub/notion/base.py#L89-L91 | b476d3bd2c963cad9dfe2944de7d6ce408aac65a |
llama-hub | github_2023 | run-llama | python | is_risk_title | def is_risk_title(title: str, filing_type: Optional[str]) -> bool:
"""Checks to see if the title matches the pattern for the risk heading."""
if filing_type in REPORT_TYPES:
return is_10k_risk_title(clean_sec_text(title, lowercase=True))
elif filing_type in S1_TYPES:
return is_s1_risk_title(... | """Checks to see if the title matches the pattern for the risk heading.""" | https://github.com/run-llama/llama-hub/blob/b476d3bd2c963cad9dfe2944de7d6ce408aac65a/llama_hub/sec_filings/prepline_sec_filings/sec_document.py#L359-L365 | b476d3bd2c963cad9dfe2944de7d6ce408aac65a |
MS-AMP | github_2023 | Azure | python | _configure_optimizer | def _configure_optimizer(self, client_optimizer, model_parameters):
"""Config basic optimizer and optimizer.
Args:
client_optimizer (torch.optim.Optimizer or callable): client optimizer.
model_parameters (list): list of model parameters.
"""
if client_optimizer i... | """Config basic optimizer and optimizer.
Args:
client_optimizer (torch.optim.Optimizer or callable): client optimizer.
model_parameters (list): list of model parameters.
""" | https://github.com/Azure/MS-AMP/blob/8de09e00c45ce1ce44dcd0ccf1d4e6e4f4ca04fa/msamp/deepspeed/runtime/engine.py#L63-L124 | 8de09e00c45ce1ce44dcd0ccf1d4e6e4f4ca04fa |
MS-AMP | github_2023 | Azure | python | __getattr__ | def __getattr__(self, name):
"""Get attribute by name.
Args:
name (str): Attribute name.
Returns:
Attribute value.
"""
return self.__dict__.get(name, getattr(self.__dict__['ctx'], name)) | """Get attribute by name.
Args:
name (str): Attribute name.
Returns:
Attribute value.
""" | https://github.com/Azure/MS-AMP/blob/8de09e00c45ce1ce44dcd0ccf1d4e6e4f4ca04fa/msamp/te/modules.py#L156-L165 | 8de09e00c45ce1ce44dcd0ccf1d4e6e4f4ca04fa |
optimum-neuron | github_2023 | huggingface | python | load_safetensors | def load_safetensors(self, state_dict_dir):
"""
Lazily load the safetensors by associating each weight with the filename.
"""
filename = os.path.join(state_dict_dir, _SAFETENSORS_MODEL_FILENAME)
with safe_open(filename, framework="pt") as f:
keys = f.keys()
ke... | """
Lazily load the safetensors by associating each weight with the filename.
""" | https://github.com/huggingface/optimum-neuron/blob/558379f8a1f7f67820ea219323f9af434a6ae2ba/optimum/neuron/backends/hlo/module.py#L174-L182 | 558379f8a1f7f67820ea219323f9af434a6ae2ba |
manta | github_2023 | fischermoseley | python | export_csv | def export_csv(self, path):
"""
Export the capture to a CSV file.
Args:
path (str): Path to the destination file.
Returns:
None
"""
names = [p.name for p in self._probes]
values = [self.get_trace(n) for n in names]
# Transpose l... | """
Export the capture to a CSV file.
Args:
path (str): Path to the destination file.
Returns:
None
""" | https://github.com/fischermoseley/manta/blob/e11d9a8315a7a1c91ab5087955d575fc149da06c/src/manta/logic_analyzer/capture.py#L69-L93 | e11d9a8315a7a1c91ab5087955d575fc149da06c |
vllm | github_2023 | vllm-project | python | test_k_equals_zero | @pytest.mark.parametrize('k', [0])
@pytest.mark.parametrize('batch_size', [1, 2, 32])
@pytest.mark.parametrize("acceptance_sampler_method",
["rejection_sampler", "typical_acceptance_sampler"])
@torch.inference_mode()
def test_k_equals_zero(k: int, batch_size: int,
accepta... | """Verify that the SpecDecodeWorker calls the draft and target workers
when k is zero. This happens during prefill.
""" | https://github.com/vllm-project/vllm/blob/c9e2d644e728e8e93ef2871276ed7a6b39c1d0eb/tests/spec_decode/test_spec_decode_worker.py#L474-L521 | c9e2d644e728e8e93ef2871276ed7a6b39c1d0eb |
python_motion_planning | github_2023 | ai-winter | python | mod2pi | def mod2pi(self, theta: float) -> float:
"""
Perform modulus operation on 2π.
"""
return theta - 2.0 * math.pi * math.floor(theta / math.pi / 2.0) | """
Perform modulus operation on 2π.
""" | https://github.com/ai-winter/python_motion_planning/blob/dc5f45c42488383a488ace21495e70e8129a2b55/python_motion_planning/curve_generation/curve.py#L51-L55 | dc5f45c42488383a488ace21495e70e8129a2b55 |
devine | github_2023 | devine-dl | python | clear | @env.group(name="clear", short_help="Clear an environment directory.", context_settings=context_settings)
def clear() -> None:
"""Clear an environment directory.""" | """Clear an environment directory.""" | https://github.com/devine-dl/devine/blob/09eda168824157851e30003b196f4851298ec3ac/devine/commands/env.py#L66-L68 | 09eda168824157851e30003b196f4851298ec3ac |
REAL-Video-Enhancer | github_2023 | TNTwise | python | checkForNCNN | def checkForNCNN() -> bool:
"""
function that checks if the pytorch backend is available
"""
try:
from rife_ncnn_vulkan_python import Rife
import ncnn
try:
from upscale_ncnn_py import UPSCALE
except Exception:
printAndLog(
"Warning... | """
function that checks if the pytorch backend is available
""" | https://github.com/TNTwise/REAL-Video-Enhancer/blob/46bda804944d050db1413ea2493b15a295e13441/backend/src/utils/Util.py#L270-L289 | 46bda804944d050db1413ea2493b15a295e13441 |
se3_diffusion | github_2023 | jasonkyuyim | python | _to_a3m | def _to_a3m(sequences: Sequence[str]) -> str:
"""Converts sequences to an a3m file."""
names = ["sequence %d" % i for i in range(1, len(sequences) + 1)]
a3m = []
for sequence, name in zip(sequences, names):
a3m.append(u">" + name + u"\n")
a3m.append(sequence + u"\n")
return "".join(a... | """Converts sequences to an a3m file.""" | https://github.com/jasonkyuyim/se3_diffusion/blob/53359d71cfabc819ffaa571abd2cef736c871a5d/openfold/data/tools/kalign.py#L26-L33 | 53359d71cfabc819ffaa571abd2cef736c871a5d |
home-assistant-petkit | github_2023 | RobertD502 | python | async_turn_on | async def async_turn_on(self, **kwargs) -> None:
"""Turn light on."""
if not self.coordinator.client.use_ble_relay:
raise HomeAssistantError(f'A PetKit BLE relay is required to control {self.wf_data.data["name"]}')
if not self.wf_data.group_relay:
raise HomeAssistantErro... | """Turn light on.""" | https://github.com/RobertD502/home-assistant-petkit/blob/a7e5d617678bca56466e3571f72f60dce4aa98bd/custom_components/petkit/switch.py#L171-L191 | a7e5d617678bca56466e3571f72f60dce4aa98bd |
home-assistant-petkit | github_2023 | RobertD502 | python | ManualFeed.native_value | @property
def native_value(self) -> str:
"""Always reset to 0,0"""
return "0,0" | """Always reset to 0,0""" | https://github.com/RobertD502/home-assistant-petkit/blob/a7e5d617678bca56466e3571f72f60dce4aa98bd/custom_components/petkit/text.py#L114-L118 | a7e5d617678bca56466e3571f72f60dce4aa98bd |
Online-HD-Map-Construction-CVPR2023 | github_2023 | Tsinghua-MARS-Lab | python | _init_branch | def _init_branch(self,):
"""Initialize classification branch and regression branch of head."""
fc_cls = Linear(self.embed_dims*self.bbox_size, self.cls_out_channels)
# fc_cls = Linear(self.embed_dims, self.cls_out_channels)
reg_branch = []
for _ in range(self.num_reg_fcs):
... | """Initialize classification branch and regression branch of head.""" | https://github.com/Tsinghua-MARS-Lab/Online-HD-Map-Construction-CVPR2023/blob/775b203aeab56be4248fb5495be452fa404bd29d/src/models/heads/map_element_detector.py#L124-L162 | 775b203aeab56be4248fb5495be452fa404bd29d |
YOWOv2 | github_2023 | yjh0410 | python | _remove_invalid_boxes | def _remove_invalid_boxes(
self,
detected_boxes,
detected_scores,
detected_class_labels,
detected_masks=None,
):
"""Removes entries with invalid boxes.
A box is invalid if either its xmax is smaller than its xmin, or its ymax
is smaller than its ymin.
Ar... | """Removes entries with invalid boxes.
A box is invalid if either its xmax is smaller than its xmin, or its ymax
is smaller than its ymin.
Args:
detected_boxes: A float numpy array of size [num_boxes, 4] containing box
coordinates in [ymin, xmin, ymax, xmax] format.
detected_scores: A ... | https://github.com/yjh0410/YOWOv2/blob/9e8d23c11ad26ef5e6cfc01e3f4f1112dee634bf/evaluator/ava_evaluation/per_image_evaluation.py#L411-L453 | 9e8d23c11ad26ef5e6cfc01e3f4f1112dee634bf |
grove | github_2023 | hashicorp-forge | python | finalize | def finalize(self):
"""Performs a final set of operations after logs have been saved."""
return | """Performs a final set of operations after logs have been saved.""" | https://github.com/hashicorp-forge/grove/blob/a2b4bea0e15ef1a2a80bf092f4a7cb835901ecbd/grove/processors/__init__.py#L54-L57 | a2b4bea0e15ef1a2a80bf092f4a7cb835901ecbd |
CEDNet | github_2023 | zhanggang001 | python | center_of_mass | def center_of_mass(mask, esp=1e-6):
"""Calculate the centroid coordinates of the mask.
Args:
mask (Tensor): The mask to be calculated, shape (h, w).
esp (float): Avoid dividing by zero. Default: 1e-6.
Returns:
tuple[Tensor]: the coordinates of the center point of the mask.
... | """Calculate the centroid coordinates of the mask.
Args:
mask (Tensor): The mask to be calculated, shape (h, w).
esp (float): Avoid dividing by zero. Default: 1e-6.
Returns:
tuple[Tensor]: the coordinates of the center point of the mask.
- center_h (Tensor): the center poi... | https://github.com/zhanggang001/CEDNet/blob/305d6371db427bcf3c93b5f85a2609d05e9eb4f1/ced-mmdet/mmdet/core/utils/misc.py#L168-L187 | 305d6371db427bcf3c93b5f85a2609d05e9eb4f1 |
CEDNet | github_2023 | zhanggang001 | python | _init_predictor | def _init_predictor(self):
"""Initialize predictor layers of the head."""
self.conv_cls = nn.Conv2d(
self.feat_channels, self.cls_out_channels, 3, padding=1)
self.conv_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1) | """Initialize predictor layers of the head.""" | https://github.com/zhanggang001/CEDNet/blob/305d6371db427bcf3c93b5f85a2609d05e9eb4f1/ced-mmdet/mmdet/models/dense_heads/anchor_free_head.py#L153-L157 | 305d6371db427bcf3c93b5f85a2609d05e9eb4f1 |
not1mm | github_2023 | mbridak | python | cty_lookup | def cty_lookup(self, callsign: str) -> list:
"""Lookup callsign in cty.dat file.
Parameters
----------
callsign : str
callsign to lookup
Returns
-------
return : list
list of dicts containing the callsign and the station.
"""
call... | """Lookup callsign in cty.dat file.
Parameters
----------
callsign : str
callsign to lookup
Returns
-------
return : list
list of dicts containing the callsign and the station.
""" | https://github.com/mbridak/not1mm/blob/c7dbdaf4e509a865a1bf64bc037e0efac6b4e200/not1mm/__main__.py#L1972-L1997 | c7dbdaf4e509a865a1bf64bc037e0efac6b4e200 |
not1mm | github_2023 | mbridak | python | change_mode | def change_mode(self, mode: str, intended_freq=None) -> None:
"""
Change mode to given mode.
Send the new mode to the rig control.
Set the band indicator.
Set the window title.
Clear the inputs.
Read the CW macros.
Parameters
----------
mo... | """
Change mode to given mode.
Send the new mode to the rig control.
Set the band indicator.
Set the window title.
Clear the inputs.
Read the CW macros.
Parameters
----------
mode : str
Mode to change to.
Returns
-------
... | https://github.com/mbridak/not1mm/blob/c7dbdaf4e509a865a1bf64bc037e0efac6b4e200/not1mm/__main__.py#L3433-L3507 | c7dbdaf4e509a865a1bf64bc037e0efac6b4e200 |
sd-webui-controlnet | github_2023 | Mikubill | python | preprocess | def preprocess(
img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256)
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Do preprocessing for DWPose model inference.
Args:
img (np.ndarray): Input image in shape.
input_size (tuple): Input image size in shape (w, h).
Return... | """Do preprocessing for DWPose model inference.
Args:
img (np.ndarray): Input image in shape.
input_size (tuple): Input image size in shape (w, h).
Returns:
tuple:
- resized_img (np.ndarray): Preprocessed image.
- center (np.ndarray): Center of image.
- scale (n... | https://github.com/Mikubill/sd-webui-controlnet/blob/56cec5b2958edf3b1807b7e7b2b1b5186dbd2f81/annotator/openpose/cv_ox_pose.py#L6-L48 | 56cec5b2958edf3b1807b7e7b2b1b5186dbd2f81 |
sd-webui-controlnet | github_2023 | Mikubill | python | __init__ | def __init__(self):
"""
Init method.
"""
super().__init__() | """
Init method.
""" | https://github.com/Mikubill/sd-webui-controlnet/blob/56cec5b2958edf3b1807b7e7b2b1b5186dbd2f81/annotator/teed/Xsmish.py#L33-L37 | 56cec5b2958edf3b1807b7e7b2b1b5186dbd2f81 |
Time-Series-Library | github_2023 | thuml | python | forward | def forward(self, coeffs):
"""
Args:
coeffs (yl, yh): tuple of lowpass and bandpass coefficients, should
match the format returned by DWT1DForward.
Returns:
Reconstructed input of shape :math:`(N, C_{in}, L_{in})`
Note:
Can have None fo... | """
Args:
coeffs (yl, yh): tuple of lowpass and bandpass coefficients, should
match the format returned by DWT1DForward.
Returns:
Reconstructed input of shape :math:`(N, C_{in}, L_{in})`
Note:
Can have None for any of the highpass scales and wi... | https://github.com/thuml/Time-Series-Library/blob/4ddf869d999424b037d451a4757e36813d66a13b/layers/DWT_Decomposition.py#L224-L249 | 4ddf869d999424b037d451a4757e36813d66a13b |
tiktok-uploader | github_2023 | wkaisertexas | python | get_auth_args | def get_auth_args():
"""
Generates a parser which is used to get all of the authentication information
"""
parser = ArgumentParser(
description='TikTok Auth is a program which can log you into multiple accounts sequentially'
)
# authentication arguments
parser.add_argument('-o', '--... | """
Generates a parser which is used to get all of the authentication information
""" | https://github.com/wkaisertexas/tiktok-uploader/blob/59dc97852b70a2f13be6a48c6046f089baa1054e/src/tiktok_uploader/cli.py#L112-L129 | 59dc97852b70a2f13be6a48c6046f089baa1054e |
nastools | github_2023 | mhdpdp | python | get_transfer_statistics | def get_transfer_statistics(self, data=None):
"""
查询转移历史统计数据
"""
MovieChartLabels = []
MovieNums = []
TvChartData = {}
TvNums = []
AnimeNums = []
for statistic in self.dbhelper.get_transfer_statistics():
if statistic[0] == "电影":
... | """
查询转移历史统计数据
""" | https://github.com/mhdpdp/nastools/blob/b9fa7cad74649fa4cd70e8bde378aa02a2d27c29/web/action.py#L3396-L3428 | b9fa7cad74649fa4cd70e8bde378aa02a2d27c29 |
nastools | github_2023 | mhdpdp | python | FilterRuleUpdate.post | @filterrule.doc(parser=parser)
def post(self):
"""
新增/修改规则
"""
return WebAction().api_action(cmd='add_filterrule', data=self.parser.parse_args()) | """
新增/修改规则
""" | https://github.com/mhdpdp/nastools/blob/b9fa7cad74649fa4cd70e8bde378aa02a2d27c29/web/apiv1.py#L1803-L1808 | b9fa7cad74649fa4cd70e8bde378aa02a2d27c29 |
PyMammotion | github_2023 | mikey0000 | python | DeviceType.is_luba1 | @staticmethod
def is_luba1(device_name: str, product_key: str = ""):
"""Check if the given device is of type LUBA.
This function determines if the device specified by 'device_name' is of
type LUBA. If 'product_key' is provided, it is used to further identify
the device type.
... | """Check if the given device is of type LUBA.
This function determines if the device specified by 'device_name' is of
type LUBA. If 'product_key' is provided, it is used to further identify
the device type.
Args:
device_name (str): The name of the device.
produc... | https://github.com/mikey0000/PyMammotion/blob/2c5e100b8cc50d393ff5ec460c612e1da5ec4935/pymammotion/utility/device_type.py#L127-L149 | 2c5e100b8cc50d393ff5ec460c612e1da5ec4935 |
GHOST | github_2023 | dvl-tum | python | update | def update(oids, hids, dists, indices, events, m):
"""
tracks : my results of shape {tr_id: {'id', 'im_index', 'max_iou', 'bbox'}
num_frames : number of frames
"""
import pandas as pd
asso = dict()
hypo = dict()
cols = ['Type', 'id', 'frame', 'tr_id', 'iou', 'w', 'h']
events ... | """
tracks : my results of shape {tr_id: {'id', 'im_index', 'max_iou', 'bbox'}
num_frames : number of frames
""" | https://github.com/dvl-tum/GHOST/blob/755a5dacfcf4dd122a4cac73061b24e9c84f3c19/src/utils.py#L119-L294 | 755a5dacfcf4dd122a4cac73061b24e9c84f3c19 |
safari | github_2023 | HazyResearch | python | checkpoint_filter_fn | def checkpoint_filter_fn(state_dict, model):
""" convert patch embedding weight from manual patchify + linear proj to conv"""
out_dict = {}
if 'model' in state_dict:
# For deit models
state_dict = state_dict['model']
for k, v in state_dict.items():
if 'patch_embed.proj.weight' in... | """ convert patch embedding weight from manual patchify + linear proj to conv""" | https://github.com/HazyResearch/safari/blob/02220c69d247e5473616cd053a443ad99fd2559b/src/models/baselines/vit_all.py#L341-L357 | 02220c69d247e5473616cd053a443ad99fd2559b |
safari | github_2023 | HazyResearch | python | setup_filters | def setup_filters(self, filter_cls, filter_args):
"Initializes the explicit and implicit filters"
assert self.order >= 2, f'Order must be at least 2, (got {self.order})'
total_width = self.d_model * self.inner_factor * (self.order + 1)
self.short_filter = nn.Conv1d(
... | "Initializes the explicit and implicit filters" | https://github.com/HazyResearch/safari/blob/02220c69d247e5473616cd053a443ad99fd2559b/src/models/sequence/hyena.py#L280-L303 | 02220c69d247e5473616cd053a443ad99fd2559b |
VAD | github_2023 | hustvl | python | custom_weight_dir_reduce_loss | @mmcv.jit(derivate=True, coderize=True)
def custom_weight_dir_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): num_sample, num_dir
weight (Tensor): Element-wise weights.
reduction (str): Same as built-i... | """Apply element-wise weight and reduce loss.
Args:
loss (Tensor): num_sample, num_dir
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Average factor when computing the mean of losses.
Returns:
Tensor: Proc... | https://github.com/hustvl/VAD/blob/70bb364aa3f33316960da06053c0d168628fb15f/projects/mmdet3d_plugin/VAD/utils/CD_loss.py#L33-L64 | 70bb364aa3f33316960da06053c0d168628fb15f |
unicom | github_2023 | deepglint | python | add_model_config | def add_model_config(path):
"""add model config path or file and update registry"""
if not isinstance(path, Path):
path = Path(path)
_MODEL_CONFIG_PATHS.append(path)
_rescan_model_configs() | """add model config path or file and update registry""" | https://github.com/deepglint/unicom/blob/7e503c908a1b9deb6cd2c2d6287500b95233884f/downstream/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/factory.py#L62-L67 | 7e503c908a1b9deb6cd2c2d6287500b95233884f |
nas-tools | github_2023 | receyuki | python | WebAction.set_config_value | @staticmethod
def set_config_value(cfg, cfg_key, cfg_value):
"""
根据Key设置配置值
"""
# 密码
if cfg_key == "app.login_password":
if cfg_value and not cfg_value.startswith("[hash]"):
cfg['app']['login_password'] = "[hash]%s" % generate_password_hash(
... | """
根据Key设置配置值
""" | https://github.com/receyuki/nas-tools/blob/e3a43d4f0896db49de02e9a9201ef2e5877af56f/web/action.py#L299-L353 | e3a43d4f0896db49de02e9a9201ef2e5877af56f |
ChatFred | github_2023 | chrislemke | python | post | async def post(self) -> "MultiDictProxy[Union[str, bytes, FileField]]":
"""Return POST parameters."""
if self._post is not None:
return self._post
if self._method not in self.POST_METHODS:
self._post = MultiDictProxy(MultiDict())
return self._post
con... | """Return POST parameters.""" | https://github.com/chrislemke/ChatFred/blob/4356986c2cc3eaf57b5329774c9e593c01554789/workflow/src/libs/aiohttp/web_request.py#L677-L771 | 4356986c2cc3eaf57b5329774c9e593c01554789 |
ChatFred | github_2023 | chrislemke | python | add_put | def add_put(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method PUT."""
return self.add_route(hdrs.METH_PUT, path, handler, **kwargs) | """Shortcut for add_route with method PUT.""" | https://github.com/chrislemke/ChatFred/blob/4356986c2cc3eaf57b5329774c9e593c01554789/workflow/src/libs/aiohttp/web_urldispatcher.py#L1168-L1170 | 4356986c2cc3eaf57b5329774c9e593c01554789 |
ChatFred | github_2023 | chrislemke | python | create_memory_object_stream | def create_memory_object_stream(
max_buffer_size: float = 0, item_type: type[T_Item] | None = None
) -> tuple[MemoryObjectSendStream[Any], MemoryObjectReceiveStream[Any]]:
"""
Create a memory object stream.
:param max_buffer_size: number of items held in the buffer until ``send()`` starts blocking
... | """
Create a memory object stream.
:param max_buffer_size: number of items held in the buffer until ``send()`` starts blocking
:param item_type: type of item, for marking the streams with the right generic type for
static typing (not used at run time)
:return: a tuple of (send stream, receive s... | https://github.com/chrislemke/ChatFred/blob/4356986c2cc3eaf57b5329774c9e593c01554789/workflow/src/libs/anyio/_core/_streams.py#L29-L47 | 4356986c2cc3eaf57b5329774c9e593c01554789 |
ChatFred | github_2023 | chrislemke | python | _colors_to_code | def _colors_to_code(self, fg_color: str, bg_color: str) -> Iterable[str]:
"""
Return a tuple with the vt100 values that represent this color.
"""
# When requesting ANSI colors only, and both fg/bg color were converted
# to ANSI, ensure that the foreground and background color ar... | """
Return a tuple with the vt100 values that represent this color.
""" | https://github.com/chrislemke/ChatFred/blob/4356986c2cc3eaf57b5329774c9e593c01554789/workflow/src/libs/prompt_toolkit/output/vt100.py#L319-L374 | 4356986c2cc3eaf57b5329774c9e593c01554789 |
ChatFred | github_2023 | chrislemke | python | extract_from_urllib3 | def extract_from_urllib3():
"""
Undo monkey-patching by :func:`inject_into_urllib3`.
"""
util.SSLContext = orig_util_SSLContext
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_SNI
util.ssl_.HAS_SNI = orig_util_HAS_SNI
util.IS_SECURETRANSPORT = False
util.ssl_... | """
Undo monkey-patching by :func:`inject_into_urllib3`.
""" | https://github.com/chrislemke/ChatFred/blob/4356986c2cc3eaf57b5329774c9e593c01554789/workflow/src/libs/urllib3/contrib/securetransport.py#L201-L210 | 4356986c2cc3eaf57b5329774c9e593c01554789 |
ChatFred | github_2023 | chrislemke | python | Url.hostname | @property
def hostname(self):
"""For backwards-compatibility with urlparse. We're nice like that."""
return self.host | """For backwards-compatibility with urlparse. We're nice like that.""" | https://github.com/chrislemke/ChatFred/blob/4356986c2cc3eaf57b5329774c9e593c01554789/workflow/src/libs/urllib3/util/url.py#L109-L112 | 4356986c2cc3eaf57b5329774c9e593c01554789 |
catalyst | github_2023 | PennyLaneAI | python | test_decomposition_nested | def test_decomposition_nested(self):
"""Tests decompositions of nested controlled operations"""
ctrl_op = C_ctrl(C_ctrl(lambda: qml.RZ(0.123, wires=0), control=1), control=2)()
expected = [
qml.ops.Controlled(qml.RZ(0.123, wires=0), control_wires=[1, 2]),
]
assert ct... | """Tests decompositions of nested controlled operations""" | https://github.com/PennyLaneAI/catalyst/blob/729d468ad1bec692242c6b20560a2b9922debb31/frontend/test/pytest/test_quantum_control.py#L1654-L1661 | 729d468ad1bec692242c6b20560a2b9922debb31 |
catalyst | github_2023 | PennyLaneAI | python | test_pattern_matching_optimization | @pytest.mark.xfail(
reason="QJIT fails with ValueError: Eagerly computing the adjoint (lazy=False) is only supported on single operators."
)
def test_pattern_matching_optimization(backend):
"""Test pattern_matching_optimization"""
def qnode_builder(device_name):
"""Builder"""
ops = [qml.S(... | """Test pattern_matching_optimization""" | https://github.com/PennyLaneAI/catalyst/blob/729d468ad1bec692242c6b20560a2b9922debb31/frontend/test/pytest/test_transform.py#L1340-L1379 | 729d468ad1bec692242c6b20560a2b9922debb31 |
ControlLoRA | github_2023 | HighCWu | python | forward | def forward(self,
query,
key,
value,
query_pos=None,
key_pos=None,
attn_masks=None,
query_key_padding_mask=None,
key_padding_mask=None,
**kwargs):
"""Forward function f... | """Forward function for `TransformerCoder`.
Args:
query (Tensor): Input query with shape
`(num_queries, bs, embed_dims)`.
key (Tensor): The key tensor with shape
`(num_keys, bs, embed_dims)`.
value (Tensor): The value tensor with shape
... | https://github.com/HighCWu/ControlLoRA/blob/a6891215fc587af326ab1234718491741a5c2015/annotator/uniformer/mmcv/cnn/bricks/transformer.py#L549-L595 | a6891215fc587af326ab1234718491741a5c2015 |
axlearn | github_2023 | apple | python | CausalLmModelBuilder.v1_from_args | @classmethod
def v1_from_args(
cls, vocab_size: int, *, num_layers: int, hidden_dim: int, num_heads: int
) -> CausalLM:
"""Build a v1 Causal LM.
Args:
vocab_size: The vocabulary size.
num_layers: The number of transformer layers.
hidden_dim: The model... | """Build a v1 Causal LM.
Args:
vocab_size: The vocabulary size.
num_layers: The number of transformer layers.
hidden_dim: The model hidden dimension.
num_heads: THe number of attention heads.
Returns:
Initialized model.
""" | https://github.com/apple/axlearn/blob/b9551871eae1b887a55b1e7d682cc6db7a51bf1e/axlearn/common/adapter_torch.py#L2061-L2108 | b9551871eae1b887a55b1e7d682cc6db7a51bf1e |
axlearn | github_2023 | apple | python | __init__ | def __init__(
self,
*,
input_size: tuple[int, int],
num_masking_patches: int,
num_attempts: int = 10,
min_mask_patches: int = 16,
min_aspect: float = 0.3,
max_mask_patches: Optional[int] = None,
max_aspect: Optional[float] = None,
):
""... | """Initializes MaskingGenerator.
Args:
input_size: an int tuple that represents (height, width) of the patchified target.
num_masking_patches: the number of patches to be masked.
num_attempts: the max number of attempts for one mask generation trial.
min_mask_pat... | https://github.com/apple/axlearn/blob/b9551871eae1b887a55b1e7d682cc6db7a51bf1e/axlearn/vision/mask_generator.py#L30-L71 | b9551871eae1b887a55b1e7d682cc6db7a51bf1e |
axlearn | github_2023 | apple | python | MobileNets.endpoints_dims | @property
def endpoints_dims(self) -> dict[str, int]:
"""A dict of {endpoint: dim} specifies dimension of intermediate representations."""
return self._endpoints_dims | """A dict of {endpoint: dim} specifies dimension of intermediate representations.""" | https://github.com/apple/axlearn/blob/b9551871eae1b887a55b1e7d682cc6db7a51bf1e/axlearn/vision/mobilenets.py#L514-L517 | b9551871eae1b887a55b1e7d682cc6db7a51bf1e |
rl4co | github_2023 | ai4co | python | spatial_encoding | def spatial_encoding(td: TensorDict):
"""We use a spatial encoing as proposed in GraphFormer (https://arxiv.org/abs/2106.05234)
The spatial encoding in GraphFormer determines the distance of the shortest path between and
nodes i and j and uses a special value for node pairs that cannot be connected at all.
... | """We use a spatial encoing as proposed in GraphFormer (https://arxiv.org/abs/2106.05234)
The spatial encoding in GraphFormer determines the distance of the shortest path between and
nodes i and j and uses a special value for node pairs that cannot be connected at all.
For any two operations i<j of the same... | https://github.com/ai4co/rl4co/blob/643ef99d118ce535e615a9441838782a2decf412/rl4co/envs/scheduling/fjsp/utils.py#L157-L193 | 643ef99d118ce535e615a9441838782a2decf412 |
SubpopBench | github_2023 | YyzHarry | python | _create_examples | def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text_a = line[3]
label = line[1]
examples.append(
Inp... | """Creates examples for the training and dev sets.""" | https://github.com/YyzHarry/SubpopBench/blob/4d3dbbe21029666ef19d040e110ec22908640c5b/utils_glue.py#L183-L195 | 4d3dbbe21029666ef19d040e110ec22908640c5b |
semantic-kernel | github_2023 | microsoft | python | _get_database_proxy | async def _get_database_proxy(self, **kwargs) -> DatabaseProxy:
"""Gets the database proxy."""
try:
if await self._does_database_exist():
return self.cosmos_client.get_database_client(self.database_name)
if self.create_database:
return await self.... | """Gets the database proxy.""" | https://github.com/microsoft/semantic-kernel/blob/cd84e877980187e62d86bb5bc6086d264e62ee83/python/semantic_kernel/connectors/memory/azure_cosmos_db/azure_cosmos_db_no_sql_base.py#L101-L111 | cd84e877980187e62d86bb5bc6086d264e62ee83 |
semantic-kernel | github_2023 | microsoft | python | _get_underlying_type | def _get_underlying_type(annotation: Any) -> Any:
"""Get the underlying type of the annotation."""
if isinstance(annotation, types.UnionType):
return _get_non_none_type(annotation.__args__)
if hasattr(annotation, "__origin__"):
if annotation.__origin__ is Union:
return _get_non_... | """Get the underlying type of the annotation.""" | https://github.com/microsoft/semantic-kernel/blob/cd84e877980187e62d86bb5bc6086d264e62ee83/python/semantic_kernel/functions/kernel_function_decorator.py#L88-L102 | cd84e877980187e62d86bb5bc6086d264e62ee83 |
semantic-kernel | github_2023 | microsoft | python | get_collections | async def get_collections(self) -> list[str]:
"""Nullifies behavior of SemanticTextMemoryBase get_collections."""
return [] | """Nullifies behavior of SemanticTextMemoryBase get_collections.""" | https://github.com/microsoft/semantic-kernel/blob/cd84e877980187e62d86bb5bc6086d264e62ee83/python/semantic_kernel/memory/null_memory.py#L49-L51 | cd84e877980187e62d86bb5bc6086d264e62ee83 |
semantic-kernel | github_2023 | microsoft | python | azure_cognitive_search_memory_store | @pytest.fixture
def azure_cognitive_search_memory_store(azure_ai_search_unit_test_env):
"""Fixture to instantiate AzureCognitiveSearchMemoryStore with basic configuration."""
return AzureCognitiveSearchMemoryStore(
1536, "https://test.search.windows.net", azure_credentials=AzureKeyCredential("test_key")... | """Fixture to instantiate AzureCognitiveSearchMemoryStore with basic configuration.""" | https://github.com/microsoft/semantic-kernel/blob/cd84e877980187e62d86bb5bc6086d264e62ee83/python/tests/unit/memory/test_azure_cognitive_search_memory_store_unit_tests.py#L13-L18 | cd84e877980187e62d86bb5bc6086d264e62ee83 |
StableDiffusionReconstruction | github_2023 | yu-takagi | python | forward | def forward(self, *xs):
"""Forward pass.
Returns:
tensor: output
"""
output = xs[0]
if len(xs) == 2:
res = self.resConfUnit1(xs[1])
output = self.skip_add.add(output, res)
# output += res
output = self.resConfUnit2(output... | """Forward pass.
Returns:
tensor: output
""" | https://github.com/yu-takagi/StableDiffusionReconstruction/blob/e187d4b3db1d647ee3e1b4256a2068ffd15df683/codes/diffusion_sd2/stablediffusion/ldm/modules/midas/midas/blocks.py#L320-L341 | e187d4b3db1d647ee3e1b4256a2068ffd15df683 |
SillyTavern-Extras | github_2023 | SillyTavern | python | posedict_to_pose | def posedict_to_pose(posedict: Dict[str, float]) -> List[float]:
"""Convert a posedict (from an emotion JSON) into a list of morph values (in the order the models expect them)."""
# sanity check
unrecognized_keys = set(posedict.keys()) - set(posedict_keys)
if unrecognized_keys:
logger.warning(f"... | """Convert a posedict (from an emotion JSON) into a list of morph values (in the order the models expect them).""" | https://github.com/SillyTavern/SillyTavern-Extras/blob/fdc1ec04b632b1d871cc0ad3a9aa132e985fc398/talkinghead/tha3/app/util.py#L118-L129 | fdc1ec04b632b1d871cc0ad3a9aa132e985fc398 |
BiFormer | github_2023 | rayleizhu | python | to_tensor | def to_tensor(self, dtype, device):
"""See :func:`BaseInstanceMasks.to_tensor`."""
if len(self.masks) == 0:
return torch.empty((0, self.height, self.width),
dtype=dtype,
device=device)
ndarray_masks = self.to_ndarray()
... | """See :func:`BaseInstanceMasks.to_tensor`.""" | https://github.com/rayleizhu/BiFormer/blob/1697bbbeafb8680524898f1dcaac10defd0604be/object_detection/mmdet/core/mask/structures.py#L881-L888 | 1697bbbeafb8680524898f1dcaac10defd0604be |
BiFormer | github_2023 | rayleizhu | python | __call__ | def __call__(self, results):
"""Call function to load proposals from file.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded proposal annotations.
"""
proposals = results['proposals']
if p... | """Call function to load proposals from file.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded proposal annotations.
""" | https://github.com/rayleizhu/BiFormer/blob/1697bbbeafb8680524898f1dcaac10defd0604be/object_detection/mmdet/datasets/pipelines/loading.py#L401-L425 | 1697bbbeafb8680524898f1dcaac10defd0604be |
BiFormer | github_2023 | rayleizhu | python | forward | def forward(self, x):
"""Forward function."""
if self.num_branches == 1:
return [self.branches[0](x[0])]
for i in range(self.num_branches):
x[i] = self.branches[i](x[i])
x_fuse = []
for i in range(len(self.fuse_layers)):
y = 0
for... | """Forward function.""" | https://github.com/rayleizhu/BiFormer/blob/1697bbbeafb8680524898f1dcaac10defd0604be/object_detection/mmdet/models/backbones/hrnet.py#L177-L194 | 1697bbbeafb8680524898f1dcaac10defd0604be |
BiFormer | github_2023 | rayleizhu | python | varifocal_loss | @mmcv.jit(derivate=True, coderize=True)
def varifocal_loss(pred,
target,
weight=None,
alpha=0.75,
gamma=2.0,
iou_weighted=True,
reduction='mean',
avg_factor=None):
"""`Varifocal Loss ... | """`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_
Args:
pred (torch.Tensor): The prediction with shape (N, C), C is the
number of classes
target (torch.Tensor): The learning target of the iou-aware
classification score with shape (N, C), C is the number of classes.
... | https://github.com/rayleizhu/BiFormer/blob/1697bbbeafb8680524898f1dcaac10defd0604be/object_detection/mmdet/models/losses/varifocal_loss.py#L9-L55 | 1697bbbeafb8680524898f1dcaac10defd0604be |
PegasusSimulator | github_2023 | PegasusSimulator | python | PeopleManager.get_people_manager | @staticmethod
def get_people_manager():
"""
Method that returns the current people manager.
"""
return PeopleManager() | """
Method that returns the current people manager.
""" | https://github.com/PegasusSimulator/PegasusSimulator/blob/31367ff57d2c44eb39d8fc7fced5044a24a930eb/extensions/pegasus.simulator/pegasus/simulator/logic/people_manager.py#L59-L64 | 31367ff57d2c44eb39d8fc7fced5044a24a930eb |
foundry-dev-tools | github_2023 | emdgroup | python | _convert_old_conf | def _convert_old_conf(console: Console, path: Path) -> str:
"""Reads old config file and converts it to the v2 toml."""
cp = ConfigParser()
cp.read_string(path.read_text())
if not cp.has_section("default"):
console.print(f"The config file {path!s} does not contain any configuration, nothing to m... | """Reads old config file and converts it to the v2 toml.""" | https://github.com/emdgroup/foundry-dev-tools/blob/605e8c1d810dc67f45cefad7edc3f368f39b0d2c/libs/foundry-dev-tools/src/foundry_dev_tools/cli/config.py#L180-L194 | 605e8c1d810dc67f45cefad7edc3f368f39b0d2c |
mmrotate-dcfl | github_2023 | Chasel-Tsui | python | _resize_seg | def _resize_seg(self, results):
"""Resize semantic segmentation map with ``results['scale']``."""
for key in results.get('seg_fields', []):
if self.keep_ratio:
gt_seg = mmcv.imrescale(
results[key],
results['scale'],
... | """Resize semantic segmentation map with ``results['scale']``.""" | https://github.com/Chasel-Tsui/mmrotate-dcfl/blob/d60ca27234a3276a4ca714b5ad616366a4bbdd9a/mmdet/datasets/pipelines/transforms.py#L268-L283 | d60ca27234a3276a4ca714b5ad616366a4bbdd9a |
mmrotate-dcfl | github_2023 | Chasel-Tsui | python | simple_test | def simple_test(self, img, img_metas, rescale=False):
"""Test function without test time augmentation.
Args:
imgs (list[torch.Tensor]): List of multiple images
img_metas (list[dict]): List of image information.
rescale (bool, optional): Whether to rescale the results... | """Test function without test time augmentation.
Args:
imgs (list[torch.Tensor]): List of multiple images
img_metas (list[dict]): List of image information.
rescale (bool, optional): Whether to rescale the results.
Defaults to False.
Returns:
... | https://github.com/Chasel-Tsui/mmrotate-dcfl/blob/d60ca27234a3276a4ca714b5ad616366a4bbdd9a/mmdet/models/detectors/rpn.py#L91-L115 | d60ca27234a3276a4ca714b5ad616366a4bbdd9a |
nas-tools | github_2023 | linyuan0213 | python | WebAction.__get_site | @staticmethod
def __get_site(data):
"""
查询单个站点信息
"""
tid = data.get("id")
site_free = False
site_2xfree = False
site_hr = False
if tid:
ret = Sites().get_sites(siteid=tid)
if ret.get("signurl"):
site_attr = SiteC... | """
查询单个站点信息
""" | https://github.com/linyuan0213/nas-tools/blob/0badded472a89b9171abba049ea05bd6f3611364/web/action.py#L1153-L1174 | 0badded472a89b9171abba049ea05bd6f3611364 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.