blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e251d622490df247303aaa275371321013e0363f | [
"n1, n2 = (len(self), len(other))\nv1, v2 = (self._data.var(), other._data.var())\nx1, x2 = (self._data.mean(), other._data.mean())\ns = (((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2)) ** 0.5\nreturn (x1 - x2) / s",
"dists: Dict[str, DCDM] = {category: self.filter_to(categorical.keep(category)).rename(category)... | <|body_start_0|>
n1, n2 = (len(self), len(other))
v1, v2 = (self._data.var(), other._data.var())
x1, x2 = (self._data.mean(), other._data.mean())
s = (((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2)) ** 0.5
return (x1 - x2) / s
<|end_body_0|>
<|body_start_1|>
dists: Dict... | DataCohensDMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCohensDMixin:
def cohens_d(self: DCDM, other: DCDM) -> float:
"""Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Effect_size#Cohen's_d"""
<|body_0|>
def conditional_cohens_d(self: DCDM, categorical: DataCateg... | stack_v2_sparse_classes_36k_train_031500 | 2,575 | permissive | [
{
"docstring": "Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Effect_size#Cohen's_d",
"name": "cohens_d",
"signature": "def cohens_d(self: DCDM, other: DCDM) -> float"
},
{
"docstring": "Return a matrix of the Cohen's d of the Rati... | 2 | stack_v2_sparse_classes_30k_train_011802 | Implement the Python class `DataCohensDMixin` described below.
Class description:
Implement the DataCohensDMixin class.
Method signatures and docstrings:
- def cohens_d(self: DCDM, other: DCDM) -> float: Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Eff... | Implement the Python class `DataCohensDMixin` described below.
Class description:
Implement the DataCohensDMixin class.
Method signatures and docstrings:
- def cohens_d(self: DCDM, other: DCDM) -> float: Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Eff... | ff3f5434d3da0d46b127b02cf733699e5a43c904 | <|skeleton|>
class DataCohensDMixin:
def cohens_d(self: DCDM, other: DCDM) -> float:
"""Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Effect_size#Cohen's_d"""
<|body_0|>
def conditional_cohens_d(self: DCDM, categorical: DataCateg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataCohensDMixin:
def cohens_d(self: DCDM, other: DCDM) -> float:
"""Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Effect_size#Cohen's_d"""
n1, n2 = (len(self), len(other))
v1, v2 = (self._data.var(), other._data.var())
... | the_stack_v2_python_sparse | probability/distributions/mixins/data/data_comparison_mixins.py | vahndi/probability | train | 3 | |
245e26466fbd216eda585cfef1abd3c865c92162 | [
"super(ValueChange, self).__init__(env, realign_fn)\nself.state_var = state_var\nself.normalize_by_steps = normalize_by_steps",
"history = self._extract_history(env)\ninitial_state = history[0].state\nfinal_state = history[-1].state\ndelta = getattr(final_state, self.state_var) - getattr(initial_state, self.state... | <|body_start_0|>
super(ValueChange, self).__init__(env, realign_fn)
self.state_var = state_var
self.normalize_by_steps = normalize_by_steps
<|end_body_0|>
<|body_start_1|>
history = self._extract_history(env)
initial_state = history[0].state
final_state = history[-1].sta... | Metric that returns how much a value has changed over the experiment. | ValueChange | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to... | stack_v2_sparse_classes_36k_train_031501 | 7,087 | permissive | [
{
"docstring": "Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to track. normalize_by_steps: Whether to divide by number of steps to get an average change. realign_fn: Optional. If not None, defines how to realign history for use by a metric.",
... | 2 | stack_v2_sparse_classes_30k_train_018971 | Implement the Python class `ValueChange` described below.
Class description:
Metric that returns how much a value has changed over the experiment.
Method signatures and docstrings:
- def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None): Initializes the ValueChange metric. Args: env: A `core.Fa... | Implement the Python class `ValueChange` described below.
Class description:
Metric that returns how much a value has changed over the experiment.
Method signatures and docstrings:
- def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None): Initializes the ValueChange metric. Args: env: A `core.Fa... | 38eaf4514062892e0c3ce5d7cff4b4c1a7e49242 | <|skeleton|>
class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to track. norma... | the_stack_v2_python_sparse | metrics/value_tracking_metrics.py | google/ml-fairness-gym | train | 310 |
ece41d286e08c7958a31f09fa320f6c950f8f8ba | [
"self.email_id = email_id\nself.to_tp_qr_code_url = to_tp_qr_code_url\nself.to_tp_secret_key = to_tp_secret_key\nself.two_fa_mode = two_fa_mode",
"if dictionary is None:\n return None\nemail_id = dictionary.get('EmailID')\nto_tp_qr_code_url = dictionary.get('TOTPQRCodeUrl')\nto_tp_secret_key = dictionary.get('... | <|body_start_0|>
self.email_id = email_id
self.to_tp_qr_code_url = to_tp_qr_code_url
self.to_tp_secret_key = to_tp_secret_key
self.two_fa_mode = two_fa_mode
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
email_id = dictionary.get('EmailID'... | Implementation of the 'GetLinuxSupportUser2FAResult' model. Attributes: email_id (string): TODO: Type Description here. to_tp_qr_code_url (string): TODO: Type Description here. to_tp_secret_key (string): TODO: Type Description here. two_fa_mode (long| int): TODO: Type Description here. | GetLinuxSupportUser2FAResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetLinuxSupportUser2FAResult:
"""Implementation of the 'GetLinuxSupportUser2FAResult' model. Attributes: email_id (string): TODO: Type Description here. to_tp_qr_code_url (string): TODO: Type Description here. to_tp_secret_key (string): TODO: Type Description here. two_fa_mode (long| int): TODO: ... | stack_v2_sparse_classes_36k_train_031502 | 2,119 | permissive | [
{
"docstring": "Constructor for the GetLinuxSupportUser2FAResult class",
"name": "__init__",
"signature": "def __init__(self, email_id=None, to_tp_qr_code_url=None, to_tp_secret_key=None, two_fa_mode=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (... | 2 | null | Implement the Python class `GetLinuxSupportUser2FAResult` described below.
Class description:
Implementation of the 'GetLinuxSupportUser2FAResult' model. Attributes: email_id (string): TODO: Type Description here. to_tp_qr_code_url (string): TODO: Type Description here. to_tp_secret_key (string): TODO: Type Descriptio... | Implement the Python class `GetLinuxSupportUser2FAResult` described below.
Class description:
Implementation of the 'GetLinuxSupportUser2FAResult' model. Attributes: email_id (string): TODO: Type Description here. to_tp_qr_code_url (string): TODO: Type Description here. to_tp_secret_key (string): TODO: Type Descriptio... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GetLinuxSupportUser2FAResult:
"""Implementation of the 'GetLinuxSupportUser2FAResult' model. Attributes: email_id (string): TODO: Type Description here. to_tp_qr_code_url (string): TODO: Type Description here. to_tp_secret_key (string): TODO: Type Description here. two_fa_mode (long| int): TODO: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetLinuxSupportUser2FAResult:
"""Implementation of the 'GetLinuxSupportUser2FAResult' model. Attributes: email_id (string): TODO: Type Description here. to_tp_qr_code_url (string): TODO: Type Description here. to_tp_secret_key (string): TODO: Type Description here. two_fa_mode (long| int): TODO: Type Descript... | the_stack_v2_python_sparse | cohesity_management_sdk/models/get_linux_support_user_2fa_result.py | cohesity/management-sdk-python | train | 24 |
154933a215c4a40bd9d9cafcf130fcd4ecc4fa60 | [
"self.fenetre = fenetre\nself.nombre_parties = nombre_parties\nself.joueurs = joueurs\nself.affichage = affichage\nself.display = display\nself.gagnants = []",
"for i in range(self.nombre_parties):\n if self.fenetre:\n jeu = Othello(self.joueurs, self.fenetre)\n else:\n jeu = Othello(self.joue... | <|body_start_0|>
self.fenetre = fenetre
self.nombre_parties = nombre_parties
self.joueurs = joueurs
self.affichage = affichage
self.display = display
self.gagnants = []
<|end_body_0|>
<|body_start_1|>
for i in range(self.nombre_parties):
if self.fenet... | Simulateur | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulateur:
def __init__(self, joueurs, nombre_parties=10, fenetre=None):
"""Cree un simulateur de partie avec une fenetre, des joueurs, un nombre de partie"""
<|body_0|>
def __call__(self):
"""Boucle 'for' principale du simulateur."""
<|body_1|>
def __r... | stack_v2_sparse_classes_36k_train_031503 | 1,615 | no_license | [
{
"docstring": "Cree un simulateur de partie avec une fenetre, des joueurs, un nombre de partie",
"name": "__init__",
"signature": "def __init__(self, joueurs, nombre_parties=10, fenetre=None)"
},
{
"docstring": "Boucle 'for' principale du simulateur.",
"name": "__call__",
"signature": "... | 3 | null | Implement the Python class `Simulateur` described below.
Class description:
Implement the Simulateur class.
Method signatures and docstrings:
- def __init__(self, joueurs, nombre_parties=10, fenetre=None): Cree un simulateur de partie avec une fenetre, des joueurs, un nombre de partie
- def __call__(self): Boucle 'fo... | Implement the Python class `Simulateur` described below.
Class description:
Implement the Simulateur class.
Method signatures and docstrings:
- def __init__(self, joueurs, nombre_parties=10, fenetre=None): Cree un simulateur de partie avec une fenetre, des joueurs, un nombre de partie
- def __call__(self): Boucle 'fo... | ebfcaaf4a028eddb36bbc99184eb3f7a86eb24ed | <|skeleton|>
class Simulateur:
def __init__(self, joueurs, nombre_parties=10, fenetre=None):
"""Cree un simulateur de partie avec une fenetre, des joueurs, un nombre de partie"""
<|body_0|>
def __call__(self):
"""Boucle 'for' principale du simulateur."""
<|body_1|>
def __r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulateur:
def __init__(self, joueurs, nombre_parties=10, fenetre=None):
"""Cree un simulateur de partie avec une fenetre, des joueurs, un nombre de partie"""
self.fenetre = fenetre
self.nombre_parties = nombre_parties
self.joueurs = joueurs
self.affichage = affichage
... | the_stack_v2_python_sparse | Othello/TIPE/simulateur.py | MarcPartensky/Python-Games | train | 2 | |
70edcb73239287b25b55f3bf69d90b40addb98ae | [
"self.doi_prefix = prefix\nif self.doi_prefix[-1] == '/':\n self.doi_prefix = self.doi_prefix[:-1]\nif not message_testing:\n self.message_testing = 'The prefix 10.5072 is invalid. The prefixis only used for testing purposes, and no DOIs with this prefix are attached to any meaningful content.'\nif not messag... | <|body_start_0|>
self.doi_prefix = prefix
if self.doi_prefix[-1] == '/':
self.doi_prefix = self.doi_prefix[:-1]
if not message_testing:
self.message_testing = 'The prefix 10.5072 is invalid. The prefixis only used for testing purposes, and no DOIs with this prefix are att... | Validate if DOI. | InvalidDOIPrefix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvalidDOIPrefix:
"""Validate if DOI."""
def __init__(self, prefix='10.5072', message=None, message_testing=None):
"""Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072"""
<|body_0|>
def __call__(self, form, field):
"""Validate."""
<|body_1... | stack_v2_sparse_classes_36k_train_031504 | 11,750 | no_license | [
{
"docstring": "Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072",
"name": "__init__",
"signature": "def __init__(self, prefix='10.5072', message=None, message_testing=None)"
},
{
"docstring": "Validate.",
"name": "__call__",
"signature": "def __call__(self, form, field)... | 2 | stack_v2_sparse_classes_30k_train_005813 | Implement the Python class `InvalidDOIPrefix` described below.
Class description:
Validate if DOI.
Method signatures and docstrings:
- def __init__(self, prefix='10.5072', message=None, message_testing=None): Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072
- def __call__(self, form, field): Validate... | Implement the Python class `InvalidDOIPrefix` described below.
Class description:
Validate if DOI.
Method signatures and docstrings:
- def __init__(self, prefix='10.5072', message=None, message_testing=None): Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072
- def __call__(self, form, field): Validate... | 4de8910fff569fc9028300c70b63200da521ddb9 | <|skeleton|>
class InvalidDOIPrefix:
"""Validate if DOI."""
def __init__(self, prefix='10.5072', message=None, message_testing=None):
"""Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072"""
<|body_0|>
def __call__(self, form, field):
"""Validate."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvalidDOIPrefix:
"""Validate if DOI."""
def __init__(self, prefix='10.5072', message=None, message_testing=None):
"""Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072"""
self.doi_prefix = prefix
if self.doi_prefix[-1] == '/':
self.doi_prefix = self.doi... | the_stack_v2_python_sparse | inspirehep/modules/forms/validation_utils.py | nikpap/inspire-next | train | 1 |
56231980632630a1752fc961353311f38d9b64e4 | [
"dp = [0] * len(nums)\nsize = 0\nfor n in nums:\n i, j = (0, size)\n while i < j:\n m = (i + j) // 2\n if dp[m] < n:\n i = m + 1\n else:\n j = m\n dp[i] = n\n size = max(size, i + 1)\n if size >= 3:\n return True\nreturn False",
"first = second = fl... | <|body_start_0|>
dp = [0] * len(nums)
size = 0
for n in nums:
i, j = (0, size)
while i < j:
m = (i + j) // 2
if dp[m] < n:
i = m + 1
else:
j = m
dp[i] = n
size ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * len(nums)
si... | stack_v2_sparse_classes_36k_train_031505 | 1,206 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
d... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
dp = [0] * len(nums)
size = 0
for n in nums:
i, j = (0, size)
while i < j:
m = (i + j) // 2
if dp[m] < n:
i = m + 1
... | the_stack_v2_python_sparse | problems/increasingTriplet.py | joddiy/leetcode | train | 1 | |
68922c9299bfebc473d12368c700209b8193ef99 | [
"self._context = context\nself._target = cloudpickle.dumps(target)\nself._global_state = []\nfor saver in _STATE_SAVERS:\n try:\n self._global_state.append(cloudpickle.dumps(saver.collect_state()))\n except TypeError as e:\n context.get_logger().error('Error while pickling global state from save... | <|body_start_0|>
self._context = context
self._target = cloudpickle.dumps(target)
self._global_state = []
for saver in _STATE_SAVERS:
try:
self._global_state.append(cloudpickle.dumps(saver.collect_state()))
except TypeError as e:
co... | Wraps a function to reload global state before it executes in a subprocess. The `__call__` method calls `target()` after reloading global state; it also logs any errors to stderr. After creation, this object will be pickled by the multiprocessing module; and its __call__ method is executed in the subprocess. We take gr... | _WrappedTargetWithState | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _WrappedTargetWithState:
"""Wraps a function to reload global state before it executes in a subprocess. The `__call__` method calls `target()` after reloading global state; it also logs any errors to stderr. After creation, this object will be pickled by the multiprocessing module; and its __call... | stack_v2_sparse_classes_36k_train_031506 | 9,095 | permissive | [
{
"docstring": "Store target function and global state. This function runs on the process that's creating subprocesses. Args: context: An instance of a multiprocessing BaseContext. target: A callable that will be run in a subprocess.",
"name": "__init__",
"signature": "def __init__(self, context, target... | 2 | null | Implement the Python class `_WrappedTargetWithState` described below.
Class description:
Wraps a function to reload global state before it executes in a subprocess. The `__call__` method calls `target()` after reloading global state; it also logs any errors to stderr. After creation, this object will be pickled by the... | Implement the Python class `_WrappedTargetWithState` described below.
Class description:
Wraps a function to reload global state before it executes in a subprocess. The `__call__` method calls `target()` after reloading global state; it also logs any errors to stderr. After creation, this object will be pickled by the... | eca1093d3a047e538f17f6ab92ab4d8144284f23 | <|skeleton|>
class _WrappedTargetWithState:
"""Wraps a function to reload global state before it executes in a subprocess. The `__call__` method calls `target()` after reloading global state; it also logs any errors to stderr. After creation, this object will be pickled by the multiprocessing module; and its __call... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _WrappedTargetWithState:
"""Wraps a function to reload global state before it executes in a subprocess. The `__call__` method calls `target()` after reloading global state; it also logs any errors to stderr. After creation, this object will be pickled by the multiprocessing module; and its __call__ method is ... | the_stack_v2_python_sparse | tf_agents/system/system_multiprocessing.py | tensorflow/agents | train | 2,755 |
6527dc2d023c70ace52ac0d05728de30b3619619 | [
"super().__init__()\nself.set_mount('NASMYTH_COROTATING')\nself.instrument_name = None\nself.data_type = None\nself.instrument_config = None\nself.instrument_mode = None\nself.mccs_mode = None\nself.spectral_element_1 = None\nself.spectral_element_2 = None\nself.slit_id = None\nself.detector_channel = None\nself.sp... | <|body_start_0|>
super().__init__()
self.set_mount('NASMYTH_COROTATING')
self.instrument_name = None
self.data_type = None
self.instrument_config = None
self.instrument_mode = None
self.mccs_mode = None
self.spectral_element_1 = None
self.spectral_... | SofiaInstrumentInfo | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SofiaInstrumentInfo:
def __init__(self):
"""Initialize the SOFIA instrument information. Contains information on the SOFIA instrument parameters."""
<|body_0|>
def apply_configuration(self):
"""Update SOFIA instrument information with FITS header information. Updates... | stack_v2_sparse_classes_36k_train_031507 | 6,601 | permissive | [
{
"docstring": "Initialize the SOFIA instrument information. Contains information on the SOFIA instrument parameters.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update SOFIA instrument information with FITS header information. Updates the chopping information by t... | 4 | stack_v2_sparse_classes_30k_train_018752 | Implement the Python class `SofiaInstrumentInfo` described below.
Class description:
Implement the SofiaInstrumentInfo class.
Method signatures and docstrings:
- def __init__(self): Initialize the SOFIA instrument information. Contains information on the SOFIA instrument parameters.
- def apply_configuration(self): U... | Implement the Python class `SofiaInstrumentInfo` described below.
Class description:
Implement the SofiaInstrumentInfo class.
Method signatures and docstrings:
- def __init__(self): Initialize the SOFIA instrument information. Contains information on the SOFIA instrument parameters.
- def apply_configuration(self): U... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class SofiaInstrumentInfo:
def __init__(self):
"""Initialize the SOFIA instrument information. Contains information on the SOFIA instrument parameters."""
<|body_0|>
def apply_configuration(self):
"""Update SOFIA instrument information with FITS header information. Updates... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SofiaInstrumentInfo:
def __init__(self):
"""Initialize the SOFIA instrument information. Contains information on the SOFIA instrument parameters."""
super().__init__()
self.set_mount('NASMYTH_COROTATING')
self.instrument_name = None
self.data_type = None
self.in... | the_stack_v2_python_sparse | sofia_redux/scan/custom/sofia/info/instrument.py | SOFIA-USRA/sofia_redux | train | 12 | |
8f1405a424cc762550761498782d17b1cddb0821 | [
"if model._meta.app_label == 'recommends':\n return RECOMMENDS_STORAGE_DATABASE_ALIAS\nreturn None",
"if model._meta.app_label == 'recommends':\n return RECOMMENDS_STORAGE_DATABASE_ALIAS\nreturn None",
"if obj1._meta.app_label == 'recommends' or obj2._meta.app_label == 'recommends':\n return True\nretu... | <|body_start_0|>
if model._meta.app_label == 'recommends':
return RECOMMENDS_STORAGE_DATABASE_ALIAS
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'recommends':
return RECOMMENDS_STORAGE_DATABASE_ALIAS
return None
<|end_body_1|>
<|body_s... | RecommendsRouter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecommendsRouter:
def db_for_read(self, model, **hints):
"""Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE_NAME"""
<|body_0|>
def db_for_write(self, model, **hints):
"""Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE... | stack_v2_sparse_classes_36k_train_031508 | 1,192 | permissive | [
{
"docstring": "Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE_NAME",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE_NAME",
"name": "db_for_write... | 4 | stack_v2_sparse_classes_30k_train_019495 | Implement the Python class `RecommendsRouter` described below.
Class description:
Implement the RecommendsRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE_NAME
- def db_for_write(self, model, **hints): Poi... | Implement the Python class `RecommendsRouter` described below.
Class description:
Implement the RecommendsRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE_NAME
- def db_for_write(self, model, **hints): Poi... | 414436f83b8a0fc5a0c45eb585f9db7a4ed4e70a | <|skeleton|>
class RecommendsRouter:
def db_for_read(self, model, **hints):
"""Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE_NAME"""
<|body_0|>
def db_for_write(self, model, **hints):
"""Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecommendsRouter:
def db_for_read(self, model, **hints):
"""Point all operations on recommends models to RECOMMENDS_STORAGE_DATABASE_NAME"""
if model._meta.app_label == 'recommends':
return RECOMMENDS_STORAGE_DATABASE_ALIAS
return None
def db_for_write(self, model, **h... | the_stack_v2_python_sparse | recommends/storages/djangoorm/routers.py | fcurella/django-recommends | train | 162 | |
51849c650229ee88235f960f3fb6a4185dca9e0c | [
"self.sflist = sflist\nself.noise_model = [case.noise_turn, case.noise_velocity]\nself.c_map = c_map\nself.goal_graph = case.goal_graph\nself.cmd_algo = CmdBiased(case, c_map)\nself.deltick = case.deltick\nself.pfilters = {}\nfor sf in self.sflist:\n pf = RobotPF(sf, case.num_particles, case.init_p_wt, self.nois... | <|body_start_0|>
self.sflist = sflist
self.noise_model = [case.noise_turn, case.noise_velocity]
self.c_map = c_map
self.goal_graph = case.goal_graph
self.cmd_algo = CmdBiased(case, c_map)
self.deltick = case.deltick
self.pfilters = {}
for sf in self.sflist... | DrunkWalk deployment algorithm | DrunkWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DrunkWalk:
"""DrunkWalk deployment algorithm"""
def __init__(self, sflist, c_map, case):
"""Constructor"""
<|body_0|>
def command(self):
"""Command as per the planning algorithm"""
<|body_1|>
def update(self):
"""Update the estimates as per c... | stack_v2_sparse_classes_36k_train_031509 | 3,658 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, sflist, c_map, case)"
},
{
"docstring": "Command as per the planning algorithm",
"name": "command",
"signature": "def command(self)"
},
{
"docstring": "Update the estimates as per command",
"na... | 3 | stack_v2_sparse_classes_30k_test_000038 | Implement the Python class `DrunkWalk` described below.
Class description:
DrunkWalk deployment algorithm
Method signatures and docstrings:
- def __init__(self, sflist, c_map, case): Constructor
- def command(self): Command as per the planning algorithm
- def update(self): Update the estimates as per command | Implement the Python class `DrunkWalk` described below.
Class description:
DrunkWalk deployment algorithm
Method signatures and docstrings:
- def __init__(self, sflist, c_map, case): Constructor
- def command(self): Command as per the planning algorithm
- def update(self): Update the estimates as per command
<|skele... | 778044f9e090739b1663ee2253287a941917fd37 | <|skeleton|>
class DrunkWalk:
"""DrunkWalk deployment algorithm"""
def __init__(self, sflist, c_map, case):
"""Constructor"""
<|body_0|>
def command(self):
"""Command as per the planning algorithm"""
<|body_1|>
def update(self):
"""Update the estimates as per c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DrunkWalk:
"""DrunkWalk deployment algorithm"""
def __init__(self, sflist, c_map, case):
"""Constructor"""
self.sflist = sflist
self.noise_model = [case.noise_turn, case.noise_velocity]
self.c_map = c_map
self.goal_graph = case.goal_graph
self.cmd_algo = Cm... | the_stack_v2_python_sparse | DrunkWalk/drunkwalk.py | alexchonglian/sensor-ipsn2016 | train | 0 |
27cdd7594cf60ed3e2b0cf08486d287165029797 | [
"result = 0\ndp = [0] * len(nums)\nfor i, v2 in enumerate(nums):\n if i == 0:\n dp[i] = 1\n else:\n max_count = 0\n for j, v1 in enumerate(nums[:i]):\n if v1 < v2 and max_count < dp[j]:\n max_count = dp[j]\n dp[i] = max_count + 1 if max_count else 1\n ... | <|body_start_0|>
result = 0
dp = [0] * len(nums)
for i, v2 in enumerate(nums):
if i == 0:
dp[i] = 1
else:
max_count = 0
for j, v1 in enumerate(nums[:i]):
if v1 < v2 and max_count < dp[j]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int 思入1:动态规划, 状态量: 包含该点的最长上升子序列的长度。 复杂度: 时间O(n^2)"""
<|body_0|>
def lengthOfLIS2(self, nums):
"""思入2: 贪心+二分搜索 定义d[k]:长度为k的上升子序列的最末元素,若有多个长度为k的上升子序列,则记录最小的那个最末元素. 核心:维护一个递增的dp,二分搜索后可能出现替换 :param n... | stack_v2_sparse_classes_36k_train_031510 | 1,517 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 思入1:动态规划, 状态量: 包含该点的最长上升子序列的长度。 复杂度: 时间O(n^2)",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": "思入2: 贪心+二分搜索 定义d[k]:长度为k的上升子序列的最末元素,若有多个长度为k的上升子序列,则记录最小的那个最末元素. 核心:维护一个递增的dp,二分搜索后可能出现替换 :param nums: :return:",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int 思入1:动态规划, 状态量: 包含该点的最长上升子序列的长度。 复杂度: 时间O(n^2)
- def lengthOfLIS2(self, nums): 思入2: 贪心+二分搜索 定义d[k]:长度为k的上升子序列的最末元素,若... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int 思入1:动态规划, 状态量: 包含该点的最长上升子序列的长度。 复杂度: 时间O(n^2)
- def lengthOfLIS2(self, nums): 思入2: 贪心+二分搜索 定义d[k]:长度为k的上升子序列的最末元素,若... | d1ddcbabfa7cc4d4f41b46f21f3227984f57bc40 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int 思入1:动态规划, 状态量: 包含该点的最长上升子序列的长度。 复杂度: 时间O(n^2)"""
<|body_0|>
def lengthOfLIS2(self, nums):
"""思入2: 贪心+二分搜索 定义d[k]:长度为k的上升子序列的最末元素,若有多个长度为k的上升子序列,则记录最小的那个最末元素. 核心:维护一个递增的dp,二分搜索后可能出现替换 :param n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int 思入1:动态规划, 状态量: 包含该点的最长上升子序列的长度。 复杂度: 时间O(n^2)"""
result = 0
dp = [0] * len(nums)
for i, v2 in enumerate(nums):
if i == 0:
dp[i] = 1
else:
max_coun... | the_stack_v2_python_sparse | 动态规划/300_longest_increasing_subsequence.py | whitefly/leetcode_python | train | 6 | |
eeb1c03ca48b80c113cd4dd2626fe042363f071b | [
"preprocessor = BinaryChecker(num_variables, phenome_preprocessor)\nTestProblem.__init__(self, [leading_ones, trailing_zeros], num_objectives=2, phenome_preprocessor=preprocessor, **kwargs)\nself.num_variables = num_variables\nself.is_deterministic = True\nself.do_maximize = True",
"assert max_number is None or m... | <|body_start_0|>
preprocessor = BinaryChecker(num_variables, phenome_preprocessor)
TestProblem.__init__(self, [leading_ones, trailing_zeros], num_objectives=2, phenome_preprocessor=preprocessor, **kwargs)
self.num_variables = num_variables
self.is_deterministic = True
self.do_max... | A bi-objective binary problem. | LeadingOnesTrailingZeros | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeadingOnesTrailingZeros:
"""A bi-objective binary problem."""
def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):
"""Constructor. Parameters ---------- num_variables : int, optional The search space dimension. phenome_preprocessor : callable, optional A callab... | stack_v2_sparse_classes_36k_train_031511 | 7,172 | permissive | [
{
"docstring": "Constructor. Parameters ---------- num_variables : int, optional The search space dimension. phenome_preprocessor : callable, optional A callable potentially applying transformations or checks to the phenome. Modifications should only be applied to a copy of the input. The (modified) phenome mus... | 2 | stack_v2_sparse_classes_30k_train_021657 | Implement the Python class `LeadingOnesTrailingZeros` described below.
Class description:
A bi-objective binary problem.
Method signatures and docstrings:
- def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs): Constructor. Parameters ---------- num_variables : int, optional The search space dime... | Implement the Python class `LeadingOnesTrailingZeros` described below.
Class description:
A bi-objective binary problem.
Method signatures and docstrings:
- def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs): Constructor. Parameters ---------- num_variables : int, optional The search space dime... | df14bf0cc263d8fa0ad0a539e94327ac35e33d1c | <|skeleton|>
class LeadingOnesTrailingZeros:
"""A bi-objective binary problem."""
def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):
"""Constructor. Parameters ---------- num_variables : int, optional The search space dimension. phenome_preprocessor : callable, optional A callab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeadingOnesTrailingZeros:
"""A bi-objective binary problem."""
def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):
"""Constructor. Parameters ---------- num_variables : int, optional The search space dimension. phenome_preprocessor : callable, optional A callable potentiall... | the_stack_v2_python_sparse | pybandit/optproblems/binary.py | chunjenpeng/pyBandit | train | 0 |
3fee780c60b34917c126c6b9e4d56de81c5cb20b | [
"parser.add_argument('instance', help='Cloud SQL instance ID.')\nparser.add_argument('--uri', '-u', required=True, help='The path to the file in Google Cloud Storage where the export will be stored. The URI is in the form gs://bucketName/fileName. If the file already exists, the operation fails. If the filename end... | <|body_start_0|>
parser.add_argument('instance', help='Cloud SQL instance ID.')
parser.add_argument('--uri', '-u', required=True, help='The path to the file in Google Cloud Storage where the export will be stored. The URI is in the form gs://bucketName/fileName. If the file already exists, the operation... | Exports data from a Cloud SQL instance. Exports data from a Cloud SQL instance to a Google Cloud Storage bucket as a MySQL dump file. | Export | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Export:
"""Exports data from a Cloud SQL instance. Exports data from a Cloud SQL instance to a Google Cloud Storage bucket as a MySQL dump file."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use ... | stack_v2_sparse_classes_36k_train_031512 | 4,258 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_020024 | Implement the Python class `Export` described below.
Class description:
Exports data from a Cloud SQL instance. Exports data from a Cloud SQL instance to a Google Cloud Storage bucket as a MySQL dump file.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this co... | Implement the Python class `Export` described below.
Class description:
Exports data from a Cloud SQL instance. Exports data from a Cloud SQL instance to a Google Cloud Storage bucket as a MySQL dump file.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this co... | 90d87b2adb1eab7f218b075886aa620d8d6eeedb | <|skeleton|>
class Export:
"""Exports data from a Cloud SQL instance. Exports data from a Cloud SQL instance to a Google Cloud Storage bucket as a MySQL dump file."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Export:
"""Exports data from a Cloud SQL instance. Exports data from a Cloud SQL instance to a Google Cloud Storage bucket as a MySQL dump file."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arg... | the_stack_v2_python_sparse | old/google-cloud-sdk/lib/googlecloudsdk/sql/tools/instances/export.py | altock/dev | train | 0 |
a5453690d8b7effd231cd61fa80600e8d431960e | [
"self.unique_identifier = unique_identifier\nself.enduses = enduses\nself.shape_yd = shape_yd\nself.shape_yh = shape_yh\nself.enduse_peak_yd_factor = enduse_peak_yd_factor\nself.shape_y_dh = self.calc_y_dh_shape_from_yh()\nself.shape_peak_dh = shape_peak_dh",
"sum_every_day_p = 1 / np.sum(self.shape_yh, axis=1)\n... | <|body_start_0|>
self.unique_identifier = unique_identifier
self.enduses = enduses
self.shape_yd = shape_yd
self.shape_yh = shape_yh
self.enduse_peak_yd_factor = enduse_peak_yd_factor
self.shape_y_dh = self.calc_y_dh_shape_from_yh()
self.shape_peak_dh = shape_peak... | Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_yd_factor : float Factor to calculate daily demand from yearly demand Standard ... | LoadProfile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadProfile:
"""Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_yd_factor : float Factor to calculate da... | stack_v2_sparse_classes_36k_train_031513 | 11,374 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, enduses, unique_identifier, shape_yd, shape_yh, enduse_peak_yd_factor, shape_peak_dh)"
},
{
"docstring": "Calculate shape for every day Returns ------- shape_y_dh : array Shape for every day Note ---- The output g... | 2 | stack_v2_sparse_classes_30k_train_009318 | Implement the Python class `LoadProfile` described below.
Class description:
Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_y... | Implement the Python class `LoadProfile` described below.
Class description:
Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_y... | 59a2712f353f47e3dc237479cc6cc46666b7d0f1 | <|skeleton|>
class LoadProfile:
"""Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_yd_factor : float Factor to calculate da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadProfile:
"""Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_yd_factor : float Factor to calculate daily demand fr... | the_stack_v2_python_sparse | energy_demand/profiles/load_profile.py | willu47/energy_demand | train | 0 |
bc69204d1498eb33d7c0f305c76a8450b6c3415f | [
"if type(dm) is not int:\n raise TypeError('dm must be int representing dimensionality of model')\nif type(h) is not int:\n raise TypeError('h must be int representing number of heads')\nif type(hidden) is not int:\n raise TypeError('hidden must be int representing number of hidden units')\nif type(drop_ra... | <|body_start_0|>
if type(dm) is not int:
raise TypeError('dm must be int representing dimensionality of model')
if type(h) is not int:
raise TypeError('h must be int representing number of heads')
if type(hidden) is not int:
raise TypeError('hidden must be int... | Class to create a decoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha1: the first MultiHeadAttention layer mha2: the second MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the ou... | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""Class to create a decoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha1: the first MultiHeadAttention layer mha2: the second MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden uni... | stack_v2_sparse_classes_36k_train_031514 | 5,154 | no_license | [
{
"docstring": "Class constructor parameters: dm [int]: represents the dimensionality of the model h [int]: represents the number of heads hidden [int]: represents the number of hidden units in fully connected layer drop_rate [float]: the dropout rate sets the public instance attributes: mha1: the first MultiHe... | 2 | stack_v2_sparse_classes_30k_val_000334 | Implement the Python class `DecoderBlock` described below.
Class description:
Class to create a decoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha1: the first MultiHeadAttention layer mha2: the second MultiHeadAttention layer dense_hidden:... | Implement the Python class `DecoderBlock` described below.
Class description:
Class to create a decoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha1: the first MultiHeadAttention layer mha2: the second MultiHeadAttention layer dense_hidden:... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class DecoderBlock:
"""Class to create a decoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha1: the first MultiHeadAttention layer mha2: the second MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden uni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""Class to create a decoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha1: the first MultiHeadAttention layer mha2: the second MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu acti... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
48505463af0fc4fa9e477daae3a01830a30ac4e2 | [
"super().__init__(path)\nself._seq_list = []\nself._parse(max_seq)",
"line = file.readline()\nwhile line and REPLAY_END not in line:\n line = file.readline()",
"checker = line.split(CHECKER, 2)[1][2:]\nif checker not in seq.checker_requests:\n seq.checker_requests[checker] = []\nwhile line and CHECKER_END... | <|body_start_0|>
super().__init__(path)
self._seq_list = []
self._parse(max_seq)
<|end_body_0|>
<|body_start_1|>
line = file.readline()
while line and REPLAY_END not in line:
line = file.readline()
<|end_body_1|>
<|body_start_2|>
checker = line.split(CHECKER... | Responsible for parsing standard fuzzing logs | FuzzingLogParser | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuzzingLogParser:
"""Responsible for parsing standard fuzzing logs"""
def __init__(self, path, max_seq=-1):
"""FuzzingLogParser constructor @param path: The path to the fuzzing log to parse @type path: Str"""
<|body_0|>
def _skip_replay(self, file):
"""Moves the ... | stack_v2_sparse_classes_36k_train_031515 | 9,641 | permissive | [
{
"docstring": "FuzzingLogParser constructor @param path: The path to the fuzzing log to parse @type path: Str",
"name": "__init__",
"signature": "def __init__(self, path, max_seq=-1)"
},
{
"docstring": "Moves the log file's pointer beyond a replay section @param file: The log file's pointer @ty... | 5 | stack_v2_sparse_classes_30k_train_005286 | Implement the Python class `FuzzingLogParser` described below.
Class description:
Responsible for parsing standard fuzzing logs
Method signatures and docstrings:
- def __init__(self, path, max_seq=-1): FuzzingLogParser constructor @param path: The path to the fuzzing log to parse @type path: Str
- def _skip_replay(se... | Implement the Python class `FuzzingLogParser` described below.
Class description:
Responsible for parsing standard fuzzing logs
Method signatures and docstrings:
- def __init__(self, path, max_seq=-1): FuzzingLogParser constructor @param path: The path to the fuzzing log to parse @type path: Str
- def _skip_replay(se... | 5a9ba1af74953334fcf54570f1e31e74ea057688 | <|skeleton|>
class FuzzingLogParser:
"""Responsible for parsing standard fuzzing logs"""
def __init__(self, path, max_seq=-1):
"""FuzzingLogParser constructor @param path: The path to the fuzzing log to parse @type path: Str"""
<|body_0|>
def _skip_replay(self, file):
"""Moves the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FuzzingLogParser:
"""Responsible for parsing standard fuzzing logs"""
def __init__(self, path, max_seq=-1):
"""FuzzingLogParser constructor @param path: The path to the fuzzing log to parse @type path: Str"""
super().__init__(path)
self._seq_list = []
self._parse(max_seq)
... | the_stack_v2_python_sparse | restler/test_servers/log_parser.py | wisec/restler-fuzzer | train | 0 |
897869c998776c67cbfce2f552e2fd2397c06eb1 | [
"super().__init__('opendr_object_tracking_3d_ab3dmot_node')\nself.detector = detector\nself.learner = ObjectTracking3DAb3dmotLearner(device=device)\nself.bridge = ROS2Bridge()\nif output_detection3d_topic is not None:\n self.detection_publisher = self.create_publisher(Detection3DArray, output_detection3d_topic, ... | <|body_start_0|>
super().__init__('opendr_object_tracking_3d_ab3dmot_node')
self.detector = detector
self.learner = ObjectTracking3DAb3dmotLearner(device=device)
self.bridge = ROS2Bridge()
if output_detection3d_topic is not None:
self.detection_publisher = self.create... | ObjectTracking3DAb3dmotNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectTracking3DAb3dmotNode:
def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', output_tracking3d_id_topic='/opendr/tracking3d_id', device='cuda:0'):
"""Creates a ROS2 Node for 3D object tracking :param... | stack_v2_sparse_classes_36k_train_031516 | 7,413 | permissive | [
{
"docstring": "Creates a ROS2 Node for 3D object tracking :param detector: Learner that provides 3D object detections :type detector: Learner :param input_point_cloud_topic: Topic from which we are reading the input point cloud :type input_point_cloud_topic: str :param output_detection3d_topic: Topic to which ... | 2 | stack_v2_sparse_classes_30k_train_005840 | Implement the Python class `ObjectTracking3DAb3dmotNode` described below.
Class description:
Implement the ObjectTracking3DAb3dmotNode class.
Method signatures and docstrings:
- def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', out... | Implement the Python class `ObjectTracking3DAb3dmotNode` described below.
Class description:
Implement the ObjectTracking3DAb3dmotNode class.
Method signatures and docstrings:
- def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', out... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class ObjectTracking3DAb3dmotNode:
def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', output_tracking3d_id_topic='/opendr/tracking3d_id', device='cuda:0'):
"""Creates a ROS2 Node for 3D object tracking :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectTracking3DAb3dmotNode:
def __init__(self, detector=None, input_point_cloud_topic='/opendr/dataset_point_cloud', output_detection3d_topic='/opendr/detection3d', output_tracking3d_id_topic='/opendr/tracking3d_id', device='cuda:0'):
"""Creates a ROS2 Node for 3D object tracking :param detector: Lea... | the_stack_v2_python_sparse | projects/opendr_ws_2/src/opendr_perception/opendr_perception/object_tracking_3d_ab3dmot_node.py | opendr-eu/opendr | train | 535 | |
2cf39ae831a923e80197608352057a8860df9d28 | [
"x = []\nif root:\n stack = [root]\n while stack:\n node = stack.pop()\n x.append(node.val)\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\nreturn ' '.join(map(str, x))",
"x = deque([int(v) for v in data.split()])\nif n... | <|body_start_0|>
x = []
if root:
stack = [root]
while stack:
node = stack.pop()
x.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)... | optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder). | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder)."""
def serialize(self, root: TreeNode) -> str:
... | stack_v2_sparse_classes_36k_train_031517 | 2,340 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_013662 | Implement the Python class `Codec` described below.
Class description:
optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder).
Method signatures... | Implement the Python class `Codec` described below.
Class description:
optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder).
Method signatures... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Codec:
"""optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder)."""
def serialize(self, root: TreeNode) -> str:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
"""optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder)."""
def serialize(self, root: TreeNode) -> str:
"""Encodes... | the_stack_v2_python_sparse | src/0400-0499/0449.serialize.deserialize.bst.py | gyang274/leetcode | train | 1 |
0c8b99a6da96fca7477bff40bae1439bca4abee5 | [
"try:\n file_name = cls.get_unique_name(file_name, width, height)\n content = StringIO(file_body)\n img = Image.open(content)\n cover = ImageCover(img)\n format_size = (int(width), int(height))\n img = cover.resize(format_size)\n filename = MongodbUtil.put(file_name, img)\n return filename\n... | <|body_start_0|>
try:
file_name = cls.get_unique_name(file_name, width, height)
content = StringIO(file_body)
img = Image.open(content)
cover = ImageCover(img)
format_size = (int(width), int(height))
img = cover.resize(format_size)
... | 图片上传工具类 | UploadUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadUtil:
"""图片上传工具类"""
def upload_pic(cls, file_name, file_body, width=128, height=128):
"""上传logo到mangodb"""
<|body_0|>
def get_unique_name(cls, file_name, width=128, height=128, length=32):
"""生成唯一文件名"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_031518 | 1,740 | no_license | [
{
"docstring": "上传logo到mangodb",
"name": "upload_pic",
"signature": "def upload_pic(cls, file_name, file_body, width=128, height=128)"
},
{
"docstring": "生成唯一文件名",
"name": "get_unique_name",
"signature": "def get_unique_name(cls, file_name, width=128, height=128, length=32)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003568 | Implement the Python class `UploadUtil` described below.
Class description:
图片上传工具类
Method signatures and docstrings:
- def upload_pic(cls, file_name, file_body, width=128, height=128): 上传logo到mangodb
- def get_unique_name(cls, file_name, width=128, height=128, length=32): 生成唯一文件名 | Implement the Python class `UploadUtil` described below.
Class description:
图片上传工具类
Method signatures and docstrings:
- def upload_pic(cls, file_name, file_body, width=128, height=128): 上传logo到mangodb
- def get_unique_name(cls, file_name, width=128, height=128, length=32): 生成唯一文件名
<|skeleton|>
class UploadUtil:
... | 2e8b14b8e7957d2ed27cadbfa2b5b8ab01902531 | <|skeleton|>
class UploadUtil:
"""图片上传工具类"""
def upload_pic(cls, file_name, file_body, width=128, height=128):
"""上传logo到mangodb"""
<|body_0|>
def get_unique_name(cls, file_name, width=128, height=128, length=32):
"""生成唯一文件名"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UploadUtil:
"""图片上传工具类"""
def upload_pic(cls, file_name, file_body, width=128, height=128):
"""上传logo到mangodb"""
try:
file_name = cls.get_unique_name(file_name, width, height)
content = StringIO(file_body)
img = Image.open(content)
cover = I... | the_stack_v2_python_sparse | lib/util/upload_util.py | iwangkang/affiliate | train | 1 |
417e4d76cc43e42570732762fff79c3935845bb4 | [
"if storage != None and (not isinstance(storage, RepositoryStorage)):\n raise ResourceInvalidStorageError('RepositoryProvider accepts RepositoryStorage only')\nif not isinstance(retriever, RepositoryRetriever):\n raise ResourceInvalidRetrieverError('RepositoryProvider accepts RepositoryRetriever only')\nProvi... | <|body_start_0|>
if storage != None and (not isinstance(storage, RepositoryStorage)):
raise ResourceInvalidStorageError('RepositoryProvider accepts RepositoryStorage only')
if not isinstance(retriever, RepositoryRetriever):
raise ResourceInvalidRetrieverError('RepositoryProvider ... | RepositoryProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryProvider:
def __init__(self, storage, retriever, working_directory):
""":param storage: repository storage :type storage: RepositoryStorage :param retriever: repository retriever :type retriever: RepositoryRetriever :param working_directory: working directory for provider :type... | stack_v2_sparse_classes_36k_train_031519 | 1,798 | no_license | [
{
"docstring": ":param storage: repository storage :type storage: RepositoryStorage :param retriever: repository retriever :type retriever: RepositoryRetriever :param working_directory: working directory for provider :type working_directory: string",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | stack_v2_sparse_classes_30k_train_001606 | Implement the Python class `RepositoryProvider` described below.
Class description:
Implement the RepositoryProvider class.
Method signatures and docstrings:
- def __init__(self, storage, retriever, working_directory): :param storage: repository storage :type storage: RepositoryStorage :param retriever: repository re... | Implement the Python class `RepositoryProvider` described below.
Class description:
Implement the RepositoryProvider class.
Method signatures and docstrings:
- def __init__(self, storage, retriever, working_directory): :param storage: repository storage :type storage: RepositoryStorage :param retriever: repository re... | 7e414c78930a81167dc2cd4d3e9adb79eeed38a6 | <|skeleton|>
class RepositoryProvider:
def __init__(self, storage, retriever, working_directory):
""":param storage: repository storage :type storage: RepositoryStorage :param retriever: repository retriever :type retriever: RepositoryRetriever :param working_directory: working directory for provider :type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepositoryProvider:
def __init__(self, storage, retriever, working_directory):
""":param storage: repository storage :type storage: RepositoryStorage :param retriever: repository retriever :type retriever: RepositoryRetriever :param working_directory: working directory for provider :type working_direc... | the_stack_v2_python_sparse | gofedresources/repositoryprovider.py | gofed/resources | train | 0 | |
0248f68e3d46b50396b06bafa8a55e4324528584 | [
"\"\"\"Corner Cases\"\"\"\nif x == 0 or x == 1:\n return x\nstart, end = (1, math.ceil(x / 2))\nwhile start < end - 1:\n mid = (start + end) // 2\n if mid == x // mid:\n return mid\n elif mid > x // mid:\n end = mid\n else:\n start = mid\nif start == x // start or end > x // end:... | <|body_start_0|>
"""Corner Cases"""
if x == 0 or x == 1:
return x
start, end = (1, math.ceil(x / 2))
while start < end - 1:
mid = (start + end) // 2
if mid == x // mid:
return mid
elif mid > x // mid:
end = m... | 解题思路:类似于在0, 1, 2, 3, 4, 5, 6, ... 的平方里,x离哪个e^2最近并且x >= e^2 ; 实际就对等于在sorted list里面找一个最近的element^2 >= target <=>选最closest element and element^2 <= target Time: O(logn) Space: O(1) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""解题思路:类似于在0, 1, 2, 3, 4, 5, 6, ... 的平方里,x离哪个e^2最近并且x >= e^2 ; 实际就对等于在sorted list里面找一个最近的element^2 >= target <=>选最closest element and element^2 <= target Time: O(logn) Space: O(1)"""
def sqrt(self, x):
"""input: int x return: int"""
<|body_0|>
def sqrt2(self, ... | stack_v2_sparse_classes_36k_train_031520 | 2,303 | no_license | [
{
"docstring": "input: int x return: int",
"name": "sqrt",
"signature": "def sqrt(self, x)"
},
{
"docstring": "input: int x return: int",
"name": "sqrt2",
"signature": "def sqrt2(self, x)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
解题思路:类似于在0, 1, 2, 3, 4, 5, 6, ... 的平方里,x离哪个e^2最近并且x >= e^2 ; 实际就对等于在sorted list里面找一个最近的element^2 >= target <=>选最closest element and element^2 <= target Time: O(logn) Space: O(1)
Method signatures and docstrings:
- def sqrt(self, x): input: int ... | Implement the Python class `Solution` described below.
Class description:
解题思路:类似于在0, 1, 2, 3, 4, 5, 6, ... 的平方里,x离哪个e^2最近并且x >= e^2 ; 实际就对等于在sorted list里面找一个最近的element^2 >= target <=>选最closest element and element^2 <= target Time: O(logn) Space: O(1)
Method signatures and docstrings:
- def sqrt(self, x): input: int ... | c34b55bb42dc44a9026a902f6afcc018b4154662 | <|skeleton|>
class Solution:
"""解题思路:类似于在0, 1, 2, 3, 4, 5, 6, ... 的平方里,x离哪个e^2最近并且x >= e^2 ; 实际就对等于在sorted list里面找一个最近的element^2 >= target <=>选最closest element and element^2 <= target Time: O(logn) Space: O(1)"""
def sqrt(self, x):
"""input: int x return: int"""
<|body_0|>
def sqrt2(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""解题思路:类似于在0, 1, 2, 3, 4, 5, 6, ... 的平方里,x离哪个e^2最近并且x >= e^2 ; 实际就对等于在sorted list里面找一个最近的element^2 >= target <=>选最closest element and element^2 <= target Time: O(logn) Space: O(1)"""
def sqrt(self, x):
"""input: int x return: int"""
"""Corner Cases"""
if x == 0 or x == ... | the_stack_v2_python_sparse | Algorithm/Square Root I - Lai.py | superpigBB/Happy-Coding | train | 0 |
80450931af747cb592c68ba744d56bfdf30578d1 | [
"super(ContextualCell_v1, self).__init__()\nself._ops = nn.ModuleList()\nself._pos = []\nself._collect_inds = [0]\nself._pools = ['x']\nfor ind, op in enumerate(config):\n if ind == 0:\n pos = 0\n op_id = op\n self._collect_inds.remove(pos)\n op_name = op_names[op_id]\n self._o... | <|body_start_0|>
super(ContextualCell_v1, self).__init__()
self._ops = nn.ModuleList()
self._pos = []
self._collect_inds = [0]
self._pools = ['x']
for ind, op in enumerate(config):
if ind == 0:
pos = 0
op_id = op
... | New contextual cell design. | ContextualCell_v1 | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContextualCell_v1:
"""New contextual cell design."""
def __init__(self, op_names, config, inp, repeats=1, concat=False):
"""Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of config numbers :param inp: input channel :param repeats: nu... | stack_v2_sparse_classes_36k_train_031521 | 27,877 | permissive | [
{
"docstring": "Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of config numbers :param inp: input channel :param repeats: number of repeated times :param concat: concat the result if set to True, otherwise add the result",
"name": "__init__",
"signatur... | 2 | null | Implement the Python class `ContextualCell_v1` described below.
Class description:
New contextual cell design.
Method signatures and docstrings:
- def __init__(self, op_names, config, inp, repeats=1, concat=False): Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of co... | Implement the Python class `ContextualCell_v1` described below.
Class description:
New contextual cell design.
Method signatures and docstrings:
- def __init__(self, op_names, config, inp, repeats=1, concat=False): Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of co... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class ContextualCell_v1:
"""New contextual cell design."""
def __init__(self, op_names, config, inp, repeats=1, concat=False):
"""Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of config numbers :param inp: input channel :param repeats: nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContextualCell_v1:
"""New contextual cell design."""
def __init__(self, op_names, config, inp, repeats=1, concat=False):
"""Construct ContextualCell_v1 class. :param op_names: list of operation indices :param config: list of config numbers :param inp: input channel :param repeats: number of repea... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/networks/pytorch/operator/op.py | Huawei-Ascend/modelzoo | train | 1 |
ea415a6589dd4912ce74e9f43eac2db5f35af687 | [
"super(YOLOLayer, self).__init__()\nself.anchors = torch.Tensor(anchors)\nself.number_anchor = len(anchors)\nself.number_classes = number_classes\nself.image_size = image_size\nself.number_grid = None\nself.number_x_grid = 0\nself.number_y_grid = 0\nself.stride = 0\nself.grid_xy = None\nself.anchor_wh = None\nself.... | <|body_start_0|>
super(YOLOLayer, self).__init__()
self.anchors = torch.Tensor(anchors)
self.number_anchor = len(anchors)
self.number_classes = number_classes
self.image_size = image_size
self.number_grid = None
self.number_x_grid = 0
self.number_y_grid = ... | YOLO的detection head, 使用网络预测的值和预设的anchor组合得到预测的bbox | YOLOLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YOLOLayer:
"""YOLO的detection head, 使用网络预测的值和预设的anchor组合得到预测的bbox"""
def __init__(self, anchors, number_classes, image_size):
"""Args: anchors: numpy.array, anchor的尺度大小 number_classes: 类别数目 image_size: 图片大小 arc:"""
<|body_0|>
def forward(self, feature, image_size):
... | stack_v2_sparse_classes_36k_train_031522 | 6,692 | no_license | [
{
"docstring": "Args: anchors: numpy.array, anchor的尺度大小 number_classes: 类别数目 image_size: 图片大小 arc:",
"name": "__init__",
"signature": "def __init__(self, anchors, number_classes, image_size)"
},
{
"docstring": "YOLOLayer的前向传播操作 :param feature: 输入特征图 :param image_size: 原始输入图片的大小 :return: predict:... | 3 | stack_v2_sparse_classes_30k_train_010849 | Implement the Python class `YOLOLayer` described below.
Class description:
YOLO的detection head, 使用网络预测的值和预设的anchor组合得到预测的bbox
Method signatures and docstrings:
- def __init__(self, anchors, number_classes, image_size): Args: anchors: numpy.array, anchor的尺度大小 number_classes: 类别数目 image_size: 图片大小 arc:
- def forward(se... | Implement the Python class `YOLOLayer` described below.
Class description:
YOLO的detection head, 使用网络预测的值和预设的anchor组合得到预测的bbox
Method signatures and docstrings:
- def __init__(self, anchors, number_classes, image_size): Args: anchors: numpy.array, anchor的尺度大小 number_classes: 类别数目 image_size: 图片大小 arc:
- def forward(se... | 7ed453312d1eb7b91aec536a1b009733147c871a | <|skeleton|>
class YOLOLayer:
"""YOLO的detection head, 使用网络预测的值和预设的anchor组合得到预测的bbox"""
def __init__(self, anchors, number_classes, image_size):
"""Args: anchors: numpy.array, anchor的尺度大小 number_classes: 类别数目 image_size: 图片大小 arc:"""
<|body_0|>
def forward(self, feature, image_size):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YOLOLayer:
"""YOLO的detection head, 使用网络预测的值和预设的anchor组合得到预测的bbox"""
def __init__(self, anchors, number_classes, image_size):
"""Args: anchors: numpy.array, anchor的尺度大小 number_classes: 类别数目 image_size: 图片大小 arc:"""
super(YOLOLayer, self).__init__()
self.anchors = torch.Tensor(ancho... | the_stack_v2_python_sparse | models/layers.py | XiangqianMa/yolov3.pytorch | train | 0 |
2bdbc518e74245d6487f42dbd36cceeb64da51a9 | [
"base_dict = {'!': '!!'}\nnumbers = {'1': 'one'}\nchars = {'a': 'A'}\nnew_dict = results.namespaced_dict(base_dict, numbers=numbers, chars=chars)\nself.assertDictEqual(new_dict, {'!': '!!', 'numbers.1': 'one', 'chars.a': 'A'})",
"output_path = os.path.join(self.get_temp_dir(), 'export.csv')\noutput_dict = {'1': '... | <|body_start_0|>
base_dict = {'!': '!!'}
numbers = {'1': 'one'}
chars = {'a': 'A'}
new_dict = results.namespaced_dict(base_dict, numbers=numbers, chars=chars)
self.assertDictEqual(new_dict, {'!': '!!', 'numbers.1': 'one', 'chars.a': 'A'})
<|end_body_0|>
<|body_start_1|>
... | ResultsTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultsTest:
def test_namespaced_dict(self):
"""Tests namespacing functionality."""
<|body_0|>
def test_dict_to_txt(self):
"""Tests saving functionality to txt file."""
<|body_1|>
def test_gin_dict_live(self):
"""Tests namespacing functionality b... | stack_v2_sparse_classes_36k_train_031523 | 2,878 | permissive | [
{
"docstring": "Tests namespacing functionality.",
"name": "test_namespaced_dict",
"signature": "def test_namespaced_dict(self)"
},
{
"docstring": "Tests saving functionality to txt file.",
"name": "test_dict_to_txt",
"signature": "def test_dict_to_txt(self)"
},
{
"docstring": "T... | 5 | null | Implement the Python class `ResultsTest` described below.
Class description:
Implement the ResultsTest class.
Method signatures and docstrings:
- def test_namespaced_dict(self): Tests namespacing functionality.
- def test_dict_to_txt(self): Tests saving functionality to txt file.
- def test_gin_dict_live(self): Tests... | Implement the Python class `ResultsTest` described below.
Class description:
Implement the ResultsTest class.
Method signatures and docstrings:
- def test_namespaced_dict(self): Tests namespacing functionality.
- def test_dict_to_txt(self): Tests saving functionality to txt file.
- def test_gin_dict_live(self): Tests... | fe9b9c9cf295b1309ea188869938b86173b7b718 | <|skeleton|>
class ResultsTest:
def test_namespaced_dict(self):
"""Tests namespacing functionality."""
<|body_0|>
def test_dict_to_txt(self):
"""Tests saving functionality to txt file."""
<|body_1|>
def test_gin_dict_live(self):
"""Tests namespacing functionality b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResultsTest:
def test_namespaced_dict(self):
"""Tests namespacing functionality."""
base_dict = {'!': '!!'}
numbers = {'1': 'one'}
chars = {'a': 'A'}
new_dict = results.namespaced_dict(base_dict, numbers=numbers, chars=chars)
self.assertDictEqual(new_dict, {'!':... | the_stack_v2_python_sparse | disentanglement_lib/utils/results_test.py | ecreager/disentanglement_lib | train | 1 | |
c96cef1fad8291dd7cee3bc8b5800e05065444fb | [
"buy = 0\nsell = buy + 1\nmaxDays = len(prices) - 1\nmaxProfit = 0\nwhile buy < maxDays:\n while sell <= maxDays:\n if prices[sell] > prices[buy]:\n profit = prices[sell] - prices[buy]\n if profit > maxProfit:\n maxProfit = profit\n sell += 1\n buy += 1\n ... | <|body_start_0|>
buy = 0
sell = buy + 1
maxDays = len(prices) - 1
maxProfit = 0
while buy < maxDays:
while sell <= maxDays:
if prices[sell] > prices[buy]:
profit = prices[sell] - prices[buy]
if profit > maxProfit... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type x: int array :rtype: int"""
<|body_0|>
def maxProfitFaster(self, prices):
"""This will be done in O(n) due to only 1 loop."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
buy = 0
sell = buy + 1... | stack_v2_sparse_classes_36k_train_031524 | 1,170 | no_license | [
{
"docstring": ":type x: int array :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": "This will be done in O(n) due to only 1 loop.",
"name": "maxProfitFaster",
"signature": "def maxProfitFaster(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type x: int array :rtype: int
- def maxProfitFaster(self, prices): This will be done in O(n) due to only 1 loop. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type x: int array :rtype: int
- def maxProfitFaster(self, prices): This will be done in O(n) due to only 1 loop.
<|skeleton|>
class Solution:
... | 2ae794f270868bbbd2b46b235fd2b68e4a834d71 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type x: int array :rtype: int"""
<|body_0|>
def maxProfitFaster(self, prices):
"""This will be done in O(n) due to only 1 loop."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type x: int array :rtype: int"""
buy = 0
sell = buy + 1
maxDays = len(prices) - 1
maxProfit = 0
while buy < maxDays:
while sell <= maxDays:
if prices[sell] > prices[buy]:
... | the_stack_v2_python_sparse | python/123-best-time-to-buy-and-sell-stock/answer.py | vincepmartin/leetcode | train | 0 | |
28d44614b98949f0f255c0cedcda538a6375869a | [
"SegmentSimMeasurement.__init__(self, source_segment, target_segment)\nself.lower_case = lower_case\nself.stopword_removal = stopword_removal\nself.stemming = stemming\nself.stemmer = stemmer\nself.lemmatization = lemmatization",
"if edit <= 1:\n return 1.0\nelif edit <= 4:\n return 0.5\nelif edit <= 6:\n ... | <|body_start_0|>
SegmentSimMeasurement.__init__(self, source_segment, target_segment)
self.lower_case = lower_case
self.stopword_removal = stopword_removal
self.stemming = stemming
self.stemmer = stemmer
self.lemmatization = lemmatization
<|end_body_0|>
<|body_start_1|>
... | EditDistance | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditDistance:
def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=True, stemming=False, stemmer='porter', lemmatization=False):
""":param source_segment: Segment from source article :param target_segment: Segment from target article :param lower_case: Fla... | stack_v2_sparse_classes_36k_train_031525 | 3,043 | permissive | [
{
"docstring": ":param source_segment: Segment from source article :param target_segment: Segment from target article :param lower_case: Flag, whether all tokens should be lower case :param stopword_removal: Flag, whether stop words should be removed before the computation :param stemming: Flag, whether word st... | 3 | null | Implement the Python class `EditDistance` described below.
Class description:
Implement the EditDistance class.
Method signatures and docstrings:
- def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=True, stemming=False, stemmer='porter', lemmatization=False): :param source_segment: ... | Implement the Python class `EditDistance` described below.
Class description:
Implement the EditDistance class.
Method signatures and docstrings:
- def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=True, stemming=False, stemmer='porter', lemmatization=False): :param source_segment: ... | 2e6a85dc9e95ef94bec2339987950f4e88f5d909 | <|skeleton|>
class EditDistance:
def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=True, stemming=False, stemmer='porter', lemmatization=False):
""":param source_segment: Segment from source article :param target_segment: Segment from target article :param lower_case: Fla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditDistance:
def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=True, stemming=False, stemmer='porter', lemmatization=False):
""":param source_segment: Segment from source article :param target_segment: Segment from target article :param lower_case: Flag, whether all... | the_stack_v2_python_sparse | newssimilarity/segment_sim/edit_distance.py | imackerracher/NewsSimilarity | train | 0 | |
8e3676fdcd721a02654ab67ebf08f3e04acdd363 | [
"global console\nconsole = init_console()\ncommand, options = self.parse_options(argv)\nold_argv = sys.argv\nsys.argv = argv\ntry:\n return command.run(options)\nexcept Exception as e:\n logger.exception('Unexpected exception when running command \"%s\": %s', command.name, e)\n return 1\nfinally:\n sys.... | <|body_start_0|>
global console
console = init_console()
command, options = self.parse_options(argv)
old_argv = sys.argv
sys.argv = argv
try:
return command.run(options)
except Exception as e:
logger.exception('Unexpected exception when run... | Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite. | RBExt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RBExt:
"""Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite."""
def run(self, argv):
"""Run an rbext command with the provided arguments. Dur... | stack_v2_sparse_classes_36k_train_031526 | 36,982 | permissive | [
{
"docstring": "Run an rbext command with the provided arguments. During the duration of the run, :py:data:`sys.argv` will be set to the provided arguments. Args: argv (list of unicode): The command line arguments passed to the command. This should not include the executable name as the first element. Returns: ... | 2 | stack_v2_sparse_classes_30k_train_018942 | Implement the Python class `RBExt` described below.
Class description:
Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite.
Method signatures and docstrings:
- def run(self, arg... | Implement the Python class `RBExt` described below.
Class description:
Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite.
Method signatures and docstrings:
- def run(self, arg... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class RBExt:
"""Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite."""
def run(self, argv):
"""Run an rbext command with the provided arguments. Dur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RBExt:
"""Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite."""
def run(self, argv):
"""Run an rbext command with the provided arguments. During the durat... | the_stack_v2_python_sparse | reviewboard/cmdline/rbext.py | reviewboard/reviewboard | train | 1,141 |
ff9d362034fd385df9997f0b2742eecb56a2bc0a | [
"for row in response.css('.row-fluid.text-left'):\n for plant in row.css('.fixsearchsmall'):\n url = plant.css('a::attr(href)').extract_first()\n yield response.follow(url, callback=self.parse_plant_details)",
"title = response.css('.page-title h1 .plant-name')\nfeatures = response.css('.fieldgro... | <|body_start_0|>
for row in response.css('.row-fluid.text-left'):
for plant in row.css('.fixsearchsmall'):
url = plant.css('a::attr(href)').extract_first()
yield response.follow(url, callback=self.parse_plant_details)
<|end_body_0|>
<|body_start_1|>
title = r... | PerennialsComPlants | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerennialsComPlants:
def parse_grid(self, response):
"""Parse cols and rows for grid of results."""
<|body_0|>
def parse_plant_details(self, response):
"""Parse cols and rows for grid of results."""
<|body_1|>
def pagination(self, response):
"""E... | stack_v2_sparse_classes_36k_train_031527 | 3,956 | permissive | [
{
"docstring": "Parse cols and rows for grid of results.",
"name": "parse_grid",
"signature": "def parse_grid(self, response)"
},
{
"docstring": "Parse cols and rows for grid of results.",
"name": "parse_plant_details",
"signature": "def parse_plant_details(self, response)"
},
{
... | 4 | null | Implement the Python class `PerennialsComPlants` described below.
Class description:
Implement the PerennialsComPlants class.
Method signatures and docstrings:
- def parse_grid(self, response): Parse cols and rows for grid of results.
- def parse_plant_details(self, response): Parse cols and rows for grid of results.... | Implement the Python class `PerennialsComPlants` described below.
Class description:
Implement the PerennialsComPlants class.
Method signatures and docstrings:
- def parse_grid(self, response): Parse cols and rows for grid of results.
- def parse_plant_details(self, response): Parse cols and rows for grid of results.... | 8515fcc4c86ef0a96f34278d90419e5fad2b48d3 | <|skeleton|>
class PerennialsComPlants:
def parse_grid(self, response):
"""Parse cols and rows for grid of results."""
<|body_0|>
def parse_plant_details(self, response):
"""Parse cols and rows for grid of results."""
<|body_1|>
def pagination(self, response):
"""E... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PerennialsComPlants:
def parse_grid(self, response):
"""Parse cols and rows for grid of results."""
for row in response.css('.row-fluid.text-left'):
for plant in row.css('.fixsearchsmall'):
url = plant.css('a::attr(href)').extract_first()
yield respo... | the_stack_v2_python_sparse | plantstuff/scraping/scrapers/spiders/perennialscom.py | christabor/plantstuff | train | 8 | |
3bf56be2f4d1610cfef3cdb4c3a3f6702f887d7a | [
"super().__init__(nup, ndown, atomic_pos, cuda)\nself.fc1 = nn.Linear(1, 16, bias=False)\nself.fc2 = nn.Linear(16, 8, bias=False)\nself.fc3 = nn.Linear(8, 1, bias=False)\nself.nl_func = torch.nn.Sigmoid()\nself.requires_autograd = True",
"original_shape = x.shape\nx = x.reshape(-1, 1)\nx = self.fc1(x)\nx = self.n... | <|body_start_0|>
super().__init__(nup, ndown, atomic_pos, cuda)
self.fc1 = nn.Linear(1, 16, bias=False)
self.fc2 = nn.Linear(16, 8, bias=False)
self.fc3 = nn.Linear(8, 1, bias=False)
self.nl_func = torch.nn.Sigmoid()
self.requires_autograd = True
<|end_body_0|>
<|body_st... | FullyConnectedJastrowKernel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullyConnectedJastrowKernel:
def __init__(self, nup, ndown, atomic_pos, cuda, w=1.0):
"""Computes the Simple Pade-Jastrow factor .. math:: J = \\prod_{i<j} \\exp(B_{ij}) \\quad \\quad \\\\text{with} \\quad \\quad B_{ij} = \\\\frac{w_0 r_{i,j}}{1 + w r_{i,j}} Args: nup (int): number of sp... | stack_v2_sparse_classes_36k_train_031528 | 1,826 | permissive | [
{
"docstring": "Computes the Simple Pade-Jastrow factor .. math:: J = \\\\prod_{i<j} \\\\exp(B_{ij}) \\\\quad \\\\quad \\\\\\\\text{with} \\\\quad \\\\quad B_{ij} = \\\\\\\\frac{w_0 r_{i,j}}{1 + w r_{i,j}} Args: nup (int): number of spin up electons ndow (int): number of spin down electons atoms (torch.tensor):... | 2 | null | Implement the Python class `FullyConnectedJastrowKernel` described below.
Class description:
Implement the FullyConnectedJastrowKernel class.
Method signatures and docstrings:
- def __init__(self, nup, ndown, atomic_pos, cuda, w=1.0): Computes the Simple Pade-Jastrow factor .. math:: J = \\prod_{i<j} \\exp(B_{ij}) \\... | Implement the Python class `FullyConnectedJastrowKernel` described below.
Class description:
Implement the FullyConnectedJastrowKernel class.
Method signatures and docstrings:
- def __init__(self, nup, ndown, atomic_pos, cuda, w=1.0): Computes the Simple Pade-Jastrow factor .. math:: J = \\prod_{i<j} \\exp(B_{ij}) \\... | 439a79e97ee63057e3032d28a1a5ebafd2d5b5e4 | <|skeleton|>
class FullyConnectedJastrowKernel:
def __init__(self, nup, ndown, atomic_pos, cuda, w=1.0):
"""Computes the Simple Pade-Jastrow factor .. math:: J = \\prod_{i<j} \\exp(B_{ij}) \\quad \\quad \\\\text{with} \\quad \\quad B_{ij} = \\\\frac{w_0 r_{i,j}}{1 + w r_{i,j}} Args: nup (int): number of sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullyConnectedJastrowKernel:
def __init__(self, nup, ndown, atomic_pos, cuda, w=1.0):
"""Computes the Simple Pade-Jastrow factor .. math:: J = \\prod_{i<j} \\exp(B_{ij}) \\quad \\quad \\\\text{with} \\quad \\quad B_{ij} = \\\\frac{w_0 r_{i,j}}{1 + w r_{i,j}} Args: nup (int): number of spin up electons... | the_stack_v2_python_sparse | qmctorch/wavefunction/jastrows/elec_nuclei/kernels/fully_connected_jastrow_kernel.py | NLESC-JCER/QMCTorch | train | 22 | |
466b1ef5ee8a211863ff45e5490f7953fbd61c75 | [
"lines = make_model()\nabaqus_filename = os.path.join(MODEL_PATH, 'abaqus.inp')\nwith open(abaqus_filename, 'w') as abaqus_file:\n abaqus_file.write('\\n'.join(lines))\nlog = get_logger(level='error', encoding='utf-8')\ntest = AbaqusGui()\ntest.log = log\ntest.on_load_geometry(abaqus_filename, geometry_format='a... | <|body_start_0|>
lines = make_model()
abaqus_filename = os.path.join(MODEL_PATH, 'abaqus.inp')
with open(abaqus_filename, 'w') as abaqus_file:
abaqus_file.write('\n'.join(lines))
log = get_logger(level='error', encoding='utf-8')
test = AbaqusGui()
test.log = l... | TestAbaqusGui | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAbaqusGui:
def test_abaqus_1(self):
"""simple test"""
<|body_0|>
def test_abaqus_2(self):
"""two hex blocks with duplicate node ids"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lines = make_model()
abaqus_filename = os.path.join(MODEL... | stack_v2_sparse_classes_36k_train_031529 | 1,718 | no_license | [
{
"docstring": "simple test",
"name": "test_abaqus_1",
"signature": "def test_abaqus_1(self)"
},
{
"docstring": "two hex blocks with duplicate node ids",
"name": "test_abaqus_2",
"signature": "def test_abaqus_2(self)"
}
] | 2 | null | Implement the Python class `TestAbaqusGui` described below.
Class description:
Implement the TestAbaqusGui class.
Method signatures and docstrings:
- def test_abaqus_1(self): simple test
- def test_abaqus_2(self): two hex blocks with duplicate node ids | Implement the Python class `TestAbaqusGui` described below.
Class description:
Implement the TestAbaqusGui class.
Method signatures and docstrings:
- def test_abaqus_1(self): simple test
- def test_abaqus_2(self): two hex blocks with duplicate node ids
<|skeleton|>
class TestAbaqusGui:
def test_abaqus_1(self):
... | d9ffdb4ac845b13bcf6aea96ff5d37cc026c5267 | <|skeleton|>
class TestAbaqusGui:
def test_abaqus_1(self):
"""simple test"""
<|body_0|>
def test_abaqus_2(self):
"""two hex blocks with duplicate node ids"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAbaqusGui:
def test_abaqus_1(self):
"""simple test"""
lines = make_model()
abaqus_filename = os.path.join(MODEL_PATH, 'abaqus.inp')
with open(abaqus_filename, 'w') as abaqus_file:
abaqus_file.write('\n'.join(lines))
log = get_logger(level='error', encodi... | the_stack_v2_python_sparse | pyNastran/converters/abaqus/test_abaqus_gui.py | ratalex/pyNastran | train | 0 | |
a76638a3ed4c4f00a26641467fbcee7fe582e888 | [
"self.left = []\nself.right = []\nself.even_length = True",
"if len(self.left) == 0 or num <= -1 * self.left[0]:\n if len(self.left) > len(self.right):\n tmp_num = heappushpop(self.left, -1 * num)\n heappush(self.right, -1 * tmp_num)\n else:\n heappush(self.left, -1 * num)\nelif len(sel... | <|body_start_0|>
self.left = []
self.right = []
self.even_length = True
<|end_body_0|>
<|body_start_1|>
if len(self.left) == 0 or num <= -1 * self.left[0]:
if len(self.left) > len(self.right):
tmp_num = heappushpop(self.left, -1 * num)
heappus... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k_train_031530 | 7,205 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": "Returns the ... | 3 | stack_v2_sparse_classes_30k_train_004763 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | 2157d194db12f6ea808c1f5f069ae52c1018dee1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
self.left = []
self.right = []
self.even_length = True
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
if len(self.left) == 0 or num <=... | the_stack_v2_python_sparse | leetcode/295.py | bbung24/codingStudy | train | 1 | |
b5fb919bc9b1a45f913ffebc5b4384c36cc5e85c | [
"monthly_difference_sum = 0\nfor i in range(len(monthly_fund_field)):\n if risk_free / 12 - monthly_fund_field[i] > 0:\n monthly_difference_sum += pow(risk_free / 12 - monthly_fund_field[i], 3)\nlpm3 = monthly_difference_sum / (len(monthly_fund_field) - 1)\nreturn lpm3",
"annual_earnning = RangeReturnRa... | <|body_start_0|>
monthly_difference_sum = 0
for i in range(len(monthly_fund_field)):
if risk_free / 12 - monthly_fund_field[i] > 0:
monthly_difference_sum += pow(risk_free / 12 - monthly_fund_field[i], 3)
lpm3 = monthly_difference_sum / (len(monthly_fund_field) - 1)
... | Kappa | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kappa:
def lpm_3(monthly_fund_field: list, risk_free: float):
"""计算LMP3,需要传入基金月度收益率,无风险收益率(取一年期定期存款利率/12)"""
<|body_0|>
def kappa(startvalue, endvalue, yesrs, monthly_fund_field, risk_free, isannual=True):
"""计算卡帕,需要年化收益率,需要传入始末净值和净值总天数,需要年化无风险收益率,lpm3"""
<|b... | stack_v2_sparse_classes_36k_train_031531 | 2,113 | no_license | [
{
"docstring": "计算LMP3,需要传入基金月度收益率,无风险收益率(取一年期定期存款利率/12)",
"name": "lpm_3",
"signature": "def lpm_3(monthly_fund_field: list, risk_free: float)"
},
{
"docstring": "计算卡帕,需要年化收益率,需要传入始末净值和净值总天数,需要年化无风险收益率,lpm3",
"name": "kappa",
"signature": "def kappa(startvalue, endvalue, yesrs, monthly_... | 2 | stack_v2_sparse_classes_30k_train_001203 | Implement the Python class `Kappa` described below.
Class description:
Implement the Kappa class.
Method signatures and docstrings:
- def lpm_3(monthly_fund_field: list, risk_free: float): 计算LMP3,需要传入基金月度收益率,无风险收益率(取一年期定期存款利率/12)
- def kappa(startvalue, endvalue, yesrs, monthly_fund_field, risk_free, isannual=True): ... | Implement the Python class `Kappa` described below.
Class description:
Implement the Kappa class.
Method signatures and docstrings:
- def lpm_3(monthly_fund_field: list, risk_free: float): 计算LMP3,需要传入基金月度收益率,无风险收益率(取一年期定期存款利率/12)
- def kappa(startvalue, endvalue, yesrs, monthly_fund_field, risk_free, isannual=True): ... | eae782a78ffde1276a0812a43d7deefb0bdedeb4 | <|skeleton|>
class Kappa:
def lpm_3(monthly_fund_field: list, risk_free: float):
"""计算LMP3,需要传入基金月度收益率,无风险收益率(取一年期定期存款利率/12)"""
<|body_0|>
def kappa(startvalue, endvalue, yesrs, monthly_fund_field, risk_free, isannual=True):
"""计算卡帕,需要年化收益率,需要传入始末净值和净值总天数,需要年化无风险收益率,lpm3"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Kappa:
def lpm_3(monthly_fund_field: list, risk_free: float):
"""计算LMP3,需要传入基金月度收益率,无风险收益率(取一年期定期存款利率/12)"""
monthly_difference_sum = 0
for i in range(len(monthly_fund_field)):
if risk_free / 12 - monthly_fund_field[i] > 0:
monthly_difference_sum += pow(risk... | the_stack_v2_python_sparse | public_method/indicator_calculation_method/kappa.py | liufubin-git/python | train | 0 | |
8497c76972bf4cbfa2652ab690f517e66d16eccd | [
"self.spiffe_id = spiffe_id\nself.audience = audience\nself.expiry = expiry\nself.claims = claims\nself.token = token",
"if not token:\n raise ArgumentError(INVALID_INPUT_ERROR.format('token cannot be empty'))\ntry:\n header_params = jwt.get_unverified_header(token)\n validator = JwtSvidValidator()\n ... | <|body_start_0|>
self.spiffe_id = spiffe_id
self.audience = audience
self.expiry = expiry
self.claims = claims
self.token = token
<|end_body_0|>
<|body_start_1|>
if not token:
raise ArgumentError(INVALID_INPUT_ERROR.format('token cannot be empty'))
tr... | Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>` | JwtSvid | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JwtSvid:
"""Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`"""
def __init__(self, spiffe_id: SpiffeId, audience: List[str], expiry: int, claims: Dict[str, str], token: str) -> ... | stack_v2_sparse_classes_36k_train_031532 | 6,651 | permissive | [
{
"docstring": "Creates a JwtSvid instance. Args: spiffe_id: A valid SpiffeId instance. audience: The intended recipients of JWT-SVID as present in the 'aud' claims. expiry: Date and time in UTC specifying expiry date of the JwtSvid. claims: Key-value pairs with all the claims present in the token. token: Encod... | 3 | stack_v2_sparse_classes_30k_train_011436 | Implement the Python class `JwtSvid` described below.
Class description:
Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`
Method signatures and docstrings:
- def __init__(self, spiffe_id: SpiffeId, audie... | Implement the Python class `JwtSvid` described below.
Class description:
Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`
Method signatures and docstrings:
- def __init__(self, spiffe_id: SpiffeId, audie... | ab46e05171b9d804f2aec4c6c4f024a573047215 | <|skeleton|>
class JwtSvid:
"""Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`"""
def __init__(self, spiffe_id: SpiffeId, audience: List[str], expiry: int, claims: Dict[str, str], token: str) -> ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JwtSvid:
"""Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`"""
def __init__(self, spiffe_id: SpiffeId, audience: List[str], expiry: int, claims: Dict[str, str], token: str) -> None:
... | the_stack_v2_python_sparse | src/pyspiffe/svid/jwt_svid.py | amoore877/py-spiffe | train | 0 |
1ac31b663bb5809dda90fc78c55861080f167c19 | [
"project_id, campfire_id = util.project_or_object(project, campfire, section_name=DOCK_NAME_CAMPFIRE)\nurl = self.LIST_URL.format(base_url=self.url, project_id=project_id, campfire_id=campfire_id)\nreturn self._get_list(url)",
"campfire_line = int(campfire_line)\nproject_id, campfire_id = util.project_or_object(p... | <|body_start_0|>
project_id, campfire_id = util.project_or_object(project, campfire, section_name=DOCK_NAME_CAMPFIRE)
url = self.LIST_URL.format(base_url=self.url, project_id=project_id, campfire_id=campfire_id)
return self._get_list(url)
<|end_body_0|>
<|body_start_1|>
campfire_line = ... | CampfireLines | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampfireLines:
def list(self, project=None, campfire=None):
"""Get a list of chat lines in the given Campfire. If `campfire` is a Campfire object, the `project` parameter can be omitted. If `project` is a Project object, the `campfire` parameter can be omitted. :param project: a Project ... | stack_v2_sparse_classes_36k_train_031533 | 3,769 | permissive | [
{
"docstring": "Get a list of chat lines in the given Campfire. If `campfire` is a Campfire object, the `project` parameter can be omitted. If `project` is a Project object, the `campfire` parameter can be omitted. :param project: a Project object or Project ID :param campfire: a Campfire object or Campfire ID ... | 4 | stack_v2_sparse_classes_30k_train_021406 | Implement the Python class `CampfireLines` described below.
Class description:
Implement the CampfireLines class.
Method signatures and docstrings:
- def list(self, project=None, campfire=None): Get a list of chat lines in the given Campfire. If `campfire` is a Campfire object, the `project` parameter can be omitted.... | Implement the Python class `CampfireLines` described below.
Class description:
Implement the CampfireLines class.
Method signatures and docstrings:
- def list(self, project=None, campfire=None): Get a list of chat lines in the given Campfire. If `campfire` is a Campfire object, the `project` parameter can be omitted.... | bece72d06b91de0e33afd2181c59b895dbe7ae1f | <|skeleton|>
class CampfireLines:
def list(self, project=None, campfire=None):
"""Get a list of chat lines in the given Campfire. If `campfire` is a Campfire object, the `project` parameter can be omitted. If `project` is a Project object, the `campfire` parameter can be omitted. :param project: a Project ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CampfireLines:
def list(self, project=None, campfire=None):
"""Get a list of chat lines in the given Campfire. If `campfire` is a Campfire object, the `project` parameter can be omitted. If `project` is a Project object, the `campfire` parameter can be omitted. :param project: a Project object or Proj... | the_stack_v2_python_sparse | basecampy3/endpoints/campfire_lines.py | phistrom/basecampy3 | train | 34 | |
d477469b173f4b1f99c1d178e55da7875f391428 | [
"self.padre_id = padre_id\nself.hijo_id = hijo_id\nself.versionHijo = versionHijo",
"self.padre_id = padre_id\nself.hijo_id = hijo_id\nself.versionHijo = versionHijo"
] | <|body_start_0|>
self.padre_id = padre_id
self.hijo_id = hijo_id
self.versionHijo = versionHijo
<|end_body_0|>
<|body_start_1|>
self.padre_id = padre_id
self.hijo_id = hijo_id
self.versionHijo = versionHijo
<|end_body_1|>
| Esta clase se utiliza para mapear a sus instancias con la tabla de Historial_relacion Hereda de la clase Base. La clase Base debe ser heredada por todas las clases que mapearan a una tabla. | HistorialRelacion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistorialRelacion:
"""Esta clase se utiliza para mapear a sus instancias con la tabla de Historial_relacion Hereda de la clase Base. La clase Base debe ser heredada por todas las clases que mapearan a una tabla."""
def setValues(self, padre_id, hijo_id, versionHijo):
"""Metodo para e... | stack_v2_sparse_classes_36k_train_031534 | 10,087 | no_license | [
{
"docstring": "Metodo para establecer valores de atributos de la clase. @type padre_id : number @param padre_id : nombre de la fase @type hijo_id : number @param hijo_id : descripcion de la fase @type versionHijo : number @param versionHijo : estado actual de la fase",
"name": "setValues",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_001804 | Implement the Python class `HistorialRelacion` described below.
Class description:
Esta clase se utiliza para mapear a sus instancias con la tabla de Historial_relacion Hereda de la clase Base. La clase Base debe ser heredada por todas las clases que mapearan a una tabla.
Method signatures and docstrings:
- def setVa... | Implement the Python class `HistorialRelacion` described below.
Class description:
Esta clase se utiliza para mapear a sus instancias con la tabla de Historial_relacion Hereda de la clase Base. La clase Base debe ser heredada por todas las clases que mapearan a una tabla.
Method signatures and docstrings:
- def setVa... | 9262320d4ff52bd3592365cd232f8dedff4f64da | <|skeleton|>
class HistorialRelacion:
"""Esta clase se utiliza para mapear a sus instancias con la tabla de Historial_relacion Hereda de la clase Base. La clase Base debe ser heredada por todas las clases que mapearan a una tabla."""
def setValues(self, padre_id, hijo_id, versionHijo):
"""Metodo para e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HistorialRelacion:
"""Esta clase se utiliza para mapear a sus instancias con la tabla de Historial_relacion Hereda de la clase Base. La clase Base debe ser heredada por todas las clases que mapearan a una tabla."""
def setValues(self, padre_id, hijo_id, versionHijo):
"""Metodo para establecer val... | the_stack_v2_python_sparse | models/historialModelo.py | jemaromaster/WAPM | train | 0 |
a314e9d42e749bc9a4413b8e445c96c4ab1a3ace | [
"super(InTimeToArrivalToVehicle, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._other_actor = other_actor\nself._actor = actor\nself._time = time",
"new_status = py_trees.common.Status.RUNNING\ncurrent_location = CarlaDataProvider.get_location(self._actor)\ntarget_locati... | <|body_start_0|>
super(InTimeToArrivalToVehicle, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._other_actor = other_actor
self._actor = actor
self._time = time
<|end_body_0|>
<|body_start_1|>
new_status = py_trees.common.Status.RU... | This class contains a check if a actor arrives within a given time at another actor. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is less than _time_ in seconds - other_actor: Reference actor used in this behavior The conditi... | InTimeToArrivalToVehicle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InTimeToArrivalToVehicle:
"""This class contains a check if a actor arrives within a given time at another actor. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is less than _time_ in seconds - other_acto... | stack_v2_sparse_classes_36k_train_031535 | 18,494 | permissive | [
{
"docstring": "Setup parameters",
"name": "__init__",
"signature": "def __init__(self, other_actor, actor, time, name='TimeToArrival')"
},
{
"docstring": "Check if the ego vehicle can arrive at other actor within time",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004858 | Implement the Python class `InTimeToArrivalToVehicle` described below.
Class description:
This class contains a check if a actor arrives within a given time at another actor. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is l... | Implement the Python class `InTimeToArrivalToVehicle` described below.
Class description:
This class contains a check if a actor arrives within a given time at another actor. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is l... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class InTimeToArrivalToVehicle:
"""This class contains a check if a actor arrives within a given time at another actor. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is less than _time_ in seconds - other_acto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InTimeToArrivalToVehicle:
"""This class contains a check if a actor arrives within a given time at another actor. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is less than _time_ in seconds - other_actor: Reference ... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_trigger_conditions.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
1baef454925aa40e2ed9d96329db730225ee1881 | [
"val_list = []\ncur = head\nwhile cur:\n val_list.append(cur.val)\n cur = cur.next\nreturn val_list == val_list[::-1]",
"rev = None\nfast, slow = (head, head)\nwhile fast and fast.next:\n fast = fast.next.next\n rev, rev.next, slow = (slow, rev, slow.next)\nif fast:\n slow = slow.next\nwhile rev an... | <|body_start_0|>
val_list = []
cur = head
while cur:
val_list.append(cur.val)
cur = cur.next
return val_list == val_list[::-1]
<|end_body_0|>
<|body_start_1|>
rev = None
fast, slow = (head, head)
while fast and fast.next:
fast ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_palindrome(cls, head: ListNode) -> bool:
"""将值复制到数组中判断是否回文"""
<|body_0|>
def is_palindrome_v2(cls, head: ListNode) -> bool:
"""双指针"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
val_list = []
cur = head
while cur:
... | stack_v2_sparse_classes_36k_train_031536 | 1,284 | no_license | [
{
"docstring": "将值复制到数组中判断是否回文",
"name": "is_palindrome",
"signature": "def is_palindrome(cls, head: ListNode) -> bool"
},
{
"docstring": "双指针",
"name": "is_palindrome_v2",
"signature": "def is_palindrome_v2(cls, head: ListNode) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_006056 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_palindrome(cls, head: ListNode) -> bool: 将值复制到数组中判断是否回文
- def is_palindrome_v2(cls, head: ListNode) -> bool: 双指针 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_palindrome(cls, head: ListNode) -> bool: 将值复制到数组中判断是否回文
- def is_palindrome_v2(cls, head: ListNode) -> bool: 双指针
<|skeleton|>
class Solution:
def is_palindrome(cls, ... | 1d1876620a55ff88af7bc390cf1a4fd4350d8d16 | <|skeleton|>
class Solution:
def is_palindrome(cls, head: ListNode) -> bool:
"""将值复制到数组中判断是否回文"""
<|body_0|>
def is_palindrome_v2(cls, head: ListNode) -> bool:
"""双指针"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def is_palindrome(cls, head: ListNode) -> bool:
"""将值复制到数组中判断是否回文"""
val_list = []
cur = head
while cur:
val_list.append(cur.val)
cur = cur.next
return val_list == val_list[::-1]
def is_palindrome_v2(cls, head: ListNode) -> bool:
... | the_stack_v2_python_sparse | 02-算法思想/双指针/234.回文链表.py | jh-lau/leetcode_in_python | train | 0 | |
f58f231b806ae477b3e7e8a2e1146509063fcee3 | [
"if columns is not None:\n if isinstance(columns, list) or isinstance(columns, tuple):\n self.columns = columns\n else:\n raise TypeError('Invalid type {}'.format(type(columns)))\nelse:\n self.columns = columns\nif mapping is not None:\n if isinstance(mapping, dict):\n self.mapping ... | <|body_start_0|>
if columns is not None:
if isinstance(columns, list) or isinstance(columns, tuple):
self.columns = columns
else:
raise TypeError('Invalid type {}'.format(type(columns)))
else:
self.columns = columns
if mapping i... | This transformer replace some values with others. Attributes ---------- columns: `list` of columns to transformer [n_columns] mapping: dict`, for example: ``` mapping = {"yes": 1, "no": 0} ``` Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/ReplaceTransfo... | ReplaceTransformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplaceTransformer:
"""This transformer replace some values with others. Attributes ---------- columns: `list` of columns to transformer [n_columns] mapping: dict`, for example: ``` mapping = {"yes": 1, "no": 0} ``` Examples -------- For usage examples, please see https://jaisenbe58r.github.io/ML... | stack_v2_sparse_classes_36k_train_031537 | 6,305 | permissive | [
{
"docstring": "Init replace missing values.",
"name": "__init__",
"signature": "def __init__(self, columns=None, mapping=None)"
},
{
"docstring": "Gets the columns to make a replace values. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n_samples is the ... | 3 | stack_v2_sparse_classes_30k_train_001602 | Implement the Python class `ReplaceTransformer` described below.
Class description:
This transformer replace some values with others. Attributes ---------- columns: `list` of columns to transformer [n_columns] mapping: dict`, for example: ``` mapping = {"yes": 1, "no": 0} ``` Examples -------- For usage examples, plea... | Implement the Python class `ReplaceTransformer` described below.
Class description:
This transformer replace some values with others. Attributes ---------- columns: `list` of columns to transformer [n_columns] mapping: dict`, for example: ``` mapping = {"yes": 1, "no": 0} ``` Examples -------- For usage examples, plea... | e768a4cad150b35fb5bf543ab28aa23764af51d9 | <|skeleton|>
class ReplaceTransformer:
"""This transformer replace some values with others. Attributes ---------- columns: `list` of columns to transformer [n_columns] mapping: dict`, for example: ``` mapping = {"yes": 1, "no": 0} ``` Examples -------- For usage examples, please see https://jaisenbe58r.github.io/ML... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReplaceTransformer:
"""This transformer replace some values with others. Attributes ---------- columns: `list` of columns to transformer [n_columns] mapping: dict`, for example: ``` mapping = {"yes": 1, "no": 0} ``` Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_g... | the_stack_v2_python_sparse | mlearner/preprocessing/replace_categorical.py | jaisenbe58r/MLearner | train | 9 |
a8ef28be87004bcd6d936df1350d6bbdea4b415c | [
"super(BahdanauAttention, self).__init__()\nself.W1 = tf.keras.layers.Dense(units)\nself.W2 = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"query_with_time_axis = tf.expand_dims(query, 1)\nscore = self.V(tf.nn.tanh(self.W1(query_with_time_axis) + self.W2(values)))\nattention_weights = tf.nn.s... | <|body_start_0|>
super(BahdanauAttention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
query_with_time_axis = tf.expand_dims(query, 1)
score = self.V(tf.nn... | Attention layer used with the gru model. | BahdanauAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BahdanauAttention:
"""Attention layer used with the gru model."""
def __init__(self, units):
"""Create the attention layer."""
<|body_0|>
def call(self, query, values):
"""Call of the attention layer. Note that the call must be for one caracter/word at a time."""... | stack_v2_sparse_classes_36k_train_031538 | 8,984 | no_license | [
{
"docstring": "Create the attention layer.",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "Call of the attention layer. Note that the call must be for one caracter/word at a time.",
"name": "call",
"signature": "def call(self, query, values)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006803 | Implement the Python class `BahdanauAttention` described below.
Class description:
Attention layer used with the gru model.
Method signatures and docstrings:
- def __init__(self, units): Create the attention layer.
- def call(self, query, values): Call of the attention layer. Note that the call must be for one caract... | Implement the Python class `BahdanauAttention` described below.
Class description:
Attention layer used with the gru model.
Method signatures and docstrings:
- def __init__(self, units): Create the attention layer.
- def call(self, query, values): Call of the attention layer. Note that the call must be for one caract... | 4502d9e7461520664e72165a91bedd8e65464bae | <|skeleton|>
class BahdanauAttention:
"""Attention layer used with the gru model."""
def __init__(self, units):
"""Create the attention layer."""
<|body_0|>
def call(self, query, values):
"""Call of the attention layer. Note that the call must be for one caracter/word at a time."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BahdanauAttention:
"""Attention layer used with the gru model."""
def __init__(self, units):
"""Create the attention layer."""
super(BahdanauAttention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.Dense(units)
self.V = tf.keras.... | the_stack_v2_python_sparse | src/model/gru_attention.py | nathanielsimard/Low-Resource-Machine-Translation | train | 0 |
097673aa070bfc33a82922705b908788a97d3d69 | [
"with get_oss_fuzz_repo() as oss_fuzz_repo:\n repo_man = repo_manager.RepoManager(oss_fuzz_repo)\n old_commit = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b'\n new_commit = 'fa662173bfeb3ba08d2e84cefc363be11e6c8463'\n commit_list = ['fa662173bfeb3ba08d2e84cefc363be11e6c8463', '17035317a44fa89d22fe6846d868d... | <|body_start_0|>
with get_oss_fuzz_repo() as oss_fuzz_repo:
repo_man = repo_manager.RepoManager(oss_fuzz_repo)
old_commit = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b'
new_commit = 'fa662173bfeb3ba08d2e84cefc363be11e6c8463'
commit_list = ['fa662173bfeb3ba08d2e84cef... | Tests the get_commit_list method of RepoManager. | RepoManagerGetCommitListTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepoManagerGetCommitListTest:
"""Tests the get_commit_list method of RepoManager."""
def test_get_valid_commit_list(self):
"""Tests an accurate commit list can be retrieved from the repo manager."""
<|body_0|>
def test_get_invalid_commit_list(self):
"""Tests that... | stack_v2_sparse_classes_36k_train_031539 | 8,172 | permissive | [
{
"docstring": "Tests an accurate commit list can be retrieved from the repo manager.",
"name": "test_get_valid_commit_list",
"signature": "def test_get_valid_commit_list(self)"
},
{
"docstring": "Tests that the proper errors are thrown when invalid commits are passed to get_commit_list.",
"... | 2 | null | Implement the Python class `RepoManagerGetCommitListTest` described below.
Class description:
Tests the get_commit_list method of RepoManager.
Method signatures and docstrings:
- def test_get_valid_commit_list(self): Tests an accurate commit list can be retrieved from the repo manager.
- def test_get_invalid_commit_l... | Implement the Python class `RepoManagerGetCommitListTest` described below.
Class description:
Tests the get_commit_list method of RepoManager.
Method signatures and docstrings:
- def test_get_valid_commit_list(self): Tests an accurate commit list can be retrieved from the repo manager.
- def test_get_invalid_commit_l... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class RepoManagerGetCommitListTest:
"""Tests the get_commit_list method of RepoManager."""
def test_get_valid_commit_list(self):
"""Tests an accurate commit list can be retrieved from the repo manager."""
<|body_0|>
def test_get_invalid_commit_list(self):
"""Tests that... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepoManagerGetCommitListTest:
"""Tests the get_commit_list method of RepoManager."""
def test_get_valid_commit_list(self):
"""Tests an accurate commit list can be retrieved from the repo manager."""
with get_oss_fuzz_repo() as oss_fuzz_repo:
repo_man = repo_manager.RepoManager... | the_stack_v2_python_sparse | infra/repo_manager_test.py | google/oss-fuzz | train | 9,438 |
96577966de42c8e52599726e2ea1d4a571bba2f6 | [
"date_str = str(self.plan_date)\nmain_line_rule_id = self.env.ref('metro_park_base_data_10.main_line_run_rule').id\nrecords = self.search([('rule', '=', main_line_rule_id), ('dev', '=', self.dev.id), ('plan_date', '=', date_str), ('work_start_tm', '>', self.work_end_tm)], order='work_start_tm asc')\nreturn records[... | <|body_start_0|>
date_str = str(self.plan_date)
main_line_rule_id = self.env.ref('metro_park_base_data_10.main_line_run_rule').id
records = self.search([('rule', '=', main_line_rule_id), ('dev', '=', self.dev.id), ('plan_date', '=', date_str), ('work_start_tm', '>', self.work_end_tm)], order='wo... | 车间日生产计划 | WorkShopDayPlan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkShopDayPlan:
"""车间日生产计划"""
def get_next_run_task(self):
"""当前是一个收车任务,但后面还有运行, 高峰车的情况, 这个也是判断高峰车的标准 train_no :return:"""
<|body_0|>
def get_prev_run_task(self):
"""取得之前的任务 :return:"""
<|body_1|>
def get_tasks_after_run(self):
"""取处运营任务之后的检... | stack_v2_sparse_classes_36k_train_031540 | 3,287 | no_license | [
{
"docstring": "当前是一个收车任务,但后面还有运行, 高峰车的情况, 这个也是判断高峰车的标准 train_no :return:",
"name": "get_next_run_task",
"signature": "def get_next_run_task(self)"
},
{
"docstring": "取得之前的任务 :return:",
"name": "get_prev_run_task",
"signature": "def get_prev_run_task(self)"
},
{
"docstring": "取处运... | 3 | null | Implement the Python class `WorkShopDayPlan` described below.
Class description:
车间日生产计划
Method signatures and docstrings:
- def get_next_run_task(self): 当前是一个收车任务,但后面还有运行, 高峰车的情况, 这个也是判断高峰车的标准 train_no :return:
- def get_prev_run_task(self): 取得之前的任务 :return:
- def get_tasks_after_run(self): 取处运营任务之后的检修任务, 一般是找到这些任务后... | Implement the Python class `WorkShopDayPlan` described below.
Class description:
车间日生产计划
Method signatures and docstrings:
- def get_next_run_task(self): 当前是一个收车任务,但后面还有运行, 高峰车的情况, 这个也是判断高峰车的标准 train_no :return:
- def get_prev_run_task(self): 取得之前的任务 :return:
- def get_tasks_after_run(self): 取处运营任务之后的检修任务, 一般是找到这些任务后... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class WorkShopDayPlan:
"""车间日生产计划"""
def get_next_run_task(self):
"""当前是一个收车任务,但后面还有运行, 高峰车的情况, 这个也是判断高峰车的标准 train_no :return:"""
<|body_0|>
def get_prev_run_task(self):
"""取得之前的任务 :return:"""
<|body_1|>
def get_tasks_after_run(self):
"""取处运营任务之后的检... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkShopDayPlan:
"""车间日生产计划"""
def get_next_run_task(self):
"""当前是一个收车任务,但后面还有运行, 高峰车的情况, 这个也是判断高峰车的标准 train_no :return:"""
date_str = str(self.plan_date)
main_line_rule_id = self.env.ref('metro_park_base_data_10.main_line_run_rule').id
records = self.search([('rule', '=',... | the_stack_v2_python_sparse | mdias_addons/metro_park_base_data_8/models/work_shop_day_plan_data.py | rezaghanimi/main_mdias | train | 0 |
00caa4a1925c26b087b2375c382d02818aa00af0 | [
"translatable_content_ids = exploration.get_translatable_content_ids()\nupdated_suggestions = []\nfor suggestion in suggestions:\n if suggestion.change_cmd['content_id'] in translatable_content_ids:\n continue\n suggestion.status = suggestion_models.STATUS_REJECTED\n suggestion.final_reviewer_id = f... | <|body_start_0|>
translatable_content_ids = exploration.get_translatable_content_ids()
updated_suggestions = []
for suggestion in suggestions:
if suggestion.change_cmd['content_id'] in translatable_content_ids:
continue
suggestion.status = suggestion_model... | Job that rejects translation suggestions with missing content ids. | RejectTranslationSuggestionsWithMissingContentIdJob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RejectTranslationSuggestionsWithMissingContentIdJob:
"""Job that rejects translation suggestions with missing content ids."""
def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[suggestion_models.GeneralSu... | stack_v2_sparse_classes_36k_train_031541 | 11,707 | permissive | [
{
"docstring": "Marks translation suggestion models as 'rejected' if the content ID for the suggestion no longer exists. The final_reviewer_id will be set to feconf.SUGGESTION_BOT_USER_ID. Args: suggestions: list(GeneralSuggestionModel). A list of translation suggestion models corresponding to the given explora... | 2 | stack_v2_sparse_classes_30k_train_018269 | Implement the Python class `RejectTranslationSuggestionsWithMissingContentIdJob` described below.
Class description:
Job that rejects translation suggestions with missing content ids.
Method signatures and docstrings:
- def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], expl... | Implement the Python class `RejectTranslationSuggestionsWithMissingContentIdJob` described below.
Class description:
Job that rejects translation suggestions with missing content ids.
Method signatures and docstrings:
- def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], expl... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class RejectTranslationSuggestionsWithMissingContentIdJob:
"""Job that rejects translation suggestions with missing content ids."""
def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[suggestion_models.GeneralSu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RejectTranslationSuggestionsWithMissingContentIdJob:
"""Job that rejects translation suggestions with missing content ids."""
def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[suggestion_models.GeneralSuggestionModel... | the_stack_v2_python_sparse | core/jobs/batch_jobs/rejecting_suggestion_for_invalid_content_ids_jobs.py | oppia/oppia | train | 6,172 |
4d312b627466621e5c71ccf2617988a108323fbb | [
"super(FinalizeSlicedDownloadTask, self).__init__()\nself._source_resource = source_resource\nself._destination_resource = destination_resource",
"tracker_file_util.delete_download_tracker_files(self._destination_resource.storage_url)\nwith files.BinaryFileReader(self._destination_resource.storage_url.object_name... | <|body_start_0|>
super(FinalizeSlicedDownloadTask, self).__init__()
self._source_resource = source_resource
self._destination_resource = destination_resource
<|end_body_0|>
<|body_start_1|>
tracker_file_util.delete_download_tracker_files(self._destination_resource.storage_url)
w... | Performs final steps of sliced download. | FinalizeSlicedDownloadTask | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, destination_resource):
"""Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. destin... | stack_v2_sparse_classes_36k_train_031542 | 3,847 | permissive | [
{
"docstring": "Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. destination_resource (resource_reference.FileObjectResource): Must contain local filesystem path to downloaded object.",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_020599 | Implement the Python class `FinalizeSlicedDownloadTask` described below.
Class description:
Performs final steps of sliced download.
Method signatures and docstrings:
- def __init__(self, source_resource, destination_resource): Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contai... | Implement the Python class `FinalizeSlicedDownloadTask` described below.
Class description:
Performs final steps of sliced download.
Method signatures and docstrings:
- def __init__(self, source_resource, destination_resource): Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contai... | 849d09dd7863efecbdf4072a504e1554e119f6ae | <|skeleton|>
class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, destination_resource):
"""Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. destin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, destination_resource):
"""Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. destination_resourc... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/tasks/cp/finalize_sliced_download_task.py | PrateekKhatri/gcloud_cli | train | 0 |
143758b7a4c3091ebe280a532eb9e012acd08437 | [
"obj = super().__new__(cls, _str_)\nobj.if_empty = if_empty\nobj.separator = s\nobj.quote_args = quote_args\nreturn obj",
"tovar: Callable[[Any], Var] = _tovar\nif self.quote_args:\n tovar = lambda var: Var(repr(str(_tovar(var))))\nif args:\n args = tuple((tovar(arg) for arg in args if arg))\n if self ==... | <|body_start_0|>
obj = super().__new__(cls, _str_)
obj.if_empty = if_empty
obj.separator = s
obj.quote_args = quote_args
return obj
<|end_body_0|>
<|body_start_1|>
tovar: Callable[[Any], Var] = _tovar
if self.quote_args:
tovar = lambda var: Var(repr(s... | ``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args passed to ``__call__``. If not `` or ``, all occurrences of `` or `` presen... | AtRule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtRule:
"""``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args passed to ``__call__``. If not `` or ``, ... | stack_v2_sparse_classes_36k_train_031543 | 44,402 | permissive | [
{
"docstring": "Create the ``AtRule`` and save parameters. Parameters ---------- _str_ : str The string of the current ``Var`` For the other parameters, see the class docstring (``if_empty`` and ``quote_args`` have the same name as the arguments to ``__new__`, but ``separator`` comes from the ``s`` argument. Re... | 2 | stack_v2_sparse_classes_30k_train_020308 | Implement the Python class `AtRule` described below.
Class description:
``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args pa... | Implement the Python class `AtRule` described below.
Class description:
``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args pa... | adeff652784f0d814835fd16a8cacab09f426922 | <|skeleton|>
class AtRule:
"""``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args passed to ``__call__``. If not `` or ``, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AtRule:
"""``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args passed to ``__call__``. If not `` or ``, all occurrenc... | the_stack_v2_python_sparse | src/mixt/contrib/css/vars.py | twidi/mixt | train | 37 |
6f6231354f84d3e7b2c91e9c4a8055c56ec2ea40 | [
"super(FocalLoss, self).__init__()\nself.size_average = size_average\nif isinstance(alpha, list):\n assert len(alpha) == num_classes\n self.alpha = torch.Tensor(alpha)\nelse:\n assert alpha < 1\n self.alpha = torch.zeros(num_classes)\n self.alpha[0] += alpha\n self.alpha[1:] += 1 - alpha\nself.gam... | <|body_start_0|>
super(FocalLoss, self).__init__()
self.size_average = size_average
if isinstance(alpha, list):
assert len(alpha) == num_classes
self.alpha = torch.Tensor(alpha)
else:
assert alpha < 1
self.alpha = torch.zeros(num_classes)
... | FocalLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FocalLoss:
def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本... | stack_v2_sparse_classes_36k_train_031544 | 6,576 | no_license | [
{
"docstring": "focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainnet中设置为2 :param num_classes: 类别数量 :param size_average: 损失计算方式,默认取均值",
"name": "__... | 2 | stack_v2_sparse_classes_30k_train_009113 | Implement the Python class `FocalLoss` described below.
Class description:
Implement the FocalLoss class.
Method signatures and docstrings:
- def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,... | Implement the Python class `FocalLoss` described below.
Class description:
Implement the FocalLoss class.
Method signatures and docstrings:
- def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,... | 4b138537ad35448f65f6695aee68c68ca60c4b7c | <|skeleton|>
class FocalLoss:
def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FocalLoss:
def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainne... | the_stack_v2_python_sparse | src/loss/focalloss.py | jimeffry/retinanet-pytorch | train | 1 | |
4106684f650b3c3ce5898640242e238f27937e56 | [
"if exog is None:\n exog = np.zeros_like(endog)\nsuper(_CensoredPoisson, self).__init__(endog, exog, **kwds)\nself.data.xnames = ['x1']",
"lambda_ = params[0]\nll_output = self._LL(self.endog, rate=lambda_)\nreturn -np.log(ll_output)",
"if start_params is None:\n lambda_start = self.endog[:, 0].mean()\n ... | <|body_start_0|>
if exog is None:
exog = np.zeros_like(endog)
super(_CensoredPoisson, self).__init__(endog, exog, **kwds)
self.data.xnames = ['x1']
<|end_body_0|>
<|body_start_1|>
lambda_ = params[0]
ll_output = self._LL(self.endog, rate=lambda_)
return -np.l... | Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent. | _CensoredPoisson | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CensoredPoisson:
"""Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent."""
def __init__(self, endog, exog=None, **kwds):
"""Initializes the model. Args: endog : array-like dependent variable. exog : array-like independent variables. **kwds: ot... | stack_v2_sparse_classes_36k_train_031545 | 25,038 | permissive | [
{
"docstring": "Initializes the model. Args: endog : array-like dependent variable. exog : array-like independent variables. **kwds: other kwds.",
"name": "__init__",
"signature": "def __init__(self, endog, exog=None, **kwds)"
},
{
"docstring": "Return the negative loglikelihood of endog given t... | 4 | stack_v2_sparse_classes_30k_train_017935 | Implement the Python class `_CensoredPoisson` described below.
Class description:
Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent.
Method signatures and docstrings:
- def __init__(self, endog, exog=None, **kwds): Initializes the model. Args: endog : array-like dependent vari... | Implement the Python class `_CensoredPoisson` described below.
Class description:
Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent.
Method signatures and docstrings:
- def __init__(self, endog, exog=None, **kwds): Initializes the model. Args: endog : array-like dependent vari... | 38eaf4514062892e0c3ce5d7cff4b4c1a7e49242 | <|skeleton|>
class _CensoredPoisson:
"""Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent."""
def __init__(self, endog, exog=None, **kwds):
"""Initializes the model. Args: endog : array-like dependent variable. exog : array-like independent variables. **kwds: ot... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _CensoredPoisson:
"""Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent."""
def __init__(self, endog, exog=None, **kwds):
"""Initializes the model. Args: endog : array-like dependent variable. exog : array-like independent variables. **kwds: other kwds."""
... | the_stack_v2_python_sparse | agents/allocation_agents.py | google/ml-fairness-gym | train | 310 |
caf84754334606aaa096d3bcd3b5c58778d89c77 | [
"graph = build_graph(nodes_attributes, [('placeholder_1', 'placeholder_1_data'), ('placeholder_1_data', 'slice'), ('slice', 'slice_data'), ('slice_data', 'output_op'), ('output_op', 'output_data'), ('output_data', 'op_output')], {'placeholder_1_data': {'shape': np.array([4, 5, 6])}, 'slice': {'start': np.array([1, ... | <|body_start_0|>
graph = build_graph(nodes_attributes, [('placeholder_1', 'placeholder_1_data'), ('placeholder_1_data', 'slice'), ('slice', 'slice_data'), ('slice_data', 'output_op'), ('output_op', 'output_data'), ('output_data', 'op_output')], {'placeholder_1_data': {'shape': np.array([4, 5, 6])}, 'slice': {'s... | ConvertSliceTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertSliceTests:
def test_1(self):
"""Testing case with non-constant path and multiple slicing dimensions :return:"""
<|body_0|>
def test_2(self):
"""Testing case with constant path and one slicing dimension"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_031546 | 6,296 | permissive | [
{
"docstring": "Testing case with non-constant path and multiple slicing dimensions :return:",
"name": "test_1",
"signature": "def test_1(self)"
},
{
"docstring": "Testing case with constant path and one slicing dimension",
"name": "test_2",
"signature": "def test_2(self)"
}
] | 2 | null | Implement the Python class `ConvertSliceTests` described below.
Class description:
Implement the ConvertSliceTests class.
Method signatures and docstrings:
- def test_1(self): Testing case with non-constant path and multiple slicing dimensions :return:
- def test_2(self): Testing case with constant path and one slici... | Implement the Python class `ConvertSliceTests` described below.
Class description:
Implement the ConvertSliceTests class.
Method signatures and docstrings:
- def test_1(self): Testing case with non-constant path and multiple slicing dimensions :return:
- def test_2(self): Testing case with constant path and one slici... | ed372319eca66a534e1dd6a521613b0caf187b26 | <|skeleton|>
class ConvertSliceTests:
def test_1(self):
"""Testing case with non-constant path and multiple slicing dimensions :return:"""
<|body_0|>
def test_2(self):
"""Testing case with constant path and one slicing dimension"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvertSliceTests:
def test_1(self):
"""Testing case with non-constant path and multiple slicing dimensions :return:"""
graph = build_graph(nodes_attributes, [('placeholder_1', 'placeholder_1_data'), ('placeholder_1_data', 'slice'), ('slice', 'slice_data'), ('slice_data', 'output_op'), ('outpu... | the_stack_v2_python_sparse | model-optimizer/extensions/middle/SliceConvert_test.py | ni/dldt | train | 1 | |
522930f6233f03311e8cfd44a9dfbf511b4ff3e7 | [
"if PiStreamingCamera.camera is None:\n PiStreamingCamera.camera = PiCamera(framerate=settings.FRAME_RATE, resolution=settings.CAMERA_RESOLUTION)\n sleep(2)\nif PiStreamingCamera.streamer is None:\n PiStreamingCamera.streamer = MeowlPiStreamer()\nPiStreamingCamera.camera.start_recording(PiStreamingCamera.s... | <|body_start_0|>
if PiStreamingCamera.camera is None:
PiStreamingCamera.camera = PiCamera(framerate=settings.FRAME_RATE, resolution=settings.CAMERA_RESOLUTION)
sleep(2)
if PiStreamingCamera.streamer is None:
PiStreamingCamera.streamer = MeowlPiStreamer()
PiStr... | A Raspberry Pi Camera class interface for streaming purposes | PiStreamingCamera | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PiStreamingCamera:
"""A Raspberry Pi Camera class interface for streaming purposes"""
def start(video_format='h264'):
"""Starts streaming from the camera on to the endpoint"""
<|body_0|>
def stop():
"""Stops streaming from the camera"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_031547 | 1,599 | no_license | [
{
"docstring": "Starts streaming from the camera on to the endpoint",
"name": "start",
"signature": "def start(video_format='h264')"
},
{
"docstring": "Stops streaming from the camera",
"name": "stop",
"signature": "def stop()"
}
] | 2 | stack_v2_sparse_classes_30k_train_008018 | Implement the Python class `PiStreamingCamera` described below.
Class description:
A Raspberry Pi Camera class interface for streaming purposes
Method signatures and docstrings:
- def start(video_format='h264'): Starts streaming from the camera on to the endpoint
- def stop(): Stops streaming from the camera | Implement the Python class `PiStreamingCamera` described below.
Class description:
A Raspberry Pi Camera class interface for streaming purposes
Method signatures and docstrings:
- def start(video_format='h264'): Starts streaming from the camera on to the endpoint
- def stop(): Stops streaming from the camera
<|skele... | 5201f67b3c3dd35283a649e7b47c26a68105f7ee | <|skeleton|>
class PiStreamingCamera:
"""A Raspberry Pi Camera class interface for streaming purposes"""
def start(video_format='h264'):
"""Starts streaming from the camera on to the endpoint"""
<|body_0|>
def stop():
"""Stops streaming from the camera"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PiStreamingCamera:
"""A Raspberry Pi Camera class interface for streaming purposes"""
def start(video_format='h264'):
"""Starts streaming from the camera on to the endpoint"""
if PiStreamingCamera.camera is None:
PiStreamingCamera.camera = PiCamera(framerate=settings.FRAME_RAT... | the_stack_v2_python_sparse | src/camera/pi/meowlpi/camera/camera.py | meowl-surveillance-system/meowl | train | 1 |
404141f8499f629060a22da177643388ec37459b | [
"super(CustomSchedule, self).__init__()\nself.d_model = tf.cast(d_model, tf.float32)\nself.warmup_steps = warmup_steps",
"arg1 = tf.math.rsqrt(step)\narg2 = step * self.warmup_steps ** (-1.5)\nreturn tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)"
] | <|body_start_0|>
super(CustomSchedule, self).__init__()
self.d_model = tf.cast(d_model, tf.float32)
self.warmup_steps = warmup_steps
<|end_body_0|>
<|body_start_1|>
arg1 = tf.math.rsqrt(step)
arg2 = step * self.warmup_steps ** (-1.5)
return tf.math.rsqrt(self.d_model) * ... | calculate learning rate for optimizers | CustomSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSchedule:
"""calculate learning rate for optimizers"""
def __init__(self, d_model, warmup_steps=4000):
"""constructor"""
<|body_0|>
def __call__(self, step):
"""initialize class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CustomS... | stack_v2_sparse_classes_36k_train_031548 | 3,770 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, d_model, warmup_steps=4000)"
},
{
"docstring": "initialize class",
"name": "__call__",
"signature": "def __call__(self, step)"
}
] | 2 | null | Implement the Python class `CustomSchedule` described below.
Class description:
calculate learning rate for optimizers
Method signatures and docstrings:
- def __init__(self, d_model, warmup_steps=4000): constructor
- def __call__(self, step): initialize class | Implement the Python class `CustomSchedule` described below.
Class description:
calculate learning rate for optimizers
Method signatures and docstrings:
- def __init__(self, d_model, warmup_steps=4000): constructor
- def __call__(self, step): initialize class
<|skeleton|>
class CustomSchedule:
"""calculate learn... | bda9efa60075afa834433ff1b5179db80f2487ae | <|skeleton|>
class CustomSchedule:
"""calculate learning rate for optimizers"""
def __init__(self, d_model, warmup_steps=4000):
"""constructor"""
<|body_0|>
def __call__(self, step):
"""initialize class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomSchedule:
"""calculate learning rate for optimizers"""
def __init__(self, d_model, warmup_steps=4000):
"""constructor"""
super(CustomSchedule, self).__init__()
self.d_model = tf.cast(d_model, tf.float32)
self.warmup_steps = warmup_steps
def __call__(self, step):... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-train.py | vandeldiegoc/holbertonschool-machine_learning | train | 0 |
f15a4a9a0b0b3c9dd5c781e1566b6b11145cca84 | [
"self.data.c[0]['a_c (Pa m6 mol-2)'][0] = ''\nself.data.c[0]['b_c (m3 mol-1)'][0] = ''\ns, p = pure.pure_sim(self.data)\nself.data.c[0]['a_c (Pa m6 mol-2)'] = [0.533365967206]\nself.data.c[0]['b_c (m3 mol-1)'] = [6.36225762119e-05]\nnumpy.testing.assert_allclose([self.p1_ans1, self.p1_ans2], [p['a_c'], p['b_c']], r... | <|body_start_0|>
self.data.c[0]['a_c (Pa m6 mol-2)'][0] = ''
self.data.c[0]['b_c (m3 mol-1)'][0] = ''
s, p = pure.pure_sim(self.data)
self.data.c[0]['a_c (Pa m6 mol-2)'] = [0.533365967206]
self.data.c[0]['b_c (m3 mol-1)'] = [6.36225762119e-05]
numpy.testing.assert_allclos... | Test known pure results. | TestPureFuncs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPureFuncs:
"""Test known pure results."""
def test_p1(self):
"""Critical parameters"""
<|body_0|>
def test_p2(self):
"""Soave model optimisation"""
<|body_1|>
def test_p3(self):
"""Adachi-Lu model optimisation"""
<|body_2|>
d... | stack_v2_sparse_classes_36k_train_031549 | 2,915 | no_license | [
{
"docstring": "Critical parameters",
"name": "test_p1",
"signature": "def test_p1(self)"
},
{
"docstring": "Soave model optimisation",
"name": "test_p2",
"signature": "def test_p2(self)"
},
{
"docstring": "Adachi-Lu model optimisation",
"name": "test_p3",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_train_019664 | Implement the Python class `TestPureFuncs` described below.
Class description:
Test known pure results.
Method signatures and docstrings:
- def test_p1(self): Critical parameters
- def test_p2(self): Soave model optimisation
- def test_p3(self): Adachi-Lu model optimisation
- def test_p4(self): Phase equilibrium at f... | Implement the Python class `TestPureFuncs` described below.
Class description:
Test known pure results.
Method signatures and docstrings:
- def test_p1(self): Critical parameters
- def test_p2(self): Soave model optimisation
- def test_p3(self): Adachi-Lu model optimisation
- def test_p4(self): Phase equilibrium at f... | 91ae76ae50cb46530545b69beaf0fbb4e20450fc | <|skeleton|>
class TestPureFuncs:
"""Test known pure results."""
def test_p1(self):
"""Critical parameters"""
<|body_0|>
def test_p2(self):
"""Soave model optimisation"""
<|body_1|>
def test_p3(self):
"""Adachi-Lu model optimisation"""
<|body_2|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPureFuncs:
"""Test known pure results."""
def test_p1(self):
"""Critical parameters"""
self.data.c[0]['a_c (Pa m6 mol-2)'][0] = ''
self.data.c[0]['b_c (m3 mol-1)'][0] = ''
s, p = pure.pure_sim(self.data)
self.data.c[0]['a_c (Pa m6 mol-2)'] = [0.533365967206]
... | the_stack_v2_python_sparse | pure_tests.py | Stefan-Endres/DWPM-Mixture-Model | train | 5 |
1fe9edaa3431996ba1ef82fa3d46520818bce48c | [
"self.rov = rov\nself.i2c = busio.I2C(board.SCL, board.SDA)\nself.ads13 = ADS.ADS1115(self.i2c)\nself.adc46 = ADS.ADS1115(self.i2c, address=73)\na1 = AnalogIn(self.ads13, ADS.P0)\na2 = AnalogIn(self.ads13, ADS.P1)\na3 = AnalogIn(self.ads13, ADS.P2)\na4 = AnalogIn(self.adc46, ADS.P0)\na5 = AnalogIn(self.adc46, ADS.P... | <|body_start_0|>
self.rov = rov
self.i2c = busio.I2C(board.SCL, board.SDA)
self.ads13 = ADS.ADS1115(self.i2c)
self.adc46 = ADS.ADS1115(self.i2c, address=73)
a1 = AnalogIn(self.ads13, ADS.P0)
a2 = AnalogIn(self.ads13, ADS.P1)
a3 = AnalogIn(self.ads13, ADS.P2)
... | Acp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Acp:
def __init__(self, rov: MainRov):
"""Класс описывающий взаимодействие и опрос датчиков тока"""
<|body_0|>
def mainAmperemeter(self):
"""Функция опроса датчиков тока"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rov = rov
self.i2c... | stack_v2_sparse_classes_36k_train_031550 | 23,756 | no_license | [
{
"docstring": "Класс описывающий взаимодействие и опрос датчиков тока",
"name": "__init__",
"signature": "def __init__(self, rov: MainRov)"
},
{
"docstring": "Функция опроса датчиков тока",
"name": "mainAmperemeter",
"signature": "def mainAmperemeter(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019700 | Implement the Python class `Acp` described below.
Class description:
Implement the Acp class.
Method signatures and docstrings:
- def __init__(self, rov: MainRov): Класс описывающий взаимодействие и опрос датчиков тока
- def mainAmperemeter(self): Функция опроса датчиков тока | Implement the Python class `Acp` described below.
Class description:
Implement the Acp class.
Method signatures and docstrings:
- def __init__(self, rov: MainRov): Класс описывающий взаимодействие и опрос датчиков тока
- def mainAmperemeter(self): Функция опроса датчиков тока
<|skeleton|>
class Acp:
def __init_... | 00ebd2dba3781da5d9e426a61136652708a74987 | <|skeleton|>
class Acp:
def __init__(self, rov: MainRov):
"""Класс описывающий взаимодействие и опрос датчиков тока"""
<|body_0|>
def mainAmperemeter(self):
"""Функция опроса датчиков тока"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Acp:
def __init__(self, rov: MainRov):
"""Класс описывающий взаимодействие и опрос датчиков тока"""
self.rov = rov
self.i2c = busio.I2C(board.SCL, board.SDA)
self.ads13 = ADS.ADS1115(self.i2c)
self.adc46 = ADS.ADS1115(self.i2c, address=73)
a1 = AnalogIn(self.ads... | the_stack_v2_python_sparse | Soft/Apparatus/client.py | Yarik9001/SoftProteus | train | 2 | |
fc099052310bca63f0cb51323d091e23546c163f | [
"ExecutionContext().transition(ExecutionContext.phases.VERIFICATION)\nlogstr = 'DirCopy: Checking source is readable + traversable, ' + '{0}'.format(self.dst)\nlogger.info('{0}: {1}'.format(self.file_context, logstr))\nif not filesys.access(self.src, access_codes.R_OK | access_codes.X_OK):\n return self.verifica... | <|body_start_0|>
ExecutionContext().transition(ExecutionContext.phases.VERIFICATION)
logstr = 'DirCopy: Checking source is readable + traversable, ' + '{0}'.format(self.dst)
logger.info('{0}: {1}'.format(self.file_context, logstr))
if not filesys.access(self.src, access_codes.R_OK | acce... | DirCopyAction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirCopyAction:
def verify_can_exec(self, filesys):
"""Check to ensure that execution can proceed without errors. Ensures that the the target directory is writable."""
<|body_0|>
def execute(self, filesys):
"""Copy a directory tree from one location to another."""
... | stack_v2_sparse_classes_36k_train_031551 | 2,041 | permissive | [
{
"docstring": "Check to ensure that execution can proceed without errors. Ensures that the the target directory is writable.",
"name": "verify_can_exec",
"signature": "def verify_can_exec(self, filesys)"
},
{
"docstring": "Copy a directory tree from one location to another.",
"name": "execu... | 2 | stack_v2_sparse_classes_30k_train_002601 | Implement the Python class `DirCopyAction` described below.
Class description:
Implement the DirCopyAction class.
Method signatures and docstrings:
- def verify_can_exec(self, filesys): Check to ensure that execution can proceed without errors. Ensures that the the target directory is writable.
- def execute(self, fi... | Implement the Python class `DirCopyAction` described below.
Class description:
Implement the DirCopyAction class.
Method signatures and docstrings:
- def verify_can_exec(self, filesys): Check to ensure that execution can proceed without errors. Ensures that the the target directory is writable.
- def execute(self, fi... | 5711b5c71e39b958bc8185c6b893358de7598ae2 | <|skeleton|>
class DirCopyAction:
def verify_can_exec(self, filesys):
"""Check to ensure that execution can proceed without errors. Ensures that the the target directory is writable."""
<|body_0|>
def execute(self, filesys):
"""Copy a directory tree from one location to another."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirCopyAction:
def verify_can_exec(self, filesys):
"""Check to ensure that execution can proceed without errors. Ensures that the the target directory is writable."""
ExecutionContext().transition(ExecutionContext.phases.VERIFICATION)
logstr = 'DirCopy: Checking source is readable + tr... | the_stack_v2_python_sparse | salve/action/copy/directory.py | sirosen/SALVE | train | 0 | |
0c5f6499b9171f82263002cff04a3929feac16ec | [
"super(SdrSnrScorer, self).__init__(conf, evalconf, dataconf, rec_dir, numbatches, task, scorer_name, checkpoint_file)\nnoise_names = conf['noise'].split(' ')\nnoise_dataconfs = []\nfor noise_name in noise_names:\n noise_dataconfs.append(dict(dataconf.items(noise_name)))\nself.noise_reader = data_reader.DataRead... | <|body_start_0|>
super(SdrSnrScorer, self).__init__(conf, evalconf, dataconf, rec_dir, numbatches, task, scorer_name, checkpoint_file)
noise_names = conf['noise'].split(' ')
noise_dataconfs = []
for noise_name in noise_names:
noise_dataconfs.append(dict(dataconf.items(noise_n... | the SDR scorer class. Uses the script from C. Raffel, B. McFee, E. J. Humphrey, J. Salamon, O. Nieto, D. Liang, and D. P. W. Ellis, 'mir_eval: A Transparent Implementation of Common MIR Metrics', Proceedings of the 15th International Conference on Music Information Retrieval, 2014 a scorer using SDR | SdrSnrScorer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SdrSnrScorer:
"""the SDR scorer class. Uses the script from C. Raffel, B. McFee, E. J. Humphrey, J. Salamon, O. Nieto, D. Liang, and D. P. W. Ellis, 'mir_eval: A Transparent Implementation of Common MIR Metrics', Proceedings of the 15th International Conference on Music Information Retrieval, 201... | stack_v2_sparse_classes_36k_train_031552 | 3,231 | permissive | [
{
"docstring": "Reconstructor constructor Args: conf: the scorer configuration as a dictionary evalconf: the evaluator configuration as a ConfigParser dataconf: the database configuration rec_dir: the directory where the reconstructions are numbatches: the number of batches to process",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_014479 | Implement the Python class `SdrSnrScorer` described below.
Class description:
the SDR scorer class. Uses the script from C. Raffel, B. McFee, E. J. Humphrey, J. Salamon, O. Nieto, D. Liang, and D. P. W. Ellis, 'mir_eval: A Transparent Implementation of Common MIR Metrics', Proceedings of the 15th International Confere... | Implement the Python class `SdrSnrScorer` described below.
Class description:
the SDR scorer class. Uses the script from C. Raffel, B. McFee, E. J. Humphrey, J. Salamon, O. Nieto, D. Liang, and D. P. W. Ellis, 'mir_eval: A Transparent Implementation of Common MIR Metrics', Proceedings of the 15th International Confere... | 5e862cbf846d45b8a317f87588533f3fde9f0726 | <|skeleton|>
class SdrSnrScorer:
"""the SDR scorer class. Uses the script from C. Raffel, B. McFee, E. J. Humphrey, J. Salamon, O. Nieto, D. Liang, and D. P. W. Ellis, 'mir_eval: A Transparent Implementation of Common MIR Metrics', Proceedings of the 15th International Conference on Music Information Retrieval, 201... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SdrSnrScorer:
"""the SDR scorer class. Uses the script from C. Raffel, B. McFee, E. J. Humphrey, J. Salamon, O. Nieto, D. Liang, and D. P. W. Ellis, 'mir_eval: A Transparent Implementation of Common MIR Metrics', Proceedings of the 15th International Conference on Music Information Retrieval, 2014 a scorer us... | the_stack_v2_python_sparse | nabu/postprocessing/scorers/sdr_snr_scorer.py | JeroenZegers/Nabu-MSSS | train | 19 |
675f1fd78983342da841d16e51b55d1771cd228a | [
"if journey is None:\n return self.filter(Q(journey__template__user=user) | Q(journey__passengers__user=user))\nif not journey.is_messenger_allowed(user):\n return self.none()\nreturn self.filter(journey=journey)",
"if not journey.is_messenger_allowed(user):\n raise UserNotAllowed()\nreturn self.create(u... | <|body_start_0|>
if journey is None:
return self.filter(Q(journey__template__user=user) | Q(journey__passengers__user=user))
if not journey.is_messenger_allowed(user):
return self.none()
return self.filter(journey=journey)
<|end_body_0|>
<|body_start_1|>
if not j... | Manager to handle messages. | MessageManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageManager:
"""Manager to handle messages."""
def list(self, user, journey=None):
"""Gets the list of all messages the given user could read. :param user: :param journey:"""
<|body_0|>
def send(self, user, message, journey):
"""User tries send 'message' to 'j... | stack_v2_sparse_classes_36k_train_031553 | 9,126 | no_license | [
{
"docstring": "Gets the list of all messages the given user could read. :param user: :param journey:",
"name": "list",
"signature": "def list(self, user, journey=None)"
},
{
"docstring": "User tries send 'message' to 'journey' group.",
"name": "send",
"signature": "def send(self, user, ... | 2 | stack_v2_sparse_classes_30k_train_013439 | Implement the Python class `MessageManager` described below.
Class description:
Manager to handle messages.
Method signatures and docstrings:
- def list(self, user, journey=None): Gets the list of all messages the given user could read. :param user: :param journey:
- def send(self, user, message, journey): User tries... | Implement the Python class `MessageManager` described below.
Class description:
Manager to handle messages.
Method signatures and docstrings:
- def list(self, user, journey=None): Gets the list of all messages the given user could read. :param user: :param journey:
- def send(self, user, message, journey): User tries... | 1713bb544bbddacda34b7d7dbd6e422872546776 | <|skeleton|>
class MessageManager:
"""Manager to handle messages."""
def list(self, user, journey=None):
"""Gets the list of all messages the given user could read. :param user: :param journey:"""
<|body_0|>
def send(self, user, message, journey):
"""User tries send 'message' to 'j... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageManager:
"""Manager to handle messages."""
def list(self, user, journey=None):
"""Gets the list of all messages the given user could read. :param user: :param journey:"""
if journey is None:
return self.filter(Q(journey__template__user=user) | Q(journey__passengers__use... | the_stack_v2_python_sparse | upvcarshare/journeys/managers.py | marcosgabarda/upvcarshare | train | 0 |
c5afd837def6a6ec93ab77a5746a49b3d3ffd86d | [
"self.name = name\nconv2d = functools.partial(LayerConv, stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope)\navg_pool = functools.partial(downscale, n=2)\nnc_in, nc_out = n\nwith tf.variable_scope(self.name):\n self.path1_blocks = []\n with tf.variable_scope('bb_path1'):\n layer... | <|body_start_0|>
self.name = name
conv2d = functools.partial(LayerConv, stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope)
avg_pool = functools.partial(downscale, n=2)
nc_in, nc_out = n
with tf.variable_scope(self.name):
self.path1_blocks = []
... | BasicBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock:
def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0):
"""Layer constructor. Args: TODO"""
<|body_0|>
def __call__(self, x_init):
"""Apply layer to tensor ... | stack_v2_sparse_classes_36k_train_031554 | 13,442 | permissive | [
{
"docstring": "Layer constructor. Args: TODO",
"name": "__init__",
"signature": "def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0)"
},
{
"docstring": "Apply layer to tensor x.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_014868 | Implement the Python class `BasicBlock` described below.
Class description:
Implement the BasicBlock class.
Method signatures and docstrings:
- def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0): Layer constructor. ... | Implement the Python class `BasicBlock` described below.
Class description:
Implement the BasicBlock class.
Method signatures and docstrings:
- def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0): Layer constructor. ... | 091d6ae9e087cf5a6e18b00bce7d8f7ede9d9d08 | <|skeleton|>
class BasicBlock:
def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0):
"""Layer constructor. Args: TODO"""
<|body_0|>
def __call__(self, x_init):
"""Apply layer to tensor ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicBlock:
def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0):
"""Layer constructor. Args: TODO"""
self.name = name
conv2d = functools.partial(LayerConv, stride=1, padding=padding, u... | the_stack_v2_python_sparse | layers.py | MoustafaMeshry/StEP | train | 6 | |
bb3bc6092c99d7e8b4ff9b0483b32e167e844b76 | [
"with patch.object(receive_async, 'delay') as mock_method:\n connections = self.lookup_connections(['1112223333'])\n msg = self.receive('test', connections[0], fields={'a': 'b'})\nmock_method.assert_called_once_with(msg.text, msg.connections[0].id, msg.id, msg.fields)",
"connection = self.lookup_connections... | <|body_start_0|>
with patch.object(receive_async, 'delay') as mock_method:
connections = self.lookup_connections(['1112223333'])
msg = self.receive('test', connections[0], fields={'a': 'b'})
mock_method.assert_called_once_with(msg.text, msg.connections[0].id, msg.id, msg.fields)
... | Tests for the CeleryRouter proxy class | CeleryRouterTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CeleryRouterTest:
"""Tests for the CeleryRouter proxy class"""
def test_incoming(self):
"""Make sure the proper fields are passed to receive_async."""
<|body_0|>
def test_outgoing(self):
"""send() should preserve all message context."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_031555 | 3,254 | permissive | [
{
"docstring": "Make sure the proper fields are passed to receive_async.",
"name": "test_incoming",
"signature": "def test_incoming(self)"
},
{
"docstring": "send() should preserve all message context.",
"name": "test_outgoing",
"signature": "def test_outgoing(self)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_015588 | Implement the Python class `CeleryRouterTest` described below.
Class description:
Tests for the CeleryRouter proxy class
Method signatures and docstrings:
- def test_incoming(self): Make sure the proper fields are passed to receive_async.
- def test_outgoing(self): send() should preserve all message context.
- def te... | Implement the Python class `CeleryRouterTest` described below.
Class description:
Tests for the CeleryRouter proxy class
Method signatures and docstrings:
- def test_incoming(self): Make sure the proper fields are passed to receive_async.
- def test_outgoing(self): send() should preserve all message context.
- def te... | aaa2ddab68e19d979525c3823c3ec0e646e92c83 | <|skeleton|>
class CeleryRouterTest:
"""Tests for the CeleryRouter proxy class"""
def test_incoming(self):
"""Make sure the proper fields are passed to receive_async."""
<|body_0|>
def test_outgoing(self):
"""send() should preserve all message context."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CeleryRouterTest:
"""Tests for the CeleryRouter proxy class"""
def test_incoming(self):
"""Make sure the proper fields are passed to receive_async."""
with patch.object(receive_async, 'delay') as mock_method:
connections = self.lookup_connections(['1112223333'])
ms... | the_stack_v2_python_sparse | rapidsms/router/celery/tests.py | rapidsms/rapidsms | train | 409 |
a8f3c7a256a5eb5b06b6988049109bae6d20b7bc | [
"self.case_input = case_input\nself.weights = weights\nself.biases = biases\nself.net0 = net0\nself.out0 = out0\nself.net1 = net1\nself.out1 = out1",
"print('Input array:')\nprint(self.case_input)\nprint('\\nWeights (first row corresponds to first output):')\nprint(self.weights)\nprint('\\nBiases:')\nprint(self.b... | <|body_start_0|>
self.case_input = case_input
self.weights = weights
self.biases = biases
self.net0 = net0
self.out0 = out0
self.net1 = net1
self.out1 = out1
<|end_body_0|>
<|body_start_1|>
print('Input array:')
print(self.case_input)
prin... | Describes a neural network of the type used in this example. | NeuralNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralNet:
"""Describes a neural network of the type used in this example."""
def __init__(self, case_input, weights, biases, net0, out0, net1, out1):
"""Create starting parts of the neural net."""
<|body_0|>
def describe(self):
"""Print information about the neu... | stack_v2_sparse_classes_36k_train_031556 | 11,919 | no_license | [
{
"docstring": "Create starting parts of the neural net.",
"name": "__init__",
"signature": "def __init__(self, case_input, weights, biases, net0, out0, net1, out1)"
},
{
"docstring": "Print information about the neural network.",
"name": "describe",
"signature": "def describe(self)"
}... | 2 | stack_v2_sparse_classes_30k_train_021609 | Implement the Python class `NeuralNet` described below.
Class description:
Describes a neural network of the type used in this example.
Method signatures and docstrings:
- def __init__(self, case_input, weights, biases, net0, out0, net1, out1): Create starting parts of the neural net.
- def describe(self): Print info... | Implement the Python class `NeuralNet` described below.
Class description:
Describes a neural network of the type used in this example.
Method signatures and docstrings:
- def __init__(self, case_input, weights, biases, net0, out0, net1, out1): Create starting parts of the neural net.
- def describe(self): Print info... | bdde45fc936783fd80589c53e23aa3aabd11cc88 | <|skeleton|>
class NeuralNet:
"""Describes a neural network of the type used in this example."""
def __init__(self, case_input, weights, biases, net0, out0, net1, out1):
"""Create starting parts of the neural net."""
<|body_0|>
def describe(self):
"""Print information about the neu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeuralNet:
"""Describes a neural network of the type used in this example."""
def __init__(self, case_input, weights, biases, net0, out0, net1, out1):
"""Create starting parts of the neural net."""
self.case_input = case_input
self.weights = weights
self.biases = biases
... | the_stack_v2_python_sparse | Artificial Intelligence and Deep Learning/Training X-OR with Backpropagation/Codes/results_xor.py | yfeng47/Data-Science-Portfolio | train | 1 |
2623fb0a574a519ca52d50df8f17aee09572fbac | [
"self._directive: dict[str, Any] = request[API_DIRECTIVE]\nself.namespace: str = self._directive[API_HEADER]['namespace']\nself.name: str = self._directive[API_HEADER]['name']\nself.payload: dict[str, Any] = self._directive[API_PAYLOAD]\nself.has_endpoint: bool = API_ENDPOINT in self._directive\nself.instance = Non... | <|body_start_0|>
self._directive: dict[str, Any] = request[API_DIRECTIVE]
self.namespace: str = self._directive[API_HEADER]['namespace']
self.name: str = self._directive[API_HEADER]['name']
self.payload: dict[str, Any] = self._directive[API_PAYLOAD]
self.has_endpoint: bool = API_... | An incoming Alexa directive. | AlexaDirective | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlexaDirective:
"""An incoming Alexa directive."""
def __init__(self, request: dict[str, Any]) -> None:
"""Initialize a directive."""
<|body_0|>
def load_entity(self, hass: HomeAssistant, config: AbstractConfig) -> None:
"""Set attributes related to the entity fo... | stack_v2_sparse_classes_36k_train_031557 | 17,851 | permissive | [
{
"docstring": "Initialize a directive.",
"name": "__init__",
"signature": "def __init__(self, request: dict[str, Any]) -> None"
},
{
"docstring": "Set attributes related to the entity for this request. Sets these attributes when self.has_endpoint is True: - entity - entity_id - endpoint - insta... | 4 | stack_v2_sparse_classes_30k_train_019295 | Implement the Python class `AlexaDirective` described below.
Class description:
An incoming Alexa directive.
Method signatures and docstrings:
- def __init__(self, request: dict[str, Any]) -> None: Initialize a directive.
- def load_entity(self, hass: HomeAssistant, config: AbstractConfig) -> None: Set attributes rel... | Implement the Python class `AlexaDirective` described below.
Class description:
An incoming Alexa directive.
Method signatures and docstrings:
- def __init__(self, request: dict[str, Any]) -> None: Initialize a directive.
- def load_entity(self, hass: HomeAssistant, config: AbstractConfig) -> None: Set attributes rel... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AlexaDirective:
"""An incoming Alexa directive."""
def __init__(self, request: dict[str, Any]) -> None:
"""Initialize a directive."""
<|body_0|>
def load_entity(self, hass: HomeAssistant, config: AbstractConfig) -> None:
"""Set attributes related to the entity fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlexaDirective:
"""An incoming Alexa directive."""
def __init__(self, request: dict[str, Any]) -> None:
"""Initialize a directive."""
self._directive: dict[str, Any] = request[API_DIRECTIVE]
self.namespace: str = self._directive[API_HEADER]['namespace']
self.name: str = se... | the_stack_v2_python_sparse | homeassistant/components/alexa/state_report.py | home-assistant/core | train | 35,501 |
2668a678747c3cca786a8d71f654860df92968b3 | [
"try:\n DeleteAnnotationLayerCommand(pk).run()\n return self.response(200, message='OK')\nexcept AnnotationLayerNotFoundError:\n return self.response_404()\nexcept AnnotationLayerDeleteIntegrityError as ex:\n return self.response_422(message=str(ex))\nexcept AnnotationLayerDeleteFailedError as ex:\n ... | <|body_start_0|>
try:
DeleteAnnotationLayerCommand(pk).run()
return self.response(200, message='OK')
except AnnotationLayerNotFoundError:
return self.response_404()
except AnnotationLayerDeleteIntegrityError as ex:
return self.response_422(message=... | AnnotationLayerRestApi | [
"Apache-2.0",
"OFL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnotationLayerRestApi:
def delete(self, pk: int) -> Response:
"""Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema: type: integer name: pk description: The annotation layer pk for this annotation responses: 200: description: ... | stack_v2_sparse_classes_36k_train_031558 | 12,412 | permissive | [
{
"docstring": "Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema: type: integer name: pk description: The annotation layer pk for this annotation responses: 200: description: Item deleted content: application/json: schema: type: object properties: m... | 4 | stack_v2_sparse_classes_30k_train_007106 | Implement the Python class `AnnotationLayerRestApi` described below.
Class description:
Implement the AnnotationLayerRestApi class.
Method signatures and docstrings:
- def delete(self, pk: int) -> Response: Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema... | Implement the Python class `AnnotationLayerRestApi` described below.
Class description:
Implement the AnnotationLayerRestApi class.
Method signatures and docstrings:
- def delete(self, pk: int) -> Response: Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema... | 0945d4a2f46667aebb9b93d0d7685215627ad237 | <|skeleton|>
class AnnotationLayerRestApi:
def delete(self, pk: int) -> Response:
"""Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema: type: integer name: pk description: The annotation layer pk for this annotation responses: 200: description: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnnotationLayerRestApi:
def delete(self, pk: int) -> Response:
"""Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema: type: integer name: pk description: The annotation layer pk for this annotation responses: 200: description: Item deleted c... | the_stack_v2_python_sparse | superset/annotation_layers/api.py | apache-superset/incubator-superset | train | 21 | |
73e48dbc0947267cbae8328175f6ef2bd7c269c4 | [
"if not root:\n return ''\ndqueue = collections.deque([root])\nrslt = []\nwhile dqueue:\n temp = dqueue.popleft()\n if temp:\n rslt.append(str(temp.val))\n dqueue.append(temp.left)\n dqueue.append(temp.right)\n else:\n rslt.append('')\nreturn ','.join(rslt)",
"dqueue = coll... | <|body_start_0|>
if not root:
return ''
dqueue = collections.deque([root])
rslt = []
while dqueue:
temp = dqueue.popleft()
if temp:
rslt.append(str(temp.val))
dqueue.append(temp.left)
dqueue.append(temp.r... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_031559 | 1,246 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_007794 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 498308e6a065af444a1d5570341231e4c51dfa3f | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
dqueue = collections.deque([root])
rslt = []
while dqueue:
temp = dqueue.popleft()
if temp:
... | the_stack_v2_python_sparse | lc297_tree.py | Mela2014/lc_punch | train | 0 | |
1eb0ef809ca18a38ab8bb30020a1142f5c4fc255 | [
"if type(self) is CommutativeRingElement:\n raise NotImplementedError('CommutativeRingElement is an abstract class.')\nRingElement.__init__(self)",
"try:\n self_ring = self.getRing()\n other_ring = getRing(other)\n if self_ring.hasaction(other_ring):\n return self_ring.getaction(other_ring)(oth... | <|body_start_0|>
if type(self) is CommutativeRingElement:
raise NotImplementedError('CommutativeRingElement is an abstract class.')
RingElement.__init__(self)
<|end_body_0|>
<|body_start_1|>
try:
self_ring = self.getRing()
other_ring = getRing(other)
... | CommutativeRingElement is an abstract class for elements of commutative rings. | CommutativeRingElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommutativeRingElement:
"""CommutativeRingElement is an abstract class for elements of commutative rings."""
def __init__(self):
"""This class is abstract and cannot be instantiated."""
<|body_0|>
def mul_module_action(self, other):
"""Return the result of a modu... | stack_v2_sparse_classes_36k_train_031560 | 26,077 | no_license | [
{
"docstring": "This class is abstract and cannot be instantiated.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return the result of a module action. other must be in one of the action rings of self's ring.",
"name": "mul_module_action",
"signature": "def mu... | 3 | stack_v2_sparse_classes_30k_train_016169 | Implement the Python class `CommutativeRingElement` described below.
Class description:
CommutativeRingElement is an abstract class for elements of commutative rings.
Method signatures and docstrings:
- def __init__(self): This class is abstract and cannot be instantiated.
- def mul_module_action(self, other): Return... | Implement the Python class `CommutativeRingElement` described below.
Class description:
CommutativeRingElement is an abstract class for elements of commutative rings.
Method signatures and docstrings:
- def __init__(self): This class is abstract and cannot be instantiated.
- def mul_module_action(self, other): Return... | a48ae9efcf0d9ad1485c2e9863c948a7f1b20311 | <|skeleton|>
class CommutativeRingElement:
"""CommutativeRingElement is an abstract class for elements of commutative rings."""
def __init__(self):
"""This class is abstract and cannot be instantiated."""
<|body_0|>
def mul_module_action(self, other):
"""Return the result of a modu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommutativeRingElement:
"""CommutativeRingElement is an abstract class for elements of commutative rings."""
def __init__(self):
"""This class is abstract and cannot be instantiated."""
if type(self) is CommutativeRingElement:
raise NotImplementedError('CommutativeRingElement ... | the_stack_v2_python_sparse | nzmath/ring.py | turkeydonkey/nzmath3 | train | 2 |
d17fcd4134c7de74cd02c960c7eeeb8fb32fdecf | [
"output = ''\nfor st in strs:\n output += str(len(st)) + '#' + st\nreturn output",
"output, i = ([], 0)\nwhile i < len(s):\n j = i\n while s[j] != '#':\n j += 1\n length = int(s[i:j])\n output.append(s[j + 1:j + 1 + length])\n i = j + 1 + length\nreturn output"
] | <|body_start_0|>
output = ''
for st in strs:
output += str(len(st)) + '#' + st
return output
<|end_body_0|>
<|body_start_1|>
output, i = ([], 0)
while i < len(s):
j = i
while s[j] != '#':
j += 1
length = int(s[i:j])... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
output = ... | stack_v2_sparse_classes_36k_train_031561 | 853 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | a9c83cf709c66100b6232e644c630520cd921131 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
output = ''
for st in strs:
output += str(len(st)) + '#' + st
return output
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strin... | the_stack_v2_python_sparse | Python/encode-and-decode-strings.py | utcsox/Leetcode-Solutions | train | 0 | |
f281cb604e8f1469829908b6c1b98451827da3a2 | [
"super().__init__()\nself.seed = torch.manual_seed(seed)\nself.layer1 = nn.Linear(state_size, layer1_units)\nself.layer2 = nn.Linear(layer1_units, layer2_units)\nself.layer3 = nn.Linear(layer2_units, layer3_units)\nself.layer4 = nn.Linear(layer3_units, action_size)",
"x = F.relu(self.layer1(x))\nx = F.relu(self.l... | <|body_start_0|>
super().__init__()
self.seed = torch.manual_seed(seed)
self.layer1 = nn.Linear(state_size, layer1_units)
self.layer2 = nn.Linear(layer1_units, layer2_units)
self.layer3 = nn.Linear(layer2_units, layer3_units)
self.layer4 = nn.Linear(layer3_units, action_s... | MLPNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLPNetwork:
def __init__(self, state_size, action_size, seed, layer1_units=100, layer2_units=100, layer3_units=100):
"""MLP model for agent :param state_size: :param action_size: :param seed: :param layer1_units: :param layer2_units: :param layer3_units:"""
<|body_0|>
def fo... | stack_v2_sparse_classes_36k_train_031562 | 975 | no_license | [
{
"docstring": "MLP model for agent :param state_size: :param action_size: :param seed: :param layer1_units: :param layer2_units: :param layer3_units:",
"name": "__init__",
"signature": "def __init__(self, state_size, action_size, seed, layer1_units=100, layer2_units=100, layer3_units=100)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_019922 | Implement the Python class `MLPNetwork` described below.
Class description:
Implement the MLPNetwork class.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed, layer1_units=100, layer2_units=100, layer3_units=100): MLP model for agent :param state_size: :param action_size: :param see... | Implement the Python class `MLPNetwork` described below.
Class description:
Implement the MLPNetwork class.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed, layer1_units=100, layer2_units=100, layer3_units=100): MLP model for agent :param state_size: :param action_size: :param see... | 21ceb0d5fe143848f0b58f8f92e455faf5013154 | <|skeleton|>
class MLPNetwork:
def __init__(self, state_size, action_size, seed, layer1_units=100, layer2_units=100, layer3_units=100):
"""MLP model for agent :param state_size: :param action_size: :param seed: :param layer1_units: :param layer2_units: :param layer3_units:"""
<|body_0|>
def fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLPNetwork:
def __init__(self, state_size, action_size, seed, layer1_units=100, layer2_units=100, layer3_units=100):
"""MLP model for agent :param state_size: :param action_size: :param seed: :param layer1_units: :param layer2_units: :param layer3_units:"""
super().__init__()
self.seed... | the_stack_v2_python_sparse | src/agents/models/nn_model.py | ylcoldplayer/bidding | train | 1 | |
b3b06e495044b2c5b5889a3f971cb715508a9e68 | [
"if not root:\n return ''\nqueue = deque()\nqueue.append(root)\nresult = []\nwhile queue:\n curr = queue.popleft()\n if curr != None:\n result.append(str(curr.val))\n result.append(',')\n queue.append(curr.left)\n queue.append(curr.right)\n else:\n result.append('null'... | <|body_start_0|>
if not root:
return ''
queue = deque()
queue.append(root)
result = []
while queue:
curr = queue.popleft()
if curr != None:
result.append(str(curr.val))
result.append(',')
queue.ap... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_031563 | 2,099 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_000188 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 52bf12095996a9137b1ea213ac43e1fe07806956 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
queue = deque()
queue.append(root)
result = []
while queue:
curr = queue.popleft()
if curr != N... | the_stack_v2_python_sparse | serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.py | siva4646/LeetCode_Python | train | 0 | |
4f87f20708a0c163cd828cc3d3b76290cc2dc825 | [
"this_positive_matrix_3d, this_negative_matrix_3d = human_vs_machine._reshape_human_maps(model_metadata_dict=MODEL_METADATA_DICT, positive_mask_matrix_4d=HUMAN_POSITIVE_MASK_MATRIX_4D, negative_mask_matrix_4d=HUMAN_NEGATIVE_MASK_MATRIX_4D)\nself.assertTrue(numpy.array_equal(this_positive_matrix_3d, HUMAN_POSITIVE_M... | <|body_start_0|>
this_positive_matrix_3d, this_negative_matrix_3d = human_vs_machine._reshape_human_maps(model_metadata_dict=MODEL_METADATA_DICT, positive_mask_matrix_4d=HUMAN_POSITIVE_MASK_MATRIX_4D, negative_mask_matrix_4d=HUMAN_NEGATIVE_MASK_MATRIX_4D)
self.assertTrue(numpy.array_equal(this_positive_... | Each method is a unit test for compare_human_vs_machine_interpretn.py. | HumanVsMachineTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HumanVsMachineTests:
"""Each method is a unit test for compare_human_vs_machine_interpretn.py."""
def test_reshape_human_maps(self):
"""Ensures correct output from _reshape_human_maps."""
<|body_0|>
def test_do_comparison_one_channel(self):
"""Ensures correct out... | stack_v2_sparse_classes_36k_train_031564 | 5,836 | permissive | [
{
"docstring": "Ensures correct output from _reshape_human_maps.",
"name": "test_reshape_human_maps",
"signature": "def test_reshape_human_maps(self)"
},
{
"docstring": "Ensures correct output from _do_comparison_one_channel.",
"name": "test_do_comparison_one_channel",
"signature": "def ... | 2 | null | Implement the Python class `HumanVsMachineTests` described below.
Class description:
Each method is a unit test for compare_human_vs_machine_interpretn.py.
Method signatures and docstrings:
- def test_reshape_human_maps(self): Ensures correct output from _reshape_human_maps.
- def test_do_comparison_one_channel(self)... | Implement the Python class `HumanVsMachineTests` described below.
Class description:
Each method is a unit test for compare_human_vs_machine_interpretn.py.
Method signatures and docstrings:
- def test_reshape_human_maps(self): Ensures correct output from _reshape_human_maps.
- def test_do_comparison_one_channel(self)... | 1835a71ababb7ad7e47bfa19e62948d466559d56 | <|skeleton|>
class HumanVsMachineTests:
"""Each method is a unit test for compare_human_vs_machine_interpretn.py."""
def test_reshape_human_maps(self):
"""Ensures correct output from _reshape_human_maps."""
<|body_0|>
def test_do_comparison_one_channel(self):
"""Ensures correct out... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HumanVsMachineTests:
"""Each method is a unit test for compare_human_vs_machine_interpretn.py."""
def test_reshape_human_maps(self):
"""Ensures correct output from _reshape_human_maps."""
this_positive_matrix_3d, this_negative_matrix_3d = human_vs_machine._reshape_human_maps(model_metadat... | the_stack_v2_python_sparse | gewittergefahr/scripts/compare_human_vs_machine_interpretn_test.py | thunderhoser/GewitterGefahr | train | 29 |
a2c1e4b1b7366c34d8b89f2e3b4dc7268c8ca066 | [
"self.Game = game\nself.dx = 1\nself.paddle = self.Game.canevas.create_rectangle(370, 500, 370 + 60, 500 + 8, fill='grey')\nself.Game.root.bind('<Motion>', self.motion)",
"if event.x - 30 <= 0:\n self.Game.canevas.coords(self.paddle, 0, 500, 60, 500 + 8)\n if self.Game.ball.static:\n self.Game.root.b... | <|body_start_0|>
self.Game = game
self.dx = 1
self.paddle = self.Game.canevas.create_rectangle(370, 500, 370 + 60, 500 + 8, fill='grey')
self.Game.root.bind('<Motion>', self.motion)
<|end_body_0|>
<|body_start_1|>
if event.x - 30 <= 0:
self.Game.canevas.coords(self.p... | Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left | Paddle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Paddle:
"""Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left"""
def __init__(self, game):
"""Creation of all the features of the paddle : width, height, movement speed Bin... | stack_v2_sparse_classes_36k_train_031565 | 2,368 | no_license | [
{
"docstring": "Creation of all the features of the paddle : width, height, movement speed Bind <motion> for the object paddle : it moves when the user moves the mouse PRE: Game class is running POST: - Creation of the paddle label which represents the paddle in the Graphic User Interface - Binding of the movem... | 2 | stack_v2_sparse_classes_30k_train_017809 | Implement the Python class `Paddle` described below.
Class description:
Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left
Method signatures and docstrings:
- def __init__(self, game): Creation of all the f... | Implement the Python class `Paddle` described below.
Class description:
Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left
Method signatures and docstrings:
- def __init__(self, game): Creation of all the f... | 663120fb4b69e9727b48d7f7bd96180e09be2c76 | <|skeleton|>
class Paddle:
"""Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left"""
def __init__(self, game):
"""Creation of all the features of the paddle : width, height, movement speed Bin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Paddle:
"""Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left"""
def __init__(self, game):
"""Creation of all the features of the paddle : width, height, movement speed Bind <motion> fo... | the_stack_v2_python_sparse | libs/paddle/classe.py | Mathis-Dory/Projet-Python-brick-breaker | train | 0 |
49a48b322fc3333b186cbb11016bf28a5ba220a7 | [
"self.queryFile = os.path.realpath(queryFile)\nif os.path.exists(self.queryFile) == False:\n raise Exception('ERROR: Could not locate the fasta file... \\n%s' % self.queryFile)\nif BLASTDB != None:\n os.environ['BLASTDB'] = BLASTDB",
"queryFileName = os.path.split(self.queryFile)[-1]\nnewQueryFile = os.path... | <|body_start_0|>
self.queryFile = os.path.realpath(queryFile)
if os.path.exists(self.queryFile) == False:
raise Exception('ERROR: Could not locate the fasta file... \n%s' % self.queryFile)
if BLASTDB != None:
os.environ['BLASTDB'] = BLASTDB
<|end_body_0|>
<|body_start_1|... | A generic class to run blast | Blast | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Blast:
"""A generic class to run blast"""
def __init__(self, queryFile, BLASTDB='/usr/local/share/htsint'):
"""Constructor queryFile - is a fasta file of sequences"""
<|body_0|>
def get_query_file(self, outDir, start, stop):
"""indexing start = 0 and stop = 2 wil... | stack_v2_sparse_classes_36k_train_031566 | 5,662 | permissive | [
{
"docstring": "Constructor queryFile - is a fasta file of sequences",
"name": "__init__",
"signature": "def __init__(self, queryFile, BLASTDB='/usr/local/share/htsint')"
},
{
"docstring": "indexing start = 0 and stop = 2 will return a file with the first and second sequences in it. This means t... | 3 | stack_v2_sparse_classes_30k_train_016339 | Implement the Python class `Blast` described below.
Class description:
A generic class to run blast
Method signatures and docstrings:
- def __init__(self, queryFile, BLASTDB='/usr/local/share/htsint'): Constructor queryFile - is a fasta file of sequences
- def get_query_file(self, outDir, start, stop): indexing start... | Implement the Python class `Blast` described below.
Class description:
A generic class to run blast
Method signatures and docstrings:
- def __init__(self, queryFile, BLASTDB='/usr/local/share/htsint'): Constructor queryFile - is a fasta file of sequences
- def get_query_file(self, outDir, start, stop): indexing start... | a343aff9b833979b4f5d4ba6d16fc2b65d8ccfc1 | <|skeleton|>
class Blast:
"""A generic class to run blast"""
def __init__(self, queryFile, BLASTDB='/usr/local/share/htsint'):
"""Constructor queryFile - is a fasta file of sequences"""
<|body_0|>
def get_query_file(self, outDir, start, stop):
"""indexing start = 0 and stop = 2 wil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Blast:
"""A generic class to run blast"""
def __init__(self, queryFile, BLASTDB='/usr/local/share/htsint'):
"""Constructor queryFile - is a fasta file of sequences"""
self.queryFile = os.path.realpath(queryFile)
if os.path.exists(self.queryFile) == False:
raise Excepti... | the_stack_v2_python_sparse | htsint/blast/Blast.py | changanla/htsint | train | 0 |
60a0b4cc3e67a2a50083e6d5b749a82c4f81d0ed | [
"A1 = set([(r, c) for r, row in enumerate(A) for c, val in enumerate(row) if val == 1])\nB1 = set([(r, c) for r, row in enumerate(B) for c, val in enumerate(row) if val == 1])\nans = 0\nseen = {}\nfor a in A1:\n for b in B1:\n delta = (a[0] - b[0], a[1] - b[1])\n if delta not in seen:\n ... | <|body_start_0|>
A1 = set([(r, c) for r, row in enumerate(A) for c, val in enumerate(row) if val == 1])
B1 = set([(r, c) for r, row in enumerate(B) for c, val in enumerate(row) if val == 1])
ans = 0
seen = {}
for a in A1:
for b in B1:
delta = (a[0] - b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int:
"""time: O(N^6) space: O(N^2)"""
<|body_0|>
def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int:
"""time: O(N^4) space: O(N^2)"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_031567 | 2,123 | no_license | [
{
"docstring": "time: O(N^6) space: O(N^2)",
"name": "largestOverlap1",
"signature": "def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int"
},
{
"docstring": "time: O(N^4) space: O(N^2)",
"name": "largestOverlap1",
"signature": "def largestOverlap1(self, A: List[List[... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int: time: O(N^6) space: O(N^2)
- def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int: t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int: time: O(N^6) space: O(N^2)
- def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int: t... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int:
"""time: O(N^6) space: O(N^2)"""
<|body_0|>
def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int:
"""time: O(N^4) space: O(N^2)"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestOverlap1(self, A: List[List[int]], B: List[List[int]]) -> int:
"""time: O(N^6) space: O(N^2)"""
A1 = set([(r, c) for r, row in enumerate(A) for c, val in enumerate(row) if val == 1])
B1 = set([(r, c) for r, row in enumerate(B) for c, val in enumerate(row) if val ==... | the_stack_v2_python_sparse | Leetcode 0835. Image Overlap.py | Chaoran-sjsu/leetcode | train | 0 | |
c1f33ae6c971a9db893222436b06e5a81aae0245 | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('id', required=True, type=str)\nself.reqparser.add_argument('description', required=False, default='', type=str)",
"if not get_jwt_claims()['admin']:\n abort(HTTPStatus.FORBIDDEN.value, error='administration privileges required')\nargs = s... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('id', required=True, type=str)
self.reqparser.add_argument('description', required=False, default='', type=str)
<|end_body_0|>
<|body_start_1|>
if not get_jwt_claims()['admin']:
abort(HTTP... | Update Tracker | UpdateTracker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateTracker:
"""Update Tracker"""
def __init__(self) -> None:
"""Set required arguments for POST request"""
<|body_0|>
def post(self) -> (str, HTTPStatus):
"""Update existing Tracker :param tracker_id: Tracker Id number :param description: Description of the tr... | stack_v2_sparse_classes_36k_train_031568 | 1,623 | permissive | [
{
"docstring": "Set required arguments for POST request",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Update existing Tracker :param tracker_id: Tracker Id number :param description: Description of the tracker :return: Tracker and an HTTPStatus code 200 (OK) ... | 2 | null | Implement the Python class `UpdateTracker` described below.
Class description:
Update Tracker
Method signatures and docstrings:
- def __init__(self) -> None: Set required arguments for POST request
- def post(self) -> (str, HTTPStatus): Update existing Tracker :param tracker_id: Tracker Id number :param description: ... | Implement the Python class `UpdateTracker` described below.
Class description:
Update Tracker
Method signatures and docstrings:
- def __init__(self) -> None: Set required arguments for POST request
- def post(self) -> (str, HTTPStatus): Update existing Tracker :param tracker_id: Tracker Id number :param description: ... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class UpdateTracker:
"""Update Tracker"""
def __init__(self) -> None:
"""Set required arguments for POST request"""
<|body_0|>
def post(self) -> (str, HTTPStatus):
"""Update existing Tracker :param tracker_id: Tracker Id number :param description: Description of the tr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateTracker:
"""Update Tracker"""
def __init__(self) -> None:
"""Set required arguments for POST request"""
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('id', required=True, type=str)
self.reqparser.add_argument('description', required=False, def... | the_stack_v2_python_sparse | Analytics/resources/moving_sensors/update_tracker.py | thanosbnt/SharingCitiesDashboard | train | 0 |
6ae64ffb0cfba531df4882699a56bf76549f2b87 | [
"self.name: str = id\nself.role: str = role if role and role in self.valid_roles else None\nself.val: str = val if val else None\nself.next: SymbolEntry = None",
"if self.role == 'const':\n role = 'Constant'\nelif self.role == 'var':\n role = 'Variable'\nelif self.role == 'type':\n role = 'Type'\nelif se... | <|body_start_0|>
self.name: str = id
self.role: str = role if role and role in self.valid_roles else None
self.val: str = val if val else None
self.next: SymbolEntry = None
<|end_body_0|>
<|body_start_1|>
if self.role == 'const':
role = 'Constant'
elif self.r... | Record information about identifier. Attributes: valid_roles: A set of strings containing valid roles. name: A string of name. role: A string of role. val: A string of value. next: A SymbolEntry instance appended. | SymbolEntry | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SymbolEntry:
"""Record information about identifier. Attributes: valid_roles: A set of strings containing valid roles. name: A string of name. role: A string of role. val: A string of value. next: A SymbolEntry instance appended."""
def __init__(self, id: str, role: str=None, val: str=None) ... | stack_v2_sparse_classes_36k_train_031569 | 2,482 | no_license | [
{
"docstring": "Init with identifier name, optional role, and optional value.",
"name": "__init__",
"signature": "def __init__(self, id: str, role: str=None, val: str=None) -> None"
},
{
"docstring": "Convert contents into string. Returns: A string representing self contents.",
"name": "__st... | 5 | stack_v2_sparse_classes_30k_train_015028 | Implement the Python class `SymbolEntry` described below.
Class description:
Record information about identifier. Attributes: valid_roles: A set of strings containing valid roles. name: A string of name. role: A string of role. val: A string of value. next: A SymbolEntry instance appended.
Method signatures and docst... | Implement the Python class `SymbolEntry` described below.
Class description:
Record information about identifier. Attributes: valid_roles: A set of strings containing valid roles. name: A string of name. role: A string of role. val: A string of value. next: A SymbolEntry instance appended.
Method signatures and docst... | 7016eaec5c520ae333855ce6727954b764f27145 | <|skeleton|>
class SymbolEntry:
"""Record information about identifier. Attributes: valid_roles: A set of strings containing valid roles. name: A string of name. role: A string of role. val: A string of value. next: A SymbolEntry instance appended."""
def __init__(self, id: str, role: str=None, val: str=None) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SymbolEntry:
"""Record information about identifier. Attributes: valid_roles: A set of strings containing valid roles. name: A string of name. role: A string of role. val: A string of value. next: A SymbolEntry instance appended."""
def __init__(self, id: str, role: str=None, val: str=None) -> None:
... | the_stack_v2_python_sparse | src/semantic_analyzer/symbol_entry.py | clearjade-kr/pl_project_copy | train | 0 |
8e581894042921bac01b3ca0de37f67d994e4a12 | [
"log.debug('Initiate SingleBiSBiS <Virtual View>')\nsuper(SingleBiSBiSVirtualizer, self).__init__(id=id, global_view=global_view, type=self.TYPE)\nself.sbb_id = sbb_id",
"dov = self.global_view.get_resource_info()\nif dov.is_empty():\n log.warning('Requested global resource view is empty! Return the default em... | <|body_start_0|>
log.debug('Initiate SingleBiSBiS <Virtual View>')
super(SingleBiSBiSVirtualizer, self).__init__(id=id, global_view=global_view, type=self.TYPE)
self.sbb_id = sbb_id
<|end_body_0|>
<|body_start_1|>
dov = self.global_view.get_resource_info()
if dov.is_empty():
... | Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view. | SingleBiSBiSVirtualizer | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleBiSBiSVirtualizer:
"""Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view."""
def __init__(self, global_view, id, sbb_id=None, **kwargs):
"""Init. :param global_view: virtualizer instance represents the global view :type glob... | stack_v2_sparse_classes_36k_train_031570 | 29,468 | permissive | [
{
"docstring": "Init. :param global_view: virtualizer instance represents the global view :type global_view: :any:`DomainVirtualizer` :param id: id of the assigned entity :type: id: str :param kwargs: optional parameters for Virtualizer :type kwargs: dict :return: None",
"name": "__init__",
"signature":... | 2 | null | Implement the Python class `SingleBiSBiSVirtualizer` described below.
Class description:
Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view.
Method signatures and docstrings:
- def __init__(self, global_view, id, sbb_id=None, **kwargs): Init. :param global_view: v... | Implement the Python class `SingleBiSBiSVirtualizer` described below.
Class description:
Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view.
Method signatures and docstrings:
- def __init__(self, global_view, id, sbb_id=None, **kwargs): Init. :param global_view: v... | 21b95843aa9308a5d3689bc2d30b2752b7121117 | <|skeleton|>
class SingleBiSBiSVirtualizer:
"""Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view."""
def __init__(self, global_view, id, sbb_id=None, **kwargs):
"""Init. :param global_view: virtualizer instance represents the global view :type glob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleBiSBiSVirtualizer:
"""Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view."""
def __init__(self, global_view, id, sbb_id=None, **kwargs):
"""Init. :param global_view: virtualizer instance represents the global view :type global_view: :any... | the_stack_v2_python_sparse | escape/escape/adapt/virtualization.py | JerryLX/escape | train | 0 |
7f79c63e2ace12c00bd64007466083135eb391c2 | [
"data = {'username': 'python31', 'password': 'lemonban'}\nexpected = {'code': 0, 'msg': '登录成功'}\nres = login_check(**data)\nself.assertEqual(expected, res)",
"data = {'username': 'python31', 'password': 'lemonban111'}\nexpected = {'code': 1, 'msg': '账号或密码不正确'}\nres = login_check(**data)\nself.assertEqual(expected... | <|body_start_0|>
data = {'username': 'python31', 'password': 'lemonban'}
expected = {'code': 0, 'msg': '登录成功'}
res = login_check(**data)
self.assertEqual(expected, res)
<|end_body_0|>
<|body_start_1|>
data = {'username': 'python31', 'password': 'lemonban111'}
expected = ... | 登录的测试用例类 | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
"""登录的测试用例类"""
def test_login_pass(self):
"""登录成功的用例"""
<|body_0|>
def test_login_pwd_error(self):
"""密码错误"""
<|body_1|>
def test_login_pwd_is_none(self):
"""密码为空"""
<|body_2|>
def test_login_user_is_none(self):
... | stack_v2_sparse_classes_36k_train_031571 | 3,469 | no_license | [
{
"docstring": "登录成功的用例",
"name": "test_login_pass",
"signature": "def test_login_pass(self)"
},
{
"docstring": "密码错误",
"name": "test_login_pwd_error",
"signature": "def test_login_pwd_error(self)"
},
{
"docstring": "密码为空",
"name": "test_login_pwd_is_none",
"signature": "... | 5 | stack_v2_sparse_classes_30k_train_008293 | Implement the Python class `TestLogin` described below.
Class description:
登录的测试用例类
Method signatures and docstrings:
- def test_login_pass(self): 登录成功的用例
- def test_login_pwd_error(self): 密码错误
- def test_login_pwd_is_none(self): 密码为空
- def test_login_user_is_none(self): 账号为空
- def test_login_user_error(self): 账号错误 | Implement the Python class `TestLogin` described below.
Class description:
登录的测试用例类
Method signatures and docstrings:
- def test_login_pass(self): 登录成功的用例
- def test_login_pwd_error(self): 密码错误
- def test_login_pwd_is_none(self): 密码为空
- def test_login_user_is_none(self): 账号为空
- def test_login_user_error(self): 账号错误
... | 734a049ecd84bfddc607ef852366eb5b7d16c6cb | <|skeleton|>
class TestLogin:
"""登录的测试用例类"""
def test_login_pass(self):
"""登录成功的用例"""
<|body_0|>
def test_login_pwd_error(self):
"""密码错误"""
<|body_1|>
def test_login_pwd_is_none(self):
"""密码为空"""
<|body_2|>
def test_login_user_is_none(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLogin:
"""登录的测试用例类"""
def test_login_pass(self):
"""登录成功的用例"""
data = {'username': 'python31', 'password': 'lemonban'}
expected = {'code': 0, 'msg': '登录成功'}
res = login_check(**data)
self.assertEqual(expected, res)
def test_login_pwd_error(self):
"... | the_stack_v2_python_sparse | day13unittest初识/day13_teacher/demo_02单元测试框架.py | guoyunfei0603/py31 | train | 0 |
4aede80ab43e7211107fe8c5d6b2a62abb897f5d | [
"m = 0\nfor i, n in enumerate(nums):\n if m == len(nums) - 1:\n return True\n if n == 0 and m <= i:\n return False\n m = max(m, i + n)\nreturn True",
"reachable = 0\ni = 0\nwhile i < len(nums):\n if i > reachable:\n break\n reachable = max(reachable, i + nums[i])\n if reacha... | <|body_start_0|>
m = 0
for i, n in enumerate(nums):
if m == len(nums) - 1:
return True
if n == 0 and m <= i:
return False
m = max(m, i + n)
return True
<|end_body_0|>
<|body_start_1|>
reachable = 0
i = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums):
"""12/30/2017 20:17"""
<|body_0|>
def canJump(self, nums: List[int]) -> bool:
"""Oct 13, 2021 11:16"""
<|body_1|>
def canJump(self, nums: List[int]) -> bool:
"""Feb 19, 2023 21:40"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k_train_031572 | 2,004 | no_license | [
{
"docstring": "12/30/2017 20:17",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": "Oct 13, 2021 11:16",
"name": "canJump",
"signature": "def canJump(self, nums: List[int]) -> bool"
},
{
"docstring": "Feb 19, 2023 21:40",
"name": "canJump",
"si... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): 12/30/2017 20:17
- def canJump(self, nums: List[int]) -> bool: Oct 13, 2021 11:16
- def canJump(self, nums: List[int]) -> bool: Feb 19, 2023 21:40 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): 12/30/2017 20:17
- def canJump(self, nums: List[int]) -> bool: Oct 13, 2021 11:16
- def canJump(self, nums: List[int]) -> bool: Feb 19, 2023 21:40
<|ske... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def canJump(self, nums):
"""12/30/2017 20:17"""
<|body_0|>
def canJump(self, nums: List[int]) -> bool:
"""Oct 13, 2021 11:16"""
<|body_1|>
def canJump(self, nums: List[int]) -> bool:
"""Feb 19, 2023 21:40"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums):
"""12/30/2017 20:17"""
m = 0
for i, n in enumerate(nums):
if m == len(nums) - 1:
return True
if n == 0 and m <= i:
return False
m = max(m, i + n)
return True
def canJump(... | the_stack_v2_python_sparse | leetcode/solved/55_Jump_Game/solution.py | sungminoh/algorithms | train | 0 | |
32f7c3700045023f2e50252a59b90f773f490e69 | [
"self.x = x\nself.y = y\nself.width = width\nself.length = length\nself.psi = psi\nself.skewness = skewness",
"skew23 = np.abs(self.skewness) ** (2 / 3)\ndelta = np.sign(self.skewness) * np.sqrt(np.pi / 2 * skew23 / (skew23 + (0.5 * (4 - np.pi)) ** (2 / 3)))\na = delta / np.sqrt(1 - delta ** 2)\nscale = self.leng... | <|body_start_0|>
self.x = x
self.y = y
self.width = width
self.length = length
self.psi = psi
self.skewness = skewness
<|end_body_0|>
<|body_start_1|>
skew23 = np.abs(self.skewness) ** (2 / 3)
delta = np.sign(self.skewness) * np.sqrt(np.pi / 2 * skew23 / ... | A shower image that has a skewness along the major axis. | SkewedGaussian | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkewedGaussian:
"""A shower image that has a skewness along the major axis."""
def __init__(self, x, y, length, width, psi, skewness):
"""Create 2D skewed Gaussian model for a shower image in a camera. Skewness is only applied along the main shower axis. See https://en.wikipedia.org/... | stack_v2_sparse_classes_36k_train_031573 | 12,327 | permissive | [
{
"docstring": "Create 2D skewed Gaussian model for a shower image in a camera. Skewness is only applied along the main shower axis. See https://en.wikipedia.org/wiki/Skew_normal_distribution and https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skewnorm.html for details. Parameters ---------- ce... | 3 | stack_v2_sparse_classes_30k_train_020400 | Implement the Python class `SkewedGaussian` described below.
Class description:
A shower image that has a skewness along the major axis.
Method signatures and docstrings:
- def __init__(self, x, y, length, width, psi, skewness): Create 2D skewed Gaussian model for a shower image in a camera. Skewness is only applied ... | Implement the Python class `SkewedGaussian` described below.
Class description:
A shower image that has a skewness along the major axis.
Method signatures and docstrings:
- def __init__(self, x, y, length, width, psi, skewness): Create 2D skewed Gaussian model for a shower image in a camera. Skewness is only applied ... | 10b058f8dcc166177d1eb5b2af638ca37722a021 | <|skeleton|>
class SkewedGaussian:
"""A shower image that has a skewness along the major axis."""
def __init__(self, x, y, length, width, psi, skewness):
"""Create 2D skewed Gaussian model for a shower image in a camera. Skewness is only applied along the main shower axis. See https://en.wikipedia.org/... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkewedGaussian:
"""A shower image that has a skewness along the major axis."""
def __init__(self, x, y, length, width, psi, skewness):
"""Create 2D skewed Gaussian model for a shower image in a camera. Skewness is only applied along the main shower axis. See https://en.wikipedia.org/wiki/Skew_nor... | the_stack_v2_python_sparse | ctapipe/image/toymodel.py | cta-sst-1m/ctapipe | train | 1 |
52a5aaa0a6ffd494b7a39a6aefeaeb74c278761c | [
"table_names = []\nfor esedb_table in database.tables:\n table_names.append(esedb_table.name)\nreturn table_names",
"format_specification = specification.FormatSpecification(cls.NAME)\nformat_specification.AddNewSignature(b'\\xef\\xcd\\xab\\x89', offset=4)\nreturn format_specification",
"esedb_file = pyesedb... | <|body_start_0|>
table_names = []
for esedb_table in database.tables:
table_names.append(esedb_table.name)
return table_names
<|end_body_0|>
<|body_start_1|>
format_specification = specification.FormatSpecification(cls.NAME)
format_specification.AddNewSignature(b'\xe... | Parses Extensible Storage Engine (ESE) database files (EDB). | ESEDBParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESEDBParser:
"""Parses Extensible Storage Engine (ESE) database files (EDB)."""
def _GetTableNames(self, database):
"""Retrieves the table names in a database. Args: database (pyesedb.file): ESE database. Returns: list[str]: table names."""
<|body_0|>
def GetFormatSpecif... | stack_v2_sparse_classes_36k_train_031574 | 2,968 | permissive | [
{
"docstring": "Retrieves the table names in a database. Args: database (pyesedb.file): ESE database. Returns: list[str]: table names.",
"name": "_GetTableNames",
"signature": "def _GetTableNames(self, database)"
},
{
"docstring": "Retrieves the format specification. Returns: FormatSpecification... | 3 | stack_v2_sparse_classes_30k_train_000115 | Implement the Python class `ESEDBParser` described below.
Class description:
Parses Extensible Storage Engine (ESE) database files (EDB).
Method signatures and docstrings:
- def _GetTableNames(self, database): Retrieves the table names in a database. Args: database (pyesedb.file): ESE database. Returns: list[str]: ta... | Implement the Python class `ESEDBParser` described below.
Class description:
Parses Extensible Storage Engine (ESE) database files (EDB).
Method signatures and docstrings:
- def _GetTableNames(self, database): Retrieves the table names in a database. Args: database (pyesedb.file): ESE database. Returns: list[str]: ta... | 9f8e05f21fa23793bfdade6af1d617e9dd092531 | <|skeleton|>
class ESEDBParser:
"""Parses Extensible Storage Engine (ESE) database files (EDB)."""
def _GetTableNames(self, database):
"""Retrieves the table names in a database. Args: database (pyesedb.file): ESE database. Returns: list[str]: table names."""
<|body_0|>
def GetFormatSpecif... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESEDBParser:
"""Parses Extensible Storage Engine (ESE) database files (EDB)."""
def _GetTableNames(self, database):
"""Retrieves the table names in a database. Args: database (pyesedb.file): ESE database. Returns: list[str]: table names."""
table_names = []
for esedb_table in data... | the_stack_v2_python_sparse | plaso/parsers/esedb.py | joshlemon/plaso | train | 1 |
d7f580022a72b4c2293c9e94cf046064a35ed999 | [
"self.window = window\nself.rho = rho\nself.k = k\nself.number_of_experts = self.window * self.rho\nsuper().__init__(number_of_experts=self.number_of_experts, weighted='top-k', k=self.k)",
"if not isinstance(self.window, int):\n raise ValueError('Window value must be an integer.')\nif not isinstance(self.rho, ... | <|body_start_0|>
self.window = window
self.rho = rho
self.k = k
self.number_of_experts = self.window * self.rho
super().__init__(number_of_experts=self.number_of_experts, weighted='top-k', k=self.k)
<|end_body_0|>
<|body_start_1|>
if not isinstance(self.window, int):
... | This class implements the Correlation Driven Nonparametric Learning - K strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for portfolio selection. ACM TIST, 2, 21:1-21:29. <https://dl.acm.org/do... | CORNK | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CORNK:
"""This class implements the Correlation Driven Nonparametric Learning - K strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for portfolio selection. ACM TIST, 2, 2... | stack_v2_sparse_classes_36k_train_031575 | 5,080 | permissive | [
{
"docstring": "Initializes Correlation Driven Nonparametric Learning - K with the given number of windows, rho values, and k experts. :param window: (int) Number of windows to look back for similarity sets. Generates experts with range of [1, 2, ..., w]. The window ranges typically work well with shorter terms... | 3 | null | Implement the Python class `CORNK` described below.
Class description:
This class implements the Correlation Driven Nonparametric Learning - K strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach ... | Implement the Python class `CORNK` described below.
Class description:
This class implements the Correlation Driven Nonparametric Learning - K strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach ... | 046c47d995da08b1003bba3f9c07d5bfb73d9c1f | <|skeleton|>
class CORNK:
"""This class implements the Correlation Driven Nonparametric Learning - K strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for portfolio selection. ACM TIST, 2, 2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CORNK:
"""This class implements the Correlation Driven Nonparametric Learning - K strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for portfolio selection. ACM TIST, 2, 21:1-21:29. <h... | the_stack_v2_python_sparse | src/collection/portfoliolab/online_portfolio_selection/cornk.py | Ta-nu-ki/dissertacao | train | 0 |
69464eb91ef9df18ed0e2a36b8731f501ae66f9b | [
"if self._original_res_logits is not None:\n x = self._original_res_logits\nelse:\n x = self.logits\nreturn x > self.mask_threshold",
"x = self.logits\nif isinstance(image_size_encoder, tuple):\n x = resize(x, size=image_size_encoder, interpolation='bilinear', align_corners=False, antialias=False)\nx = x... | <|body_start_0|>
if self._original_res_logits is not None:
x = self._original_res_logits
else:
x = self.logits
return x > self.mask_threshold
<|end_body_0|>
<|body_start_1|>
x = self.logits
if isinstance(image_size_encoder, tuple):
x = resize(... | Encapsulate the results obtained by a Segmentation model. Args: logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks scores: The scores from the logits. Shape :math:`(B,)` mask_threshold: The threshold value to generate the `binary_masks` from the `logits` | SegmentationResults | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentationResults:
"""Encapsulate the results obtained by a Segmentation model. Args: logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks scores: The scores from the logits. Shape :math:`(B,)` mask_threshold: The threshold value to gen... | stack_v2_sparse_classes_36k_train_031576 | 4,320 | permissive | [
{
"docstring": "Binary mask generated from logits considering the mask_threshold. Shape will be the same of logits :math:`(B, C, H, W)` where :math:`C` is the number masks predicted. .. note:: If you run `original_res_logits`, this will generate the masks based on the original resolution logits. Otherwise, this... | 3 | null | Implement the Python class `SegmentationResults` described below.
Class description:
Encapsulate the results obtained by a Segmentation model. Args: logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks scores: The scores from the logits. Shape :math:`(B,)` mas... | Implement the Python class `SegmentationResults` described below.
Class description:
Encapsulate the results obtained by a Segmentation model. Args: logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks scores: The scores from the logits. Shape :math:`(B,)` mas... | 1e0f8baa7318c05b17ea6dbb48605691bca8972f | <|skeleton|>
class SegmentationResults:
"""Encapsulate the results obtained by a Segmentation model. Args: logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks scores: The scores from the logits. Shape :math:`(B,)` mask_threshold: The threshold value to gen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegmentationResults:
"""Encapsulate the results obtained by a Segmentation model. Args: logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks scores: The scores from the logits. Shape :math:`(B,)` mask_threshold: The threshold value to generate the `bi... | the_stack_v2_python_sparse | kornia/contrib/models/structures.py | kornia/kornia | train | 7,351 |
c0d1df093f133e1bbddcdee6f5fd57057ba28aa4 | [
"super(SepConv, self).__init__()\nself.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels)\nself.pconv = nn.Conv2d(in_channels * filters, out_channels, kernel_size=1)\nself.padding = dilation[0] * (kernel_size[0] - 1)",
"x = F.pad(input, [0, 0, self.padding, 0... | <|body_start_0|>
super(SepConv, self).__init__()
self.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels)
self.pconv = nn.Conv2d(in_channels * filters, out_channels, kernel_size=1)
self.padding = dilation[0] * (kernel_size[0] - 1)
<|e... | SepConv | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SepConv:
def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)):
""":param kernel_size (time, frequency)"""
<|body_0|>
def forward(self, input):
"""input: [B, C, T, F]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031577 | 14,384 | permissive | [
{
"docstring": ":param kernel_size (time, frequency)",
"name": "__init__",
"signature": "def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1))"
},
{
"docstring": "input: [B, C, T, F]",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004311 | Implement the Python class `SepConv` described below.
Class description:
Implement the SepConv class.
Method signatures and docstrings:
- def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): :param kernel_size (time, frequency)
- def forward(self, input): input: [B, C, T, F] | Implement the Python class `SepConv` described below.
Class description:
Implement the SepConv class.
Method signatures and docstrings:
- def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): :param kernel_size (time, frequency)
- def forward(self, input): input: [B, C, T, F]
<... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class SepConv:
def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)):
""":param kernel_size (time, frequency)"""
<|body_0|>
def forward(self, input):
"""input: [B, C, T, F]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SepConv:
def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)):
""":param kernel_size (time, frequency)"""
super(SepConv, self).__init__()
self.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels... | the_stack_v2_python_sparse | ai/modelscope/modelscope/models/audio/aec/layers/uni_deep_fsmn.py | alldatacenter/alldata | train | 774 | |
e48aabcb406525c1eb16ea5dbf997cdb78db3b9c | [
"self.environment = environment\nself.error = error\nself.job_run_id = job_run_id\nself.message = message\nself.metadata_deleted = metadata_deleted\nself.quiesced = quiesced\nself.run_type = run_type\nself.sla_violated = sla_violated\nself.snapshots_deleted = snapshots_deleted\nself.snapshots_deleted_time_usecs = s... | <|body_start_0|>
self.environment = environment
self.error = error
self.job_run_id = job_run_id
self.message = message
self.metadata_deleted = metadata_deleted
self.quiesced = quiesced
self.run_type = run_type
self.sla_violated = sla_violated
self.... | Implementation of the 'BackupRun' model. Specifies details about the Backup task for a Job Run. A Backup task captures the original backup snapshots for each Protection Source in the Job. Attributes: environment (EnvironmentBackupRunEnum): Specifies the environment type that the task is protecting. Supported environmen... | BackupRun | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackupRun:
"""Implementation of the 'BackupRun' model. Specifies details about the Backup task for a Job Run. A Backup task captures the original backup snapshots for each Protection Source in the Job. Attributes: environment (EnvironmentBackupRunEnum): Specifies the environment type that the tas... | stack_v2_sparse_classes_36k_train_031578 | 12,619 | permissive | [
{
"docstring": "Constructor for the BackupRun class",
"name": "__init__",
"signature": "def __init__(self, environment=None, error=None, job_run_id=None, message=None, metadata_deleted=None, quiesced=None, run_type=None, sla_violated=None, snapshots_deleted=None, snapshots_deleted_time_usecs=None, sourc... | 2 | null | Implement the Python class `BackupRun` described below.
Class description:
Implementation of the 'BackupRun' model. Specifies details about the Backup task for a Job Run. A Backup task captures the original backup snapshots for each Protection Source in the Job. Attributes: environment (EnvironmentBackupRunEnum): Spec... | Implement the Python class `BackupRun` described below.
Class description:
Implementation of the 'BackupRun' model. Specifies details about the Backup task for a Job Run. A Backup task captures the original backup snapshots for each Protection Source in the Job. Attributes: environment (EnvironmentBackupRunEnum): Spec... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class BackupRun:
"""Implementation of the 'BackupRun' model. Specifies details about the Backup task for a Job Run. A Backup task captures the original backup snapshots for each Protection Source in the Job. Attributes: environment (EnvironmentBackupRunEnum): Specifies the environment type that the tas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackupRun:
"""Implementation of the 'BackupRun' model. Specifies details about the Backup task for a Job Run. A Backup task captures the original backup snapshots for each Protection Source in the Job. Attributes: environment (EnvironmentBackupRunEnum): Specifies the environment type that the task is protecti... | the_stack_v2_python_sparse | cohesity_management_sdk/models/backup_run.py | cohesity/management-sdk-python | train | 24 |
6d8eb49159978b4fec61bec4051b7d4e6ed7cb88 | [
"from collections import defaultdict\n\ndef f(path, res):\n word = ''\n i = 0\n while i < max_word and i < len(res):\n word += res[i]\n if word in wordDict:\n path.append(word)\n mem[''.join(path)].append(' '.join(path))\n f(path, res[i + 1:])\n pat... | <|body_start_0|>
from collections import defaultdict
def f(path, res):
word = ''
i = 0
while i < max_word and i < len(res):
word += res[i]
if word in wordDict:
path.append(word)
mem[''.join(path)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_031579 | 1,443 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: List[str]",
"name": "wordBreak1",
"signature": "def wordBreak1(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: List[str]",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDi... | 2 | stack_v2_sparse_classes_30k_train_003852 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[str]
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[str]
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: Lis... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
from collections import defaultdict
def f(path, res):
word = ''
i = 0
while i < max_word and i < len(res):
word += res[i]
... | the_stack_v2_python_sparse | word-break-ii/solution.py | uxlsl/leetcode_practice | train | 0 | |
ea7316cf19405bfa0d792eb8a884fde98ab8abd7 | [
"if not isinstance(secret_key, (str, bytes)):\n log.warning('Do not use request in PoorSession constructor, see new api and call load method manually.')\n if secret_key.secret_key is None:\n raise SessionError('poor_SecretKey is not set!')\n self.__secret_key = secret_key.secret_key\nelse:\n self... | <|body_start_0|>
if not isinstance(secret_key, (str, bytes)):
log.warning('Do not use request in PoorSession constructor, see new api and call load method manually.')
if secret_key.secret_key is None:
raise SessionError('poor_SecretKey is not set!')
self.__sec... | Self-contained cookie with session data. You cat store or read data from object via PoorSession.data variable which must be dictionary. Data is stored to cookie by pickle dump, and next hidden with app.secret_key. So it must be set on Application object or with poor_SecretKey environment variable. Be careful with store... | PoorSession | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoorSession:
"""Self-contained cookie with session data. You cat store or read data from object via PoorSession.data variable which must be dictionary. Data is stored to cookie by pickle dump, and next hidden with app.secret_key. So it must be set on Application object or with poor_SecretKey envi... | stack_v2_sparse_classes_36k_train_031580 | 10,843 | no_license | [
{
"docstring": "Constructor. Arguments: expires : int Cookie ``Expires`` time in seconds, if it 0, no expire is set max_age : int Cookie ``Max-Age`` attribute. If both expires and max-age are set, max_age has precedence. domain : str Cookie ``Host`` to which the cookie will be sent. path : str Cookie ``Path`` t... | 5 | stack_v2_sparse_classes_30k_train_005921 | Implement the Python class `PoorSession` described below.
Class description:
Self-contained cookie with session data. You cat store or read data from object via PoorSession.data variable which must be dictionary. Data is stored to cookie by pickle dump, and next hidden with app.secret_key. So it must be set on Applica... | Implement the Python class `PoorSession` described below.
Class description:
Self-contained cookie with session data. You cat store or read data from object via PoorSession.data variable which must be dictionary. Data is stored to cookie by pickle dump, and next hidden with app.secret_key. So it must be set on Applica... | dfa37218ddac9fb5abcc08d08f13d5c11cb906f9 | <|skeleton|>
class PoorSession:
"""Self-contained cookie with session data. You cat store or read data from object via PoorSession.data variable which must be dictionary. Data is stored to cookie by pickle dump, and next hidden with app.secret_key. So it must be set on Application object or with poor_SecretKey envi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PoorSession:
"""Self-contained cookie with session data. You cat store or read data from object via PoorSession.data variable which must be dictionary. Data is stored to cookie by pickle dump, and next hidden with app.secret_key. So it must be set on Application object or with poor_SecretKey environment varia... | the_stack_v2_python_sparse | poorwsgi/session.py | PoorHttp/PoorWSGI | train | 4 |
60a2f6fe75dfb6667769403e14c469232d8ac81f | [
"super(ConvQNetwork, self).__init__()\nself.action_size = action_size\nself.seed = torch.manual_seed(seed)\nself.conv1 = nn.Conv2d(1, 32, kernel_size=8, stride=4)\nself.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\nself.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\nself.fc1 = nn.Linear(7 * 7 * 64, 256)\... | <|body_start_0|>
super(ConvQNetwork, self).__init__()
self.action_size = action_size
self.seed = torch.manual_seed(seed)
self.conv1 = nn.Conv2d(1, 32, kernel_size=8, stride=4)
self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)
self.conv3 = nn.Conv2d(64, 64, kernel_si... | ConvQNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvQNetwork:
def __init__(self, state_size, action_size, seed):
"""Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (discrete or numpy) - shape of action applied to environment seed (int) - seed for random numbers"""
... | stack_v2_sparse_classes_36k_train_031581 | 2,797 | no_license | [
{
"docstring": "Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (discrete or numpy) - shape of action applied to environment seed (int) - seed for random numbers",
"name": "__init__",
"signature": "def __init__(self, state_size, action_s... | 2 | stack_v2_sparse_classes_30k_train_020527 | Implement the Python class `ConvQNetwork` described below.
Class description:
Implement the ConvQNetwork class.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed): Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (dis... | Implement the Python class `ConvQNetwork` described below.
Class description:
Implement the ConvQNetwork class.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed): Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (dis... | bcb0b7beb8a41a8cd008a3c790dd007356190abc | <|skeleton|>
class ConvQNetwork:
def __init__(self, state_size, action_size, seed):
"""Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (discrete or numpy) - shape of action applied to environment seed (int) - seed for random numbers"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvQNetwork:
def __init__(self, state_size, action_size, seed):
"""Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (discrete or numpy) - shape of action applied to environment seed (int) - seed for random numbers"""
super(Conv... | the_stack_v2_python_sparse | conv_model.py | jeffreyfeng99/reinforcement_learning | train | 0 | |
c398076fb6c577ddc08a313722d0633ee83493ee | [
"self.session = requests.Session()\nself.host = host\nself.port = port\nself.start_eid = netaddr.IPAddress(start_eid)\nself.mask = mask\nself.start_rloc = netaddr.IPAddress(start_rloc)\nself.nmappings = nmappings\nif v == 'Li' or v == 'li':\n print('Using the Lithium RPC URL')\n rpc_url = self.RPC_URL_LI\nels... | <|body_start_0|>
self.session = requests.Session()
self.host = host
self.port = port
self.start_eid = netaddr.IPAddress(start_eid)
self.mask = mask
self.start_rloc = netaddr.IPAddress(start_rloc)
self.nmappings = nmappings
if v == 'Li' or v == 'li':
... | MappingRPCBlaster | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MappingRPCBlaster:
def __init__(self, host, port, start_eid, mask, start_rloc, nmappings, v):
"""Args: :param host: The host running ODL where we want to send the RPCs :param port: The RESTCONF port on the ODL host :param start_eid: The starting EID for adding mappings as an IPv4 literal... | stack_v2_sparse_classes_36k_train_031582 | 8,000 | no_license | [
{
"docstring": "Args: :param host: The host running ODL where we want to send the RPCs :param port: The RESTCONF port on the ODL host :param start_eid: The starting EID for adding mappings as an IPv4 literal :param mask: The network mask for the EID prefixes to be added :param start_rloc: The starting RLOC for ... | 5 | stack_v2_sparse_classes_30k_train_009462 | Implement the Python class `MappingRPCBlaster` described below.
Class description:
Implement the MappingRPCBlaster class.
Method signatures and docstrings:
- def __init__(self, host, port, start_eid, mask, start_rloc, nmappings, v): Args: :param host: The host running ODL where we want to send the RPCs :param port: T... | Implement the Python class `MappingRPCBlaster` described below.
Class description:
Implement the MappingRPCBlaster class.
Method signatures and docstrings:
- def __init__(self, host, port, start_eid, mask, start_rloc, nmappings, v): Args: :param host: The host running ODL where we want to send the RPCs :param port: T... | ff1bb51a8a14f89ceefd91c6fc535a4bce78e0de | <|skeleton|>
class MappingRPCBlaster:
def __init__(self, host, port, start_eid, mask, start_rloc, nmappings, v):
"""Args: :param host: The host running ODL where we want to send the RPCs :param port: The RESTCONF port on the ODL host :param start_eid: The starting EID for adding mappings as an IPv4 literal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MappingRPCBlaster:
def __init__(self, host, port, start_eid, mask, start_rloc, nmappings, v):
"""Args: :param host: The host running ODL where we want to send the RPCs :param port: The RESTCONF port on the ODL host :param start_eid: The starting EID for adding mappings as an IPv4 literal :param mask: ... | the_stack_v2_python_sparse | tools/odl-lispflowmapping-performance-tests/mapping_blaster.py | opendaylight/integration-test | train | 29 | |
a8fc3851935f91fb22f8715d879ab3c3a0ea4b8d | [
"super(MeasureContact, self).__init__(y_variable, x_variable=x_variable, parent=parent)\nif name is None:\n self._name = 'contact_' + str(contact_id) + '_' + y_variable\nelse:\n self._name = name\nself.contact_id = contact_id\nself.y_variables = ['Fx', 'Fy', 'Fn_i', 'Ft_i', 'Fn_j', 'Ft_j', 'v_n', 'v_t', 'delt... | <|body_start_0|>
super(MeasureContact, self).__init__(y_variable, x_variable=x_variable, parent=parent)
if name is None:
self._name = 'contact_' + str(contact_id) + '_' + y_variable
else:
self._name = name
self.contact_id = contact_id
self.y_variables = ['... | classdocs | MeasureContact | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasureContact:
"""classdocs"""
def __init__(self, y_variable, contact_id, x_variable='time', name=None, parent=None):
"""Constructor"""
<|body_0|>
def _measure(self, step, h, t, q):
""":param t: :return q: vector of state of MBD system"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_031583 | 3,302 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, y_variable, contact_id, x_variable='time', name=None, parent=None)"
},
{
"docstring": ":param t: :return q: vector of state of MBD system",
"name": "_measure",
"signature": "def _measure(self, step, h, t, ... | 2 | stack_v2_sparse_classes_30k_train_014622 | Implement the Python class `MeasureContact` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, y_variable, contact_id, x_variable='time', name=None, parent=None): Constructor
- def _measure(self, step, h, t, q): :param t: :return q: vector of state of MBD system | Implement the Python class `MeasureContact` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, y_variable, contact_id, x_variable='time', name=None, parent=None): Constructor
- def _measure(self, step, h, t, q): :param t: :return q: vector of state of MBD system
<|sk... | 5e6a54dee662206664dde022ccca372f966b1789 | <|skeleton|>
class MeasureContact:
"""classdocs"""
def __init__(self, y_variable, contact_id, x_variable='time', name=None, parent=None):
"""Constructor"""
<|body_0|>
def _measure(self, step, h, t, q):
""":param t: :return q: vector of state of MBD system"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeasureContact:
"""classdocs"""
def __init__(self, y_variable, contact_id, x_variable='time', name=None, parent=None):
"""Constructor"""
super(MeasureContact, self).__init__(y_variable, x_variable=x_variable, parent=parent)
if name is None:
self._name = 'contact_' + st... | the_stack_v2_python_sparse | MBD_system/measure/measure_contact.py | xupeiwust/DyS | train | 0 |
a180acdfa6bff27a543a84082b0196036ce03947 | [
"p1, p2 = (headA, headB)\nwhile p1 != p2:\n p1 = p1.next if p1 else headB\n p2 = p2.next if p2 else headA\nreturn p1",
"p1, p2 = (headA, headB)\nc1, c2 = (0, 0)\nwhile p1:\n p1 = p1.next\n c1 += 1\nwhile p2:\n p2 = p2.next\n c2 += 1\nif c1 > c2:\n for _ in range(c1 - c2):\n headA = hea... | <|body_start_0|>
p1, p2 = (headA, headB)
while p1 != p2:
p1 = p1.next if p1 else headB
p2 = p2.next if p2 else headA
return p1
<|end_body_0|>
<|body_start_1|>
p1, p2 = (headA, headB)
c1, c2 = (0, 0)
while p1:
p1 = p1.next
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode2(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_031584 | 1,478 | no_license | [
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA, headB)"
},
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNode2",
"signature": "def getIntersectionNo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
- def getIntersectionNode2(self, headA, headB): :type head1, head1: ListNode :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
- def getIntersectionNode2(self, headA, headB): :type head1, head1: ListNode :rtype: Li... | d4215451f1cad3ab6dfb4b082f4fd694fe0d31b4 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode2(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
p1, p2 = (headA, headB)
while p1 != p2:
p1 = p1.next if p1 else headB
p2 = p2.next if p2 else headA
return p1
def getIntersectionNode2(self, h... | the_stack_v2_python_sparse | leetcode/分组刷题/3链表/160.相交链表.py | FishRedLeaf/my_code | train | 3 | |
521f9f51c98c7984edcf4a1eac589899b02eaea4 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | PSIServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PSIServiceServicer:
"""Missing associated documentation comment in .proto file."""
def getSalt(self, request, context):
"""Gives SHA256 Hash salt"""
<|body_0|>
def uploadSet(self, request, context):
"""Missing associated documentation comment in .proto file."""
... | stack_v2_sparse_classes_36k_train_031585 | 5,542 | permissive | [
{
"docstring": "Gives SHA256 Hash salt",
"name": "getSalt",
"signature": "def getSalt(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "uploadSet",
"signature": "def uploadSet(self, request, context)"
},
{
"docstring":... | 3 | null | Implement the Python class `PSIServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def getSalt(self, request, context): Gives SHA256 Hash salt
- def uploadSet(self, request, context): Missing associated documentation comment... | Implement the Python class `PSIServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def getSalt(self, request, context): Gives SHA256 Hash salt
- def uploadSet(self, request, context): Missing associated documentation comment... | 4ffa012a426e0d16ed13b707b03d8787ddca6aa4 | <|skeleton|>
class PSIServiceServicer:
"""Missing associated documentation comment in .proto file."""
def getSalt(self, request, context):
"""Gives SHA256 Hash salt"""
<|body_0|>
def uploadSet(self, request, context):
"""Missing associated documentation comment in .proto file."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PSIServiceServicer:
"""Missing associated documentation comment in .proto file."""
def getSalt(self, request, context):
"""Gives SHA256 Hash salt"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Me... | the_stack_v2_python_sparse | python/ppml/src/bigdl/ppml/fl/nn/generated/psi_service_pb2_grpc.py | intel-analytics/BigDL | train | 4,913 |
c4e05e92e78803735d70a85a07b0c0197cbce02b | [
"self.embeddings = embeddings\nself.action = action\nself.config = embeddings.config\nself.offset = self.config.get('offset', 0) if action == Action.UPSERT else 0\nautoid = self.config.get('autoid', self.offset)\nautoid = 0 if isinstance(autoid, int) and action != Action.UPSERT else autoid\nself.autoid = AutoId(aut... | <|body_start_0|>
self.embeddings = embeddings
self.action = action
self.config = embeddings.config
self.offset = self.config.get('offset', 0) if action == Action.UPSERT else 0
autoid = self.config.get('autoid', self.offset)
autoid = 0 if isinstance(autoid, int) and action... | Yields input document as standard (id, data, tags) tuples. | Stream | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stream:
"""Yields input document as standard (id, data, tags) tuples."""
def __init__(self, embeddings, action=None):
"""Create a new stream. Args: embeddings: embeddings instance action: optional index action"""
<|body_0|>
def __call__(self, documents):
"""Yield... | stack_v2_sparse_classes_36k_train_031586 | 2,109 | permissive | [
{
"docstring": "Create a new stream. Args: embeddings: embeddings instance action: optional index action",
"name": "__init__",
"signature": "def __init__(self, embeddings, action=None)"
},
{
"docstring": "Yield (id, data, tags) tuples from a stream of documents. Args: documents: input documents"... | 2 | null | Implement the Python class `Stream` described below.
Class description:
Yields input document as standard (id, data, tags) tuples.
Method signatures and docstrings:
- def __init__(self, embeddings, action=None): Create a new stream. Args: embeddings: embeddings instance action: optional index action
- def __call__(se... | Implement the Python class `Stream` described below.
Class description:
Yields input document as standard (id, data, tags) tuples.
Method signatures and docstrings:
- def __init__(self, embeddings, action=None): Create a new stream. Args: embeddings: embeddings instance action: optional index action
- def __call__(se... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class Stream:
"""Yields input document as standard (id, data, tags) tuples."""
def __init__(self, embeddings, action=None):
"""Create a new stream. Args: embeddings: embeddings instance action: optional index action"""
<|body_0|>
def __call__(self, documents):
"""Yield... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stream:
"""Yields input document as standard (id, data, tags) tuples."""
def __init__(self, embeddings, action=None):
"""Create a new stream. Args: embeddings: embeddings instance action: optional index action"""
self.embeddings = embeddings
self.action = action
self.confi... | the_stack_v2_python_sparse | src/python/txtai/embeddings/index/stream.py | neuml/txtai | train | 4,804 |
1e1ecc7307237f59e8080c2ad7fcf5a0f0fd0bae | [
"self.validate_options()\nstatsd_port = self.options['statsd_port']\nout = self.conf % statsd_port\nif system.write_file(self.conf_path, out):\n message.print_success(f'Wrote StatsD service plugin configuration to {self.conf_path}')\nelse:\n message.print_warn(f'Failed writing StatsD config file to {self.conf... | <|body_start_0|>
self.validate_options()
statsd_port = self.options['statsd_port']
out = self.conf % statsd_port
if system.write_file(self.conf_path, out):
message.print_success(f'Wrote StatsD service plugin configuration to {self.conf_path}')
else:
messag... | Manage StatsD input plugin. | StatsD | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsD:
"""Manage StatsD input plugin."""
def install(self):
"""Install StatsD input plugin."""
<|body_0|>
def validate_options(self):
"""Validate required parameter for StatsD input plugin."""
<|body_1|>
def remove(self):
"""Remove StatsD in... | stack_v2_sparse_classes_36k_train_031587 | 3,074 | permissive | [
{
"docstring": "Install StatsD input plugin.",
"name": "install",
"signature": "def install(self)"
},
{
"docstring": "Validate required parameter for StatsD input plugin.",
"name": "validate_options",
"signature": "def validate_options(self)"
},
{
"docstring": "Remove StatsD inpu... | 3 | stack_v2_sparse_classes_30k_train_010142 | Implement the Python class `StatsD` described below.
Class description:
Manage StatsD input plugin.
Method signatures and docstrings:
- def install(self): Install StatsD input plugin.
- def validate_options(self): Validate required parameter for StatsD input plugin.
- def remove(self): Remove StatsD input plugin. NB:... | Implement the Python class `StatsD` described below.
Class description:
Manage StatsD input plugin.
Method signatures and docstrings:
- def install(self): Install StatsD input plugin.
- def validate_options(self): Validate required parameter for StatsD input plugin.
- def remove(self): Remove StatsD input plugin. NB:... | dded18f12abb65ce5b1c5114a53e36bf8cb20187 | <|skeleton|>
class StatsD:
"""Manage StatsD input plugin."""
def install(self):
"""Install StatsD input plugin."""
<|body_0|>
def validate_options(self):
"""Validate required parameter for StatsD input plugin."""
<|body_1|>
def remove(self):
"""Remove StatsD in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatsD:
"""Manage StatsD input plugin."""
def install(self):
"""Install StatsD input plugin."""
self.validate_options()
statsd_port = self.options['statsd_port']
out = self.conf % statsd_port
if system.write_file(self.conf_path, out):
message.print_succ... | the_stack_v2_python_sparse | wavefront_cli/integrations/statsd.py | wavefrontHQ/wavefront-cli | train | 6 |
da77f116a79c8cd863999e52b989d3e0892c8543 | [
"self._map = {}\nself._cdllist = CDLList()\nself._cap = capacity",
"node = self._map.get(key, None)\nif node:\n self._cdllist.set_head(node)\n return node.val\nreturn -1",
"if self._cap < 1:\n return\nflag = False\nnode = self._map.get(key, None)\nif node:\n flag = True\n node.val = value\nelse:\... | <|body_start_0|>
self._map = {}
self._cdllist = CDLList()
self._cap = capacity
<|end_body_0|>
<|body_start_1|>
node = self._map.get(key, None)
if node:
self._cdllist.set_head(node)
return node.val
return -1
<|end_body_1|>
<|body_start_2|>
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
"""_map: :types capacity: int"""
<|body_0|>
def get(self, key):
""":types key: int :rtypes: int"""
<|body_1|>
def put(self, key, value):
""":types key: int :types value: int :rtypes: void"""
<|body_... | stack_v2_sparse_classes_36k_train_031588 | 4,351 | no_license | [
{
"docstring": "_map: :types capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":types key: int :rtypes: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":types key: int :types value: int :rtypes: void",
... | 3 | stack_v2_sparse_classes_30k_train_010094 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): _map: :types capacity: int
- def get(self, key): :types key: int :rtypes: int
- def put(self, key, value): :types key: int :types value: int :rtypes... | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): _map: :types capacity: int
- def get(self, key): :types key: int :rtypes: int
- def put(self, key, value): :types key: int :types value: int :rtypes... | 8c0c2a8bcd51825e6902e4d03dabbaf6f303ba83 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
"""_map: :types capacity: int"""
<|body_0|>
def get(self, key):
""":types key: int :rtypes: int"""
<|body_1|>
def put(self, key, value):
""":types key: int :types value: int :rtypes: void"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
"""_map: :types capacity: int"""
self._map = {}
self._cdllist = CDLList()
self._cap = capacity
def get(self, key):
""":types key: int :rtypes: int"""
node = self._map.get(key, None)
if node:
self._... | the_stack_v2_python_sparse | python_fundemental/104_Lru_cache.py | Deanwinger/python_project | train | 0 | |
0f1cfd488184dd04d0106156c487fc44df5925ef | [
"n = len(words[0])\n\ndef iter_prefix(prefix):\n l = len(prefix)\n for word in words:\n if word[:l] == prefix:\n yield word\n\ndef backtrack(path, sqr):\n if len(path) == n:\n sqr.append(path[:])\n return\n i = len(path)\n prefix = ''.join([w[i] for w in path])\n fo... | <|body_start_0|>
n = len(words[0])
def iter_prefix(prefix):
l = len(prefix)
for word in words:
if word[:l] == prefix:
yield word
def backtrack(path, sqr):
if len(path) == n:
sqr.append(path[:])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*L^(N*L)) space O(L)"""
<|body_0|>
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*26^L) space O(N*L)"""
<|body_1|>
def wordSquares(self, words: List... | stack_v2_sparse_classes_36k_train_031589 | 4,307 | no_license | [
{
"docstring": "time O(N*L^(N*L)) space O(L)",
"name": "wordSquares",
"signature": "def wordSquares(self, words: List[str]) -> List[List[str]]"
},
{
"docstring": "time O(N*26^L) space O(N*L)",
"name": "wordSquares",
"signature": "def wordSquares(self, words: List[str]) -> List[List[str]]... | 3 | stack_v2_sparse_classes_30k_train_013748 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSquares(self, words: List[str]) -> List[List[str]]: time O(N*L^(N*L)) space O(L)
- def wordSquares(self, words: List[str]) -> List[List[str]]: time O(N*26^L) space O(N*L)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSquares(self, words: List[str]) -> List[List[str]]: time O(N*L^(N*L)) space O(L)
- def wordSquares(self, words: List[str]) -> List[List[str]]: time O(N*26^L) space O(N*L)... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*L^(N*L)) space O(L)"""
<|body_0|>
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*26^L) space O(N*L)"""
<|body_1|>
def wordSquares(self, words: List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*L^(N*L)) space O(L)"""
n = len(words[0])
def iter_prefix(prefix):
l = len(prefix)
for word in words:
if word[:l] == prefix:
yield word
... | the_stack_v2_python_sparse | Leetcode 0425. Word Squares.py | Chaoran-sjsu/leetcode | train | 0 | |
3a5b7fc58833d193313ba8fa356d15ca151b2315 | [
"res = 0\nself.lambtha = float(lambtha)\nif data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n... | <|body_start_0|>
res = 0
self.lambtha = float(lambtha)
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
else:
if type(data) is not list:
raise TypeError('data must be a list')
if len... | Represents a poisson distribution | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""Represents a poisson distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Calculates the lambtha of data"""
<|body_0|>
def factorial(self, val):
"""Calculates factorial of a number"""
<|body_1|>
def pmf(self, k):
"""Calc... | stack_v2_sparse_classes_36k_train_031590 | 1,576 | no_license | [
{
"docstring": "Calculates the lambtha of data",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Calculates factorial of a number",
"name": "factorial",
"signature": "def factorial(self, val)"
},
{
"docstring": "Calculates the valu... | 4 | stack_v2_sparse_classes_30k_train_001681 | Implement the Python class `Poisson` described below.
Class description:
Represents a poisson distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Calculates the lambtha of data
- def factorial(self, val): Calculates factorial of a number
- def pmf(self, k): Calculates the valu... | Implement the Python class `Poisson` described below.
Class description:
Represents a poisson distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Calculates the lambtha of data
- def factorial(self, val): Calculates factorial of a number
- def pmf(self, k): Calculates the valu... | d9b5fa4d60cd896c42242d9e72c348bd33046fba | <|skeleton|>
class Poisson:
"""Represents a poisson distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Calculates the lambtha of data"""
<|body_0|>
def factorial(self, val):
"""Calculates factorial of a number"""
<|body_1|>
def pmf(self, k):
"""Calc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poisson:
"""Represents a poisson distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Calculates the lambtha of data"""
res = 0
self.lambtha = float(lambtha)
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positiv... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | BrianFs04/holbertonschool-machine_learning | train | 0 |
631c8197b1ca065769ce9c3377778715f269d513 | [
"self.name: str = yaml['name']\nself.defaults: Optional[Defaults] = Defaults(yaml['defaults']) if 'defaults' in yaml else None\nself.sources: Optional[List[Source]] = None\nif 'sources' in yaml:\n self.sources: Optional[List[Source]] = [Source(SourceName(name), source) for name, source in yaml['sources'].items()... | <|body_start_0|>
self.name: str = yaml['name']
self.defaults: Optional[Defaults] = Defaults(yaml['defaults']) if 'defaults' in yaml else None
self.sources: Optional[List[Source]] = None
if 'sources' in yaml:
self.sources: Optional[List[Source]] = [Source(SourceName(name), sou... | clowder yaml base class :ivar str name: Name of clowder :ivar Optional[Defaults] defaults: Name of clowder :ivar Optional[List[Source]] sources: Sources :ivar Clowder clowder: Clowder model :ivar Optional[Protocol] protocol: Git protocol | ClowderBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClowderBase:
"""clowder yaml base class :ivar str name: Name of clowder :ivar Optional[Defaults] defaults: Name of clowder :ivar Optional[List[Source]] sources: Sources :ivar Clowder clowder: Clowder model :ivar Optional[Protocol] protocol: Git protocol"""
def __init__(self, yaml: dict):
... | stack_v2_sparse_classes_36k_train_031591 | 1,963 | permissive | [
{
"docstring": "Upstream __init__ :param dict yaml: Parsed yaml dict",
"name": "__init__",
"signature": "def __init__(self, yaml: dict)"
},
{
"docstring": "Return python object representation for saving yaml :param bool resolved: Whether to get resolved commit hashes :return: YAML python object"... | 2 | null | Implement the Python class `ClowderBase` described below.
Class description:
clowder yaml base class :ivar str name: Name of clowder :ivar Optional[Defaults] defaults: Name of clowder :ivar Optional[List[Source]] sources: Sources :ivar Clowder clowder: Clowder model :ivar Optional[Protocol] protocol: Git protocol
Met... | Implement the Python class `ClowderBase` described below.
Class description:
clowder yaml base class :ivar str name: Name of clowder :ivar Optional[Defaults] defaults: Name of clowder :ivar Optional[List[Source]] sources: Sources :ivar Clowder clowder: Clowder model :ivar Optional[Protocol] protocol: Git protocol
Met... | 1438fc8b1bb7379de66142ffcb0e20b459b59159 | <|skeleton|>
class ClowderBase:
"""clowder yaml base class :ivar str name: Name of clowder :ivar Optional[Defaults] defaults: Name of clowder :ivar Optional[List[Source]] sources: Sources :ivar Clowder clowder: Clowder model :ivar Optional[Protocol] protocol: Git protocol"""
def __init__(self, yaml: dict):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClowderBase:
"""clowder yaml base class :ivar str name: Name of clowder :ivar Optional[Defaults] defaults: Name of clowder :ivar Optional[List[Source]] sources: Sources :ivar Clowder clowder: Clowder model :ivar Optional[Protocol] protocol: Git protocol"""
def __init__(self, yaml: dict):
"""Upstr... | the_stack_v2_python_sparse | clowder/model/clowder_base.py | JrGoodle/clowder | train | 17 |
7d040af16ce6617886ee53ed0a37b7a4d06baf9f | [
"super(RelPositionalEncoding, self).__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))",
"self.max_len = x.size(1)\nself.pe = torch.zeros(self.max_len, self.d_model)\nposit... | <|body_start_0|>
super(RelPositionalEncoding, self).__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
<|end_body_0|>
<|body_start_1|>... | Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. | RelPositionalEncoding | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_36k_train_031592 | 5,260 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
"docstring": "... | 3 | null | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | e2f834dd60e7939672c1795b4ac62e89ad0bca49 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum inpu... | the_stack_v2_python_sparse | speech/conformer/pytorch/src/layers/embedding.py | graphcore/examples | train | 311 |
545d415e1b8f5e589c37ac8886e98bf32c36bf1c | [
"if '词汇选择(复习)' not in game_type[-2]:\n print('====== 🌟🌟 词汇选择 - 根据单词选解释模式(复习)🌟🌟 =====\\n')\nself.next_btn_operate('false', self.fab_next_btn)\nword = self.question_content()\nprint('题目:', word.text)\nexplain_id = word.get_attribute('contentDescription')\nright_explain = self.data.get_explain_by_id(explain_id)... | <|body_start_0|>
if '词汇选择(复习)' not in game_type[-2]:
print('====== 🌟🌟 词汇选择 - 根据单词选解释模式(复习)🌟🌟 =====\n')
self.next_btn_operate('false', self.fab_next_btn)
word = self.question_content()
print('题目:', word.text)
explain_id = word.get_attribute('contentDescription')
... | VocabGamePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VocabGamePage:
def select_explain_by_word(self, index, wrong_again_words, game_type):
"""根据解释选单词"""
<|body_0|>
def select_word_by_explain(self, stu_id, index, wrong_again_words, game_type):
"""根据解释选单词"""
<|body_1|>
def vocab_apply_game_operate(self, stu_... | stack_v2_sparse_classes_36k_train_031593 | 4,694 | no_license | [
{
"docstring": "根据解释选单词",
"name": "select_explain_by_word",
"signature": "def select_explain_by_word(self, index, wrong_again_words, game_type)"
},
{
"docstring": "根据解释选单词",
"name": "select_word_by_explain",
"signature": "def select_word_by_explain(self, stu_id, index, wrong_again_words,... | 3 | null | Implement the Python class `VocabGamePage` described below.
Class description:
Implement the VocabGamePage class.
Method signatures and docstrings:
- def select_explain_by_word(self, index, wrong_again_words, game_type): 根据解释选单词
- def select_word_by_explain(self, stu_id, index, wrong_again_words, game_type): 根据解释选单词
... | Implement the Python class `VocabGamePage` described below.
Class description:
Implement the VocabGamePage class.
Method signatures and docstrings:
- def select_explain_by_word(self, index, wrong_again_words, game_type): 根据解释选单词
- def select_word_by_explain(self, stu_id, index, wrong_again_words, game_type): 根据解释选单词
... | f70ab6b1bc2f69d40299760f91870b61e012992e | <|skeleton|>
class VocabGamePage:
def select_explain_by_word(self, index, wrong_again_words, game_type):
"""根据解释选单词"""
<|body_0|>
def select_word_by_explain(self, stu_id, index, wrong_again_words, game_type):
"""根据解释选单词"""
<|body_1|>
def vocab_apply_game_operate(self, stu_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VocabGamePage:
def select_explain_by_word(self, index, wrong_again_words, game_type):
"""根据解释选单词"""
if '词汇选择(复习)' not in game_type[-2]:
print('====== 🌟🌟 词汇选择 - 根据单词选解释模式(复习)🌟🌟 =====\n')
self.next_btn_operate('false', self.fab_next_btn)
word = self.question_conte... | the_stack_v2_python_sparse | app/honor/student/word_book/object_page/vocab_game.py | vectorhuztt/test_android_copy | train | 1 | |
4814742139003f0bdc3ecb2c7be564754abf6ffe | [
"self._type = type\nself._project = project\nself._location = location\nself._creds, _ = google.auth.default()\nself._gcp_resources = gcp_resources\nself._session = self._get_session()",
"retry = Retry(total=_CONNECTION_ERROR_RETRY_LIMIT, status_forcelist=[429, 503], backoff_factor=_CONNECTION_RETRY_BACKOFF_FACTO... | <|body_start_0|>
self._type = type
self._project = project
self._location = location
self._creds, _ = google.auth.default()
self._gcp_resources = gcp_resources
self._session = self._get_session()
<|end_body_0|>
<|body_start_1|>
retry = Retry(total=_CONNECTION_ERR... | Common module for creating Dataproc Flex Template jobs. | DataflowFlexTemplateRemoteRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataflowFlexTemplateRemoteRunner:
"""Common module for creating Dataproc Flex Template jobs."""
def __init__(self, type: str, project: str, location: str, gcp_resources: str):
"""Initializes a DataflowFlexTemplateRemoteRunner object."""
<|body_0|>
def _get_session(self) ... | stack_v2_sparse_classes_36k_train_031594 | 9,632 | permissive | [
{
"docstring": "Initializes a DataflowFlexTemplateRemoteRunner object.",
"name": "__init__",
"signature": "def __init__(self, type: str, project: str, location: str, gcp_resources: str)"
},
{
"docstring": "Gets a http session.",
"name": "_get_session",
"signature": "def _get_session(self... | 5 | stack_v2_sparse_classes_30k_train_004738 | Implement the Python class `DataflowFlexTemplateRemoteRunner` described below.
Class description:
Common module for creating Dataproc Flex Template jobs.
Method signatures and docstrings:
- def __init__(self, type: str, project: str, location: str, gcp_resources: str): Initializes a DataflowFlexTemplateRemoteRunner o... | Implement the Python class `DataflowFlexTemplateRemoteRunner` described below.
Class description:
Common module for creating Dataproc Flex Template jobs.
Method signatures and docstrings:
- def __init__(self, type: str, project: str, location: str, gcp_resources: str): Initializes a DataflowFlexTemplateRemoteRunner o... | 3fb199658f68e7debf4906d9ce32a9a307e39243 | <|skeleton|>
class DataflowFlexTemplateRemoteRunner:
"""Common module for creating Dataproc Flex Template jobs."""
def __init__(self, type: str, project: str, location: str, gcp_resources: str):
"""Initializes a DataflowFlexTemplateRemoteRunner object."""
<|body_0|>
def _get_session(self) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataflowFlexTemplateRemoteRunner:
"""Common module for creating Dataproc Flex Template jobs."""
def __init__(self, type: str, project: str, location: str, gcp_resources: str):
"""Initializes a DataflowFlexTemplateRemoteRunner object."""
self._type = type
self._project = project
... | the_stack_v2_python_sparse | components/google-cloud/google_cloud_pipeline_components/container/preview/dataflow/flex_template/remote_runner.py | kubeflow/pipelines | train | 3,434 |
9e1ec45bc2e3e3ce6c82c214ab95947df12b356b | [
"super().__init__(screen_width, screen_height, State.TWO_PLAYER_MENU, screen, 0, 0, debug)\nfirst_pixel = self.screen_height // 2\nself.write(self.title_font, WHITE, '2 player modes', self.screen_width // 2, self.screen_height // 5)\nself.local_vs = self.write(self.end_font, WHITE, 'Player VS Player', self.screen_w... | <|body_start_0|>
super().__init__(screen_width, screen_height, State.TWO_PLAYER_MENU, screen, 0, 0, debug)
first_pixel = self.screen_height // 2
self.write(self.title_font, WHITE, '2 player modes', self.screen_width // 2, self.screen_height // 5)
self.local_vs = self.write(self.end_font,... | TwoPlayerScreen | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoPlayerScreen:
def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False):
"""Constructor for the main class for the 2 player screen"""
<|body_0|>
def check_mouse_press(self) -> State:
"""Check the mouse press of the user"""
<|body... | stack_v2_sparse_classes_36k_train_031595 | 2,211 | permissive | [
{
"docstring": "Constructor for the main class for the 2 player screen",
"name": "__init__",
"signature": "def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False)"
},
{
"docstring": "Check the mouse press of the user",
"name": "check_mouse_press",
"signature"... | 3 | null | Implement the Python class `TwoPlayerScreen` described below.
Class description:
Implement the TwoPlayerScreen class.
Method signatures and docstrings:
- def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False): Constructor for the main class for the 2 player screen
- def check_mouse_press... | Implement the Python class `TwoPlayerScreen` described below.
Class description:
Implement the TwoPlayerScreen class.
Method signatures and docstrings:
- def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False): Constructor for the main class for the 2 player screen
- def check_mouse_press... | 6f8f2da4fd26ef1d77c0c6183230c3a5e6bf0bb9 | <|skeleton|>
class TwoPlayerScreen:
def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False):
"""Constructor for the main class for the 2 player screen"""
<|body_0|>
def check_mouse_press(self) -> State:
"""Check the mouse press of the user"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoPlayerScreen:
def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False):
"""Constructor for the main class for the 2 player screen"""
super().__init__(screen_width, screen_height, State.TWO_PLAYER_MENU, screen, 0, 0, debug)
first_pixel = self.screen_height... | the_stack_v2_python_sparse | gym_invaders/gym_game/envs/classes/Game/Screens/TwoPlayerScreen.py | Jh123x/Orbital | train | 4 | |
06e6146673b2f1d27f75534b98237268c395bedd | [
"if not matrix or not matrix[0]:\n return []\nrow = len(matrix)\ncol = len(matrix[0])\ndigits = [[] for _ in range(row + col - 1)]\nfor i in range(row):\n for j in range(col):\n digits[i + j].append(matrix[i][j])\nret = []\nfor k in range(row + col - 1):\n if k % 2 == 0:\n ret.extend(digits[k... | <|body_start_0|>
if not matrix or not matrix[0]:
return []
row = len(matrix)
col = len(matrix[0])
digits = [[] for _ in range(row + col - 1)]
for i in range(row):
for j in range(col):
digits[i + j].append(matrix[i][j])
ret = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findDiagonalOrder2(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031596 | 1,552 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "findDiagonalOrder",
"signature": "def findDiagonalOrder(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "findDiagonalOrder2",
"signature": "def findDiagonalOrder2(self, ... | 2 | stack_v2_sparse_classes_30k_train_005312 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def findDiagonalOrder2(self, matrix): :type matrix: List[List[int]] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def findDiagonalOrder2(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
<|sk... | 7841cf88fa7c78376a6a162c0077b05c51c1491b | <|skeleton|>
class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findDiagonalOrder2(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
if not matrix or not matrix[0]:
return []
row = len(matrix)
col = len(matrix[0])
digits = [[] for _ in range(row + col - 1)]
for i in range(row):
... | the_stack_v2_python_sparse | python/498/Diagonal_Traverse.py | Leetcode-tc/Leetcode | train | 2 | |
91b383d4c3aa383f7e82fe7bb9fe689cd2efa435 | [
"super(Get_direction_to_point, self).__init__(outcomes=['done', 'fail'], input_keys=['targetPoint'], output_keys=['yaw', 'pitch'])\nself.service = get_directionRequest()\nself.service.reference = frame_reference\nself.service.origine = frame_origin\nLogger.loginfo('waiting for service /get_direction')\nrospy.wait_f... | <|body_start_0|>
super(Get_direction_to_point, self).__init__(outcomes=['done', 'fail'], input_keys=['targetPoint'], output_keys=['yaw', 'pitch'])
self.service = get_directionRequest()
self.service.reference = frame_reference
self.service.origine = frame_origin
Logger.loginfo('wa... | Gets the direction to a given point. Receives an input_key: point and has 2 parameters : frame_reference and frame_origin. Returns 2 angles within userdata. -- frame_reference string Name for the frame the targetPoint is compared to -- frame_origin string Name for the frame, who will return an angle ># targetPoint poin... | Get_direction_to_point | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Get_direction_to_point:
"""Gets the direction to a given point. Receives an input_key: point and has 2 parameters : frame_reference and frame_origin. Returns 2 angles within userdata. -- frame_reference string Name for the frame the targetPoint is compared to -- frame_origin string Name for the f... | stack_v2_sparse_classes_36k_train_031597 | 1,870 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, frame_origin, frame_reference)"
},
{
"docstring": "Wait for action result and return outcome accordingly",
"name": "execute",
"signature": "def execute(self, userdata)"
}
] | 2 | null | Implement the Python class `Get_direction_to_point` described below.
Class description:
Gets the direction to a given point. Receives an input_key: point and has 2 parameters : frame_reference and frame_origin. Returns 2 angles within userdata. -- frame_reference string Name for the frame the targetPoint is compared t... | Implement the Python class `Get_direction_to_point` described below.
Class description:
Gets the direction to a given point. Receives an input_key: point and has 2 parameters : frame_reference and frame_origin. Returns 2 angles within userdata. -- frame_reference string Name for the frame the targetPoint is compared t... | fcb55d274331915cd39d7d444546f17a39f85a44 | <|skeleton|>
class Get_direction_to_point:
"""Gets the direction to a given point. Receives an input_key: point and has 2 parameters : frame_reference and frame_origin. Returns 2 angles within userdata. -- frame_reference string Name for the frame the targetPoint is compared to -- frame_origin string Name for the f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Get_direction_to_point:
"""Gets the direction to a given point. Receives an input_key: point and has 2 parameters : frame_reference and frame_origin. Returns 2 angles within userdata. -- frame_reference string Name for the frame the targetPoint is compared to -- frame_origin string Name for the frame, who wil... | the_stack_v2_python_sparse | sara_flexbe_states/src/sara_flexbe_states/Get_direction_to_point.py | WalkingMachine/sara_behaviors | train | 5 |
805aa8692198787f918b28aa48ad964fb0fafb7e | [
"l = 0\nr = len(List) - 1\nif l > r:\n return None\nif l == r:\n return TreeNode(List[l])\nif (l + r) % 2 == 0:\n mid = int((l + r) / 2)\nelse:\n mid = int((l + r) / 2) + 1\nroot = TreeNode(List[mid])\nroot.left = self.build_tree(List[:mid])\nroot.right = self.build_tree(List[mid + 1:])\nreturn root",
... | <|body_start_0|>
l = 0
r = len(List) - 1
if l > r:
return None
if l == r:
return TreeNode(List[l])
if (l + r) % 2 == 0:
mid = int((l + r) / 2)
else:
mid = int((l + r) / 2) + 1
root = TreeNode(List[mid])
root.... | 二叉树结构类 | BinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
"""二叉树结构类"""
def build_tree(self, List):
"""构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树"""
<|body_0|>
def PrintFromTopToBottom(self, root):
"""从上往下打印二叉树——层序遍历"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = 0
r = len(List) - 1
... | stack_v2_sparse_classes_36k_train_031598 | 2,320 | no_license | [
{
"docstring": "构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树",
"name": "build_tree",
"signature": "def build_tree(self, List)"
},
{
"docstring": "从上往下打印二叉树——层序遍历",
"name": "PrintFromTopToBottom",
"signature": "def PrintFromTopToBottom(self, root)"
}
] | 2 | null | Implement the Python class `BinaryTree` described below.
Class description:
二叉树结构类
Method signatures and docstrings:
- def build_tree(self, List): 构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树
- def PrintFromTopToBottom(self, root): 从上往下打印二叉树——层序遍历 | Implement the Python class `BinaryTree` described below.
Class description:
二叉树结构类
Method signatures and docstrings:
- def build_tree(self, List): 构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树
- def PrintFromTopToBottom(self, root): 从上往下打印二叉树——层序遍历
<|skeleton|>
class BinaryTree:
"""二叉树结构类"""
def build_tree(self, List):
... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class BinaryTree:
"""二叉树结构类"""
def build_tree(self, List):
"""构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树"""
<|body_0|>
def PrintFromTopToBottom(self, root):
"""从上往下打印二叉树——层序遍历"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinaryTree:
"""二叉树结构类"""
def build_tree(self, List):
"""构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树"""
l = 0
r = len(List) - 1
if l > r:
return None
if l == r:
return TreeNode(List[l])
if (l + r) % 2 == 0:
mid = int((l + r) / 2)
... | the_stack_v2_python_sparse | Big大话数据结构/tree树结构/4、层序遍历.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 |
fd11976e89ca00ee97c567afceacb0e1beeb501a | [
"ret = 0\nfor i in range(len(data) - 1, -1, -1):\n ret <<= 8\n ret += data[i]\nreturn ret",
"ret = [0] * 16\nfor i, _ in enumerate(ret):\n ret[i] = num & 255\n num >>= 8\nreturn bytearray(ret)",
"if len(key) != 32:\n raise ValueError('Key must be 256 bit long')\nself.acc = 0\nself.r = self.le_byt... | <|body_start_0|>
ret = 0
for i in range(len(data) - 1, -1, -1):
ret <<= 8
ret += data[i]
return ret
<|end_body_0|>
<|body_start_1|>
ret = [0] * 16
for i, _ in enumerate(ret):
ret[i] = num & 255
num >>= 8
return bytearray(re... | Poly1305 authenticator | Poly1305 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poly1305:
"""Poly1305 authenticator"""
def le_bytes_to_num(data):
"""Convert a number from little endian byte format"""
<|body_0|>
def num_to_16_le_bytes(num):
"""Convert number to 16 bytes in little endian format"""
<|body_1|>
def __init__(self, key... | stack_v2_sparse_classes_36k_train_031599 | 1,504 | permissive | [
{
"docstring": "Convert a number from little endian byte format",
"name": "le_bytes_to_num",
"signature": "def le_bytes_to_num(data)"
},
{
"docstring": "Convert number to 16 bytes in little endian format",
"name": "num_to_16_le_bytes",
"signature": "def num_to_16_le_bytes(num)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_021611 | Implement the Python class `Poly1305` described below.
Class description:
Poly1305 authenticator
Method signatures and docstrings:
- def le_bytes_to_num(data): Convert a number from little endian byte format
- def num_to_16_le_bytes(num): Convert number to 16 bytes in little endian format
- def __init__(self, key): S... | Implement the Python class `Poly1305` described below.
Class description:
Poly1305 authenticator
Method signatures and docstrings:
- def le_bytes_to_num(data): Convert a number from little endian byte format
- def num_to_16_le_bytes(num): Convert number to 16 bytes in little endian format
- def __init__(self, key): S... | b26ebb6a74c2670ae28052079f2fac95d88e832a | <|skeleton|>
class Poly1305:
"""Poly1305 authenticator"""
def le_bytes_to_num(data):
"""Convert a number from little endian byte format"""
<|body_0|>
def num_to_16_le_bytes(num):
"""Convert number to 16 bytes in little endian format"""
<|body_1|>
def __init__(self, key... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poly1305:
"""Poly1305 authenticator"""
def le_bytes_to_num(data):
"""Convert a number from little endian byte format"""
ret = 0
for i in range(len(data) - 1, -1, -1):
ret <<= 8
ret += data[i]
return ret
def num_to_16_le_bytes(num):
"""C... | the_stack_v2_python_sparse | scalyr_agent/third_party_tls/tlslite/utils/poly1305.py | Kami/scalyr-agent-2 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.