complexity int64 1 139 | fun_name stringlengths 1 80 | code stringlengths 101 62.2k | commit_id stringlengths 40 40 | ast_errors stringlengths 0 3.11k | ast_levels int64 6 36 | file_name stringlengths 5 79 | n_ast_nodes int64 17 19.2k | commit_message stringlengths 3 15.3k | d_id int64 12 121k | n_ast_errors int64 0 9 | n_whitespaces int64 4 10.8k | token_counts int64 5 3.06k | vocab_size int64 4 1.11k | id int64 20 338k | n_words int64 4 4.82k | repo stringlengths 3 22 | n_identifiers int64 2 176 | path stringlengths 7 134 | language stringclasses 1
value | nloc int64 1 413 | documentation dict | url stringlengths 31 59 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9 | get_snuba_column_name | def get_snuba_column_name(name, dataset=Dataset.Events):
no_conversion = {"group_id", "group_ids", "project_id", "start", "end"}
if name in no_conversion:
return name
if not name or name.startswith("tags[") or QUOTED_LITERAL_RE.match(name):
return name
measurement_name = get_meas... | 1bcb129d69a6c4e481b950ebc5871e9c118db74f | 11 | snuba.py | 200 | perf(issue-search): optimize querying on perf issues by using hasAny on transaction.group_id (#41685)
Special optimization for searching on transactions for performance
issues by doing a `hasAny` check instead of arrayJoining `group_ids`
column and applying a filter after.
before query:
```
SELECT (arrayJoin(... | 18,492 | 0 | 121 | 110 | 37 | 89,031 | 56 | sentry | 16 | src/sentry/utils/snuba.py | Python | 15 | {
"docstring": "\n Get corresponding Snuba column name from Sentry snuba map, if not found\n the column is assumed to be a tag. If name is falsy or name is a quoted literal\n (e.g. \"'name'\"), leave unchanged.\n ",
"language": "en",
"n_whitespaces": 47,
"n_words": 34,
"vocab_size": 28
} | https://github.com/getsentry/sentry.git | |
1 | test_skip_noarchive_withtext | def test_skip_noarchive_withtext(self):
parser = RasterisedDocumentParser(None)
parser.parse(
os.path.join(self.SAMPLE_FILES, "multi-page-digital.pdf"),
"application/pdf",
)
self.assertIsNone(parser.archive_path)
self.assertContainsStrings(
... | b3b2519bf03185aa12028fa68d3b8f8860555e6e | 11 | test_parser.py | 109 | Fixes the creation of an archive file, even if noarchive was specified | 117,019 | 0 | 113 | 63 | 18 | 319,924 | 20 | paperless-ngx | 14 | src/paperless_tesseract/tests/test_parser.py | Python | 11 | {
"docstring": "\n GIVEN:\n - File with existing text layer\n - OCR mode set to skip_noarchive\n WHEN:\n - Document is parsed\n THEN:\n - Text from images is extracted\n - No archive file is created\n ",
"language": "en",
"n_whites... | https://github.com/paperless-ngx/paperless-ngx.git | |
1 | test_createcachetable_with_table_argument | def test_createcachetable_with_table_argument(self):
self.drop_table()
out = io.StringIO()
management.call_command(
"createcachetable",
"test cache table",
verbosity=2,
stdout=out,
)
self.assertEqual(out.getvalue(), "Cache ... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 9 | tests.py | 83 | Refs #33476 -- Reformatted code with Black. | 50,030 | 0 | 107 | 47 | 20 | 201,975 | 21 | django | 12 | tests/cache/tests.py | Python | 10 | {
"docstring": "\n Delete and recreate cache table with legacy behavior (explicitly\n specifying the table name).\n ",
"language": "en",
"n_whitespaces": 35,
"n_words": 13,
"vocab_size": 12
} | https://github.com/django/django.git | |
1 | get_engle_granger_two_step_cointegration_test | def get_engle_granger_two_step_cointegration_test(dependent_series, independent_series):
warnings.simplefilter(action="ignore", category=FutureWarning)
long_run_ols = sm.OLS(dependent_series, sm.add_constant(independent_series))
warnings.simplefilter(action="default", category=FutureWarning)
long_... | 9e1a58e2dbedec4e4a9f9c2e32ddf091776c606b | 13 | econometrics_model.py | 230 | Here we merge all API Refactor related branches (#2236)
* Update api.py
* Updated forex menu
* refactor ycrv command
* refactor ycrv command black
* refactor ecocal command
* Minh changes
* Adding space to test pushing
* title fix ecocal df
* get economic calendar annotation
* fix investingc... | 85,239 | 0 | 151 | 147 | 88 | 285,199 | 103 | OpenBBTerminal | 31 | openbb_terminal/econometrics/econometrics_model.py | Python | 12 | {
"docstring": "Estimates long-run and short-run cointegration relationship for series y and x and apply\n the two-step Engle & Granger test for cointegration.\n\n Uses a 2-step process to first estimate coefficients for the long-run relationship\n y_t = c + gamma * x_t + z_t\n\n and then the short-te... | https://github.com/OpenBB-finance/OpenBBTerminal.git | |
12 | naive_all_pairs_lowest_common_ancestor | def naive_all_pairs_lowest_common_ancestor(G, pairs=None):
if not nx.is_directed_acyclic_graph(G):
raise nx.NetworkXError("LCA only defined on directed acyclic graphs.")
if len(G) == 0:
raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
ancestor_cache = {}
if pai... | 8b6c25ec952b80539a38e7a884c0fdc3fd735b28 | @not_implemented_for("undirected")
@not_implemented_for("multigraph") | 16 | lowest_common_ancestors.py | 319 | Improve LCA input validation (#5877)
* Remove explicit checks for None nodes.
The graph objects already do not allow None nodes.
* Change elif to if for raising branches. | 42,256 | 1 | 387 | 188 | 60 | 177,062 | 101 | networkx | 22 | networkx/algorithms/lowest_common_ancestors.py | Python | 28 | {
"docstring": "Return the lowest common ancestor of all pairs or the provided pairs\n\n Parameters\n ----------\n G : NetworkX directed graph\n\n pairs : iterable of pairs of nodes, optional (default: all pairs)\n The pairs of nodes of interest.\n If None, will find the LCA of all pairs of ... | https://github.com/networkx/networkx.git |
6 | unquote_unreserved | def unquote_unreserved(uri):
parts = uri.split("%")
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL(f"Invalid percent-escape sequence: '{h}'"... | cd5a9683be69c86c8f3adcd13385a9bc5db198ec | 16 | utils.py | 215 | Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir. | 4,233 | 0 | 198 | 119 | 37 | 22,163 | 50 | pipenv | 16 | pipenv/patched/pip/_vendor/requests/utils.py | Python | 16 | {
"docstring": "Un-escape any percent-escape sequences in a URI that are unreserved\n characters. This leaves all reserved, illegal and non-ASCII bytes encoded.\n\n :rtype: str\n ",
"language": "en",
"n_whitespaces": 31,
"n_words": 22,
"vocab_size": 22
} | https://github.com/pypa/pipenv.git | |
2 | is_named_tuple | def is_named_tuple(obj) -> bool:
return isinstance(obj, abc.Sequence) and hasattr(obj, "_fields")
| bce995817caf00ab5e82cb4cf1b540f1530cf4ea | 9 | inference.py | 41 | Fix some dosctring RT02 error (#50197) | 40,758 | 0 | 16 | 24 | 10 | 172,104 | 10 | pandas | 7 | pandas/core/dtypes/inference.py | Python | 25 | {
"docstring": "\n Check if the object is a named tuple.\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n bool\n Whether `obj` is a named tuple.\n\n Examples\n --------\n >>> from collections import namedtuple\n >>> Point = namedtuple(\"Point\", [... | https://github.com/pandas-dev/pandas.git | |
9 | _laplace_rule_timescale | def _laplace_rule_timescale(f, t, s, doit=True, **hints):
r
_simplify = hints.pop('simplify', True)
b = Wild('b', exclude=[t])
g = WildFunction('g', nargs=1)
ma1 = f.match(g)
if ma1:
arg = ma1[g].args[0].collect(t)
ma2 = arg.match(b*t)
if ma2 and ma2[b]>0:
deb... | af443377dd48c2caf440d2b6dd76830dbe84712f | 19 | transforms.py | 407 | Moved all constant-factor calculations to `_laplace_apply_rules` | 49,677 | 0 | 506 | 266 | 71 | 200,509 | 99 | sympy | 35 | sympy/integrals/transforms.py | Python | 37 | {
"docstring": "\n This internal helper function tries to apply the time-scaling rule of the\n Laplace transform and returns `None` if it cannot do it.\n\n Time-scaling means the following: if $F(s)$ is the Laplace transform of,\n $f(t)$, then, for any $a>0$, the Laplace transform of $f(at)$ will be\n ... | https://github.com/sympy/sympy.git | |
7 | _read | def _read(cls, path_or_buf, **kwargs):
path_or_buf = cls.get_path_or_buffer(path_or_buf)
if isinstance(path_or_buf, str):
if not cls.file_exists(path_or_buf):
return cls.single_worker_read(path_or_buf, **kwargs)
path_or_buf = cls.get_path(path_or_buf)
... | 97769988a6f19e4b76f34238c97bf159ee7626a5 | 16 | json_dispatcher.py | 641 | REFACTOR-#3853: interacting with Dask interface through 'DaskWrapper' class (#3854)
Co-authored-by: Devin Petersohn <devin-petersohn@users.noreply.github.com>
Co-authored-by: Dmitry Chigarev <dchigarev@users.noreply.github.com>
Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru>
Signed-off-by: Anatoly Myachev <... | 35,438 | 0 | 655 | 398 | 106 | 153,549 | 157 | modin | 58 | modin/core/io/text/json_dispatcher.py | Python | 48 | {
"docstring": "\n Read data from `path_or_buf` according to the passed `read_json` `kwargs` parameters.\n\n Parameters\n ----------\n path_or_buf : str, path object or file-like object\n `path_or_buf` parameter of `read_json` function.\n **kwargs : dict\n Para... | https://github.com/modin-project/modin.git | |
5 | _store | def _store(self, messages, response, remove_oldest=True, *args, **kwargs):
unstored_messages = []
encoded_data = self._encode(messages)
if self.max_cookie_size:
# data is going to be stored eventually by SimpleCookie, which
# adds its own overhead, which we must ... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 10 | cookie.py | 70 | Refs #33476 -- Reformatted code with Black. | 50,673 | 0 | 106 | 112 | 39 | 204,181 | 44 | django | 13 | django/contrib/messages/storage/cookie.py | Python | 16 | {
"docstring": "\n Store the messages to a cookie and return a list of any messages which\n could not be stored.\n\n If the encoded data is larger than ``max_cookie_size``, remove\n messages until the data fits (these are the messages which are\n returned), and add the not_finished ... | https://github.com/django/django.git | |
11 | handle_out | def handle_out(out, result):
if isinstance(out, tuple):
if len(out) == 1:
out = out[0]
elif len(out) > 1:
raise NotImplementedError("The out parameter is not fully supported")
else:
out = None
# Notice, we use .__class__ as opposed to type() in o... | bc43d692e8f5fc55e6d81c91053598bd89f79267 | 18 | core.py | 373 | Add sanity checks to divisions setter (#8806)
Adds a few sanity checks to the divisions property setter
- New divisions are compatible with the existing `npartitions`
- New divisions don't mix None and non-None values
- New divisions are sorted (except for ordered categorical dtypes, where
that's hard) | 36,599 | 0 | 424 | 227 | 90 | 156,197 | 148 | dask | 23 | dask/dataframe/core.py | Python | 34 | {
"docstring": "Handle out parameters\n\n If out is a dask.DataFrame, dask.Series or dask.Scalar then\n this overwrites the contents of it with the result\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 21,
"vocab_size": 19
} | https://github.com/dask/dask.git | |
1 | test_regressor_predict_on_arraylikes | def test_regressor_predict_on_arraylikes():
X = [[5, 1], [3, 1], [4, 3], [0, 3]]
y = [2, 3, 5, 6]
| 742d39ca38f713027091324c4555f9b4e1b9da05 | 8 | test_neighbors.py | 60 | FIX Fixes KNeighborsRegressor.predict with array-likes (#22687)
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com> | 75,566 | 0 | 27 | 90 | 16 | 259,100 | 18 | scikit-learn | 3 | sklearn/neighbors/tests/test_neighbors.py | Python | 7 | {
"docstring": "Ensures that `predict` works for array-likes when `weights` is a callable.\n\n Non-regression test for #22687.\n ",
"language": "en",
"n_whitespaces": 21,
"n_words": 15,
"vocab_size": 14
} | https://github.com/scikit-learn/scikit-learn.git | |
9 | _send_msg | def _send_msg(self, msg):
self.logger.info(f"Sending discord message: {msg}")
# TODO: handle other message types
if msg['type'] == RPCMessageType.EXIT_FILL:
profit_ratio = msg.get('profit_ratio')
open_date = msg.get('open_date').strftime('%Y-%m-%d %H:%M:%S')
... | 45c47bda6000b2b57026fdedffaaa69f8fc1797e | 19 | discord.py | 994 | refactor into discord rpc module | 34,602 | 0 | 953 | 535 | 130 | 149,948 | 237 | freqtrade | 31 | freqtrade/rpc/discord.py | Python | 45 | {
"docstring": "\n msg = {\n 'type': (RPCMessageType.EXIT_FILL if fill\n else RPCMessageType.EXIT),\n 'trade_id': trade.id,\n 'exchange': trade.exchange.capitalize(),\n 'pair': trade.pair,\n 'leverage': trade.leverage,\n 'dir... | https://github.com/freqtrade/freqtrade.git | |
4 | _get_arithmetic_result_freq | def _get_arithmetic_result_freq(self, other) -> BaseOffset | None:
# Adding or subtracting a Timedelta/Timestamp scalar is freq-preserving
# whenever self.freq is a Tick
if is_period_dtype(self.dtype):
return self.freq
elif not lib.is_scalar(other):
retu... | 8f26ab7c184c7f6fc7337bfed47ac9d86ee4551f | 9 | datetimelike.py | 85 | REF: helpers to de-duplicate datetimelike arithmetic (#48844) | 40,423 | 0 | 136 | 51 | 31 | 169,366 | 42 | pandas | 11 | pandas/core/arrays/datetimelike.py | Python | 11 | {
"docstring": "\n Check if we can preserve self.freq in addition or subtraction.\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 10,
"vocab_size": 10
} | https://github.com/pandas-dev/pandas.git | |
3 | __reset_trigger_counts | def __reset_trigger_counts(self):
for trigger_id in self.trigger_alert_counts:
self.trigger_alert_counts[trigger_id] = 0
for trigger_id in self.trigger_resolve_counts:
self.trigger_resolve_counts[trigger_id] = 0
self.update_alert_rule_stats()
| 524c8579d4d87954d993cd3fb7a29e0422058e6a | 10 | subscription_processor.py | 66 | feat(alerts): Clear counters for null subscription updates (#30831)
Adds logic that clears trigger count and resolve
count for crash rate alerts and metrics crash rate
alerts in the case an empty subscription update is sent
or if a min session count threshold is set and the count
in the subscription update is lowe... | 19,202 | 0 | 67 | 41 | 12 | 95,336 | 17 | sentry | 6 | src/sentry/incidents/subscription_processor.py | Python | 6 | {
"docstring": "\n Helper method that clears both the trigger alert and the trigger resolve counts\n ",
"language": "en",
"n_whitespaces": 28,
"n_words": 13,
"vocab_size": 11
} | https://github.com/getsentry/sentry.git | |
1 | wide_resnet50_2 | def wide_resnet50_2(pretrained=False, **kwargs):
kwargs['width'] = 64 * 2
return _resnet('wide_resnet50_2', BottleneckBlock, 50, pretrained, **kwargs)
| ffcde21305c61d950a9f93e57e6180c9a9665b87 | 8 | resnet.py | 54 | add disco_diffusion_ernievil_base | 10,081 | 0 | 23 | 33 | 14 | 50,301 | 14 | PaddleHub | 5 | modules/image/text_to_image/disco_diffusion_ernievil_base/vit_b_16x/ernievil2/transformers/resnet.py | Python | 3 | {
"docstring": "Wide ResNet-50-2 model from\n `\"Wide Residual Networks\" <https://arxiv.org/pdf/1605.07146.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.vision... | https://github.com/PaddlePaddle/PaddleHub.git | |
1 | piecewise_linear | def piecewise_linear(t, deltas, k, m, changepoint_ts):
deltas_t = (changepoint_ts[None, :] <= t[..., None]) * deltas
k_t = deltas_t.sum(axis=1) + k
m_t = (deltas_t * -changepoint_ts).sum(axis=1) + m
return k_t * t + m_t
| 8fbf8ba2a5bfcdb892e8ca596e338894614000b5 | 12 | forecaster.py | 103 | Speed Up Uncertainty Predictions (#2186) | 440 | 0 | 68 | 68 | 25 | 3,305 | 33 | prophet | 11 | python/prophet/forecaster.py | Python | 5 | {
"docstring": "Evaluate the piecewise linear function.\n\n Parameters\n ----------\n t: np.array of times on which the function is evaluated.\n deltas: np.array of rate changes at each changepoint.\n k: Float initial rate.\n m: Float initial offset.\n changepoint_ts: ... | https://github.com/facebook/prophet.git | |
3 | test_cache_metric | def test_cache_metric(self):
CACHE_NAME = "cache_metrics_test_fgjkbdfg"
cache: DeferredCache[str, str] = DeferredCache(CACHE_NAME, max_entries=777)
items = {
x.split(b"{")[0].decode("ascii"): x.split(b" ")[1].decode("ascii")
for x in filter(
lamb... | 2bb2c32e8ed5642a5bf3ba1e8c49e10cecc88905 | 14 | test_metrics.py | 336 | Avoid incrementing bg process utime/stime counters by negative durations (#14323) | 73,114 | 0 | 267 | 198 | 33 | 249,768 | 57 | synapse | 16 | tests/metrics/test_metrics.py | Python | 22 | {
"docstring": "\n Caches produce metrics reflecting their state when scraped.\n ",
"language": "en",
"n_whitespaces": 23,
"n_words": 8,
"vocab_size": 8
} | https://github.com/matrix-org/synapse.git | |
1 | test_multilabel_y_explicit_zeros | def test_multilabel_y_explicit_zeros(tmp_path):
save_path = str(tmp_path / "svm_explicit_zero")
rng = np.random.RandomState(42)
X = rng.randn(3, 5).astype(np.float64)
indptr = np.array([0, 2, 3, 6])
indices = np.array([0, 2, 2, 0, 1, 2])
# The first and last element are explicit zeros.
... | 2e3a0474a6195161e7e3ff02be9d1ff18591ca7b | 10 | test_svmlight_format.py | 244 | ENH Cythonize `dump_svmlight_file` (#23127)
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
Co-authored-by: Julien Jerphanion <git@jjerphan.xyz> | 76,118 | 0 | 145 | 174 | 64 | 260,207 | 92 | scikit-learn | 26 | sklearn/datasets/tests/test_svmlight_format.py | Python | 12 | {
"docstring": "\n Ensure that if y contains explicit zeros (i.e. elements of y.data equal to\n 0) then those explicit zeros are not encoded.\n ",
"language": "en",
"n_whitespaces": 31,
"n_words": 21,
"vocab_size": 19
} | https://github.com/scikit-learn/scikit-learn.git | |
1 | handler_name | def handler_name(self) -> str:
# Property to make it read only
return self._handler_name
| 1013f84ffc67bdce04bf13eaf401ab5ced572bb0 | 6 | message.py | 23 | diagrams | 44,890 | 0 | 34 | 12 | 13 | 185,071 | 13 | textual | 4 | src/textual/message.py | Python | 3 | {
"docstring": "The name of the handler associated with this message.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/Textualize/textual.git | |
4 | load_sample_image | def load_sample_image(image_name):
images = load_sample_images()
index = None
for i, filename in enumerate(images.filenames):
if filename.endswith(image_name):
index = i
break
if index is None:
raise AttributeError("Cannot find sample image: %s" % image_name)... | 9d7220b57ccac4ac12268a96281940667a4de1d8 | 11 | _base.py | 96 | DOC changed some typo of _shrunk_covariance.ledoit_wolf_shrinkage (#22798)
* Changed from 3rd to 1st person the 1st word and remote blanck space.
* Add two periods in the content | 75,626 | 0 | 87 | 57 | 28 | 259,175 | 33 | scikit-learn | 11 | sklearn/datasets/_base.py | Python | 10 | {
"docstring": "Load the numpy array of a single sample image.\n\n Read more in the :ref:`User Guide <sample_images>`.\n\n Parameters\n ----------\n image_name : {`china.jpg`, `flower.jpg`}\n The name of the sample image loaded\n\n Returns\n -------\n img : 3D array\n The image as a... | https://github.com/scikit-learn/scikit-learn.git | |
6 | test_vr_connector_with_multiple_buffers | def test_vr_connector_with_multiple_buffers(self):
context_len = 5
# This view requirement simulates the use-case of a decision transformer
# without reward-to-go.
view_rq_dict = {
# obs[t-context_len+1:t]
"context_obs": ViewRequirement("obs", shift=f"-{c... | 5bf9d5084fe38d864c1b5075145d2e778c431a5b | 15 | test_agent.py | 572 | [RLlib] Pass input dict into action connectors, because sometimes input data is useful for adapting output actions. (#28588)
Based on user feedback. Input data is sometimes useful for adapting outputs, for example action masks.
Signed-off-by: Jun Gong <jungong@anyscale.com> | 28,520 | 0 | 731 | 349 | 122 | 127,777 | 166 | ray | 43 | rllib/connectors/tests/test_agent.py | Python | 44 | {
"docstring": "Test that the ViewRequirementAgentConnector can handle slice shifts correctly\n when it has multiple buffers to shift.",
"language": "en",
"n_whitespaces": 22,
"n_words": 16,
"vocab_size": 16
} | https://github.com/ray-project/ray.git | |
4 | reversed | def reversed(G):
msg = (
"context manager reversed is deprecated and to be removed in 3.0."
"Use G.reverse(copy=False) if G.is_directed() else G instead."
)
warnings.warn(msg, DeprecationWarning)
directed = G.is_directed()
if directed:
G._pred, G._succ = G._succ, G._pre... | cc1db275efc709cb964ce88abbfa877798d58c10 | 13 | contextmanagers.py | 141 | Minor improvements from general code readthrough (#5414)
* Add deprecated directive to reversed docstring.
* Add missing dep directives to shpfiles.
* Remove defn of INF sentinel.
* typo.
* str -> comment in forloop.
* STY: appropriate casing for var name. | 41,913 | 0 | 155 | 82 | 40 | 176,452 | 56 | networkx | 11 | networkx/utils/contextmanagers.py | Python | 16 | {
"docstring": "A context manager for temporarily reversing a directed graph in place.\n\n .. deprecated:: 2.6\n\n This context manager is deprecated and will be removed in 3.0.\n Use ``G.reverse(copy=False) if G.is_directed() else G`` instead.\n\n This is a no-op for undirected graphs.\n\n Param... | https://github.com/networkx/networkx.git | |
5 | train_epoch_ch3 | def train_epoch_ch3(net, train_iter, loss, updater):
# Sum of training loss, sum of training accuracy, no. of examples
metric = Accumulator(3)
for X, y in train_iter:
# Compute gradients and update parameters
with tf.GradientTape() as tape:
y_hat = net(X)
# Keras... | b64b41d8c1ac23c43f7a4e3f9f6339d6f0012ab2 | 15 | tensorflow.py | 324 | [PaddlePaddle] Merge master into Paddle branch (#1186)
* change 15.2 title in chinese version (#1109)
change title ’15.2. 情感分析:使用递归神经网络‘ to ’15.2. 情感分析:使用循环神经网络‘
* 修改部分语义表述 (#1105)
* Update r0.17.5 (#1120)
* Bump versions in installation
* 94行typo: (“bert.mall”)->(“bert.small”) (#1129)
* line 313: "b... | 37,440 | 0 | 352 | 207 | 98 | 158,287 | 134 | d2l-zh | 33 | d2l/tensorflow.py | Python | 19 | {
"docstring": "The training loop defined in Chapter 3.\n\n Defined in :numref:`sec_softmax_scratch`",
"language": "en",
"n_whitespaces": 12,
"n_words": 10,
"vocab_size": 9
} | https://github.com/d2l-ai/d2l-zh.git | |
9 | _laplace_apply_rules | def _laplace_apply_rules(f, t, s, doit=True, **hints):
k, func = f.as_independent(t, as_Add=False)
simple_rules = _laplace_build_rules(t, s)
for t_dom, s_dom, check, plane, prep in simple_rules:
ma = prep(func).match(t_dom)
if ma:
debug('_laplace_apply_rules match:')
... | af443377dd48c2caf440d2b6dd76830dbe84712f | 18 | transforms.py | 365 | Moved all constant-factor calculations to `_laplace_apply_rules` | 49,680 | 0 | 469 | 237 | 77 | 200,512 | 110 | sympy | 39 | sympy/integrals/transforms.py | Python | 32 | {
"docstring": "\n Helper function for the class LaplaceTransform.\n\n This function does a Laplace transform based on rules and, after\n applying the rules, hands the rest over to `_laplace_transform`, which\n will attempt to integrate.\n\n If it is called with `doit=False`, then it will instead retur... | https://github.com/sympy/sympy.git | |
1 | _object2proto | def _object2proto(self) -> SMPCActionSeqBatchMessage_PB:
return SMPCActionSeqBatchMessage_PB(
smpc_actions=list(map(lambda x: serialize(x), self.smpc_actions)),
address=serialize(self.address),
msg_id=serialize(self.id),
)
| e272ed2fa4c58e0a89e273a3e85da7d13a85e04c | 15 | smpc_action_seq_batch_message.py | 79 | [syft.core.node.common.action] Change syft import absolute -> relative | 349 | 0 | 67 | 50 | 13 | 2,719 | 13 | PySyft | 11 | packages/syft/src/syft/core/node/common/action/smpc_action_seq_batch_message.py | Python | 20 | {
"docstring": "Returns a protobuf serialization of self.\n\n As a requirement of all objects which inherit from Serializable,\n this method transforms the current object into the corresponding\n Protobuf object so that it can be further serialized.\n\n :return: returns a protobuf object\n... | https://github.com/OpenMined/PySyft.git | |
3 | postprocessing | def postprocessing(data):
if type_to_string(type(data)) == "torch.Tensor":
try:
import torch
from torchvision import transforms
# By default Torch tensors are displayed as images. To display them as JSON,
# the user can simply convert them to numpy arra... | 203253321d34543aa25483803ebc21e3903679b6 | 13 | gradio_visualize_graph.py | 101 | [serve] Add additional features to DAG visualization with Gradio (#28246) | 28,435 | 0 | 196 | 55 | 50 | 127,405 | 59 | ray | 13 | python/ray/serve/experimental/gradio_visualize_graph.py | Python | 13 | {
"docstring": "Add support for types that are not supported by Gradio.\n\n Some data types like PyTorch tensors, cannot be processed and displayed through\n Gradio. Thus we extend support to these data types by transforming them into a form\n that Gradio can process and display.\n ",
"language": "en",
... | https://github.com/ray-project/ray.git | |
1 | get_anchor_yield_reserve | def get_anchor_yield_reserve() -> pd.DataFrame:
df = get_history_asset_from_terra_address(
address="terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8"
)
return df
| 72b0a9f1ee8b91ad9fd9e76d80d2ccab51ee6d21 | 10 | terraengineer_model.py | 36 | Next release : reports on steroids (#2349)
* fix gov tests
* refactor insider
* new virtual path extraction
* removed some symbol default params as they're considered critical
* little adjustments
* portfolio refactor
* merge API factory
* add helpers, stocks, crypto, forex
* minor forex change... | 85,377 | 0 | 30 | 19 | 10 | 285,679 | 11 | OpenBBTerminal | 6 | openbb_terminal/cryptocurrency/defi/terraengineer_model.py | Python | 13 | {
"docstring": "Displays the 30-day history of the Anchor Yield Reserve.\n [Source: https://terra.engineer/]\n\n Returns\n ----------\n pd.DataFrame\n Dataframe containing historical data\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 17
} | https://github.com/OpenBB-finance/OpenBBTerminal.git | |
1 | disable_telemetry | def disable_telemetry():
os.environ[HAYSTACK_TELEMETRY_ENABLED] = "False"
logger.info("Telemetry has been disabled.")
| ac5617e757e9ace6f30b7291686d9dbbc339f433 | 8 | telemetry.py | 38 | Add basic telemetry features (#2314)
* add basic telemetry features
* change pipeline_config to _component_config
* Update Documentation & Code Style
* add super().__init__() calls to error classes
* make posthog mock work with python 3.7
* Update Documentation & Code Style
* update link to docs web ... | 74,975 | 0 | 18 | 19 | 9 | 256,958 | 9 | haystack | 6 | haystack/telemetry.py | Python | 3 | {
"docstring": "\n Disables telemetry so that no events are sent anymore, except for one final event.\n ",
"language": "en",
"n_whitespaces": 21,
"n_words": 14,
"vocab_size": 14
} | https://github.com/deepset-ai/haystack.git | |
3 | cyclic_reduction | def cyclic_reduction(self, removed=False):
word = self.copy()
g = self.group.identity
while not word.is_cyclically_reduced():
exp1 = abs(word.exponent_syllable(0))
exp2 = abs(word.exponent_syllable(-1))
exp = min(exp1, exp2)
start = word[0... | 498015021131af4dbb07eb110e5badaba8250c7b | 13 | free_groups.py | 184 | Updated import locations | 47,569 | 0 | 171 | 113 | 28 | 196,069 | 41 | sympy | 17 | sympy/combinatorics/free_groups.py | Python | 14 | {
"docstring": "Return a cyclically reduced version of the word. Unlike\n `identity_cyclic_reduction`, this will not cyclically permute\n the reduced word - just remove the \"unreduced\" bits on either\n side of it. Compare the examples with those of\n `identity_cyclic_reduction`.\n\n ... | https://github.com/sympy/sympy.git | |
2 | clear_bpbynumber | def clear_bpbynumber(self, arg):
try:
bp = self.get_bpbynumber(arg)
except ValueError as err:
return str(err)
bp.deleteMe()
self._prune_breaks(bp.file, bp.line)
return None
| 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 10 | bdb.py | 79 | add python 3.10.4 for windows | 56,223 | 0 | 82 | 47 | 17 | 221,122 | 18 | XX-Net | 12 | python3.10.4/Lib/bdb.py | Python | 8 | {
"docstring": "Delete a breakpoint by its index in Breakpoint.bpbynumber.\n\n If arg is invalid, return an error message.\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 16,
"vocab_size": 16
} | https://github.com/XX-net/XX-Net.git | |
3 | test_mapped_dag_pre_existing_tis | def test_mapped_dag_pre_existing_tis(self, dag_maker, session):
from airflow.decorators import task
from airflow.operators.python import PythonOperator
list_result = [[1], [2], [{'a': 'b'}]]
| de3bf06863714c6c02ad0c7f5999c961b382bf4a | 11 | test_backfill_job.py | 68 | Ensure that BackfillJob re-runs existing mapped task instances (#22952)
* Ensure that BackfillJob re-runs existing mapped task instances
`expand_mapped_task` only returns _new_ TaskInstances, so if a backfill
job was run for a dag that already existed the mapped task would never
be executed.
* Fix tests for ch... | 9,086 | 0 | 46 | 487 | 16 | 47,369 | 18 | airflow | 11 | tests/jobs/test_backfill_job.py | Python | 61 | {
"docstring": "If the DagRun already some mapped TIs, ensure that we re-run them successfully",
"language": "en",
"n_whitespaces": 12,
"n_words": 13,
"vocab_size": 13
} | https://github.com/apache/airflow.git | |
4 | _collate_rejected | def _collate_rejected(self, pair, row):
# It could be fun to enable hyperopt mode to write
# a loss function to reduce rejected signals
if (self.config.get('export', 'none') == 'signals' and
self.dataprovider.runmode == RunMode.BACKTEST):
if pair not in self.... | 5a4e99b413f84f818662cc3012819db76aec47c1 | 12 | backtesting.py | 120 | Add support for collating and analysing rejected trades in backtest | 35,136 | 0 | 122 | 74 | 37 | 151,789 | 42 | freqtrade | 14 | freqtrade/optimize/backtesting.py | Python | 6 | {
"docstring": "\n Temporarily store rejected trade information for downstream use in backtesting_analysis\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 10,
"vocab_size": 10
} | https://github.com/freqtrade/freqtrade.git | |
2 | not_found | def not_found(error):
return (
render_template(
'airflow/not_found.html',
hostname=get_hostname()
if conf.getboolean('webserver', 'EXPOSE_HOSTNAME', fallback=True)
else 'redact',
),
404,
)
| e29543ec00c0a3eae7a789cb49350499c3b584c2 | 13 | views.py | 65 | Use `get_hostname` instead of `socket.getfqdn` (#24260)
We allow users to configure a different function to determine the
hostname, so we should use that consistently when we need the hostname. | 7,853 | 0 | 90 | 38 | 16 | 43,181 | 16 | airflow | 8 | airflow/www/views.py | Python | 10 | {
"docstring": "Show Not Found on screen for any error in the Webserver",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/apache/airflow.git | |
1 | test_http_proxy_relative_request_no_host_header | def test_http_proxy_relative_request_no_host_header(tctx):
assert (
Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)
>> DataReceived(tctx.client, b"GET / HTTP/1.1\r\n\r\n")
<< SendData(tctx.client, BytesMatching(b"400 Bad Request.+"
... | 56eea20f6389b751d38079fb09b29237a0d2b262 | 14 | test_http.py | 96 | tutils: add BytesMatching placeholder | 73,596 | 0 | 134 | 61 | 27 | 251,116 | 28 | mitmproxy | 13 | test/mitmproxy/proxy/layers/http/test_http.py | Python | 8 | {
"docstring": "Test handling of a relative-form \"GET /\" in regular proxy mode, but without a host header.",
"language": "en",
"n_whitespaces": 15,
"n_words": 16,
"vocab_size": 15
} | https://github.com/mitmproxy/mitmproxy.git | |
1 | project | def project(x):
return torch.cat([torch.sqrt(1.0 + torch.sum(x * x, 1, keepdim=True)), x], 1)
| 04eb35c234de59d4a47848a4f85cb5be3c58c24e | 14 | hyperbolic.py | 60 | Added prototypical decoder | 53,731 | 0 | 18 | 41 | 12 | 214,304 | 12 | flair | 7 | flair/models/sandbox/prototypical_decoder/distance/hyperbolic.py | Python | 2 | {
"docstring": "Project onto the hyeprboloid embedded in in n+1 dimensions.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 8
} | https://github.com/flairNLP/flair.git | |
1 | _create_method | def _create_method(cls, op, coerce_to_dtype=True, result_dtype=None):
# NOTE(Clark): This overrides, but coerce_to_dtype, result_dtype might
# not be needed
| 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | 6 | tensor_extension.py | 27 | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 29,321 | 0 | 38 | 31 | 16 | 130,594 | 17 | ray | 5 | python/ray/data/extensions/tensor_extension.py | Python | 4 | {
"docstring": "\n Add support for binary operators by unwrapping, applying, and\n rewrapping.\n ",
"language": "en",
"n_whitespaces": 32,
"n_words": 10,
"vocab_size": 10
} | https://github.com/ray-project/ray.git | |
2 | _collect_tcl_modules | def _collect_tcl_modules(tcl_root):
# Obtain Tcl major version.
tcl_major_version = tcl_version.split('.')[0]
modules_dirname = f"tcl{tcl_major_version}"
modules_path = os.path.join(tcl_root, '..', modules_dirname)
if not os.path.isdir(modules_path):
logger.warning('Tcl modules direc... | 2b2559af1c7790596e7b2040f48e56baef608f9d | 10 | tcl_tk.py | 116 | hookutils: tcl/tk: port to PyInstaller.isolated framework | 77,582 | 0 | 69 | 66 | 30 | 264,061 | 34 | pyinstaller | 15 | PyInstaller/utils/hooks/tcl_tk.py | Python | 8 | {
"docstring": "\n Get a list of TOC-style 3-tuples describing Tcl modules. The modules directory is separate from the library/data\n one, and is located at $tcl_root/../tclX, where X is the major Tcl version.\n\n Returns\n -------\n Tree\n Such list, if the modules directory exists.\n ",
"... | https://github.com/pyinstaller/pyinstaller.git | |
2 | policy_scope | def policy_scope(policy):
old_policy = _global_policy
try:
set_global_policy(policy)
yield
finally:
set_global_policy(old_policy)
| 84afc5193d38057e2e2badf9c889ea87d80d8fbf | 10 | policy.py | 43 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 81,316 | 0 | 43 | 22 | 10 | 275,141 | 10 | keras | 5 | keras/mixed_precision/policy.py | Python | 7 | {
"docstring": "A context manager that sets the global Policy under it.\n\n Args:\n policy: A Policy, or a string that will be converted to a Policy..\n\n Yields:\n Nothing.\n ",
"language": "en",
"n_whitespaces": 45,
"n_words": 26,
"vocab_size": 23
} | https://github.com/keras-team/keras.git | |
15 | directed_edge_swap | def directed_edge_swap(G, *, nswap=1, max_tries=100, seed=None):
if nswap > max_tries:
raise nx.NetworkXError("Number of swaps > number of tries allowed.")
if len(G) < 4:
raise nx.NetworkXError("DiGraph has fewer than four nodes.")
if len(G.edges) < 3:
raise nx.NetworkXError("Di... | 247231f0154badc4a07b6a4ceb40148ea18f264b | @py_random_state(3) | 14 | swap.py | 549 | Bug fix in swap: directed_edge_swap and double_edge_swap (#6149)
* raise exception if graph has no edges and test for that
* Simplify code: raise exception if G has less than 3 edges
* add correction
* Solved bug in double_edge_swap and added tests for that. Also updated the doc entry
* Update networkx/al... | 42,431 | 1 | 620 | 332 | 139 | 177,539 | 228 | networkx | 34 | networkx/algorithms/swap.py | Python | 47 | {
"docstring": "Swap three edges in a directed graph while keeping the node degrees fixed.\n\n A directed edge swap swaps three edges such that a -> b -> c -> d becomes\n a -> c -> b -> d. This pattern of swapping allows all possible states with the\n same in- and out-degree distribution in a directed graph ... | https://github.com/networkx/networkx.git |
3 | open | def open(fp, mode="r"):
if mode != "r":
raise ValueError("bad mode")
try:
return GdImageFile(fp)
except SyntaxError as e:
raise UnidentifiedImageError("cannot identify this image file") from e
| 965df6df6f806887fca3f7b5c6dd6c70a20e803e | 11 | GdImageFile.py | 73 | Add missing paramters to docstrings | 69,912 | 0 | 58 | 39 | 24 | 242,760 | 25 | Pillow | 8 | src/PIL/GdImageFile.py | Python | 7 | {
"docstring": "\n Load texture from a GD image file.\n\n :param fp: GD file name, or an opened file handle.\n :param mode: Optional mode. In this version, if the mode argument\n is given, it must be \"r\".\n :returns: An image instance.\n :raises OSError: If the image could not be read.\n "... | https://github.com/python-pillow/Pillow.git | |
2 | _make_relation_requests | def _make_relation_requests(self) -> Tuple[List[str], JsonDict]:
# Request the relations of the event.
channel = self.make_request(
"GET",
f"/_matrix/client/unstable/rooms/{self.room}/relations/{self.parent_id}",
access_token=self.user_token,
)
... | f63bedef07360216a8de71dc38f00f1aea503903 | 11 | test_relations.py | 214 | Invalidate caches when an event with a relation is redacted. (#12121)
The caches for the target of the relation must be cleared
so that the bundled aggregations are re-calculated after
the redaction is processed. | 71,671 | 0 | 204 | 117 | 36 | 247,439 | 54 | synapse | 19 | tests/rest/client/test_relations.py | Python | 24 | {
"docstring": "\n Makes requests and ensures they result in a 200 response, returns a\n tuple of results:\n\n 1. `/relations` -> Returns a list of event IDs.\n 2. `/event` -> Returns the response's m.relations field (from unsigned),\n if it exists.\n ",
"language": "en... | https://github.com/matrix-org/synapse.git | |
3 | at_time | def at_time(self, time, asof=False, axis=None): # noqa: PR01, RT01, D200
axis = self._get_axis_number(axis)
idx = self.index if axis == 0 else self.columns
indexer = pandas.Series(index=idx).at_time(time, asof=asof).index
return self.loc[indexer] if axis == 0 else self.loc[:, i... | 605efa618e7994681f57b11d04d417f353ef8d50 | 12 | base.py | 118 | DOCS-#3099: Fix `BasePandasDataSet` docstrings warnings (#4333)
Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru>
Signed-off-by: Alexander Myskov <alexander.myskov@intel.com> | 35,498 | 0 | 71 | 78 | 27 | 153,617 | 35 | modin | 13 | modin/pandas/base.py | Python | 5 | {
"docstring": "\n Select values at particular time of day (e.g., 9:30AM).\n ",
"language": "en",
"n_whitespaces": 24,
"n_words": 9,
"vocab_size": 9
} | https://github.com/modin-project/modin.git | |
6 | _check_fields | def _check_fields(self, obj):
if obj.fields is None:
return []
elif not isinstance(obj.fields, (list, tuple)):
return must_be("a list or tuple", option="fields", obj=obj, id="admin.E004")
elif obj.fieldsets:
return [
checks.Error(
... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 13 | checks.py | 228 | Refs #33476 -- Reformatted code with Black. | 50,313 | 0 | 418 | 142 | 55 | 203,337 | 70 | django | 21 | django/contrib/admin/checks.py | Python | 28 | {
"docstring": "Check that `fields` only refer to existing fields, doesn't contain\n duplicates. Check if at most one of `fields` and `fieldsets` is defined.\n ",
"language": "en",
"n_whitespaces": 36,
"n_words": 22,
"vocab_size": 20
} | https://github.com/django/django.git | |
3 | register_for_auto_class | def register_for_auto_class(cls, auto_class="TFAutoModel"):
if not isinstance(auto_class, str):
auto_class = auto_class.__name__
import transformers.models.auto as auto_module
if not hasattr(auto_module, auto_class):
raise ValueError(f"{auto_class} is not a val... | 811c4c9f79758235762b4f70ffae00deae494fb1 | 11 | modeling_tf_utils.py | 89 | fix bug: register_for_auto_class should be defined on TFPreTrainedModel instead of TFSequenceSummary (#18607) | 6,074 | 0 | 86 | 52 | 24 | 33,222 | 29 | transformers | 13 | src/transformers/modeling_tf_utils.py | Python | 7 | {
"docstring": "\n Register this class with a given auto class. This should only be used for custom models as the ones in the\n library are already mapped with an auto class.\n\n <Tip warning={true}>\n\n This API is experimental and may have some slight breaking changes in the next release... | https://github.com/huggingface/transformers.git | |
10 | get | def get(self, request):
model = self.queryset.model
content_type = ContentType.objects.get_for_model(model)
if self.filterset:
self.queryset = self.filterset(request.GET, self.queryset).qs
# Compile a dictionary indicating which permissions are available to the cur... | 54834c47f8870e7faabcd847c3270da0bd3d2884 | 17 | bulk_views.py | 565 | Refactor generic views; add plugins dev documentation | 77,669 | 0 | 698 | 342 | 123 | 264,296 | 192 | netbox | 47 | netbox/netbox/views/generic/bulk_views.py | Python | 40 | {
"docstring": "\n GET request handler.\n\n Args:\n request: The current request\n ",
"language": "en",
"n_whitespaces": 41,
"n_words": 8,
"vocab_size": 7
} | https://github.com/netbox-community/netbox.git | |
1 | load_audio | def load_audio(file_path):
x, sr = torchaudio.load(file_path)
assert (x > 1).sum() + (x < -1).sum() == 0
return x, sr
| 00c7600103ee34ac50506af88f1b34b713f849e7 | 12 | vits.py | 72 | Update Vits model API | 77,159 | 0 | 31 | 43 | 16 | 262,249 | 19 | TTS | 7 | TTS/tts/models/vits.py | Python | 4 | {
"docstring": "Load the audio file normalized in [-1, 1]\n\n Return Shapes:\n - x: :math:`[1, T]`\n ",
"language": "en",
"n_whitespaces": 27,
"n_words": 14,
"vocab_size": 14
} | https://github.com/coqui-ai/TTS.git | |
2 | state | def state(self) -> Mapping[str, Any]:
if self._cursor_value:
return {
self.cursor_field: self._cursor_value,
"include_deleted": self._include_deleted,
}
return {}
| a3aae8017a0a40ff2006e2567f71dccb04c997a5 | 10 | base_streams.py | 61 | 🎉 🎉 Source FB Marketing: performance and reliability fixes (#9805)
* Facebook Marketing performance improvement
* add comments and little refactoring
* fix integration tests with the new config
* improve job status handling, limit concurrency to 10
* fix campaign jobs, refactor manager
* big refactori... | 553 | 0 | 89 | 38 | 15 | 3,767 | 16 | airbyte | 8 | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/base_streams.py | Python | 8 | {
"docstring": "State getter, get current state and serialize it to emmit Airbyte STATE message",
"language": "en",
"n_whitespaces": 12,
"n_words": 13,
"vocab_size": 13
} | https://github.com/airbytehq/airbyte.git | |
4 | create_nested_bom | def create_nested_bom(tree, prefix="_Test bom "):
def create_items(bom_tree):
for item_code, subtree in bom_tree.items():
bom_item_code = prefix + item_code
if not frappe.db.exists("Item", bom_item_code):
frappe.get_doc(doctype="Item", item_code=bom_item_code, item_group="_Test Item Group").insert()
... | 8dff4d66a4a13def61276c2b46cbf0984c469819 | 17 | test_bom.py | 346 | fix: bom valuation - handle lack of LPP (#30454) | 13,699 | 0 | 74 | 107 | 65 | 64,713 | 102 | erpnext | 32 | erpnext/manufacturing/doctype/bom/test_bom.py | Python | 17 | {
"docstring": " Helper function to create a simple nested bom from tree describing item names. (along with required items)\n\tnaive implementation for searching right subtree",
"language": "en",
"n_whitespaces": 22,
"n_words": 23,
"vocab_size": 23
} | https://github.com/frappe/erpnext.git | |
3 | _make_historical_mat_time | def _make_historical_mat_time(deltas, changepoints_t, t_time, n_row=1, single_diff=None):
if single_diff is None:
single_diff = np.diff(t_time).mean()
prev_time = np.arange(0, 1 + single_diff, single_diff)
idxs = []
for changepoint in changepoints_t:
idxs... | 8fbf8ba2a5bfcdb892e8ca596e338894614000b5 | 14 | forecaster.py | 183 | Speed Up Uncertainty Predictions (#2186) | 441 | 0 | 130 | 120 | 37 | 3,306 | 45 | prophet | 21 | python/prophet/forecaster.py | Python | 11 | {
"docstring": "\n Creates a matrix of slope-deltas where these changes occured in training data according to the trained prophet obj\n ",
"language": "en",
"n_whitespaces": 33,
"n_words": 18,
"vocab_size": 18
} | https://github.com/facebook/prophet.git | |
1 | test_lm_generate_gpt2_xla | def test_lm_generate_gpt2_xla(self):
model = TFGPT2LMHeadModel.from_pretrained("gpt2")
input_ids = tf.convert_to_tensor([[464, 3290]], dtype=tf.int32) # The dog
# The dog was found in a field near the intersection of West and West Streets.\n\nThe dog
# fmt: off
expecte... | cd4c5c90605b2e23879fcca484f7079b0fc0c361 | 12 | test_modeling_tf_gpt2.py | 173 | TF XLA greedy generation (#15786)
* First attempt at TF XLA generation
* Fix comments
* Update XLA greedy generate with direct XLA calls
* Support attention mask, prepare_inputs_for_generation no longer hardcoded for greedy
* Handle position_ids correctly
* make xla generate work for non xla case
* f... | 6,584 | 0 | 139 | 120 | 54 | 36,194 | 68 | transformers | 20 | tests/gpt2/test_modeling_tf_gpt2.py | Python | 7 | {
"docstring": "This test gives the exact same results as the non-xla test above",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 10
} | https://github.com/huggingface/transformers.git | |
4 | Error | def Error(filename, linenum, category, confidence, message):
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
filename, linenum, message, category, conf... | cc4d0564756ca067516f71718a3d135996525909 | 14 | cpp_lint.py | 241 | Balanced joint maximum mean discrepancy for deep transfer learning | 12,139 | 0 | 246 | 106 | 120 | 60,411 | 192 | transferlearning | 20 | code/deep/BJMMD/caffe/scripts/cpp_lint.py | Python | 12 | {
"docstring": "Logs the fact we've found a lint error.\n\n We log where the error was found, and also our confidence in the error,\n that is, how certain we are this is a legitimate style regression, and\n not a misidentification or a use that's sometimes justified.\n\n False positives can be suppressed by the u... | https://github.com/jindongwang/transferlearning.git | |
1 | write_gexf | def write_gexf(G, path, encoding="utf-8", prettyprint=True, version="1.2draft"):
writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint, version=version)
writer.add_graph(G)
writer.write(path)
| 54e36acb36c75e09bc53dfcb81c73386b82a20c9 | 9 | gexf.py | 77 | Update gexf website link in documentation (#5275)
Hi, we've recently put the GEXF website again into its own domain http://gexf.net/ so this documentation should be updated. Thanks! | 41,769 | 0 | 25 | 48 | 13 | 176,216 | 13 | networkx | 10 | networkx/readwrite/gexf.py | Python | 4 | {
"docstring": "Write G in GEXF format to path.\n\n \"GEXF (Graph Exchange XML Format) is a language for describing\n complex networks structures, their associated data and dynamics\" [1]_.\n\n Node attributes are checked according to the version of the GEXF\n schemas used for parameters which are not use... | https://github.com/networkx/networkx.git | |
1 | test_user_supplied_base_job_with_labels | def test_user_supplied_base_job_with_labels(self):
manifest = KubernetesJob(
command=["echo", "hello"],
job={
"apiVersion": "batch/v1",
"kind": "Job",
"metadata": {"labels": {"my-custom-label": "sweet"}},
"spec": {
... | daddc2985f0cba6c6e0ae3903232cbca155e7e91 | 23 | test_kubernetes_job.py | 201 | Port KubernetesFlowRunner tests to KubernetesJob tests | 11,669 | 0 | 574 | 104 | 47 | 57,490 | 58 | prefect | 7 | tests/infrastructure/test_kubernetes_job.py | Python | 27 | {
"docstring": "The user can supply a custom base job with labels and they will be\n included in the final manifest",
"language": "en",
"n_whitespaces": 25,
"n_words": 19,
"vocab_size": 19
} | https://github.com/PrefectHQ/prefect.git | |
1 | require_torch_bf16_gpu | def require_torch_bf16_gpu(test_case):
return unittest.skipUnless(
is_torch_bf16_gpu_available(),
"test requires torch>=1.10, using Ampere GPU or newer arch with cuda>=11.0",
)(test_case)
| a2d34b7c040723b92823310e3b8fd66874c9d667 | 10 | testing_utils.py | 38 | deprecate is_torch_bf16_available (#17738)
* deprecate is_torch_bf16_available
* address suggestions | 5,727 | 0 | 40 | 21 | 17 | 31,379 | 17 | transformers | 5 | src/transformers/testing_utils.py | Python | 5 | {
"docstring": "Decorator marking a test that requires torch>=1.10, using Ampere GPU or newer arch with cuda>=11.0",
"language": "en",
"n_whitespaces": 14,
"n_words": 15,
"vocab_size": 15
} | https://github.com/huggingface/transformers.git | |
1 | test_enable_disable_conflict_with_config | def test_enable_disable_conflict_with_config():
nlp = English()
nlp.add_pipe("tagger")
nlp.add_pipe("senter")
nlp.add_pipe("sentencizer")
with make_tempdir() as tmp_dir:
nlp.to_disk(tmp_dir)
# Expected to fail, as config and arguments conflict.
with pytest.raises(ValueE... | aea16719be04d4d6ab889cd20fe0e323b2c7ffee | 18 | test_pipe_methods.py | 235 | Simplify and clarify enable/disable behavior of spacy.load() (#11459)
* Change enable/disable behavior so that arguments take precedence over config options. Extend error message on conflict. Add warning message in case of overwriting config option with arguments.
* Fix tests in test_serialize_pipeline.py to reflec... | 24,437 | 0 | 258 | 127 | 49 | 111,556 | 72 | spaCy | 17 | spacy/tests/pipeline/test_pipe_methods.py | Python | 19 | {
"docstring": "Test conflict between enable/disable w.r.t. `nlp.disabled` set in the config.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/explosion/spaCy.git | |
14 | broadcast_object_list | def broadcast_object_list(object_list, src=0, group=None, device=None):
if _rank_not_in_group(group):
_warn_not_in_group("broadcast_object_list")
return
my_rank = get_rank()
# Serialize object_list elements to tensors on src rank.
if my_rank == src:
tensor_list, size_list =... | e1e43c4e710389a3fcf54cd7f3537336e21d3ae5 | 16 | distributed_c10d.py | 502 | Prevent sum overflow in broadcast_object_list (#70605)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/70605
broadcast_object_list casted the sum of all object lengths to int from long causing overflows.
Test Plan:
Add a Tensor with >2GB storage requirement (in distributed_test.py) to object... | 21,501 | 0 | 584 | 301 | 149 | 102,230 | 250 | pytorch | 40 | torch/distributed/distributed_c10d.py | Python | 42 | {
"docstring": "\n Broadcasts picklable objects in ``object_list`` to the whole group. Similar\n to :func:`broadcast`, but Python objects can be passed in.\n Note that all objects in ``object_list`` must be picklable in order to be\n broadcasted.\n\n Args:\n object_list (List[Any]): List of inpu... | https://github.com/pytorch/pytorch.git | |
3 | forward | def forward(self, data, optimizer=None, return_loss=False, **kwargs):
batch_inputs, batch_data_samples = self.preprocss_data(data)
if torch.onnx.is_in_onnx_export():
# TODO: Delete
assert len(batch_inputs) == 1
return self.onnx_export(batch_inputs, batch_dat... | 924c381a78eb70cede198e042ef34e038e05c15a | 13 | base.py | 209 | Modify RetinaNet model interface | 70,395 | 0 | 372 | 135 | 55 | 244,473 | 70 | mmdetection | 25 | mmdet/models/detectors/base.py | Python | 20 | {
"docstring": "The iteration step during training and testing. This method defines\n an iteration step during training and testing, except for the back\n propagation and optimizer updating during training, which are done in\n an optimizer hook.\n\n Args:\n data (list[dict]): Th... | https://github.com/open-mmlab/mmdetection.git | |
8 | mode | def mode(a, axis=0, nan_policy='propagate'):
a, axis = _chk_asarray(a, axis)
if a.size == 0:
return ModeResult(np.array([]), np.array([]))
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return msta... | 7438fe5edfb565ff341fa6ab054461fcdd504aa2 | 13 | _stats_py.py | 336 | MAINT: stats: mode: fix negative axis issue with np.moveaxis instead of custom code (#15421) | 69,724 | 0 | 259 | 340 | 78 | 241,885 | 108 | scipy | 35 | scipy/stats/_stats_py.py | Python | 31 | {
"docstring": "Return an array of the modal (most common) value in the passed array.\n\n If there is more than one such value, only the smallest is returned.\n The bin-count for the modal bins is also returned.\n\n Parameters\n ----------\n a : array_like\n n-dimensional array of which to find ... | https://github.com/scipy/scipy.git | |
3 | ascents | def ascents(self):
a = self.array_form
pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]]
return pos
| 498015021131af4dbb07eb110e5badaba8250c7b | 13 | permutations.py | 67 | Updated import locations | 47,664 | 0 | 50 | 42 | 20 | 196,164 | 22 | sympy | 8 | sympy/combinatorics/permutations.py | Python | 4 | {
"docstring": "\n Returns the positions of ascents in a permutation, ie, the location\n where p[i] < p[i+1]\n\n Examples\n ========\n\n >>> from sympy.combinatorics import Permutation\n >>> p = Permutation([4, 0, 1, 3, 2])\n >>> p.ascents()\n [1, 2]\n\n ... | https://github.com/sympy/sympy.git | |
20 | _orbit | def _orbit(degree, generators, alpha, action='tuples'):
r
if not hasattr(alpha, '__getitem__'):
alpha = [alpha]
gens = [x._array_form for x in generators]
if len(alpha) == 1 or action == 'union':
orb = alpha
used = [False]*degree
for el in alpha:
used[el] = T... | 498015021131af4dbb07eb110e5badaba8250c7b | 17 | perm_groups.py | 405 | Updated import locations | 47,623 | 0 | 517 | 258 | 56 | 196,123 | 140 | sympy | 21 | sympy/combinatorics/perm_groups.py | Python | 74 | {
"docstring": "Compute the orbit of alpha `\\{g(\\alpha) | g \\in G\\}` as a set.\n\n Explanation\n ===========\n\n The time complexity of the algorithm used here is `O(|Orb|*r)` where\n `|Orb|` is the size of the orbit and ``r`` is the number of generators of\n the group. For a more detailed analysis... | https://github.com/sympy/sympy.git | |
1 | _obj_reference_counts | def _obj_reference_counts(self):
self._maybe_create_attribute(
"_obj_reference_counts_dict",
object_identity.ObjectIdentityDictionary(),
)
return self._obj_reference_counts_dict
| 84afc5193d38057e2e2badf9c889ea87d80d8fbf | 9 | base_layer.py | 41 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 80,532 | 0 | 58 | 23 | 8 | 270,708 | 8 | keras | 6 | keras/engine/base_layer.py | Python | 6 | {
"docstring": "A dictionary counting the number of attributes referencing an object.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/keras-team/keras.git | |
2 | on_idle | async def on_idle(self) -> None:
if self._require_styles_update:
await self.post_message(messages.StylesUpdated(self))
self._require_styles_update = False
| ada31e68de9065d5d407b16868fe1a2ddb88c548 | 12 | app.py | 53 | docstring | 43,997 | 0 | 48 | 30 | 12 | 182,890 | 12 | textual | 6 | src/textual/app.py | Python | 5 | {
"docstring": "Perform actions when there are no messages in the queue.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/Textualize/textual.git | |
4 | unset_outlier_removal | def unset_outlier_removal(self):
if self.ft_params.get('use_SVM_to_remove_outliers', False):
self.ft_params.update({'use_SVM_to_remove_outliers': False})
logger.warning('User tried to use SVM with RL. Deactivating SVM.')
if self.ft_params.get('use_DBSCAN_to_remove_outlie... | 8aac644009dd7a8ab8f006594b547abddad5aca9 | 12 | BaseReinforcementLearningModel.py | 180 | add tests. add guardrails. | 34,968 | 0 | 139 | 100 | 27 | 151,174 | 45 | freqtrade | 8 | freqtrade/freqai/RL/BaseReinforcementLearningModel.py | Python | 10 | {
"docstring": "\n If user has activated any function that may remove training points, this\n function will set them to false and warn them\n ",
"language": "en",
"n_whitespaces": 43,
"n_words": 21,
"vocab_size": 19
} | https://github.com/freqtrade/freqtrade.git | |
2 | log_has_when | def log_has_when(line, logs, when):
return any(line == message.message for message in logs.get_records(when))
| 866a5649588c77ec686ba65e581d1306d8ea3751 | 10 | conftest.py | 44 | update emc start/shutdown, initial emc tests | 34,960 | 0 | 18 | 28 | 12 | 151,131 | 12 | freqtrade | 7 | tests/conftest.py | Python | 2 | {
"docstring": "Check if line is found in caplog's messages during a specified stage",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 12
} | https://github.com/freqtrade/freqtrade.git | |
1 | bcoo_dot_general_sampled | def bcoo_dot_general_sampled(A, B, indices, *, dimension_numbers):
(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers
cdims = (api_util._ensure_index_tuple(lhs_contract),
api_util._ensure_index_tuple(rhs_contract))
bdims = (api_util._ensure_index_tuple(lhs_batch),
ap... | 3184dd65a222354bffa2466d9a375162f5649132 | @bcoo_dot_general_sampled_p.def_impl | 9 | bcoo.py | 124 | [sparse] Update docstrings for bcoo primitives.
PiperOrigin-RevId: 438685829 | 26,736 | 1 | 91 | 80 | 23 | 119,984 | 27 | jax | 16 | jax/experimental/sparse/bcoo.py | Python | 8 | {
"docstring": "A contraction operation with output computed at given sparse indices.\n\n Args:\n lhs: An ndarray.\n rhs: An ndarray.\n indices: BCOO indices.\n dimension_numbers: a tuple of tuples of the form\n `((lhs_contracting_dims, rhs_contracting_dims),\n (lhs_batch_dims, rhs_batch_dims))... | https://github.com/google/jax.git |
2 | setup_args | def setup_args(parser=None) -> ParlaiParser:
if parser is None:
parser = ParlaiParser(True, True, 'Train a model')
train = parser.add_argument_group('Training Loop Arguments')
train.add_argument(
'-et',
'--evaltask',
help='task to use for valid/test (defaults to the one ... | 7c2b199d0b315c9016072897d849811cfc8a5073 | 11 | train_model.py | 1,162 | Add WorldLogger to train_model script. (#4369)
* Add WorldLogger to train_model ParlAI script.
* Fix test_save_multiple_world_logs in test_train_model.py | 47,086 | 0 | 1,676 | 687 | 289 | 194,794 | 516 | ParlAI | 21 | parlai/scripts/train_model.py | Python | 206 | {
"docstring": "\n Build the ParlAI parser, adding command line args if necessary.\n\n :param ParlaiParser parser:\n Preexisting parser to append options to. Will be created if needed.\n\n :returns:\n the ParlaiParser with CLI options added.\n ",
"language": "en",
"n_whitespaces": 58,
... | https://github.com/facebookresearch/ParlAI.git | |
2 | test_messages_filter_not_labels | def test_messages_filter_not_labels(self) -> None:
self._send_labelled_messages_in_room()
token = "s0_0_0_0_0_0_0_0_0"
channel = self.make_request(
"GET",
"/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
% (self.room_id, self.tok, token, json.d... | 2ffaf30803f93273a4d8a65c9e6c3110c8433488 | 13 | test_rooms.py | 272 | Add type hints to `tests/rest/client` (#12108)
* Add type hints to `tests/rest/client`
* newsfile
* fix imports
* add `test_account.py`
* Remove one type hint in `test_report_event.py`
* change `on_create_room` to `async`
* update new functions in `test_third_party_rules.py`
* Add `test_filter.py`... | 71,573 | 0 | 178 | 166 | 42 | 247,290 | 50 | synapse | 16 | tests/rest/client/test_rooms.py | Python | 17 | {
"docstring": "Test that we can filter by the absence of a label on a /messages request.",
"language": "en",
"n_whitespaces": 14,
"n_words": 15,
"vocab_size": 14
} | https://github.com/matrix-org/synapse.git | |
4 | json | def json(self, body):
import streamlit as st
if isinstance(body, LazySessionState):
body = body.to_dict()
if not isinstance(body, str):
try:
body = json.dumps(body, default=repr)
except TypeError as err:
st.warning(
... | 72703b38029f9358a0ec7ca5ed875a6b438ece19 | 15 | json.py | 168 | Replace static apps with live Cloud apps (#4317)
Co-authored-by: kajarenc <kajarenc@gmail.com> | 26,392 | 0 | 246 | 101 | 51 | 118,735 | 65 | streamlit | 20 | lib/streamlit/elements/json.py | Python | 16 | {
"docstring": "Display object or string as a pretty-printed JSON string.\n\n Parameters\n ----------\n body : Object or str\n The object to print as JSON. All referenced objects should be\n serializable to JSON as well. If object is a string, we assume it\n conta... | https://github.com/streamlit/streamlit.git | |
4 | set_kill_child_on_death_win32 | def set_kill_child_on_death_win32(child_proc):
if isinstance(child_proc, subprocess.Popen):
child_proc = child_proc._handle
assert isinstance(child_proc, subprocess.Handle)
if detect_fate_sharing_support_win32():
if not win32_AssignProcessToJobObject(win32_job, int(child_proc)):
... | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | 13 | utils.py | 111 | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 29,222 | 0 | 89 | 66 | 27 | 130,302 | 31 | ray | 14 | python/ray/_private/utils.py | Python | 10 | {
"docstring": "Ensures the child process dies if this process dies (fate-sharing).\n\n Windows-only. Must be called by the parent, after spawning the child.\n\n Args:\n child_proc: The subprocess.Popen or subprocess.Handle object.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 28,
"vo... | https://github.com/ray-project/ray.git | |
4 | unflatten_superdims | def unflatten_superdims(assignment):
def check(cond):
if cond: return
raise NotImplementedError("Failed to convert OpSharding into a ShardingSpec. "
"Please open a bug report!")
flat_assignment = np.asarray(assignment, dtype=np.int64)
check(flat_assignment[0] == 0)
dims ... | 4b587fa1f0049db5366fd04812ab940d80a71a22 | 11 | pjit.py | 192 | Move `pjit.py` to `jax/_src` in preparation for merging the `jit` and `pjit` frontend APIs
PiperOrigin-RevId: 495944279 | 27,261 | 0 | 182 | 101 | 74 | 122,886 | 98 | jax | 17 | jax/_src/pjit.py | Python | 16 | {
"docstring": "Unflatten a list of dimension sizes and their strides that generates assignment.\n\n If this function succeeds for a given ``assignment``, then the following property\n should be satisfied::\n\n dims_with_strides = unflatten_superdims(assignment)\n base_array = np.arange(map(fst, sorted(dims_w... | https://github.com/google/jax.git | |
4 | _get_storage_by_url | def _get_storage_by_url(self, url, storage_objects):
from io_storages.models import get_storage_classes
for storage_object in storage_objects:
# check url is string because task can have int, float, dict, list
# and 'can_resolve_url' will fail
if isinstance(... | 6293c3226e3713bdae678603d6c1300e09c41448 | 10 | models.py | 61 | fix: DEV-1476: Resolving performance for project storages (#1910)
* Fix: DEV-1476: Resolving performance for project storages
* Rewrite cache
* Remove cache completely | 42,439 | 0 | 106 | 38 | 34 | 177,558 | 37 | label-studio | 11 | label_studio/tasks/models.py | Python | 5 | {
"docstring": "Find the first compatible storage and returns pre-signed URL",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/heartexlabs/label-studio.git | |
1 | swap_memory | def swap_memory():
mem = cext.virtual_mem()
total_phys = mem[0]
free_phys = mem[1]
total_system = mem[2]
free_system = mem[3]
# Despite the name PageFile refers to total system memory here
# thus physical memory values need to be subtracted to get swap values
total = total_system ... | 471b19d2aa799cd73bded23379e864dd35bec2b6 | 9 | _pswindows.py | 142 | Fix typos | 45,962 | 0 | 114 | 85 | 53 | 188,999 | 79 | psutil | 18 | psutil/_pswindows.py | Python | 11 | {
"docstring": "Swap system memory as a (total, used, free, sin, sout) tuple.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/giampaolo/psutil.git | |
1 | test_default_disabling_entity | async def test_default_disabling_entity(hass, create_registrations, webhook_client):
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
... | 539ce7ff0e9d9bc59cd8f028f245c09f802c89cb | 15 | test_sensor.py | 230 | Allow mobile app to disable entities by default (#71562) | 99,145 | 0 | 228 | 129 | 45 | 300,279 | 61 | core | 21 | tests/components/mobile_app/test_sensor.py | Python | 25 | {
"docstring": "Test that sensors can be disabled by default upon registration.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/home-assistant/core.git | |
6 | RGS | def RGS(self):
rgs = {}
partition = self.partition
for i, part in enumerate(partition):
for j in part:
rgs[j] = i
return tuple([rgs[i] for i in sorted(
[i for p in partition for i in p], key=default_sort_key)])
| 498015021131af4dbb07eb110e5badaba8250c7b | 13 | partitions.py | 102 | Updated import locations | 47,606 | 0 | 108 | 67 | 23 | 196,106 | 36 | sympy | 13 | sympy/combinatorics/partitions.py | Python | 8 | {
"docstring": "\n Returns the \"restricted growth string\" of the partition.\n\n Explanation\n ===========\n\n The RGS is returned as a list of indices, L, where L[i] indicates\n the block in which element i appears. For example, in a partition\n of 3 elements (a, b, c) into... | https://github.com/sympy/sympy.git | |
2 | pause_time | def pause_time(self) -> int | None:
pause_time = self._status.get("timer_target")
if pause_time is not None:
return wilight_to_hass_pause_time(pause_time)
return pause_time
| 34984a8af8efc5ef6d1d204404c517e7f7c2d1bb | 9 | switch.py | 57 | Add switch to wilight (#62873)
* Created switch.py and support
* updated support.py
* test for wilight switch
* Update for Test
* Updated test_switch.py
* Trigger service with index
* Updated support.py and switch.py
* Updated support.py
* Updated switch.py as PR#63614
* Updated switch.py
... | 102,317 | 0 | 57 | 33 | 14 | 303,498 | 18 | core | 6 | homeassistant/components/wilight/switch.py | Python | 9 | {
"docstring": "Return pause time of valve switch.\n\n None is unknown, 1 is minimum, 24 is maximum.\n ",
"language": "en",
"n_whitespaces": 29,
"n_words": 15,
"vocab_size": 13
} | https://github.com/home-assistant/core.git | |
7 | set_param_recursive | def set_param_recursive(pipeline_steps, parameter, value):
for (_, obj) in pipeline_steps:
recursive_attrs = ["steps", "transformer_list", "estimators"]
for attr in recursive_attrs:
if hasattr(obj, attr):
set_param_recursive(getattr(obj, attr), parameter, value)
... | 388616b6247ca4ea8de4e2f340d6206aee523541 | 15 | export_utils.py | 159 | Revert "Deployed 7ccda9a with MkDocs version: 1.3.0"
This reverts commit bd9629c40e01241766197119b581a99409b07068. | 43,655 | 0 | 156 | 102 | 33 | 181,902 | 47 | tpot | 12 | tpot/export_utils.py | Python | 12 | {
"docstring": "Recursively iterate through all objects in the pipeline and set a given parameter.\n\n Parameters\n ----------\n pipeline_steps: array-like\n List of (str, obj) tuples from a scikit-learn pipeline or related object\n parameter: str\n The parameter to assign a value for in eac... | https://github.com/EpistasisLab/tpot.git | |
2 | embedding_dim | def embedding_dim(self) -> int:
emedding_dim = self.model.get_sentence_embedding_dimension()
if not emedding_dim:
logger.warning(
"Can't find the output embedding dimensions for '%s'. Some checks will not run as intended.",
self.model_name_or_path,
... | 101d2bc86cab29f5e93cccd58730c5932acf8ca3 | 10 | sentence_transformers.py | 59 | feat: `MultiModalRetriever` (#2891)
* Adding Data2VecVision and Data2VecText to the supported models and adapt Tokenizers accordingly
* content_types
* Splitting classes into respective folders
* small changes
* Fix EOF
* eof
* black
* API
* EOF
* whitespace
* api
* improve multimodal ... | 75,174 | 0 | 110 | 34 | 28 | 257,944 | 30 | haystack | 9 | haystack/modeling/model/multimodal/sentence_transformers.py | Python | 11 | {
"docstring": "\n Finds out the output embedding dim by running the model on a minimal amount of mock data.\n ",
"language": "en",
"n_whitespaces": 32,
"n_words": 17,
"vocab_size": 16
} | https://github.com/deepset-ai/haystack.git | |
2 | blobprotovector_str_to_arraylist | def blobprotovector_str_to_arraylist(str):
vec = caffe_pb2.BlobProtoVector()
vec.ParseFromString(str)
return [blobproto_to_array(blob) for blob in vec.blobs]
| cc4d0564756ca067516f71718a3d135996525909 | 8 | io.py | 54 | Balanced joint maximum mean discrepancy for deep transfer learning | 12,054 | 0 | 24 | 32 | 12 | 60,263 | 12 | transferlearning | 9 | code/deep/BJMMD/caffe/python/caffe/io.py | Python | 4 | {
"docstring": "Converts a serialized blobprotovec to a list of arrays.\n ",
"language": "en",
"n_whitespaces": 12,
"n_words": 9,
"vocab_size": 8
} | https://github.com/jindongwang/transferlearning.git | |
2 | dag_bag_ext | def dag_bag_ext():
clear_db_runs()
dag_bag = DagBag(dag_folder=DEV_NULL, include_examples=False)
dag_0 = DAG("dag_0", start_date=DEFAULT_DATE, schedule_interval=None)
task_a_0 = EmptyOperator(task_id="task_a_0", dag=dag_0)
task_b_0 = ExternalTaskMarker(
task_id="task_b_0", external_da... | 49e336ae0302b386a2f47269a6d13988382d975f | @pytest.fixture | 10 | test_external_task_sensor.py | 460 | Replace usage of `DummyOperator` with `EmptyOperator` (#22974)
* Replace usage of `DummyOperator` with `EmptyOperator` | 9,197 | 1 | 243 | 290 | 69 | 47,660 | 111 | airflow | 36 | tests/sensors/test_external_task_sensor.py | Python | 35 | {
"docstring": "\n Create a DagBag with DAGs looking like this. The dotted lines represent external dependencies\n set up using ExternalTaskMarker and ExternalTaskSensor.\n\n dag_0: task_a_0 >> task_b_0\n |\n |\n dag_1: ---> task_... | https://github.com/apache/airflow.git |
3 | clone_model | def clone_model(model, input_tensors=None, clone_function=None):
with serialization.DisableSharedObjectScope():
if clone_function is None:
clone_function = _clone_layer
if isinstance(model, Sequential):
return _clone_sequential_model(
model, input_tensor... | c269e3cd8fed713fb54d2971319df0bfe6e1bf10 | 13 | cloning.py | 103 | Move serialization-related logic in utils/generic_utils.py to saving/legacy/serialization.py.
PiperOrigin-RevId: 479688207 | 83,239 | 0 | 151 | 65 | 33 | 280,071 | 40 | keras | 12 | keras/models/cloning.py | Python | 12 | {
"docstring": "Clone a Functional or Sequential `Model` instance.\n\n Model cloning is similar to calling a model on new inputs,\n except that it creates new layers (and thus new weights) instead\n of sharing the weights of the existing layers.\n\n Note that\n `clone_model` will not preserve the uniqu... | https://github.com/keras-team/keras.git | |
11 | update_billed_amount_based_on_so | def update_billed_amount_based_on_so(so_detail, update_modified=True):
# Billed against Sales Order directly
billed_against_so = frappe.db.sql(, so_detail)
billed_against_so = billed_against_so and billed_against_so[0][0] or 0
# Get all Delivery Note Item rows against the Sales Order Item row
dn_details = frappe.... | b50036c04a116b2a3aa1784daf161a2f618765a8 | 17 | delivery_note.py | 331 | fix: consider returned_qty while updating billed_amt
(cherry picked from commit 63aaa1e357280b24c537a502a479f7bb7a6654e4) | 13,584 | 0 | 112 | 205 | 75 | 64,240 | 145 | erpnext | 22 | erpnext/stock/doctype/delivery_note/delivery_note.py | Python | 44 | {
"docstring": "select sum(si_item.amount)\n\t\tfrom `tabSales Invoice Item` si_item, `tabSales Invoice` si\n\t\twhere\n\t\t\tsi_item.parent = si.name\n\t\t\tand si_item.so_detail=%s\n\t\t\tand (si_item.dn_detail is null or si_item.dn_detail = '')\n\t\t\tand si_item.docstatus=1\n\t\t\tand si.update_stock = 0\n\t\tsel... | https://github.com/frappe/erpnext.git | |
4 | floyd_warshall_numpy | def floyd_warshall_numpy(G, nodelist=None, weight="weight"):
import numpy as np
if nodelist is not None:
if not (len(nodelist) == len(G) == len(set(nodelist))):
raise nx.NetworkXError(
"nodelist must contain every node in G with no repeats."
"If you want... | 930121ffb89d01077b9888abbd5e810a7e5e16a4 | 14 | dense.py | 220 | More numpy.matrix cleanups for NX2.7 (#5319)
* Fix return type in docstring of internal function.
* Rm explicit mention of numpy matrix from class docstrings.
* Fix return type of floyd_warshall_numpy docstring.
* Remove mention of numpy matrix from code comment.
* Fix simrank similarity internal docstring... | 41,826 | 0 | 230 | 139 | 96 | 176,311 | 116 | networkx | 24 | networkx/algorithms/shortest_paths/dense.py | Python | 16 | {
"docstring": "Find all-pairs shortest path lengths using Floyd's algorithm.\n\n This algorithm for finding shortest paths takes advantage of\n matrix representations of a graph and works well for dense\n graphs where all-pairs shortest path lengths are desired.\n The results are returned as a NumPy arra... | https://github.com/networkx/networkx.git | |
3 | __getattr__ | def __getattr__(cls, name):
if _is_dunder(name):
raise AttributeError(name)
try:
return cls._member_map_[name]
except KeyError:
raise AttributeError(name) from None
| 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 10 | enum.py | 62 | add python 3.10.4 for windows | 54,713 | 0 | 77 | 38 | 14 | 217,315 | 16 | XX-Net | 7 | python3.10.4/Lib/enum.py | Python | 7 | {
"docstring": "\n Return the enum member matching `name`\n\n We use __getattr__ instead of descriptors or inserting into the enum\n class' __dict__ in order to support `name` and `value` being both\n properties for enum members (which live in the class' __dict__) and\n enum members... | https://github.com/XX-net/XX-Net.git | |
2 | index_subdirectory | def index_subdirectory(directory, class_indices, follow_links, formats):
dirname = os.path.basename(directory)
valid_files = iter_valid_files(directory, follow_links, formats)
labels = []
filenames = []
for root, fname in valid_files:
labels.append(class_indices[dirname])
absolute_path = tf.io.gfil... | b3f1f645238c93ec3b283f64f73a02df3aea6b53 | 13 | dataset_utils.py | 158 | use tf.io.gfile instead of os.path to support cloud paths.
PiperOrigin-RevId: 430975400 | 79,856 | 0 | 65 | 103 | 31 | 269,045 | 39 | keras | 23 | keras/preprocessing/dataset_utils.py | Python | 12 | {
"docstring": "Recursively walks directory and list image paths and their class index.\n\n Args:\n directory: string, target directory.\n class_indices: dict mapping class names to their index.\n follow_links: boolean, whether to recursively follow subdirectories\n (if False, we only list top-level im... | https://github.com/keras-team/keras.git | |
1 | test_loading_race_condition | async def test_loading_race_condition(hass):
store = auth_store.AuthStore(hass)
with patch(
"homeassistant.helpers.entity_registry.async_get"
) as mock_ent_registry, patch(
"homeassistant.helpers.device_registry.async_get"
) as mock_dev_registry, patch(
"homeassistant.helper... | 69cc6ab5f1d58adc586c3b300a4f7f0cde2cd0c2 | 13 | test_auth_store.py | 152 | Clean up accessing entity_registry.async_get_registry helper via hass (#72005) | 99,666 | 0 | 109 | 86 | 28 | 300,810 | 35 | core | 15 | tests/auth/test_auth_store.py | Python | 14 | {
"docstring": "Test only one storage load called when concurrent loading occurred .",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/home-assistant/core.git | |
2 | test_fcos_head_loss | def test_fcos_head_loss(self):
s = 256
img_metas = [{
'img_shape': (s, s, 3),
'scale_factor': 1,
}]
fcos_head = FCOSHead(
num_classes=4,
in_channels=1,
feat_channels=1,
stacked_convs=1,
norm_cfg=... | 015f8a9bafe808fbe3db673d629f126a804a9207 | 11 | test_fcos_head.py | 780 | Refactor interface of base dense free head and fcos head | 70,419 | 0 | 1,066 | 484 | 153 | 244,526 | 314 | mmdetection | 50 | tests/test_models/test_dense_heads/test_fcos_head.py | Python | 64 | {
"docstring": "Tests fcos head loss when truth is empty and non-empty.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/open-mmlab/mmdetection.git | |
1 | test_cancellation_while_holding_read_lock | def test_cancellation_while_holding_read_lock(self):
rwlock = ReadWriteLock()
key = "key"
# 1. A reader takes the lock and blocks.
reader_d, _, _ = self._start_blocking_reader(rwlock, key, "read completed")
# 2. A writer waits for the reader to complete.
writer... | 605d161d7d585847fd1bb98d14d5281daeac8e86 | 9 | test_rwlock.py | 152 | Add cancellation support to `ReadWriteLock` (#12120)
Also convert `ReadWriteLock` to use async context managers.
Signed-off-by: Sean Quah <seanq@element.io> | 71,759 | 0 | 192 | 88 | 55 | 247,584 | 76 | synapse | 18 | tests/util/test_rwlock.py | Python | 12 | {
"docstring": "Test cancellation while holding a read lock.\n\n A waiting writer should be given the lock when the reader holding the lock is\n cancelled.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 23,
"vocab_size": 19
} | https://github.com/matrix-org/synapse.git | |
4 | description_of | def description_of(lines, name="stdin"):
u = UniversalDetector()
for line in lines:
line = bytearray(line)
u.feed(line)
# shortcut out of the loop to save reading further - particularly useful if we read a BOM.
if u.done:
break
u.close()
result = u.result... | cd5a9683be69c86c8f3adcd13385a9bc5db198ec | 11 | chardetect.py | 133 | Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir. | 4,090 | 0 | 118 | 60 | 45 | 21,896 | 51 | pipenv | 11 | pipenv/patched/pip/_vendor/chardet/cli/chardetect.py | Python | 12 | {
"docstring": "\n Return a string describing the probable encoding of a file or\n list of strings.\n\n :param lines: The lines to get the encoding of.\n :type lines: Iterable of bytes\n :param name: Name of file or collection of lines\n :type name: str\n ",
"language": "en",
"n_whitespaces":... | https://github.com/pypa/pipenv.git | |
1 | load | def load(self, loader):
loader.add_option(
"connection_strategy",
str,
"eager",
"Determine when server connections should be established. When set to lazy, mitmproxy "
"tries to defer establishing an upstream connection as long as possible. This makes ... | 42ccc85b6f1881d92b55e411ba9719f26459b720 | 10 | proxyserver.py | 217 | [quic] work on eventify layers | 73,982 | 0 | 621 | 144 | 74 | 252,727 | 114 | mitmproxy | 8 | mitmproxy/addons/proxyserver.py | Python | 76 | {
"docstring": "\n Stream data to the client if response body exceeds the given\n threshold. If streamed, the body will not be stored in any way.\n Understands k/m/g suffixes, i.e. 3m for 3 megabytes.\n \n Byte size limit of HTTP request and response bodies. Unde... | https://github.com/mitmproxy/mitmproxy.git | |
5 | parse_etags | def parse_etags(etag_str):
if etag_str.strip() == "*":
return ["*"]
else:
# Parse each ETag individually, and return any that are valid.
etag_matches = (ETAG_MATCH.match(etag.strip()) for etag in etag_str.split(","))
return [match[1] for match in etag_matches if match]
| 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 14 | http.py | 99 | Refs #33476 -- Reformatted code with Black. | 51,638 | 0 | 72 | 57 | 29 | 206,695 | 35 | django | 8 | django/utils/http.py | Python | 6 | {
"docstring": "\n Parse a string of ETags given in an If-None-Match or If-Match header as\n defined by RFC 7232. Return a list of quoted ETags, or ['*'] if all ETags\n should be matched.\n ",
"language": "en",
"n_whitespaces": 44,
"n_words": 31,
"vocab_size": 27
} | https://github.com/django/django.git | |
17 | print_ | def print_(*args, **kwargs):
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
| f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 9 | six.py | 49 | upd; format | 13,497 | 0 | 44 | 208 | 11 | 63,755 | 12 | transferlearning | 7 | .venv/lib/python3.8/site-packages/pip/_vendor/six.py | Python | 40 | {
"docstring": "The new-style print function for Python 2.4 and 2.5.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/jindongwang/transferlearning.git | |
5 | _solve_least_squares | def _solve_least_squares(M, rhs, method='CH'):
if method == 'CH':
return M.cholesky_solve(rhs)
elif method == 'QR':
return M.QRsolve(rhs)
elif method == 'LDL':
return M.LDLsolve(rhs)
elif method == 'PINV':
return M.pinv_solve(rhs)
else:
t = M.H
r... | 59d22b6bb7287613d598611027f640d068ca5748 | 12 | solvers.py | 143 | Moved imports to higher level | 47,906 | 0 | 99 | 84 | 25 | 196,406 | 39 | sympy | 11 | sympy/matrices/solvers.py | Python | 12 | {
"docstring": "Return the least-square fit to the data.\n\n Parameters\n ==========\n\n rhs : Matrix\n Vector representing the right hand side of the linear equation.\n\n method : string or boolean, optional\n If set to ``'CH'``, ``cholesky_solve`` routine will be used.\n\n If set to... | https://github.com/sympy/sympy.git | |
3 | get_bound_panel | def get_bound_panel(self, instance=None, request=None, form=None):
if self.model is None:
raise ImproperlyConfigured(
"%s.bind_to_model(model) must be called before get_bound_panel"
% type(self).__name__
)
if not issubclass(self.BoundPane... | 37784643e9207380abaed3c5720dbbcaf69b473b | 13 | panels.py | 130 | API docs for Panel | 16,647 | 0 | 193 | 83 | 34 | 77,267 | 43 | wagtail | 13 | wagtail/admin/panels.py | Python | 14 | {
"docstring": "\n Return a ``BoundPanel`` instance that can be rendered onto the template as a component. By default, this creates an instance\n of the panel class's inner ``BoundPanel`` class, which must inherit from ``Panel.BoundPanel``.\n ",
"language": "en",
"n_whitespaces": 54,
"n_wor... | https://github.com/wagtail/wagtail.git | |
3 | ols_ridge_dataset | def ols_ridge_dataset(global_random_seed, request):
# Make larger dim more than double as big as the smaller one.
# This helps when constructing singular matrices like (X, X).
if request.param == "long":
n_samples, n_features = 12, 4
else:
n_samples, n_features = 4, 12
k = min(n... | 6528e14085d059f9d0c94f93378e7e3c0b967f27 | @pytest.mark.parametrize("solver", SOLVERS)
@pytest.mark.parametrize("fit_intercept", [True, False]) | 15 | test_ridge.py | 524 | TST tight and clean tests for Ridge (#22910)
* MNT replace pinvh by solve
* DOC more info for svd solver
* TST rewrite test_ridge
* MNT remove test_ridge_singular
* MNT restructure into several tests
* MNT remove test_toy_ridge_object
* MNT remove test_ridge_sparse_svd
This is tested in test_ridge... | 75,817 | 1 | 390 | 306 | 154 | 259,553 | 238 | scikit-learn | 46 | sklearn/linear_model/tests/test_ridge.py | Python | 30 | {
"docstring": "Dataset with OLS and Ridge solutions, well conditioned X.\n\n The construction is based on the SVD decomposition of X = U S V'.\n\n Parameters\n ----------\n type : {\"long\", \"wide\"}\n If \"long\", then n_samples > n_features.\n If \"wide\", then n_features > n_samples.\n\... | https://github.com/scikit-learn/scikit-learn.git |
2 | get_supplier_details | def get_supplier_details(suppliers):
supplier_details = {}
for supp in frappe.db.sql(
% ", ".join(["%s"] * len(suppliers)),
tuple(suppliers),
as_dict=1,
):
supplier_details.setdefault(supp.name, supp.supplier_group)
return supplier_details
| 494bd9ef78313436f0424b918f200dab8fc7c20b | 13 | purchase_register.py | 96 | style: format code with black | 13,854 | 0 | 12 | 59 | 20 | 65,320 | 21 | erpnext | 14 | erpnext/accounts/report/purchase_register/purchase_register.py | Python | 11 | {
"docstring": "select name, supplier_group from `tabSupplier`\n\t\twhere name in (%s)",
"language": "en",
"n_whitespaces": 7,
"n_words": 9,
"vocab_size": 9
} | https://github.com/frappe/erpnext.git | |
1 | test_get_whois_admin | def test_get_whois_admin(self) -> None:
channel = self.make_request(
"GET",
self.url,
access_token=self.admin_user_tok,
)
self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
self.assertEqual(self.other_user, channel.json_body[... | 901b264c0c88f39cbfb8b2229e0dc57968882658 | 10 | test_user.py | 112 | Add type hints to `tests/rest/admin` (#11851) | 71,103 | 0 | 93 | 70 | 18 | 246,209 | 18 | synapse | 15 | tests/rest/admin/test_user.py | Python | 12 | {
"docstring": "\n The lookup should succeed for an admin.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 7,
"vocab_size": 7
} | https://github.com/matrix-org/synapse.git | |
8 | compute_configs | def compute_configs(organization_id=None, project_id=None, public_key=None):
from sentry.models import Project, ProjectKey
validate_args(organization_id, project_id, public_key)
configs = {}
if organization_id:
# We want to re-compute all projects in an organization, instead of simply
... | d2fdbaf39e38bacf1fc5924b3feeb46f26de2171 | 15 | relay.py | 291 | feat(relay): Eagerly recalculate project options in compute_configs (#36059) | 18,859 | 0 | 572 | 172 | 148 | 92,047 | 259 | sentry | 21 | src/sentry/tasks/relay.py | Python | 22 | {
"docstring": "Computes all configs for the org, project or single public key.\n\n You must only provide one single argument, not all.\n\n :returns: A dict mapping all affected public keys to their config. The dict will not\n contain keys which should be retained in the cache unchanged.\n ",
"langu... | https://github.com/getsentry/sentry.git | |
4 | _signature_get_bound_param | def _signature_get_bound_param(spec):
assert spec.startswith('($')
pos = spec.find(',')
if pos == -1:
pos = spec.find(')')
cpos = spec.find(':')
assert cpos == -1 or cpos > pos
cpos = spec.find('=')
assert cpos == -1 or cpos > pos
return spec[2:pos]
| 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 11 | inspect.py | 134 | add python 3.10.4 for windows | 55,271 | 0 | 72 | 76 | 19 | 218,383 | 38 | XX-Net | 6 | python3.10.4/Lib/inspect.py | Python | 10 | {
"docstring": " Private helper to get first parameter name from a\n __text_signature__ of a builtin method, which should\n be in the following format: '($param1, ...)'.\n Assumptions are that the first argument won't have\n a default value or an annotation.\n ",
"language": "en",
"n_whitespaces": ... | https://github.com/XX-net/XX-Net.git | |
6 | get_data | def get_data(report_filters):
from_date = get_unsync_date(report_filters)
if not from_date:
return []
result = []
voucher_wise_dict = {}
data = frappe.db.sql(
,
(from_date, report_filters.company),
as_dict=1,
)
for d in data:
voucher_wise_dict.setdefault((d.item_code, d.warehouse), []).append(d)
... | 494bd9ef78313436f0424b918f200dab8fc7c20b | 16 | incorrect_stock_value_report.py | 258 | style: format code with black | 14,647 | 0 | 48 | 169 | 50 | 67,870 | 73 | erpnext | 30 | erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py | Python | 36 | {
"docstring": "\n\t\t\tSELECT\n\t\t\t\tname, posting_date, posting_time, voucher_type, voucher_no,\n\t\t\t\tstock_value_difference, stock_value, warehouse, item_code\n\t\t\tFROM\n\t\t\t\t`tabStock Ledger Entry`\n\t\t\tWHERE\n\t\t\t\tposting_date\n\t\t\t\t= %s and company = %s\n\t\t\t\tand is_cancelled = 0\n\t\t\tORD... | https://github.com/frappe/erpnext.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.