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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ab20bf843447c4c0de15c02adbdb4a98be399351 | [
"cleaned_data = self.clean()\nif cleaned_data['password'] != cleaned_data['password_confirmation']:\n raise forms.ValidationError('Password confirmation does not match password')\nreturn cleaned_data['password']",
"if not self.is_valid():\n return False\ntry:\n user = User.objects.get(auth_token=self['to... | <|body_start_0|>
cleaned_data = self.clean()
if cleaned_data['password'] != cleaned_data['password_confirmation']:
raise forms.ValidationError('Password confirmation does not match password')
return cleaned_data['password']
<|end_body_0|>
<|body_start_1|>
if not self.is_vali... | Employee form class. Updates user information and creates CompanyMember object | EmployeeActivationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmployeeActivationForm:
"""Employee form class. Updates user information and creates CompanyMember object"""
def clean_password_confirmation(self):
"""Check matching of password and password confirmation."""
<|body_0|>
def submit(self):
"""Activate company member... | stack_v2_sparse_classes_36k_train_024300 | 2,154 | no_license | [
{
"docstring": "Check matching of password and password confirmation.",
"name": "clean_password_confirmation",
"signature": "def clean_password_confirmation(self)"
},
{
"docstring": "Activate company member.",
"name": "submit",
"signature": "def submit(self)"
}
] | 2 | null | Implement the Python class `EmployeeActivationForm` described below.
Class description:
Employee form class. Updates user information and creates CompanyMember object
Method signatures and docstrings:
- def clean_password_confirmation(self): Check matching of password and password confirmation.
- def submit(self): Ac... | Implement the Python class `EmployeeActivationForm` described below.
Class description:
Employee form class. Updates user information and creates CompanyMember object
Method signatures and docstrings:
- def clean_password_confirmation(self): Check matching of password and password confirmation.
- def submit(self): Ac... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class EmployeeActivationForm:
"""Employee form class. Updates user information and creates CompanyMember object"""
def clean_password_confirmation(self):
"""Check matching of password and password confirmation."""
<|body_0|>
def submit(self):
"""Activate company member... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmployeeActivationForm:
"""Employee form class. Updates user information and creates CompanyMember object"""
def clean_password_confirmation(self):
"""Check matching of password and password confirmation."""
cleaned_data = self.clean()
if cleaned_data['password'] != cleaned_data['... | the_stack_v2_python_sparse | app/companies/forms/employee_activation.py | vsokoltsov/Interview360Server | train | 2 |
5cb3c9e1b70a1229780162308f977b12230bcb72 | [
"if len(triangle) == 1:\n return triangle[0][0]\ntriangle[1][0] = triangle[0][0] + triangle[1][0]\ntriangle[1][1] = triangle[0][0] + triangle[1][1]\nfor i in range(2, len(triangle)):\n for j in range(len(triangle[i])):\n if j == 0:\n triangle[i][j] = triangle[i - 1][j] + triangle[i][j]\n ... | <|body_start_0|>
if len(triangle) == 1:
return triangle[0][0]
triangle[1][0] = triangle[0][0] + triangle[1][0]
triangle[1][1] = triangle[0][0] + triangle[1][1]
for i in range(2, len(triangle)):
for j in range(len(triangle[i])):
if j == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自顶向下"""
<|body_0|>
def minimumTotal2(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自底向上"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if l... | stack_v2_sparse_classes_36k_train_024301 | 1,395 | no_license | [
{
"docstring": ":type triangle: List[List[int]] :rtype: int 自顶向下",
"name": "minimumTotal",
"signature": "def minimumTotal(self, triangle)"
},
{
"docstring": ":type triangle: List[List[int]] :rtype: int 自底向上",
"name": "minimumTotal2",
"signature": "def minimumTotal2(self, triangle)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003401 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int 自顶向下
- def minimumTotal2(self, triangle): :type triangle: List[List[int]] :rtype: int 自底向上 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int 自顶向下
- def minimumTotal2(self, triangle): :type triangle: List[List[int]] :rtype: int 自底向上
<|skelet... | 013f6f222c6c2a617787b258f8a37003a9f51526 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自顶向下"""
<|body_0|>
def minimumTotal2(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自底向上"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自顶向下"""
if len(triangle) == 1:
return triangle[0][0]
triangle[1][0] = triangle[0][0] + triangle[1][0]
triangle[1][1] = triangle[0][0] + triangle[1][1]
for i in range(2... | the_stack_v2_python_sparse | dp/minimum_total.py | terrifyzhao/leetcode | train | 0 | |
43bcba46adcf0b9b6583501dbc12d4c652613ccb | [
"self.owner = owner\nself.cardFinder = IndexInZone(index, zoneType)\nCommand.__init__(self, [CurrentPlayer(), NoRequest(), self.cardFinder])",
"card = self.cardFinder.card\ncontext = PlayerContext(self.owner.game, card)\ncoroutine = self.owner.activatableEffects[card][0].activate(context)\nresponse = (yield corou... | <|body_start_0|>
self.owner = owner
self.cardFinder = IndexInZone(index, zoneType)
Command.__init__(self, [CurrentPlayer(), NoRequest(), self.cardFinder])
<|end_body_0|>
<|body_start_1|>
card = self.cardFinder.card
context = PlayerContext(self.owner.game, card)
coroutine... | Represents a command to activate a card | ActivateCard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivateCard:
"""Represents a command to activate a card"""
def __init__(self, index, zoneType, owner):
"""Initialize the Activate Card Command"""
<|body_0|>
def perform(self):
"""Perform the command"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_024302 | 1,001 | no_license | [
{
"docstring": "Initialize the Activate Card Command",
"name": "__init__",
"signature": "def __init__(self, index, zoneType, owner)"
},
{
"docstring": "Perform the command",
"name": "perform",
"signature": "def perform(self)"
}
] | 2 | null | Implement the Python class `ActivateCard` described below.
Class description:
Represents a command to activate a card
Method signatures and docstrings:
- def __init__(self, index, zoneType, owner): Initialize the Activate Card Command
- def perform(self): Perform the command | Implement the Python class `ActivateCard` described below.
Class description:
Represents a command to activate a card
Method signatures and docstrings:
- def __init__(self, index, zoneType, owner): Initialize the Activate Card Command
- def perform(self): Perform the command
<|skeleton|>
class ActivateCard:
"""R... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class ActivateCard:
"""Represents a command to activate a card"""
def __init__(self, index, zoneType, owner):
"""Initialize the Activate Card Command"""
<|body_0|>
def perform(self):
"""Perform the command"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActivateCard:
"""Represents a command to activate a card"""
def __init__(self, index, zoneType, owner):
"""Initialize the Activate Card Command"""
self.owner = owner
self.cardFinder = IndexInZone(index, zoneType)
Command.__init__(self, [CurrentPlayer(), NoRequest(), self.c... | the_stack_v2_python_sparse | src/Game/Commands/activate_card.py | dfwarden/DeckBuilding | train | 0 |
9e457d6e528e81c34ab09c8a715b958410ec7684 | [
"IO_files = {}\nfile_names = set()\nfor fl in in_dir.files:\n if self.name not in fl.users:\n if utils.splitext(fl.name)[-1] in self.input_types:\n IO_files['--!i'] = os.path.join(in_dir.path, fl.name)\n command_ids = [utils.infer_path_id(IO_files['--!i'])]\n in_dir.use_fi... | <|body_start_0|>
IO_files = {}
file_names = set()
for fl in in_dir.files:
if self.name not in fl.users:
if utils.splitext(fl.name)[-1] in self.input_types:
IO_files['--!i'] = os.path.join(in_dir.path, fl.name)
command_ids = [uti... | Class for creating command lines for samtools rmdup. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the function. input_type: ... | samtools_rmdup | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class samtools_rmdup:
"""Class for creating command lines for samtools rmdup. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes... | stack_v2_sparse_classes_36k_train_024303 | 7,774 | permissive | [
{
"docstring": "Infers the input and output file paths. This method must keep the directory objects up to date of the file edits! Parameters: in_cmd: A dict containing the command line. in_dir: Input directory (instance of filetypes.Directory). out_dir: Output directory (instance of filetypes.Directory). Return... | 2 | stack_v2_sparse_classes_30k_train_003251 | Implement the Python class `samtools_rmdup` described below.
Class description:
Class for creating command lines for samtools rmdup. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects ... | Implement the Python class `samtools_rmdup` described below.
Class description:
Class for creating command lines for samtools rmdup. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects ... | fd83eee4be0bb78c67a111fd1c1c1dff4c16aefe | <|skeleton|>
class samtools_rmdup:
"""Class for creating command lines for samtools rmdup. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class samtools_rmdup:
"""Class for creating command lines for samtools rmdup. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name ... | the_stack_v2_python_sparse | modules/samtools.py | tyrmi/STAPLER | train | 4 |
169bb691778eaf71d5cb6b4ec844ae07577374ce | [
"def bin_search(nums, left, right, target):\n if nums[left] == target:\n return left\n if left == right:\n return -1\n center = (left + right) // 2\n if nums[center] == target:\n return center\n elif nums[left] > nums[center] > target:\n return bin_search(nums, left, cente... | <|body_start_0|>
def bin_search(nums, left, right, target):
if nums[left] == target:
return left
if left == right:
return -1
center = (left + right) // 2
if nums[center] == target:
return center
elif nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search3(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
de... | stack_v2_sparse_classes_36k_train_024304 | 2,652 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search3",
"signature": "def search3(self, nums, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020328 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search3(self, nums, target): :type nums: List[int] :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search3(self, nums, target): :type nums: List[int] :type target: int :rtype: int
<|skel... | b6a8fe6adc15c32d2c1a7e882b0a1ee4d4581c90 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search3(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
def bin_search(nums, left, right, target):
if nums[left] == target:
return left
if left == right:
return -1
center = (left + r... | the_stack_v2_python_sparse | 001~050/_033_search_in_rotated_sorted_array.py | JeromeLee-ljl/leetcode | train | 0 | |
03f780bbaa0af7aa1ebb67bc3f2c426296214706 | [
"self.user_agent: Optional[str] = None\nself.forecast_type = 'compact'\nself.save_location = './data'\nself.base_url = 'https://api.met.no/weatherapi/locationforecast/2.0/'\nself.user_config_file: Optional[str] = None\nself.get_config()",
"for file in self.files:\n if self.cwd.joinpath(file).is_file():\n ... | <|body_start_0|>
self.user_agent: Optional[str] = None
self.forecast_type = 'compact'
self.save_location = './data'
self.base_url = 'https://api.met.no/weatherapi/locationforecast/2.0/'
self.user_config_file: Optional[str] = None
self.get_config()
<|end_body_0|>
<|body_s... | Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Optional[str]): The user config file from which the configuration was taken,... | Config | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Optional[str]): The user config file from ... | stack_v2_sparse_classes_36k_train_024305 | 2,914 | no_license | [
{
"docstring": "Create Config object with the current user configuration. Uses default config if no configuration is supplied.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Generator of files to look for user configuration.",
"name": "possible_user_config... | 4 | stack_v2_sparse_classes_30k_test_000112 | Implement the Python class `Config` described below.
Class description:
Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Opt... | Implement the Python class `Config` described below.
Class description:
Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Opt... | 49271f05d110e10035e5e017805abc9d2bd29387 | <|skeleton|>
class Config:
"""Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Optional[str]): The user config file from ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
"""Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Optional[str]): The user config file from which the con... | the_stack_v2_python_sparse | server/venv/Lib/site-packages/metno_locationforecast/config.py | WilliamMRS/CoT | train | 0 |
b797aed65350eaded5e1eea74b31b0831fa2fd4c | [
"super(MicroConv, self).__init__()\nself._in_src_feats, self._in_dst_feats = (in_feats[0], in_feats[1])\nself._out_feats = out_feats\nself._num_heads = num_heads\nself.dropout = nn.Dropout(dropout)\nself.leaky_relu = nn.LeakyReLU(negative_slope)",
"graph = graph.local_var()\nfeat_src = self.dropout(feat[0])\nfeat... | <|body_start_0|>
super(MicroConv, self).__init__()
self._in_src_feats, self._in_dst_feats = (in_feats[0], in_feats[1])
self._out_feats = out_feats
self._num_heads = num_heads
self.dropout = nn.Dropout(dropout)
self.leaky_relu = nn.LeakyReLU(negative_slope)
<|end_body_0|>
... | MicroConv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MicroConv:
def __init__(self, in_feats: tuple, out_feats: int, num_heads: int, dropout: float=0.0, negative_slope: float=0.2):
"""Parameters ---------- in_feats : pair of ints Input feature size. out_feats : int Output feature size. num_heads : int Number of heads in Multi-Head Attention... | stack_v2_sparse_classes_36k_train_024306 | 8,874 | permissive | [
{
"docstring": "Parameters ---------- in_feats : pair of ints Input feature size. out_feats : int Output feature size. num_heads : int Number of heads in Multi-Head Attention. dropout : float, optional Dropout rate, defaults: 0. negative_slope : float, optional Negative slope rate, defaults: 0.2.",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_009281 | Implement the Python class `MicroConv` described below.
Class description:
Implement the MicroConv class.
Method signatures and docstrings:
- def __init__(self, in_feats: tuple, out_feats: int, num_heads: int, dropout: float=0.0, negative_slope: float=0.2): Parameters ---------- in_feats : pair of ints Input feature ... | Implement the Python class `MicroConv` described below.
Class description:
Implement the MicroConv class.
Method signatures and docstrings:
- def __init__(self, in_feats: tuple, out_feats: int, num_heads: int, dropout: float=0.0, negative_slope: float=0.2): Parameters ---------- in_feats : pair of ints Input feature ... | f6038301c7d1f3a0cfa563264f14194c415330ea | <|skeleton|>
class MicroConv:
def __init__(self, in_feats: tuple, out_feats: int, num_heads: int, dropout: float=0.0, negative_slope: float=0.2):
"""Parameters ---------- in_feats : pair of ints Input feature size. out_feats : int Output feature size. num_heads : int Number of heads in Multi-Head Attention... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MicroConv:
def __init__(self, in_feats: tuple, out_feats: int, num_heads: int, dropout: float=0.0, negative_slope: float=0.2):
"""Parameters ---------- in_feats : pair of ints Input feature size. out_feats : int Output feature size. num_heads : int Number of heads in Multi-Head Attention. dropout : fl... | the_stack_v2_python_sparse | openhgnn/models/Micro_layer.py | liushiliushi/OpenHGNN | train | 1 | |
6f7b9a779abd8fe5f117f7610525cc19a0a63d52 | [
"super().__init__()\nself._initialize_arguments(args)\nself.embedding = nn.Linear(self.output_dim, self.rnn_units)\nself.gat_layers = nn.ModuleList([gat_cell.GATGRUCell(args) for _ in range(self.num_rnn_layers)])\nself.fc_out = nn.Linear(self.rnn_units, self.output_dim)\nself.dropout = nn.Dropout(self.dropout)\nsel... | <|body_start_0|>
super().__init__()
self._initialize_arguments(args)
self.embedding = nn.Linear(self.output_dim, self.rnn_units)
self.gat_layers = nn.ModuleList([gat_cell.GATGRUCell(args) for _ in range(self.num_rnn_layers)])
self.fc_out = nn.Linear(self.rnn_units, self.output_di... | Implements GATRNN encoder model. Decodes the input hidden vector to the output time series sequence. | Decoder | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Implements GATRNN encoder model. Decodes the input hidden vector to the output time series sequence."""
def __init__(self, args):
"""Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here."""
... | stack_v2_sparse_classes_36k_train_024307 | 13,550 | permissive | [
{
"docstring": "Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Decoder forward pass. Args: inputs: input one-step time series, with... | 2 | stack_v2_sparse_classes_30k_train_020778 | Implement the Python class `Decoder` described below.
Class description:
Implements GATRNN encoder model. Decodes the input hidden vector to the output time series sequence.
Method signatures and docstrings:
- def __init__(self, args): Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser ... | Implement the Python class `Decoder` described below.
Class description:
Implements GATRNN encoder model. Decodes the input hidden vector to the output time series sequence.
Method signatures and docstrings:
- def __init__(self, args): Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser ... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Decoder:
"""Implements GATRNN encoder model. Decodes the input hidden vector to the output time series sequence."""
def __init__(self, args):
"""Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Implements GATRNN encoder model. Decodes the input hidden vector to the output time series sequence."""
def __init__(self, args):
"""Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here."""
super().__... | the_stack_v2_python_sparse | editable_graph_temporal/model/gat_model.py | Jimmy-INL/google-research | train | 1 |
189f297efef35fd104499b26e12ed1a6ac6ccc89 | [
"start = self.cleaned_data.get('start')\nif start is not None:\n if start > date.today():\n self._errors['start'] = self.error_class(['The start date must be in the past.'])\n del self.cleaned_data['start']\n elif start < date(2000, 5, 20):\n self._errors['start'] = self.error_class([\"Th... | <|body_start_0|>
start = self.cleaned_data.get('start')
if start is not None:
if start > date.today():
self._errors['start'] = self.error_class(['The start date must be in the past.'])
del self.cleaned_data['start']
elif start < date(2000, 5, 20):
... | A form to create an officer history record, based on the OfficerHistory model class. | OfficerHistoryForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficerHistoryForm:
"""A form to create an officer history record, based on the OfficerHistory model class."""
def clean_start(self):
"""Ensure that the start date is in the past and after the chapter's installation (May 20, 2000)."""
<|body_0|>
def clean_end(self):
... | stack_v2_sparse_classes_36k_train_024308 | 3,153 | no_license | [
{
"docstring": "Ensure that the start date is in the past and after the chapter's installation (May 20, 2000).",
"name": "clean_start",
"signature": "def clean_start(self)"
},
{
"docstring": "Ensure that the end date is in the past, after the chapter's installation, and after the start date.",
... | 2 | stack_v2_sparse_classes_30k_train_014335 | Implement the Python class `OfficerHistoryForm` described below.
Class description:
A form to create an officer history record, based on the OfficerHistory model class.
Method signatures and docstrings:
- def clean_start(self): Ensure that the start date is in the past and after the chapter's installation (May 20, 20... | Implement the Python class `OfficerHistoryForm` described below.
Class description:
A form to create an officer history record, based on the OfficerHistory model class.
Method signatures and docstrings:
- def clean_start(self): Ensure that the start date is in the past and after the chapter's installation (May 20, 20... | b47232b4b05d572b74d075e0810ca85687d430f3 | <|skeleton|>
class OfficerHistoryForm:
"""A form to create an officer history record, based on the OfficerHistory model class."""
def clean_start(self):
"""Ensure that the start date is in the past and after the chapter's installation (May 20, 2000)."""
<|body_0|>
def clean_end(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OfficerHistoryForm:
"""A form to create an officer history record, based on the OfficerHistory model class."""
def clean_start(self):
"""Ensure that the start date is in the past and after the chapter's installation (May 20, 2000)."""
start = self.cleaned_data.get('start')
if star... | the_stack_v2_python_sparse | officers/forms.py | will2dye4/gtphipsi | train | 1 |
9afe4cd0b9abe7cd919710041d1b8260416c93aa | [
"if height is None or len(height) <= 1:\n return 0\nmax_area = 0\nfor i in range(len(height)):\n for j in range(i + 1, len(height)):\n max_area = max(max_area, abs(j - i) * min(height[i], height[j]))\nreturn max_area",
"if height is None or len(height) <= 1:\n return 0\nmax_area = 0\ni = 0\nj = le... | <|body_start_0|>
if height is None or len(height) <= 1:
return 0
max_area = 0
for i in range(len(height)):
for j in range(i + 1, len(height)):
max_area = max(max_area, abs(j - i) * min(height[i], height[j]))
return max_area
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea_test(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if height is None or len(height) <= 1:
... | stack_v2_sparse_classes_36k_train_024309 | 1,072 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea_test",
"signature": "def maxArea_test(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000602 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_test(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_test(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxAre... | 09b7121628df824f432b8cdd25c55f045b013c0b | <|skeleton|>
class Solution:
def maxArea_test(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea_test(self, height):
""":type height: List[int] :rtype: int"""
if height is None or len(height) <= 1:
return 0
max_area = 0
for i in range(len(height)):
for j in range(i + 1, len(height)):
max_area = max(max_area, abs... | the_stack_v2_python_sparse | array_11.py | cainingning/leetcode | train | 1 | |
45c6f0883309f6a71d663cb5174134d7344ff60d | [
"self.__robot = robot\nself.__frame_id = frame_id\nself.__joint_prefix = joint_prefix\nself.__node = node\nself.__sensors = []\nself.__timestep = int(robot.getBasicTimeStep())\nself.__last_joint_states = None\nself.__previous_time = 0\nself.__previous_position = []\nself.__joint_names = []\nfor i in range(robot.get... | <|body_start_0|>
self.__robot = robot
self.__frame_id = frame_id
self.__joint_prefix = joint_prefix
self.__node = node
self.__sensors = []
self.__timestep = int(robot.getBasicTimeStep())
self.__last_joint_states = None
self.__previous_time = 0
self... | Publishes joint states. Discovers all joints with positional sensors and publishes corresponding ROS2 messages of type [`sensor_msgs/JointState`](https://github.com/ros2/common_interfaces/blob/master/sensor_msgs/msg/JointState.msg). Args: robot (WebotsNode): Webots Robot node. jointPrefix (str): Prefix to all joint nam... | JointStatePublisher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointStatePublisher:
"""Publishes joint states. Discovers all joints with positional sensors and publishes corresponding ROS2 messages of type [`sensor_msgs/JointState`](https://github.com/ros2/common_interfaces/blob/master/sensor_msgs/msg/JointState.msg). Args: robot (WebotsNode): Webots Robot n... | stack_v2_sparse_classes_36k_train_024310 | 3,140 | permissive | [
{
"docstring": "Initialize the position sensors and the topic.",
"name": "__init__",
"signature": "def __init__(self, robot, joint_prefix, node, frame_id='joint_states')"
},
{
"docstring": "Publish the 'joint_states' topic with up to date value.",
"name": "publish",
"signature": "def pub... | 2 | stack_v2_sparse_classes_30k_val_000873 | Implement the Python class `JointStatePublisher` described below.
Class description:
Publishes joint states. Discovers all joints with positional sensors and publishes corresponding ROS2 messages of type [`sensor_msgs/JointState`](https://github.com/ros2/common_interfaces/blob/master/sensor_msgs/msg/JointState.msg). A... | Implement the Python class `JointStatePublisher` described below.
Class description:
Publishes joint states. Discovers all joints with positional sensors and publishes corresponding ROS2 messages of type [`sensor_msgs/JointState`](https://github.com/ros2/common_interfaces/blob/master/sensor_msgs/msg/JointState.msg). A... | 08a061e73e3b88d57cc27b662be0f907d8b9f15b | <|skeleton|>
class JointStatePublisher:
"""Publishes joint states. Discovers all joints with positional sensors and publishes corresponding ROS2 messages of type [`sensor_msgs/JointState`](https://github.com/ros2/common_interfaces/blob/master/sensor_msgs/msg/JointState.msg). Args: robot (WebotsNode): Webots Robot n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JointStatePublisher:
"""Publishes joint states. Discovers all joints with positional sensors and publishes corresponding ROS2 messages of type [`sensor_msgs/JointState`](https://github.com/ros2/common_interfaces/blob/master/sensor_msgs/msg/JointState.msg). Args: robot (WebotsNode): Webots Robot node. jointPre... | the_stack_v2_python_sparse | webots_ros2_core/webots_ros2_core/joint_state_publisher.py | harshag37/webots_ros2 | train | 1 |
51263c3de674fa9a86b015b923e773c43bbb6a69 | [
"blocked = models.Visit.objects.exclude(sender='').values_list('sender', flat=True)\nphone = survey_utils.convert_to_local_format(self.cleaned_data['phone'])\nif phone in blocked:\n raise forms.ValidationError('The phone is not allowed')\nreturn self.cleaned_data['phone']",
"data = self.cleaned_data['values'].... | <|body_start_0|>
blocked = models.Visit.objects.exclude(sender='').values_list('sender', flat=True)
phone = survey_utils.convert_to_local_format(self.cleaned_data['phone'])
if phone in blocked:
raise forms.ValidationError('The phone is not allowed')
return self.cleaned_data['... | Requirements from TextIt Generic feedback flow Clinic ID response come as numeric category with label "Clinic". Clinic name (if clinic is not sent) comes as text with label "Which Clinic". Complaint message comes as text with label "General Feedback". Any message that comes with category "Other" is ignored. More: Clini... | FeedbackForm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedbackForm:
"""Requirements from TextIt Generic feedback flow Clinic ID response come as numeric category with label "Clinic". Clinic name (if clinic is not sent) comes as text with label "Which Clinic". Complaint message comes as text with label "General Feedback". Any message that comes with ... | stack_v2_sparse_classes_36k_train_024311 | 6,902 | permissive | [
{
"docstring": "Validate that phone is not in blocked list.",
"name": "clean_phone",
"signature": "def clean_phone(self)"
},
{
"docstring": "Return Clinic and Message.",
"name": "clean_values",
"signature": "def clean_values(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021613 | Implement the Python class `FeedbackForm` described below.
Class description:
Requirements from TextIt Generic feedback flow Clinic ID response come as numeric category with label "Clinic". Clinic name (if clinic is not sent) comes as text with label "Which Clinic". Complaint message comes as text with label "General ... | Implement the Python class `FeedbackForm` described below.
Class description:
Requirements from TextIt Generic feedback flow Clinic ID response come as numeric category with label "Clinic". Clinic name (if clinic is not sent) comes as text with label "Which Clinic". Complaint message comes as text with label "General ... | d8e7a36041429641ef956687c99cf3a1757b22b8 | <|skeleton|>
class FeedbackForm:
"""Requirements from TextIt Generic feedback flow Clinic ID response come as numeric category with label "Clinic". Clinic name (if clinic is not sent) comes as text with label "Which Clinic". Complaint message comes as text with label "General Feedback". Any message that comes with ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeedbackForm:
"""Requirements from TextIt Generic feedback flow Clinic ID response come as numeric category with label "Clinic". Clinic name (if clinic is not sent) comes as text with label "Which Clinic". Complaint message comes as text with label "General Feedback". Any message that comes with category "Oth... | the_stack_v2_python_sparse | myvoice/clinics/forms.py | myvoice-nigeria/myvoice | train | 1 |
52570fc4af2574ce42ffbe00851bb6096dddd85e | [
"if xml_val not in cls._xml_to_member:\n raise InvalidXmlError(\"attribute value '%s' not valid for this type\" % xml_val)\nreturn cls._xml_to_member[xml_val]",
"if enum_val not in cls._member_to_xml:\n raise ValueError(\"value '%s' not in enumeration %s\" % (enum_val, cls.__name__))\nreturn cls._member_to_... | <|body_start_0|>
if xml_val not in cls._xml_to_member:
raise InvalidXmlError("attribute value '%s' not valid for this type" % xml_val)
return cls._xml_to_member[xml_val]
<|end_body_0|>
<|body_start_1|>
if enum_val not in cls._member_to_xml:
raise ValueError("value '%s' n... | Provides ``to_xml()`` and ``from_xml()`` methods in addition to base enumeration features | XmlEnumeration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlEnumeration:
"""Provides ``to_xml()`` and ``from_xml()`` methods in addition to base enumeration features"""
def from_xml(cls, xml_val):
"""Return the enumeration member corresponding to the XML value *xml_val*."""
<|body_0|>
def to_xml(cls, enum_val):
"""Retu... | stack_v2_sparse_classes_36k_train_024312 | 10,958 | permissive | [
{
"docstring": "Return the enumeration member corresponding to the XML value *xml_val*.",
"name": "from_xml",
"signature": "def from_xml(cls, xml_val)"
},
{
"docstring": "Return the XML value of the enumeration value *enum_val*.",
"name": "to_xml",
"signature": "def to_xml(cls, enum_val)... | 2 | stack_v2_sparse_classes_30k_train_009339 | Implement the Python class `XmlEnumeration` described below.
Class description:
Provides ``to_xml()`` and ``from_xml()`` methods in addition to base enumeration features
Method signatures and docstrings:
- def from_xml(cls, xml_val): Return the enumeration member corresponding to the XML value *xml_val*.
- def to_xml... | Implement the Python class `XmlEnumeration` described below.
Class description:
Provides ``to_xml()`` and ``from_xml()`` methods in addition to base enumeration features
Method signatures and docstrings:
- def from_xml(cls, xml_val): Return the enumeration member corresponding to the XML value *xml_val*.
- def to_xml... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class XmlEnumeration:
"""Provides ``to_xml()`` and ``from_xml()`` methods in addition to base enumeration features"""
def from_xml(cls, xml_val):
"""Return the enumeration member corresponding to the XML value *xml_val*."""
<|body_0|>
def to_xml(cls, enum_val):
"""Retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XmlEnumeration:
"""Provides ``to_xml()`` and ``from_xml()`` methods in addition to base enumeration features"""
def from_xml(cls, xml_val):
"""Return the enumeration member corresponding to the XML value *xml_val*."""
if xml_val not in cls._xml_to_member:
raise InvalidXmlError... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/docx/enum/base.py | ryfeus/lambda-packs | train | 1,283 |
7862f5568e9c81c645f64ec21a67c6385fb67a27 | [
"if model._meta.app_label == 'notifications':\n return NOTIFICATIONS\nreturn None",
"if model._meta.app_label == 'notifications':\n return NOTIFICATIONS\nreturn None",
"if obj1._meta.app_label == 'notifications' and obj2._meta.app_label == 'notifications':\n return True\nelif 'notifications' not in [ob... | <|body_start_0|>
if model._meta.app_label == 'notifications':
return NOTIFICATIONS
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'notifications':
return NOTIFICATIONS
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app... | Determine how to route database calls for the Notifications app. All other models will be routed to the default database. | NotificationsRouter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationsRouter:
"""Determine how to route database calls for the Notifications app. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on Notifications app models to NOTIFICATIONS."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_024313 | 4,974 | permissive | [
{
"docstring": "Send all read operations on Notifications app models to NOTIFICATIONS.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Send all write operations on Notifications app models to NOTIFICATIONS.",
"name": "db_for_write",
"signa... | 4 | null | Implement the Python class `NotificationsRouter` described below.
Class description:
Determine how to route database calls for the Notifications app. All other models will be routed to the default database.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Send all read operations on Notifica... | Implement the Python class `NotificationsRouter` described below.
Class description:
Determine how to route database calls for the Notifications app. All other models will be routed to the default database.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Send all read operations on Notifica... | cc9da2a6acd139acac3cd71c4cb05c15d4465712 | <|skeleton|>
class NotificationsRouter:
"""Determine how to route database calls for the Notifications app. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on Notifications app models to NOTIFICATIONS."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotificationsRouter:
"""Determine how to route database calls for the Notifications app. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on Notifications app models to NOTIFICATIONS."""
if model._meta.app_label... | the_stack_v2_python_sparse | kolibri/core/notifications/models.py | learningequality/kolibri | train | 689 |
8ce6b80ced815d3432502abb90702bd4969f0454 | [
"super(CtrTrainerCallback, self).__init__()\nself.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])\nself.selected_pairs = list()\nlogging.info('init autogate s2 trainer callback')",
"super().before_train(logs)\n'Be called before the training process.'\nhpo_result = FileOps.load_pickle(FileO... | <|body_start_0|>
super(CtrTrainerCallback, self).__init__()
self.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])
self.selected_pairs = list()
logging.info('init autogate s2 trainer callback')
<|end_body_0|>
<|body_start_1|>
super().before_train(logs)
... | AutoGateGrdaS2TrainerCallback module. | AutoGateGrdaS2TrainerCallback | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoGateGrdaS2TrainerCallback:
"""AutoGateGrdaS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateGrdaS2TrainerCallback class."""
<|body_0|>
def before_train(self, logs=None):
"""Call before_train of the managed callbacks."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_024314 | 2,468 | permissive | [
{
"docstring": "Construct AutoGateGrdaS2TrainerCallback class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Call before_train of the managed callbacks.",
"name": "before_train",
"signature": "def before_train(self, logs=None)"
},
{
"docstring": "Call... | 3 | null | Implement the Python class `AutoGateGrdaS2TrainerCallback` described below.
Class description:
AutoGateGrdaS2TrainerCallback module.
Method signatures and docstrings:
- def __init__(self): Construct AutoGateGrdaS2TrainerCallback class.
- def before_train(self, logs=None): Call before_train of the managed callbacks.
-... | Implement the Python class `AutoGateGrdaS2TrainerCallback` described below.
Class description:
AutoGateGrdaS2TrainerCallback module.
Method signatures and docstrings:
- def __init__(self): Construct AutoGateGrdaS2TrainerCallback class.
- def before_train(self, logs=None): Call before_train of the managed callbacks.
-... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class AutoGateGrdaS2TrainerCallback:
"""AutoGateGrdaS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateGrdaS2TrainerCallback class."""
<|body_0|>
def before_train(self, logs=None):
"""Call before_train of the managed callbacks."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoGateGrdaS2TrainerCallback:
"""AutoGateGrdaS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateGrdaS2TrainerCallback class."""
super(CtrTrainerCallback, self).__init__()
self.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])
self.... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/algorithms/nas/fis/autogate_grda_s2_trainer_callback.py | Huawei-Ascend/modelzoo | train | 1 |
0c3bce9b67a34ced9fc31d42e5e753770d9e0ebe | [
"if name is not None:\n pulumi.set(__self__, 'name', name)\nif value is not None:\n pulumi.set(__self__, 'value', value)",
"warnings.warn(\"Field 'parameters' has been deprecated from version 1.101.0. Use 'config' instead.\", DeprecationWarning)\npulumi.log.warn(\"name is deprecated: Field 'parameters' has ... | <|body_start_0|>
if name is not None:
pulumi.set(__self__, 'name', name)
if value is not None:
pulumi.set(__self__, 'value', value)
<|end_body_0|>
<|body_start_1|>
warnings.warn("Field 'parameters' has been deprecated from version 1.101.0. Use 'config' instead.", Depreca... | InstanceParameter | [
"Apache-2.0",
"MPL-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceParameter:
def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None):
""":param str name: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead. :param str value: Field `parameters` has been deprecated from provider version... | stack_v2_sparse_classes_36k_train_024315 | 32,429 | permissive | [
{
"docstring": ":param str name: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead. :param str value: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead.",
"name": "__init__",
"signature": "def __init__(__self__, *, name: Opt... | 3 | stack_v2_sparse_classes_30k_train_017785 | Implement the Python class `InstanceParameter` described below.
Class description:
Implement the InstanceParameter class.
Method signatures and docstrings:
- def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None): :param str name: Field `parameters` has been deprecated from provider version 1.... | Implement the Python class `InstanceParameter` described below.
Class description:
Implement the InstanceParameter class.
Method signatures and docstrings:
- def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None): :param str name: Field `parameters` has been deprecated from provider version 1.... | ffddb9036f7893fbd58863d8364a4977eb1bee17 | <|skeleton|>
class InstanceParameter:
def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None):
""":param str name: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead. :param str value: Field `parameters` has been deprecated from provider version... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstanceParameter:
def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None):
""":param str name: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead. :param str value: Field `parameters` has been deprecated from provider version 1.101.0 and `... | the_stack_v2_python_sparse | sdk/python/pulumi_alicloud/kvstore/outputs.py | pulumi/pulumi-alicloud | train | 56 | |
31f6604c3dd05a6a92355d21e235152ea27144da | [
"cat = getToolByName(self.context, 'portal_catalog')\nideeSejour = getattr(self.context, 'idee-sejour')\nurl = '/'.join(ideeSejour.getPhysicalPath())\ncontentFilter = {}\npath = {}\npath['query'] = url\npath['depth'] = 1\ncontentFilter['path'] = path\ncontentFilter['portal_type'] = ['Package']\ncontentFilter['sort_... | <|body_start_0|>
cat = getToolByName(self.context, 'portal_catalog')
ideeSejour = getattr(self.context, 'idee-sejour')
url = '/'.join(ideeSejour.getPhysicalPath())
contentFilter = {}
path = {}
path['query'] = url
path['depth'] = 1
contentFilter['path'] = p... | View on Idee Sejour folder | IdeeSejourRootFolder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdeeSejourRootFolder:
"""View on Idee Sejour folder"""
def getPackages(self):
"""Returns the list of Packages available in the current folder"""
<|body_0|>
def getVignette(self, packageUrl):
"""Return a vignette for the package"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_024316 | 1,569 | no_license | [
{
"docstring": "Returns the list of Packages available in the current folder",
"name": "getPackages",
"signature": "def getPackages(self)"
},
{
"docstring": "Return a vignette for the package",
"name": "getVignette",
"signature": "def getVignette(self, packageUrl)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005329 | Implement the Python class `IdeeSejourRootFolder` described below.
Class description:
View on Idee Sejour folder
Method signatures and docstrings:
- def getPackages(self): Returns the list of Packages available in the current folder
- def getVignette(self, packageUrl): Return a vignette for the package | Implement the Python class `IdeeSejourRootFolder` described below.
Class description:
View on Idee Sejour folder
Method signatures and docstrings:
- def getPackages(self): Returns the list of Packages available in the current folder
- def getVignette(self, packageUrl): Return a vignette for the package
<|skeleton|>
... | d624d1ba0354d00243290470f0585550957ee1cc | <|skeleton|>
class IdeeSejourRootFolder:
"""View on Idee Sejour folder"""
def getPackages(self):
"""Returns the list of Packages available in the current folder"""
<|body_0|>
def getVignette(self, packageUrl):
"""Return a vignette for the package"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdeeSejourRootFolder:
"""View on Idee Sejour folder"""
def getPackages(self):
"""Returns the list of Packages available in the current folder"""
cat = getToolByName(self.context, 'portal_catalog')
ideeSejour = getattr(self.context, 'idee-sejour')
url = '/'.join(ideeSejour.... | the_stack_v2_python_sparse | gites/core/browser/ideesejourrootfolder.py | gitesdewallonie/gites.core | train | 0 |
3cb43eb03e52a40357e4dbb90bf3ca7de2e5c5d1 | [
"payload = {'key': key, 'value': value, 'targets': targets}\nurl = self._url('/status/changeset')\nres = self._result(self._post(url, data=payload))\nreturn res['id']",
"u = self._url('/status/currentstatus/{0}', device_id)\nres = self._result(self._get(u))\nstatus = []\nif filter_key_by_prefix is not None and fi... | <|body_start_0|>
payload = {'key': key, 'value': value, 'targets': targets}
url = self._url('/status/changeset')
res = self._result(self._post(url, data=payload))
return res['id']
<|end_body_0|>
<|body_start_1|>
u = self._url('/status/currentstatus/{0}', device_id)
res =... | StatusApiMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatusApiMixin:
def create_changeset(self, key, value, targets):
"""Return all the tags of a workspace Args: key (str): The key of the changeset. value (json): The Value to be associated to the key. targets (list of str): List of targets of the changest. Retunrs: id (str). The id of the ... | stack_v2_sparse_classes_36k_train_024317 | 4,288 | no_license | [
{
"docstring": "Return all the tags of a workspace Args: key (str): The key of the changeset. value (json): The Value to be associated to the key. targets (list of str): List of targets of the changest. Retunrs: id (str). The id of the created changeset Raises: :py:class:`zdm.errors.APIError` If the server retu... | 3 | null | Implement the Python class `StatusApiMixin` described below.
Class description:
Implement the StatusApiMixin class.
Method signatures and docstrings:
- def create_changeset(self, key, value, targets): Return all the tags of a workspace Args: key (str): The key of the changeset. value (json): The Value to be associate... | Implement the Python class `StatusApiMixin` described below.
Class description:
Implement the StatusApiMixin class.
Method signatures and docstrings:
- def create_changeset(self, key, value, targets): Return all the tags of a workspace Args: key (str): The key of the changeset. value (json): The Value to be associate... | d27b0d6ee47b9c4f320f518705074f1032fedf8a | <|skeleton|>
class StatusApiMixin:
def create_changeset(self, key, value, targets):
"""Return all the tags of a workspace Args: key (str): The key of the changeset. value (json): The Value to be associated to the key. targets (list of str): List of targets of the changest. Retunrs: id (str). The id of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatusApiMixin:
def create_changeset(self, key, value, targets):
"""Return all the tags of a workspace Args: key (str): The key of the changeset. value (json): The Value to be associated to the key. targets (list of str): List of targets of the changest. Retunrs: id (str). The id of the created change... | the_stack_v2_python_sparse | zdevicemanager/client/api/status.py | zerynth/core-zerynth-toolchain | train | 0 | |
32e07d086c3d1b8300cf5258ab6bd60642d16ad4 | [
"self._host = 'localhost'\nself._port = 7878\nself._ftp = FTP()\nself._ftp.connect(self._host, self._port)\nself._ftp.login(user='user', passwd='12345')\nself._ftp.set_pasv(False)",
"log.info('Starting Pulsar Data Transfer...')\nsocket = self._ftp.transfercmd('STOR {0}_{1}'.format(obs_id, beam_id))\nsocket.send(j... | <|body_start_0|>
self._host = 'localhost'
self._port = 7878
self._ftp = FTP()
self._ftp.connect(self._host, self._port)
self._ftp.login(user='user', passwd='12345')
self._ftp.set_pasv(False)
<|end_body_0|>
<|body_start_1|>
log.info('Starting Pulsar Data Transfer.... | . | PulsarSender | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PulsarSender:
"""."""
def __init__(self):
"""Creates and initialises the ftp client"""
<|body_0|>
def send(self, config, log, obs_id, beam_id):
"""Send the pulsar data to the ftp server Args: config (dict): Dictionary of settings log (logging.Logger): Python logg... | stack_v2_sparse_classes_36k_train_024318 | 1,705 | permissive | [
{
"docstring": "Creates and initialises the ftp client",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Send the pulsar data to the ftp server Args: config (dict): Dictionary of settings log (logging.Logger): Python logging object obs_id: observation id beam_id: beam id... | 2 | null | Implement the Python class `PulsarSender` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): Creates and initialises the ftp client
- def send(self, config, log, obs_id, beam_id): Send the pulsar data to the ftp server Args: config (dict): Dictionary of settings log (logging... | Implement the Python class `PulsarSender` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): Creates and initialises the ftp client
- def send(self, config, log, obs_id, beam_id): Send the pulsar data to the ftp server Args: config (dict): Dictionary of settings log (logging... | 5875dc0489f707232534ce75daf3707f909bcd15 | <|skeleton|>
class PulsarSender:
"""."""
def __init__(self):
"""Creates and initialises the ftp client"""
<|body_0|>
def send(self, config, log, obs_id, beam_id):
"""Send the pulsar data to the ftp server Args: config (dict): Dictionary of settings log (logging.Logger): Python logg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PulsarSender:
"""."""
def __init__(self):
"""Creates and initialises the ftp client"""
self._host = 'localhost'
self._port = 7878
self._ftp = FTP()
self._ftp.connect(self._host, self._port)
self._ftp.login(user='user', passwd='12345')
self._ftp.set_... | the_stack_v2_python_sparse | sip/science_pipeline_workflows/receive_pss/csp_pss_sender/app/pulsar_sender.py | SKA-ScienceDataProcessor/integration-prototype | train | 3 |
0b51bdfc86a1777bcfb0a20b37203f295e515230 | [
"left = 0\nright = x\nmid = (left + right) / 2\nwhile left <= right:\n if mid ** 2 > x:\n right = mid - 1\n else:\n left = mid + 1\n mid = (left + right) / 2\nreturn mid",
"left = 0\nright = x\nmid = (left + right) // 2\nwhile left <= right:\n if mid ** 2 == x:\n return mid\n e... | <|body_start_0|>
left = 0
right = x
mid = (left + right) / 2
while left <= right:
if mid ** 2 > x:
right = mid - 1
else:
left = mid + 1
mid = (left + right) / 2
return mid
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def yourSqrt(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left = 0
right = x
mid = (left + right) / 2
while lef... | stack_v2_sparse_classes_36k_train_024319 | 1,501 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt",
"signature": "def mySqrt(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "yourSqrt",
"signature": "def yourSqrt(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005796 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def yourSqrt(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def yourSqrt(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :r... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def yourSqrt(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
left = 0
right = x
mid = (left + right) / 2
while left <= right:
if mid ** 2 > x:
right = mid - 1
else:
left = mid + 1
mid = (left + right) ... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00069.Sqrt x.py | roger6blog/LeetCode | train | 0 | |
bdf01644535cb33f6ae5cf04df4b49544cf874b0 | [
"length = len(nums)\nif length <= 1:\n return\nk = k % length\nif k > 0:\n nums[:-k], nums[-k:] = (nums[-k:], nums[:-k])",
"if not nums:\n return\nfor _ in range(k):\n nums.insert(0, nums.pop())"
] | <|body_start_0|>
length = len(nums)
if length <= 1:
return
k = k % length
if k > 0:
nums[:-k], nums[-k:] = (nums[-k:], nums[:-k])
<|end_body_0|>
<|body_start_1|>
if not nums:
return
for _ in range(k):
nums.insert(0, nums.po... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_36k_train_024320 | 1,248 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place inste... | 2 | stack_v2_sparse_classes_30k_train_012226 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate1(self, nums, k): :type nums: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate1(self, nums, k): :type nums: List[in... | 3ded7bd0f046e8f87c9b9b9bce81e52ab1bdcdac | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
length = len(nums)
if length <= 1:
return
k = k % length
if k > 0:
nums[:-k], nums[-k:] = (nums[-k:],... | the_stack_v2_python_sparse | leetcode/arrays/rotate.py | JeanChrist/Algorithms | train | 0 | |
ad65ab4f5605831463ca8b4af842b7f47ca6a196 | [
"try:\n print('收到修改班级请求')\n body = json.loads(self.request.body)\n self.sqlhandler = None\n self.stuUid = body['stuUid']\n self.inviteCode = body['inviteCode']\n if self.SetStuClass():\n self.write({'success': True})\n self.finish()\n else:\n raise RuntimeError\nexcept Exce... | <|body_start_0|>
try:
print('收到修改班级请求')
body = json.loads(self.request.body)
self.sqlhandler = None
self.stuUid = body['stuUid']
self.inviteCode = body['inviteCode']
if self.SetStuClass():
self.write({'success': True})
... | StuSetClassRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StuSetClassRequestHandler:
def post(self):
"""获取班级邀请码,写入到数据库"""
<|body_0|>
def SetStuClass(self):
"""给学生设置班级邀请码"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
print('收到修改班级请求')
body = json.loads(self.request.body)
... | stack_v2_sparse_classes_36k_train_024321 | 2,869 | no_license | [
{
"docstring": "获取班级邀请码,写入到数据库",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "给学生设置班级邀请码",
"name": "SetStuClass",
"signature": "def SetStuClass(self)"
}
] | 2 | null | Implement the Python class `StuSetClassRequestHandler` described below.
Class description:
Implement the StuSetClassRequestHandler class.
Method signatures and docstrings:
- def post(self): 获取班级邀请码,写入到数据库
- def SetStuClass(self): 给学生设置班级邀请码 | Implement the Python class `StuSetClassRequestHandler` described below.
Class description:
Implement the StuSetClassRequestHandler class.
Method signatures and docstrings:
- def post(self): 获取班级邀请码,写入到数据库
- def SetStuClass(self): 给学生设置班级邀请码
<|skeleton|>
class StuSetClassRequestHandler:
def post(self):
"... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class StuSetClassRequestHandler:
def post(self):
"""获取班级邀请码,写入到数据库"""
<|body_0|>
def SetStuClass(self):
"""给学生设置班级邀请码"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StuSetClassRequestHandler:
def post(self):
"""获取班级邀请码,写入到数据库"""
try:
print('收到修改班级请求')
body = json.loads(self.request.body)
self.sqlhandler = None
self.stuUid = body['stuUid']
self.inviteCode = body['inviteCode']
if self.S... | the_stack_v2_python_sparse | app/src/main/pythonWork/stuRequest/StuSetClassRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
5b4dd7d8f7eb47890c402f405b1eedcedefecc33 | [
"if not head:\n return True\nslow = head\nfast = head.next\nwhile fast and fast.next:\n fast = fast.next.next\n slow = slow.next\ncur = slow.next\nslow.next = None\np = None\nwhile cur:\n q = cur.next\n cur.next = p\n p = cur\n cur = q\nwhile p and head:\n if p.val != head.val:\n retu... | <|body_start_0|>
if not head:
return True
slow = head
fast = head.next
while fast and fast.next:
fast = fast.next.next
slow = slow.next
cur = slow.next
slow.next = None
p = None
while cur:
q = cur.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:"""
<|body_0|>
def isPalindrome1(self, head: ListNode) -> bool:
"""使用数学方法"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_024322 | 901 | no_license | [
{
"docstring": "1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head: ListNode) -> bool"
},
{
"docstring": "使用数学方法",
"name": "isPalindrome1",
"signature": "def isPalindrome1(self, head: List... | 2 | stack_v2_sparse_classes_30k_train_015034 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: 1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:
- def isPalindrome1(self, head: ListNode) -> bo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: 1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:
- def isPalindrome1(self, head: ListNode) -> bo... | 4328382a65ac612aa4dc397f475c1d7db25c7723 | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:"""
<|body_0|>
def isPalindrome1(self, head: ListNode) -> bool:
"""使用数学方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:"""
if not head:
return True
slow = head
fast = head.next
while fast and fast.next:
fast = fast.next.ne... | the_stack_v2_python_sparse | thor/linklist/ac_234.py | duangduangda/Thor | train | 0 | |
70e6c6a82942332594ccda160a7a4752692ec119 | [
"res = []\nfor i in lists:\n while i:\n res.append(i.val)\n i = i.next\nif res == []:\n return []\nres.sort()\nl = ListNode(0)\nfirst = l\nwhile res:\n l.next = ListNode(res.pop(0))\n l = l.next\nreturn first.next",
"if len(lists) < 1:\n return []\nhead = ListNode(0)\nhead.next = list... | <|body_start_0|>
res = []
for i in lists:
while i:
res.append(i.val)
i = i.next
if res == []:
return []
res.sort()
l = ListNode(0)
first = l
while res:
l.next = ListNode(res.pop(0))
l ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists1(self, lists):
"""不如第一种 :type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
... | stack_v2_sparse_classes_36k_train_024323 | 1,343 | no_license | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": "不如第一种 :type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists1",
"signature": "def mergeKLists1(self, lists)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005761 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists1(self, lists): 不如第一种 :type lists: List[ListNode] :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists1(self, lists): 不如第一种 :type lists: List[ListNode] :rtype: ListNode
<|skeleton|>
class... | 2fb98240258de285b43eae92c187bf36372c9668 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists1(self, lists):
"""不如第一种 :type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
res = []
for i in lists:
while i:
res.append(i.val)
i = i.next
if res == []:
return []
res.sort()
l = ListNode(0)
... | the_stack_v2_python_sparse | 笨蛋为面试做的准备/leetcode/Algorithms and Data Structures/链表/23.合并k个排序链表.py | ICESDHR/Bear-and-Pig | train | 1 | |
9d1c2795f0a9bf3d8a64e65dbf49753e00a56502 | [
"try:\n post = Post.objects.get(slug=args[0], status=1)\n self.check_object_permissions(self.request, post)\n return post\nexcept Post.DoesNotExist:\n raise Http404",
"post = self.get_object(slug)\nserializer = PostDetailSerializer(post, context={'request': request})\nhit_count = HitCount.objects.get_... | <|body_start_0|>
try:
post = Post.objects.get(slug=args[0], status=1)
self.check_object_permissions(self.request, post)
return post
except Post.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
post = self.get_object(slug)
serial... | Return detail information about blogpost. GET : return information. PATCH : edit blogpost. | PostDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostDetail:
"""Return detail information about blogpost. GET : return information. PATCH : edit blogpost."""
def get_object(self, *args, **kwargs):
"""Return object or 404"""
<|body_0|>
def get(self, request, slug):
"""Return detail blogpost information"""
... | stack_v2_sparse_classes_36k_train_024324 | 19,438 | no_license | [
{
"docstring": "Return object or 404",
"name": "get_object",
"signature": "def get_object(self, *args, **kwargs)"
},
{
"docstring": "Return detail blogpost information",
"name": "get",
"signature": "def get(self, request, slug)"
},
{
"docstring": "Edit blogpost fields",
"name... | 3 | stack_v2_sparse_classes_30k_train_003715 | Implement the Python class `PostDetail` described below.
Class description:
Return detail information about blogpost. GET : return information. PATCH : edit blogpost.
Method signatures and docstrings:
- def get_object(self, *args, **kwargs): Return object or 404
- def get(self, request, slug): Return detail blogpost ... | Implement the Python class `PostDetail` described below.
Class description:
Return detail information about blogpost. GET : return information. PATCH : edit blogpost.
Method signatures and docstrings:
- def get_object(self, *args, **kwargs): Return object or 404
- def get(self, request, slug): Return detail blogpost ... | 3e77877d1805ae2b361c9b3f564e73f698a3f4c6 | <|skeleton|>
class PostDetail:
"""Return detail information about blogpost. GET : return information. PATCH : edit blogpost."""
def get_object(self, *args, **kwargs):
"""Return object or 404"""
<|body_0|>
def get(self, request, slug):
"""Return detail blogpost information"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostDetail:
"""Return detail information about blogpost. GET : return information. PATCH : edit blogpost."""
def get_object(self, *args, **kwargs):
"""Return object or 404"""
try:
post = Post.objects.get(slug=args[0], status=1)
self.check_object_permissions(self.re... | the_stack_v2_python_sparse | api/views.py | zagorboda/django-blog | train | 0 |
126771773b18aeaeee6fc47592d43ccbc9344cf3 | [
"super().save_model(request, obj, form, change)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncache.delete('index_page_data')",
"super().delete_model(request, obj)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncach... | <|body_start_0|>
super().save_model(request, obj, form, change)
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')
<|end_body_0|>
<|body_start_1|>
super().delete_model(request, obj)
from celery_tas... | BaseModelAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""向表中添加数据,或者 更新 表中的数据时,调用该方法"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中的数据时,调用该方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().save_model(request, obj, fo... | stack_v2_sparse_classes_36k_train_024325 | 3,109 | no_license | [
{
"docstring": "向表中添加数据,或者 更新 表中的数据时,调用该方法",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "删除表中的数据时,调用该方法",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011004 | Implement the Python class `BaseModelAdmin` described below.
Class description:
Implement the BaseModelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 向表中添加数据,或者 更新 表中的数据时,调用该方法
- def delete_model(self, request, obj): 删除表中的数据时,调用该方法 | Implement the Python class `BaseModelAdmin` described below.
Class description:
Implement the BaseModelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 向表中添加数据,或者 更新 表中的数据时,调用该方法
- def delete_model(self, request, obj): 删除表中的数据时,调用该方法
<|skeleton|>
class BaseModelAdmin... | 6fca25416412603c0952c3fcf931f71acf0f9606 | <|skeleton|>
class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""向表中添加数据,或者 更新 表中的数据时,调用该方法"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中的数据时,调用该方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""向表中添加数据,或者 更新 表中的数据时,调用该方法"""
super().save_model(request, obj, form, change)
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')... | the_stack_v2_python_sparse | apps/goods/admin.py | uhuo/dailyfresh | train | 0 | |
cc75f4d7e6e06f88bf84376aed119aee8edd272d | [
"files = self._get_filesfixedforvulnerability()\nids = self._get_missedvulnerabilityreviewids(files)\nReview.objects.filter(id__in=ids).update(missed_vulnerability=True)\nreturn len(ids)",
"reviews = set()\nfor vulnerability in Vulnerability.objects.all():\n for bug in vulnerability.bugs.all():\n for re... | <|body_start_0|>
files = self._get_filesfixedforvulnerability()
ids = self._get_missedvulnerabilityreviewids(files)
Review.objects.filter(id__in=ids).update(missed_vulnerability=True)
return len(ids)
<|end_body_0|>
<|body_start_1|>
reviews = set()
for vulnerability in Vu... | Implements tagger object. | MissedVulnerabilityTagger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MissedVulnerabilityTagger:
"""Implements tagger object."""
def _tag(self):
"""Tag all of the reviews that missed a vulnerability."""
<|body_0|>
def _get_vulnerabilityfixingreviews(self):
"""Returns a list of reviews that fixed a vulnerability."""
<|body_1... | stack_v2_sparse_classes_36k_train_024326 | 2,297 | no_license | [
{
"docstring": "Tag all of the reviews that missed a vulnerability.",
"name": "_tag",
"signature": "def _tag(self)"
},
{
"docstring": "Returns a list of reviews that fixed a vulnerability.",
"name": "_get_vulnerabilityfixingreviews",
"signature": "def _get_vulnerabilityfixingreviews(self... | 5 | stack_v2_sparse_classes_30k_train_017143 | Implement the Python class `MissedVulnerabilityTagger` described below.
Class description:
Implements tagger object.
Method signatures and docstrings:
- def _tag(self): Tag all of the reviews that missed a vulnerability.
- def _get_vulnerabilityfixingreviews(self): Returns a list of reviews that fixed a vulnerability... | Implement the Python class `MissedVulnerabilityTagger` described below.
Class description:
Implements tagger object.
Method signatures and docstrings:
- def _tag(self): Tag all of the reviews that missed a vulnerability.
- def _get_vulnerabilityfixingreviews(self): Returns a list of reviews that fixed a vulnerability... | b027a5d7407043b6541e2aa02704a7239f109485 | <|skeleton|>
class MissedVulnerabilityTagger:
"""Implements tagger object."""
def _tag(self):
"""Tag all of the reviews that missed a vulnerability."""
<|body_0|>
def _get_vulnerabilityfixingreviews(self):
"""Returns a list of reviews that fixed a vulnerability."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MissedVulnerabilityTagger:
"""Implements tagger object."""
def _tag(self):
"""Tag all of the reviews that missed a vulnerability."""
files = self._get_filesfixedforvulnerability()
ids = self._get_missedvulnerabilityreviewids(files)
Review.objects.filter(id__in=ids).update(... | the_stack_v2_python_sparse | app/lib/taggers/missedvulnerability.py | andymeneely/sira-nlp | train | 1 |
71eec22f52e5bcc839915d474b2404fb52ffe73c | [
"A = list(str(num))\nans = A[:]\nfor i in range(0, len(A)):\n for j in range(i + 1, len(A)):\n A[i], A[j] = (A[j], A[i])\n if A > ans:\n ans = A[:]\n A[i], A[j] = (A[j], A[i])\nreturn int(''.join(ans))",
"A = [int(d) for d in str(num)]\nlast = {x: i for i, x in enumerate(A)}\npr... | <|body_start_0|>
A = list(str(num))
ans = A[:]
for i in range(0, len(A)):
for j in range(i + 1, len(A)):
A[i], A[j] = (A[j], A[i])
if A > ans:
ans = A[:]
A[i], A[j] = (A[j], A[i])
return int(''.join(ans))
<|e... | solution | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""solution"""
def maximum_swap1(self, num):
"""Brute force approach. O(n^3)"""
<|body_0|>
def maximum_swap2(self, num):
"""Greedy approach to solving the problem"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
A = list(str(num))
... | stack_v2_sparse_classes_36k_train_024327 | 1,870 | no_license | [
{
"docstring": "Brute force approach. O(n^3)",
"name": "maximum_swap1",
"signature": "def maximum_swap1(self, num)"
},
{
"docstring": "Greedy approach to solving the problem",
"name": "maximum_swap2",
"signature": "def maximum_swap2(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013954 | Implement the Python class `Solution` described below.
Class description:
solution
Method signatures and docstrings:
- def maximum_swap1(self, num): Brute force approach. O(n^3)
- def maximum_swap2(self, num): Greedy approach to solving the problem | Implement the Python class `Solution` described below.
Class description:
solution
Method signatures and docstrings:
- def maximum_swap1(self, num): Brute force approach. O(n^3)
- def maximum_swap2(self, num): Greedy approach to solving the problem
<|skeleton|>
class Solution:
"""solution"""
def maximum_swa... | e319481834d0d0519d50bbf00e4f46374bbcf091 | <|skeleton|>
class Solution:
"""solution"""
def maximum_swap1(self, num):
"""Brute force approach. O(n^3)"""
<|body_0|>
def maximum_swap2(self, num):
"""Greedy approach to solving the problem"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""solution"""
def maximum_swap1(self, num):
"""Brute force approach. O(n^3)"""
A = list(str(num))
ans = A[:]
for i in range(0, len(A)):
for j in range(i + 1, len(A)):
A[i], A[j] = (A[j], A[i])
if A > ans:
... | the_stack_v2_python_sparse | maximum_swap670.py | raghavgr/Leetcode | train | 1 |
cf2989a1475be7f01e38af99e8c92b541d370bf2 | [
"assert branches, 'At least one branch is required'\nif __debug__:\n for branch in branches:\n assert isinstance(branch, IBranch), 'Invalid branch %s' % branch\nself.branches = branches\nsuper().__init__(function)",
"assert isinstance(calls, list), 'Invalid calls %s' % calls\nassert isinstance(report, I... | <|body_start_0|>
assert branches, 'At least one branch is required'
if __debug__:
for branch in branches:
assert isinstance(branch, IBranch), 'Invalid branch %s' % branch
self.branches = branches
super().__init__(function)
<|end_body_0|>
<|body_start_1|>
... | Implementation for @see: IProcessor that provides branching of other processors containers. | Brancher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Brancher:
"""Implementation for @see: IProcessor that provides branching of other processors containers."""
def __init__(self, function, *branches):
"""Construct the branching processor. @see: Contextual.__init__ @param branches: arguments[IBranch] The branches to use in branching.""... | stack_v2_sparse_classes_36k_train_024328 | 19,255 | no_license | [
{
"docstring": "Construct the branching processor. @see: Contextual.__init__ @param branches: arguments[IBranch] The branches to use in branching.",
"name": "__init__",
"signature": "def __init__(self, function, *branches)"
},
{
"docstring": "@see: IProcessor.register",
"name": "register",
... | 3 | stack_v2_sparse_classes_30k_train_017775 | Implement the Python class `Brancher` described below.
Class description:
Implementation for @see: IProcessor that provides branching of other processors containers.
Method signatures and docstrings:
- def __init__(self, function, *branches): Construct the branching processor. @see: Contextual.__init__ @param branche... | Implement the Python class `Brancher` described below.
Class description:
Implementation for @see: IProcessor that provides branching of other processors containers.
Method signatures and docstrings:
- def __init__(self, function, *branches): Construct the branching processor. @see: Contextual.__init__ @param branche... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class Brancher:
"""Implementation for @see: IProcessor that provides branching of other processors containers."""
def __init__(self, function, *branches):
"""Construct the branching processor. @see: Contextual.__init__ @param branches: arguments[IBranch] The branches to use in branching.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Brancher:
"""Implementation for @see: IProcessor that provides branching of other processors containers."""
def __init__(self, function, *branches):
"""Construct the branching processor. @see: Contextual.__init__ @param branches: arguments[IBranch] The branches to use in branching."""
ass... | the_stack_v2_python_sparse | components/ally/ally/design/processor/processor.py | cristidomsa/Ally-Py | train | 0 |
d04995e55c2d6125504097bc090dfbdf42994686 | [
"super().__init__()\nself.confidence = 1.0 - smoothing\nself.smoothing = smoothing\nself.cls = num_classes\nself.dim = dim",
"assert 0 <= self.smoothing < 1\npred = pred.log_softmax(dim=self.dim)\nwith torch.no_grad():\n true_dist = torch.zeros_like(pred)\n true_dist.fill_(self.smoothing / (self.cls - 1))\n... | <|body_start_0|>
super().__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.cls = num_classes
self.dim = dim
<|end_body_0|>
<|body_start_1|>
assert 0 <= self.smoothing < 1
pred = pred.log_softmax(dim=self.dim)
with torch.no_grad(... | Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1. | LabelSmoothingLoss | [
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothingLoss:
"""Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1."""
... | stack_v2_sparse_classes_36k_train_024329 | 3,691 | permissive | [
{
"docstring": "Initializer for LabelSmoothingLoss. Args: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1.",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_011541 | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across whic... | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across whic... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class LabelSmoothingLoss:
"""Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelSmoothingLoss:
"""Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1."""
def __init_... | the_stack_v2_python_sparse | PyTorch/dev/cv/image_classification/Keyword-MLP_ID2441_for_PyTorch/utils/loss.py | Ascend/ModelZoo-PyTorch | train | 23 |
6d4d5c3d58cdd34b4a49d8f68675a0f6d1bc5dfa | [
"reader = csv.reader(stream)\nnext(reader)\nnext(reader)\nnext(reader)\nline = next(reader)\nwhile line:\n header = line[0]\n assert header.startswith('Employee: ')\n name = header[9:].strip()\n line = self.getEmployeeRecord(employees=employees, records=records, name=name, reader=reader)\nreturn",
"la... | <|body_start_0|>
reader = csv.reader(stream)
next(reader)
next(reader)
next(reader)
line = next(reader)
while line:
header = line[0]
assert header.startswith('Employee: ')
name = header[9:].strip()
line = self.getEmployeeRec... | A parser of the ADP employment records report that contains paystub summary information. | EarningsRecord | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarningsRecord:
"""A parser of the ADP employment records report that contains paystub summary information."""
def parse(self, employees, records, stream):
"""Extract employee earning records from {stream} and populate {records}"""
<|body_0|>
def getEmployeeRecord(self, ... | stack_v2_sparse_classes_36k_train_024330 | 8,078 | no_license | [
{
"docstring": "Extract employee earning records from {stream} and populate {records}",
"name": "parse",
"signature": "def parse(self, employees, records, stream)"
},
{
"docstring": "Extract the paychecks for a given employee",
"name": "getEmployeeRecord",
"signature": "def getEmployeeRe... | 4 | stack_v2_sparse_classes_30k_train_011525 | Implement the Python class `EarningsRecord` described below.
Class description:
A parser of the ADP employment records report that contains paystub summary information.
Method signatures and docstrings:
- def parse(self, employees, records, stream): Extract employee earning records from {stream} and populate {records... | Implement the Python class `EarningsRecord` described below.
Class description:
A parser of the ADP employment records report that contains paystub summary information.
Method signatures and docstrings:
- def parse(self, employees, records, stream): Extract employee earning records from {stream} and populate {records... | 5b1e846d0dcd80934c8238ab0890b2bbb5126d41 | <|skeleton|>
class EarningsRecord:
"""A parser of the ADP employment records report that contains paystub summary information."""
def parse(self, employees, records, stream):
"""Extract employee earning records from {stream} and populate {records}"""
<|body_0|>
def getEmployeeRecord(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EarningsRecord:
"""A parser of the ADP employment records report that contains paystub summary information."""
def parse(self, employees, records, stream):
"""Extract employee earning records from {stream} and populate {records}"""
reader = csv.reader(stream)
next(reader)
... | the_stack_v2_python_sparse | praxis/vendors/adp/EarningsRecord.py | Orthologue/praxis | train | 0 |
4a02a9ed9f7b8a4d78e89bc0c47eb21419f84085 | [
"hc = self.job.hazard_calculation\nnum_points = len(hc.points_to_compute())\nim_data = hc.intensity_measure_types_and_levels\nfor imt, imls in im_data.items():\n hc_prog = models.HazardCurveProgress()\n hc_prog.lt_realization = lt_rlz\n hc_prog.imt = imt\n hc_prog.result_matrix = numpy.zeros((num_points... | <|body_start_0|>
hc = self.job.hazard_calculation
num_points = len(hc.points_to_compute())
im_data = hc.intensity_measure_types_and_levels
for imt, imls in im_data.items():
hc_prog = models.HazardCurveProgress()
hc_prog.lt_realization = lt_rlz
hc_prog.... | Classical PSHA hazard calculator. Computes hazard curves for a given set of points. For each realization of the calculation, we randomly sample source models and GMPEs (Ground Motion Prediction Equations) from logic trees. | ClassicalHazardCalculator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassicalHazardCalculator:
"""Classical PSHA hazard calculator. Computes hazard curves for a given set of points. For each realization of the calculation, we randomly sample source models and GMPEs (Ground Motion Prediction Equations) from logic trees."""
def initialize_hazard_curve_progress... | stack_v2_sparse_classes_36k_train_024331 | 15,176 | no_license | [
{
"docstring": "As a calculation progresses, workers will periodically update the intermediate results. These results will be stored in `htemp.hazard_curve_progress` until the calculation is completed. Before the core calculation begins, we need to initalize these records, one data set per IMT. Each dataset wil... | 4 | null | Implement the Python class `ClassicalHazardCalculator` described below.
Class description:
Classical PSHA hazard calculator. Computes hazard curves for a given set of points. For each realization of the calculation, we randomly sample source models and GMPEs (Ground Motion Prediction Equations) from logic trees.
Meth... | Implement the Python class `ClassicalHazardCalculator` described below.
Class description:
Classical PSHA hazard calculator. Computes hazard curves for a given set of points. For each realization of the calculation, we randomly sample source models and GMPEs (Ground Motion Prediction Equations) from logic trees.
Meth... | d253f09d7848e6cf32e8c7756551436da413176b | <|skeleton|>
class ClassicalHazardCalculator:
"""Classical PSHA hazard calculator. Computes hazard curves for a given set of points. For each realization of the calculation, we randomly sample source models and GMPEs (Ground Motion Prediction Equations) from logic trees."""
def initialize_hazard_curve_progress... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassicalHazardCalculator:
"""Classical PSHA hazard calculator. Computes hazard curves for a given set of points. For each realization of the calculation, we randomly sample source models and GMPEs (Ground Motion Prediction Equations) from logic trees."""
def initialize_hazard_curve_progress(self, lt_rlz... | the_stack_v2_python_sparse | noq/openquake/calculators/hazard/classical/core.py | arbeit/openquake-packages | train | 1 |
81e911ab27e048e0ccb86128cc96852cef530d4f | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nurls = [response.url]\nparts = str(response.url.split('/')[-1])\nparts = parts.split('-', 1)\nposts_per_page = 50\npagination = response.selector.xpath('//table[contains(@class,\"forumline\")]//td[contains(@colspan,\"7\")]/span/a/text()').extract... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
urls = [response.url]
parts = str(response.url.split('/')[-1])
parts = parts.split('-', 1)
posts_per_page = 50
pagination = response.selector.xpath('//table[contains(@class,"forumline")]/... | scrape images from sunnyrhyl forum | SunnyRhylSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SunnyRhylSpider:
"""scrape images from sunnyrhyl forum"""
def parse(self, response):
"""generate links to pages in a board yields: http://sunnyrhyl.forumotion.com/f16-small-boats-section http://sunnyrhyl.forumotion.com/f16p50-small-boats-section"""
<|body_0|>
def crawl_b... | stack_v2_sparse_classes_36k_train_024332 | 4,126 | no_license | [
{
"docstring": "generate links to pages in a board yields: http://sunnyrhyl.forumotion.com/f16-small-boats-section http://sunnyrhyl.forumotion.com/f16p50-small-boats-section",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "response in http://sunnyrhyl.forumotion.com... | 4 | null | Implement the Python class `SunnyRhylSpider` described below.
Class description:
scrape images from sunnyrhyl forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: http://sunnyrhyl.forumotion.com/f16-small-boats-section http://sunnyrhyl.forumotion.com/f16p50-s... | Implement the Python class `SunnyRhylSpider` described below.
Class description:
scrape images from sunnyrhyl forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: http://sunnyrhyl.forumotion.com/f16-small-boats-section http://sunnyrhyl.forumotion.com/f16p50-s... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class SunnyRhylSpider:
"""scrape images from sunnyrhyl forum"""
def parse(self, response):
"""generate links to pages in a board yields: http://sunnyrhyl.forumotion.com/f16-small-boats-section http://sunnyrhyl.forumotion.com/f16p50-small-boats-section"""
<|body_0|>
def crawl_b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SunnyRhylSpider:
"""scrape images from sunnyrhyl forum"""
def parse(self, response):
"""generate links to pages in a board yields: http://sunnyrhyl.forumotion.com/f16-small-boats-section http://sunnyrhyl.forumotion.com/f16p50-small-boats-section"""
assert isinstance(response, scrapy.http.... | the_stack_v2_python_sparse | imgscrape/spiders/sunnyrhyl.py | gmonkman/python | train | 0 |
7d2e28218d744b11908fdc0441cd52f3aa2550c4 | [
"if not form.validate_on_submit():\n logging.debug(messages.INVALID_FORM_MESSAGE, form.errors)\n raise HttpException(messages.INVALID_FORM_MESSAGE, constants.BAD_REQUEST, 400)\nuser_id = get_current_user_id()\nadd_todo_list_id = False\ndata = {'user_id_fk': user_id, 'parent_todo_item_id_fk': form.parent_todo_... | <|body_start_0|>
if not form.validate_on_submit():
logging.debug(messages.INVALID_FORM_MESSAGE, form.errors)
raise HttpException(messages.INVALID_FORM_MESSAGE, constants.BAD_REQUEST, 400)
user_id = get_current_user_id()
add_todo_list_id = False
data = {'user_id_fk... | TodoItemData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TodoItemData:
def todo_item_add(form):
"""Add todo item"""
<|body_0|>
def assign_todo_item(form):
"""Assign todo item follower"""
<|body_1|>
def get_assign_todo_item(query_params):
"""Get Assign todo item follower"""
<|body_2|>
def a... | stack_v2_sparse_classes_36k_train_024333 | 6,396 | no_license | [
{
"docstring": "Add todo item",
"name": "todo_item_add",
"signature": "def todo_item_add(form)"
},
{
"docstring": "Assign todo item follower",
"name": "assign_todo_item",
"signature": "def assign_todo_item(form)"
},
{
"docstring": "Get Assign todo item follower",
"name": "get... | 4 | stack_v2_sparse_classes_30k_train_014942 | Implement the Python class `TodoItemData` described below.
Class description:
Implement the TodoItemData class.
Method signatures and docstrings:
- def todo_item_add(form): Add todo item
- def assign_todo_item(form): Assign todo item follower
- def get_assign_todo_item(query_params): Get Assign todo item follower
- d... | Implement the Python class `TodoItemData` described below.
Class description:
Implement the TodoItemData class.
Method signatures and docstrings:
- def todo_item_add(form): Add todo item
- def assign_todo_item(form): Assign todo item follower
- def get_assign_todo_item(query_params): Get Assign todo item follower
- d... | c84d51d67e93fd6be82fa9b8d54e8a860cf74053 | <|skeleton|>
class TodoItemData:
def todo_item_add(form):
"""Add todo item"""
<|body_0|>
def assign_todo_item(form):
"""Assign todo item follower"""
<|body_1|>
def get_assign_todo_item(query_params):
"""Get Assign todo item follower"""
<|body_2|>
def a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TodoItemData:
def todo_item_add(form):
"""Add todo item"""
if not form.validate_on_submit():
logging.debug(messages.INVALID_FORM_MESSAGE, form.errors)
raise HttpException(messages.INVALID_FORM_MESSAGE, constants.BAD_REQUEST, 400)
user_id = get_current_user_id()
... | the_stack_v2_python_sparse | todo_app/services/todo_item_management_service/todo_item_management_data.py | DhruvaDave/flask-todo-app | train | 0 | |
8f619b315680a2668da15e52f2c309258bc20ef0 | [
"if not include_boot_reasons and (not exclude_boot_reasons):\n raise ValueError('One or both of `include_boot_reasons` and `exclude_boot_reasons` must be specified.')\nsuper(CrashreportCounterFilter, self).__init__(model=Crashreport, name=name, field_name=field_name)\nself.include_boot_reasons = include_boot_rea... | <|body_start_0|>
if not include_boot_reasons and (not exclude_boot_reasons):
raise ValueError('One or both of `include_boot_reasons` and `exclude_boot_reasons` must be specified.')
super(CrashreportCounterFilter, self).__init__(model=Crashreport, name=name, field_name=field_name)
sel... | The crashreports counter filter. Attributes: include_boot_reasons: The boot reasons assumed to characterise this crashreport ("OR"ed). exclude_boot_reasons: The boot reasons assumed to *not* characterise this crashreport ( "AND"ed). inclusive_filter: The boot reasons filter for filtering reports that should be included... | CrashreportCounterFilter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrashreportCounterFilter:
"""The crashreports counter filter. Attributes: include_boot_reasons: The boot reasons assumed to characterise this crashreport ("OR"ed). exclude_boot_reasons: The boot reasons assumed to *not* characterise this crashreport ( "AND"ed). inclusive_filter: The boot reasons ... | stack_v2_sparse_classes_36k_train_024334 | 17,973 | permissive | [
{
"docstring": "Initialise the filter. One or both of `include_boot_reasons` and `exclude_boot_reasons` must be specified. Args: name: The human-readable report counter name. field_name: The counter name as defined in the stats model where it is a field. include_boot_reasons: The boot reasons assumed to charact... | 3 | stack_v2_sparse_classes_30k_train_021263 | Implement the Python class `CrashreportCounterFilter` described below.
Class description:
The crashreports counter filter. Attributes: include_boot_reasons: The boot reasons assumed to characterise this crashreport ("OR"ed). exclude_boot_reasons: The boot reasons assumed to *not* characterise this crashreport ( "AND"e... | Implement the Python class `CrashreportCounterFilter` described below.
Class description:
The crashreports counter filter. Attributes: include_boot_reasons: The boot reasons assumed to characterise this crashreport ("OR"ed). exclude_boot_reasons: The boot reasons assumed to *not* characterise this crashreport ( "AND"e... | 8b80109740ea663d23ca46bb272c8fd95f873f1e | <|skeleton|>
class CrashreportCounterFilter:
"""The crashreports counter filter. Attributes: include_boot_reasons: The boot reasons assumed to characterise this crashreport ("OR"ed). exclude_boot_reasons: The boot reasons assumed to *not* characterise this crashreport ( "AND"ed). inclusive_filter: The boot reasons ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrashreportCounterFilter:
"""The crashreports counter filter. Attributes: include_boot_reasons: The boot reasons assumed to characterise this crashreport ("OR"ed). exclude_boot_reasons: The boot reasons assumed to *not* characterise this crashreport ( "AND"ed). inclusive_filter: The boot reasons filter for fi... | the_stack_v2_python_sparse | crashreport_stats/management/commands/stats.py | FairphoneMirrors/hiccup-server | train | 0 |
48c4f3611ffc55cdc3a205da40acae304b5aa69e | [
"if os.path.isfile(path):\n with open(path, 'rb') as file:\n return (file.read(), True)\nif save:\n return (cls.fetch_and_save(url, path), False)\nreturn (cls.fetch_with_retry(url), False)",
"content = cls.fetch_with_retry(url)\nif not content:\n return False\nwith open(path, 'wb') as file:\n f... | <|body_start_0|>
if os.path.isfile(path):
with open(path, 'rb') as file:
return (file.read(), True)
if save:
return (cls.fetch_and_save(url, path), False)
return (cls.fetch_with_retry(url), False)
<|end_body_0|>
<|body_start_1|>
content = cls.fetc... | Fetcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fetcher:
def fetch_maybe(cls, url, path, save=False):
"""Fetch from url or from file if it has been cached previously"""
<|body_0|>
def fetch_and_save(cls, url, path):
"""Fetch file and save to disk"""
<|body_1|>
def fetch_with_retry(cls, url):
"... | stack_v2_sparse_classes_36k_train_024335 | 2,471 | no_license | [
{
"docstring": "Fetch from url or from file if it has been cached previously",
"name": "fetch_maybe",
"signature": "def fetch_maybe(cls, url, path, save=False)"
},
{
"docstring": "Fetch file and save to disk",
"name": "fetch_and_save",
"signature": "def fetch_and_save(cls, url, path)"
... | 4 | stack_v2_sparse_classes_30k_train_016355 | Implement the Python class `Fetcher` described below.
Class description:
Implement the Fetcher class.
Method signatures and docstrings:
- def fetch_maybe(cls, url, path, save=False): Fetch from url or from file if it has been cached previously
- def fetch_and_save(cls, url, path): Fetch file and save to disk
- def fe... | Implement the Python class `Fetcher` described below.
Class description:
Implement the Fetcher class.
Method signatures and docstrings:
- def fetch_maybe(cls, url, path, save=False): Fetch from url or from file if it has been cached previously
- def fetch_and_save(cls, url, path): Fetch file and save to disk
- def fe... | 31f29e374d8668c92f1b1c48b2d38c967f5e145f | <|skeleton|>
class Fetcher:
def fetch_maybe(cls, url, path, save=False):
"""Fetch from url or from file if it has been cached previously"""
<|body_0|>
def fetch_and_save(cls, url, path):
"""Fetch file and save to disk"""
<|body_1|>
def fetch_with_retry(cls, url):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fetcher:
def fetch_maybe(cls, url, path, save=False):
"""Fetch from url or from file if it has been cached previously"""
if os.path.isfile(path):
with open(path, 'rb') as file:
return (file.read(), True)
if save:
return (cls.fetch_and_save(url, p... | the_stack_v2_python_sparse | fetcher.py | mideind/thesis-corpus | train | 0 | |
ecc778cca74b90d35f60ab2c946dc765e96159d9 | [
"try:\n service_name = rocon_python_comms.find_service('rocon_interaction_msgs/SetInteractions', timeout=rospy.rostime.Duration(15.0), unique=True)\nexcept rocon_python_comms.NotFoundException as e:\n raise rocon_python_comms.NotFoundException(\"failed to find unique service of type 'rocon_interaction_msgs/Se... | <|body_start_0|>
try:
service_name = rocon_python_comms.find_service('rocon_interaction_msgs/SetInteractions', timeout=rospy.rostime.Duration(15.0), unique=True)
except rocon_python_comms.NotFoundException as e:
raise rocon_python_comms.NotFoundException("failed to find unique se... | This class is responsible for loading the role manager with the roles and app specifications provided in the service definitions. | InteractionsLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractionsLoader:
"""This class is responsible for loading the role manager with the roles and app specifications provided in the service definitions."""
def __init__(self):
"""Don't do any loading here, just set up infrastructure and overrides from the solution. :raises: rocon_pyt... | stack_v2_sparse_classes_36k_train_024336 | 5,357 | no_license | [
{
"docstring": "Don't do any loading here, just set up infrastructure and overrides from the solution. :raises: rocon_python_comms.NotFoundException, rospy.exceptions.ROSException, rospy.exceptions.ROSInterruptException",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "P... | 3 | null | Implement the Python class `InteractionsLoader` described below.
Class description:
This class is responsible for loading the role manager with the roles and app specifications provided in the service definitions.
Method signatures and docstrings:
- def __init__(self): Don't do any loading here, just set up infrastru... | Implement the Python class `InteractionsLoader` described below.
Class description:
This class is responsible for loading the role manager with the roles and app specifications provided in the service definitions.
Method signatures and docstrings:
- def __init__(self): Don't do any loading here, just set up infrastru... | 1f182537b26e8622eefaf6737d3b3d18b1741ca6 | <|skeleton|>
class InteractionsLoader:
"""This class is responsible for loading the role manager with the roles and app specifications provided in the service definitions."""
def __init__(self):
"""Don't do any loading here, just set up infrastructure and overrides from the solution. :raises: rocon_pyt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InteractionsLoader:
"""This class is responsible for loading the role manager with the roles and app specifications provided in the service definitions."""
def __init__(self):
"""Don't do any loading here, just set up infrastructure and overrides from the solution. :raises: rocon_python_comms.Not... | the_stack_v2_python_sparse | rocon_interactions/src/rocon_interactions/loader.py | robotics-in-concert/rocon_tools | train | 7 |
d7406678333c1c8435a770bb0a5268891ee289f8 | [
"values = []\nwhile head:\n values.append(head.val)\n head = head.next\nreturn values",
"values = self.mapListToValues(head)\n\ndef convertListToBST(left, right):\n if left > right:\n return None\n mid = (left + right) // 2\n node = TreeNode(values[mid])\n if left == right:\n retur... | <|body_start_0|>
values = []
while head:
values.append(head.val)
head = head.next
return values
<|end_body_0|>
<|body_start_1|>
values = self.mapListToValues(head)
def convertListToBST(left, right):
if left > right:
return Non... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mapListToValues(self, head):
""":type head: ListNode :rtype: List[int]"""
<|body_0|>
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
values = []
while he... | stack_v2_sparse_classes_36k_train_024337 | 2,113 | no_license | [
{
"docstring": ":type head: ListNode :rtype: List[int]",
"name": "mapListToValues",
"signature": "def mapListToValues(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: TreeNode",
"name": "sortedListToBST",
"signature": "def sortedListToBST(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mapListToValues(self, head): :type head: ListNode :rtype: List[int]
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mapListToValues(self, head): :type head: ListNode :rtype: List[int]
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
<|skeleton|>
class Solution:
... | 6bee015dac47603253018fd773920e62b29f3f20 | <|skeleton|>
class Solution:
def mapListToValues(self, head):
""":type head: ListNode :rtype: List[int]"""
<|body_0|>
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mapListToValues(self, head):
""":type head: ListNode :rtype: List[int]"""
values = []
while head:
values.append(head.val)
head = head.next
return values
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"... | the_stack_v2_python_sparse | 109-convert-sorted-list-to-binary-search-tree.py | nanli-7/algorithms | train | 4 | |
1bd78361973ef25c40bbe8f1be88320cb1a44af8 | [
"result = self.init_parameter()\nanswer_id = self.get_argument('answer_id')\nanswer = self.answer_model.get(answer_id).get('_source')\nanswers = []\nfor emotion_value, emotion in self.answer_model.emotion_dict.items():\n for answer_ in answer.get('answers', []):\n if emotion_value == answer_.get('emotion'... | <|body_start_0|>
result = self.init_parameter()
answer_id = self.get_argument('answer_id')
answer = self.answer_model.get(answer_id).get('_source')
answers = []
for emotion_value, emotion in self.answer_model.emotion_dict.items():
for answer_ in answer.get('answers', ... | AnswerInfoDetailHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnswerInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取答案详细信息 :param args: :param kwargs: :return:"""
<|body_0|>
def put(self):
"""修改答案数据 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = self.init_parameter()
answer_i... | stack_v2_sparse_classes_36k_train_024338 | 2,681 | no_license | [
{
"docstring": "获取答案详细信息 :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "修改答案数据 :return:",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016452 | Implement the Python class `AnswerInfoDetailHandler` described below.
Class description:
Implement the AnswerInfoDetailHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 获取答案详细信息 :param args: :param kwargs: :return:
- def put(self): 修改答案数据 :return: | Implement the Python class `AnswerInfoDetailHandler` described below.
Class description:
Implement the AnswerInfoDetailHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 获取答案详细信息 :param args: :param kwargs: :return:
- def put(self): 修改答案数据 :return:
<|skeleton|>
class AnswerInfoDetailH... | 9781b183cf168832b3c962d420e7f0a63287c4db | <|skeleton|>
class AnswerInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取答案详细信息 :param args: :param kwargs: :return:"""
<|body_0|>
def put(self):
"""修改答案数据 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnswerInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取答案详细信息 :param args: :param kwargs: :return:"""
result = self.init_parameter()
answer_id = self.get_argument('answer_id')
answer = self.answer_model.get(answer_id).get('_source')
answers = []
for emoti... | the_stack_v2_python_sparse | chat_bot/handlers/bot_manage/answer_info.py | jiaojianglong/MyBot | train | 0 | |
ed846e615602f0e5c4f9087e6f59dae5e34e1d30 | [
"self.file_name = file_name\nself.file_handler = None\nreturn",
"print('enter:', self.file_name)\nself.file_handler = open(self.file_name, 'r')\nreturn self.file_handler",
"print('exit:', exc_type, exc_val, exc_tb)\nif self.file_handler:\n self.file_handler.close()\nreturn False"
] | <|body_start_0|>
self.file_name = file_name
self.file_handler = None
return
<|end_body_0|>
<|body_start_1|>
print('enter:', self.file_name)
self.file_handler = open(self.file_name, 'r')
return self.file_handler
<|end_body_1|>
<|body_start_2|>
print('exit:', exc_... | MyOpen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyOpen:
def __init__(self, file_name):
"""初始化方法"""
<|body_0|>
def __enter__(self):
"""enter方法,返回file_handler"""
<|body_1|>
def __exit__(self, exc_type, exc_val, exc_tb):
"""exit方法,关闭文件并返回True"""
<|body_2|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_024339 | 910 | no_license | [
{
"docstring": "初始化方法",
"name": "__init__",
"signature": "def __init__(self, file_name)"
},
{
"docstring": "enter方法,返回file_handler",
"name": "__enter__",
"signature": "def __enter__(self)"
},
{
"docstring": "exit方法,关闭文件并返回True",
"name": "__exit__",
"signature": "def __exi... | 3 | stack_v2_sparse_classes_30k_train_010058 | Implement the Python class `MyOpen` described below.
Class description:
Implement the MyOpen class.
Method signatures and docstrings:
- def __init__(self, file_name): 初始化方法
- def __enter__(self): enter方法,返回file_handler
- def __exit__(self, exc_type, exc_val, exc_tb): exit方法,关闭文件并返回True | Implement the Python class `MyOpen` described below.
Class description:
Implement the MyOpen class.
Method signatures and docstrings:
- def __init__(self, file_name): 初始化方法
- def __enter__(self): enter方法,返回file_handler
- def __exit__(self, exc_type, exc_val, exc_tb): exit方法,关闭文件并返回True
<|skeleton|>
class MyOpen:
... | a0202c81372758922128dc6e4c8911849f2663ad | <|skeleton|>
class MyOpen:
def __init__(self, file_name):
"""初始化方法"""
<|body_0|>
def __enter__(self):
"""enter方法,返回file_handler"""
<|body_1|>
def __exit__(self, exc_type, exc_val, exc_tb):
"""exit方法,关闭文件并返回True"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyOpen:
def __init__(self, file_name):
"""初始化方法"""
self.file_name = file_name
self.file_handler = None
return
def __enter__(self):
"""enter方法,返回file_handler"""
print('enter:', self.file_name)
self.file_handler = open(self.file_name, 'r')
ret... | the_stack_v2_python_sparse | 核心编程_2/chapter_10_error/10.4_context_management/10.4.2_context_management_protocol/My_with.py | MonsterDragon/play_python | train | 1 | |
77beaa7bd4c490cf4948c4ca25bb5d3c25483a9d | [
"super(TestMarginsParams, self).__init__(parent=parent)\nself.setupUi(self)\nsession = Session()\nlist_names = [result.name for result in session.query(List.name).filter_by(is_amazon=True).all()]\nself.listBox.addItems(list_names)",
"params = {}\nparams['confidence'] = self.confidenceBox.value()\nparams['threshol... | <|body_start_0|>
super(TestMarginsParams, self).__init__(parent=parent)
self.setupUi(self)
session = Session()
list_names = [result.name for result in session.query(List.name).filter_by(is_amazon=True).all()]
self.listBox.addItems(list_names)
<|end_body_0|>
<|body_start_1|>
... | A widget for specifying parameters for the TestMargins operation. | TestMarginsParams | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMarginsParams:
"""A widget for specifying parameters for the TestMargins operation."""
def __init__(self, parent=None):
"""Initialize the widget."""
<|body_0|>
def params(self):
"""Return the selected parameters as a dictionary."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_024340 | 25,458 | no_license | [
{
"docstring": "Initialize the widget.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Return the selected parameters as a dictionary.",
"name": "params",
"signature": "def params(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009894 | Implement the Python class `TestMarginsParams` described below.
Class description:
A widget for specifying parameters for the TestMargins operation.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize the widget.
- def params(self): Return the selected parameters as a dictionary. | Implement the Python class `TestMarginsParams` described below.
Class description:
A widget for specifying parameters for the TestMargins operation.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize the widget.
- def params(self): Return the selected parameters as a dictionary.
<|skelet... | 7d22707a1782125d86140c52d20eaadd2df6e4fc | <|skeleton|>
class TestMarginsParams:
"""A widget for specifying parameters for the TestMargins operation."""
def __init__(self, parent=None):
"""Initialize the widget."""
<|body_0|>
def params(self):
"""Return the selected parameters as a dictionary."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMarginsParams:
"""A widget for specifying parameters for the TestMargins operation."""
def __init__(self, parent=None):
"""Initialize the widget."""
super(TestMarginsParams, self).__init__(parent=parent)
self.setupUi(self)
session = Session()
list_names = [resu... | the_stack_v2_python_sparse | dialogs.py | garrettmk/Prowler | train | 1 |
1f9a6aa521b4ac6948a8c0b58b34a7d90001a3da | [
"self.measures_per_point = 3\nself.nr_points = 15\nself.ts_screen_number = 1\nself.ramp_config = 'bo_ramp_flop_emit_exchange_slower'\nself.init_delay = -3\nself.final_delay = 3\nself.roix = [500, 800]\nself.roiy = [400, 600]\nself.line_window = 4",
"ftmp = '{0:26s} = {1:9.6f} {2:s}\\n'.format\ndtmp = '{0:26s} = ... | <|body_start_0|>
self.measures_per_point = 3
self.nr_points = 15
self.ts_screen_number = 1
self.ramp_config = 'bo_ramp_flop_emit_exchange_slower'
self.init_delay = -3
self.final_delay = 3
self.roix = [500, 800]
self.roiy = [400, 600]
self.line_wind... | . | BeamSizesParams | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BeamSizesParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.measures_per_point = 3
self.nr_points = 15
self.ts_screen_number = 1
self.ramp_c... | stack_v2_sparse_classes_36k_train_024341 | 13,094 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ".",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `BeamSizesParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): . | Implement the Python class `BeamSizesParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): .
<|skeleton|>
class BeamSizesParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
... | 39644161d98964a3a3d80d63269201f0a1712e82 | <|skeleton|>
class BeamSizesParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BeamSizesParams:
"""."""
def __init__(self):
"""."""
self.measures_per_point = 3
self.nr_points = 15
self.ts_screen_number = 1
self.ramp_config = 'bo_ramp_flop_emit_exchange_slower'
self.init_delay = -3
self.final_delay = 3
self.roix = [500,... | the_stack_v2_python_sparse | apsuite/commisslib/emit_exchange/beam_sizes.py | lnls-fac/apsuite | train | 1 |
58aa43c4b3a65689074bc53d4bafef1370ebf0e8 | [
"def _build(pre_start, pre_end, in_start, in_end):\n if pre_start == pre_end:\n return None\n root_val = preorder[pre_start]\n idx = inorder[in_start:in_end].index(root_val)\n root_node = TreeNode(root_val)\n left_node = _build(pre_start + 1, pre_start + 1 + idx, in_start, in_start + idx)\n ... | <|body_start_0|>
def _build(pre_start, pre_end, in_start, in_end):
if pre_start == pre_end:
return None
root_val = preorder[pre_start]
idx = inorder[in_start:in_end].index(root_val)
root_node = TreeNode(root_val)
left_node = _build(pre_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTruee(self, preorder, inorder):
"""memory limit exceeded %>_<%"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_024342 | 1,597 | no_license | [
{
"docstring": ":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, preorder, inorder)"
},
{
"docstring": "memory limit exceeded %>_<%",
"name": "buildTruee",
"signature": "def buildTruee(self, preorder, inorder)"
... | 2 | stack_v2_sparse_classes_30k_train_011920 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def buildTruee(self, preorder, inorder): memory limit exceeded %>_<% | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def buildTruee(self, preorder, inorder): memory limit exceeded %>_<%... | b7f85afe1c69f34f8c6025881224ae79042850d3 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTruee(self, preorder, inorder):
"""memory limit exceeded %>_<%"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
def _build(pre_start, pre_end, in_start, in_end):
if pre_start == pre_end:
return None
root_val = preorder[pre_start]
... | the_stack_v2_python_sparse | algorithms/105. Construct Binary Tree from Preorder and Inorder Traversal/main.py | GTxx/leetcode | train | 1 | |
2fea1ecc6bedcc6d48e75ffea93a4016faf929bc | [
"if isinstance(val, str):\n type_ = cls._name2shape[val]\n prms = [(), None]\nelse:\n type_ = cls._name2shape[val[0]]\n prms = val[1:]\nreturn type_(*prms)",
"if isinstance(vals, str):\n vals = [[vals, (), None]]\nelif isinstance(vals[0], str):\n vals = [vals]\nshapes = [cls.make1(val) for val i... | <|body_start_0|>
if isinstance(val, str):
type_ = cls._name2shape[val]
prms = [(), None]
else:
type_ = cls._name2shape[val[0]]
prms = val[1:]
return type_(*prms)
<|end_body_0|>
<|body_start_1|>
if isinstance(vals, str):
vals = ... | Utility class for making *Shape objects and reading BulletShapes. | ShapeManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShapeManager:
"""Utility class for making *Shape objects and reading BulletShapes."""
def make1(cls, val):
"""Initialize a *Shape object from input."""
<|body_0|>
def make(cls, vals):
"""Standardizes list of vals."""
<|body_1|>
def read(cls, node):
... | stack_v2_sparse_classes_36k_train_024343 | 19,768 | permissive | [
{
"docstring": "Initialize a *Shape object from input.",
"name": "make1",
"signature": "def make1(cls, val)"
},
{
"docstring": "Standardizes list of vals.",
"name": "make",
"signature": "def make(cls, vals)"
},
{
"docstring": "Get shape list from Bullet*Shape(s).",
"name": "r... | 3 | stack_v2_sparse_classes_30k_train_012132 | Implement the Python class `ShapeManager` described below.
Class description:
Utility class for making *Shape objects and reading BulletShapes.
Method signatures and docstrings:
- def make1(cls, val): Initialize a *Shape object from input.
- def make(cls, vals): Standardizes list of vals.
- def read(cls, node): Get s... | Implement the Python class `ShapeManager` described below.
Class description:
Utility class for making *Shape objects and reading BulletShapes.
Method signatures and docstrings:
- def make1(cls, val): Initialize a *Shape object from input.
- def make(cls, vals): Standardizes list of vals.
- def read(cls, node): Get s... | 2633c63bc5cb97ea99017b2e25fc9b4f66d72605 | <|skeleton|>
class ShapeManager:
"""Utility class for making *Shape objects and reading BulletShapes."""
def make1(cls, val):
"""Initialize a *Shape object from input."""
<|body_0|>
def make(cls, vals):
"""Standardizes list of vals."""
<|body_1|>
def read(cls, node):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShapeManager:
"""Utility class for making *Shape objects and reading BulletShapes."""
def make1(cls, val):
"""Initialize a *Shape object from input."""
if isinstance(val, str):
type_ = cls._name2shape[val]
prms = [(), None]
else:
type_ = cls._na... | the_stack_v2_python_sparse | scenesim/objects/pso.py | pbattaglia/scenesim | train | 9 |
3fcab16c1ba2b05d1eacfa1a84dd73d47f9ec8ec | [
"self.outages = outages\nself.seed = seed\nself.total_losses = np.zeros(8760)\nself.can_schedule_more = np.full(8760, True)",
"sorted_outages = sorted(self.outages, key=lambda o: (o.duration, o.count, o.percentage_of_capacity_lost, sum((sum(map(ord, name)) for name in o.allowed_months)), o.allow_outage_overlap))\... | <|body_start_0|>
self.outages = outages
self.seed = seed
self.total_losses = np.zeros(8760)
self.can_schedule_more = np.full(8760, True)
<|end_body_0|>
<|body_start_1|>
sorted_outages = sorted(self.outages, key=lambda o: (o.duration, o.count, o.percentage_of_capacity_lost, sum((... | A scheduler for multiple input outages. Given a list of information about different types of desired outages, this class leverages the stochastic scheduling routines of :class:`SingleOutageScheduler` to calculate the total losses due to the input outages on an hourly basis. Attributes ---------- outages : :obj:`list` o... | OutageScheduler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutageScheduler:
"""A scheduler for multiple input outages. Given a list of information about different types of desired outages, this class leverages the stochastic scheduling routines of :class:`SingleOutageScheduler` to calculate the total losses due to the input outages on an hourly basis. At... | stack_v2_sparse_classes_36k_train_024344 | 26,452 | permissive | [
{
"docstring": "Parameters ---------- outages : list of :obj:`Outages <Outage>` A list of :obj:`Outages <Outage>`, where each :obj:`Outage` contains info about a single type of outage. See the documentation of :class:`Outage` for a description of the required keys of each outage dictionary. seed : int, optional... | 2 | null | Implement the Python class `OutageScheduler` described below.
Class description:
A scheduler for multiple input outages. Given a list of information about different types of desired outages, this class leverages the stochastic scheduling routines of :class:`SingleOutageScheduler` to calculate the total losses due to t... | Implement the Python class `OutageScheduler` described below.
Class description:
A scheduler for multiple input outages. Given a list of information about different types of desired outages, this class leverages the stochastic scheduling routines of :class:`SingleOutageScheduler` to calculate the total losses due to t... | 497bb7d172197e09a9e14b1b1ca891b8c828b80a | <|skeleton|>
class OutageScheduler:
"""A scheduler for multiple input outages. Given a list of information about different types of desired outages, this class leverages the stochastic scheduling routines of :class:`SingleOutageScheduler` to calculate the total losses due to the input outages on an hourly basis. At... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutageScheduler:
"""A scheduler for multiple input outages. Given a list of information about different types of desired outages, this class leverages the stochastic scheduling routines of :class:`SingleOutageScheduler` to calculate the total losses due to the input outages on an hourly basis. Attributes ----... | the_stack_v2_python_sparse | reV/losses/scheduled.py | NREL/reV | train | 53 |
f3516c908bdf8ff8cf6fe5dc6bcebfe2a75add6d | [
"mu = self.variational_mean\nsqrt = self.variational_root_covariance\nsqrt = LowerTriangularLinearOperator.from_dense(sqrt)\nS = DenseLinearOperator.from_root(sqrt)\nqu = GaussianDistribution(loc=jnp.atleast_1d(mu.squeeze()), scale=S)\npu = GaussianDistribution(loc=jnp.zeros_like(jnp.atleast_1d(mu.squeeze())))\nret... | <|body_start_0|>
mu = self.variational_mean
sqrt = self.variational_root_covariance
sqrt = LowerTriangularLinearOperator.from_dense(sqrt)
S = DenseLinearOperator.from_root(sqrt)
qu = GaussianDistribution(loc=jnp.atleast_1d(mu.squeeze()), scale=S)
pu = GaussianDistribution... | The whitened variational Gaussian family of probability distributions. The variational family is $`q(f(\\cdot)) = \\int p(f(\\cdot)\\mid u) q(u) \\mathrm{d}u`$, where $`u = f(z)`$ are the function values at the inducing inputs $`z`$ and the distribution over the inducing inputs is $`q(u) = \\mathcal{N}(Lz \\mu + mz, Lz... | WhitenedVariationalGaussian | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhitenedVariationalGaussian:
"""The whitened variational Gaussian family of probability distributions. The variational family is $`q(f(\\cdot)) = \\int p(f(\\cdot)\\mid u) q(u) \\mathrm{d}u`$, where $`u = f(z)`$ are the function values at the inducing inputs $`z`$ and the distribution over the in... | stack_v2_sparse_classes_36k_train_024345 | 26,453 | permissive | [
{
"docstring": "Compute the KL-divergence between our variational approximation and the Gaussian process prior. For this variational family, we have ```math \\\\begin{align} \\\\operatorname{KL}[q(f(\\\\cdot))\\\\mid\\\\mid p(\\\\cdot)] & = \\\\operatorname{KL}[q(u)\\\\mid\\\\mid p(u)]\\\\\\\\ & = \\\\operatorn... | 2 | stack_v2_sparse_classes_30k_train_018901 | Implement the Python class `WhitenedVariationalGaussian` described below.
Class description:
The whitened variational Gaussian family of probability distributions. The variational family is $`q(f(\\cdot)) = \\int p(f(\\cdot)\\mid u) q(u) \\mathrm{d}u`$, where $`u = f(z)`$ are the function values at the inducing inputs... | Implement the Python class `WhitenedVariationalGaussian` described below.
Class description:
The whitened variational Gaussian family of probability distributions. The variational family is $`q(f(\\cdot)) = \\int p(f(\\cdot)\\mid u) q(u) \\mathrm{d}u`$, where $`u = f(z)`$ are the function values at the inducing inputs... | b5009ec975bf25474055cf252297ff9ac462d9f5 | <|skeleton|>
class WhitenedVariationalGaussian:
"""The whitened variational Gaussian family of probability distributions. The variational family is $`q(f(\\cdot)) = \\int p(f(\\cdot)\\mid u) q(u) \\mathrm{d}u`$, where $`u = f(z)`$ are the function values at the inducing inputs $`z`$ and the distribution over the in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WhitenedVariationalGaussian:
"""The whitened variational Gaussian family of probability distributions. The variational family is $`q(f(\\cdot)) = \\int p(f(\\cdot)\\mid u) q(u) \\mathrm{d}u`$, where $`u = f(z)`$ are the function values at the inducing inputs $`z`$ and the distribution over the inducing inputs... | the_stack_v2_python_sparse | gpjax/variational_families.py | JaxGaussianProcesses/GPJax | train | 129 |
b63f040109ebc0a77f7cd0fd6c2a330601983155 | [
"log.info('Start static topology creation...')\nlog.debug('Create Switch with name: SW1')\nsw1 = self.addSwitch('SW1')\nlog.debug('Create Switch with name: SW2')\nsw2 = self.addSwitch('SW2')\nlog.debug('Create Switch with name: SW3')\nsw3 = self.addSwitch('SW3')\nlog.debug('Create Switch with name: SW4')\nsw4 = sel... | <|body_start_0|>
log.info('Start static topology creation...')
log.debug('Create Switch with name: SW1')
sw1 = self.addSwitch('SW1')
log.debug('Create Switch with name: SW2')
sw2 = self.addSwitch('SW2')
log.debug('Create Switch with name: SW3')
sw3 = self.addSwitc... | Topology class for testing purposes and serve as a fallback topology. Use the static way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | SW1 | | SW2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----------+ +----------+ | |2 2| | | SW3 +-----------+ SW4 | | | | | +----------+ +----------... | FallbackStaticTopology | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FallbackStaticTopology:
"""Topology class for testing purposes and serve as a fallback topology. Use the static way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | SW1 | | SW2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----------+ +----------+ | |2 2| | | SW3 +-... | stack_v2_sparse_classes_36k_train_024346 | 40,815 | permissive | [
{
"docstring": "Assemble the topology description statically. :param builder: optional builder object :return: self :rtype: :any:`FallbackStaticTopology`",
"name": "construct",
"signature": "def construct(self, builder=None)"
},
{
"docstring": "Return the topology description. :return: topo desc... | 2 | null | Implement the Python class `FallbackStaticTopology` described below.
Class description:
Topology class for testing purposes and serve as a fallback topology. Use the static way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | SW1 | | SW2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----... | Implement the Python class `FallbackStaticTopology` described below.
Class description:
Topology class for testing purposes and serve as a fallback topology. Use the static way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | SW1 | | SW2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----... | 21b95843aa9308a5d3689bc2d30b2752b7121117 | <|skeleton|>
class FallbackStaticTopology:
"""Topology class for testing purposes and serve as a fallback topology. Use the static way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | SW1 | | SW2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----------+ +----------+ | |2 2| | | SW3 +-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FallbackStaticTopology:
"""Topology class for testing purposes and serve as a fallback topology. Use the static way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | SW1 | | SW2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----------+ +----------+ | |2 2| | | SW3 +-----------+ S... | the_stack_v2_python_sparse | escape/escape/infr/topology.py | JerryLX/escape | train | 0 |
b4fd9bffee583db8cc45237db4c0604fa3a2c574 | [
"super(HandBrakeVehicle, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._vehicle = vehicle\nself._control, self._type = get_actor_control(vehicle)\nself._hand_brake_value = hand_brake_value",
"new_status = py_trees.common.Status.SUCCESS\nif self._type == 'vehicle':\n s... | <|body_start_0|>
super(HandBrakeVehicle, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._vehicle = vehicle
self._control, self._type = get_actor_control(vehicle)
self._hand_brake_value = hand_brake_value
<|end_body_0|>
<|body_start_1|>
... | This class contains an atomic hand brake behavior. To set the hand brake value of the vehicle. Important parameters: - vehicle: CARLA actor to execute the behavior - hand_brake_value to be applied in [0,1] The behavior terminates after setting the hand brake value | HandBrakeVehicle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HandBrakeVehicle:
"""This class contains an atomic hand brake behavior. To set the hand brake value of the vehicle. Important parameters: - vehicle: CARLA actor to execute the behavior - hand_brake_value to be applied in [0,1] The behavior terminates after setting the hand brake value"""
def... | stack_v2_sparse_classes_36k_train_024347 | 39,839 | permissive | [
{
"docstring": "Setup vehicle control and brake value",
"name": "__init__",
"signature": "def __init__(self, vehicle, hand_brake_value, name='Braking')"
},
{
"docstring": "Set handbrake",
"name": "update",
"signature": "def update(self)"
}
] | 2 | null | Implement the Python class `HandBrakeVehicle` described below.
Class description:
This class contains an atomic hand brake behavior. To set the hand brake value of the vehicle. Important parameters: - vehicle: CARLA actor to execute the behavior - hand_brake_value to be applied in [0,1] The behavior terminates after s... | Implement the Python class `HandBrakeVehicle` described below.
Class description:
This class contains an atomic hand brake behavior. To set the hand brake value of the vehicle. Important parameters: - vehicle: CARLA actor to execute the behavior - hand_brake_value to be applied in [0,1] The behavior terminates after s... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class HandBrakeVehicle:
"""This class contains an atomic hand brake behavior. To set the hand brake value of the vehicle. Important parameters: - vehicle: CARLA actor to execute the behavior - hand_brake_value to be applied in [0,1] The behavior terminates after setting the hand brake value"""
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HandBrakeVehicle:
"""This class contains an atomic hand brake behavior. To set the hand brake value of the vehicle. Important parameters: - vehicle: CARLA actor to execute the behavior - hand_brake_value to be applied in [0,1] The behavior terminates after setting the hand brake value"""
def __init__(sel... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_behaviors.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
12da431b0aad2cf252127c4536207f7c6b034e26 | [
"ssum = (maxChoosableInteger + 1) * maxChoosableInteger // 2\nif ssum < desiredTotal:\n return False\nif desiredTotal <= 0:\n return True\nmemory = [None] * (1 << maxChoosableInteger)\nreturn self.winorloss(maxChoosableInteger, desiredTotal, memory, 0)",
"if T <= 0:\n return False\nif memory[state]:\n ... | <|body_start_0|>
ssum = (maxChoosableInteger + 1) * maxChoosableInteger // 2
if ssum < desiredTotal:
return False
if desiredTotal <= 0:
return True
memory = [None] * (1 << maxChoosableInteger)
return self.winorloss(maxChoosableInteger, desiredTotal, memory... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canIWin(self, maxChoosableInteger, desiredTotal):
"""In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re... | stack_v2_sparse_classes_36k_train_024348 | 2,881 | no_license | [
{
"docstring": "In the \"100 game,\" two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re-use integers? For example, two players might take turns drawing from a c... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canIWin(self, maxChoosableInteger, desiredTotal): In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes th... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canIWin(self, maxChoosableInteger, desiredTotal): In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes th... | 08c6d27498e35f636045fed05a6f94b760ab69ca | <|skeleton|>
class Solution:
def canIWin(self, maxChoosableInteger, desiredTotal):
"""In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canIWin(self, maxChoosableInteger, desiredTotal):
"""In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re-use integers?... | the_stack_v2_python_sparse | solutions/minimax/464.Can.I.Win.py | ljia2/leetcode.py | train | 0 | |
6632c6b6b8e14c40a7a79ca64b051a26d327a9a5 | [
"if request.user.is_authenticated and request.user.is_administrator_of_search_pages:\n return True\nreturn super().has_add_permission(request, obj)",
"if request.user.is_authenticated and request.user.is_administrator_of_search_pages:\n return True\nreturn super().has_delete_permission(request, obj)"
] | <|body_start_0|>
if request.user.is_authenticated and request.user.is_administrator_of_search_pages:
return True
return super().has_add_permission(request, obj)
<|end_body_0|>
<|body_start_1|>
if request.user.is_authenticated and request.user.is_administrator_of_search_pages:
... | WithFullPermission | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WithFullPermission:
def has_add_permission(self, request, obj=None):
"""Grant permission to authenticated users that are administrator of search pages."""
<|body_0|>
def has_delete_permission(self, request, obj=None):
"""Grant permission to authenticated users that a... | stack_v2_sparse_classes_36k_train_024349 | 1,718 | permissive | [
{
"docstring": "Grant permission to authenticated users that are administrator of search pages.",
"name": "has_add_permission",
"signature": "def has_add_permission(self, request, obj=None)"
},
{
"docstring": "Grant permission to authenticated users that are administrator of search pages.",
... | 2 | stack_v2_sparse_classes_30k_train_011406 | Implement the Python class `WithFullPermission` described below.
Class description:
Implement the WithFullPermission class.
Method signatures and docstrings:
- def has_add_permission(self, request, obj=None): Grant permission to authenticated users that are administrator of search pages.
- def has_delete_permission(s... | Implement the Python class `WithFullPermission` described below.
Class description:
Implement the WithFullPermission class.
Method signatures and docstrings:
- def has_add_permission(self, request, obj=None): Grant permission to authenticated users that are administrator of search pages.
- def has_delete_permission(s... | af9f6e6e8b1918363793fbf291f3518ef1454169 | <|skeleton|>
class WithFullPermission:
def has_add_permission(self, request, obj=None):
"""Grant permission to authenticated users that are administrator of search pages."""
<|body_0|>
def has_delete_permission(self, request, obj=None):
"""Grant permission to authenticated users that a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WithFullPermission:
def has_add_permission(self, request, obj=None):
"""Grant permission to authenticated users that are administrator of search pages."""
if request.user.is_authenticated and request.user.is_administrator_of_search_pages:
return True
return super().has_add_... | the_stack_v2_python_sparse | src/admin_lite/mixins.py | MTES-MCT/aides-territoires | train | 21 | |
c96d18600d824706d6354676b222d7aa977f7c8b | [
"if game_object is None or opacity is None:\n return False\ngame_object.opacity = opacity\nreturn True",
"if game_object is None:\n return 0\nreturn game_object.opacity",
"if game_object is None or persistence_group is None:\n return False\ngame_object.persistence_group = persistence_group\nreturn True... | <|body_start_0|>
if game_object is None or opacity is None:
return False
game_object.opacity = opacity
return True
<|end_body_0|>
<|body_start_1|>
if game_object is None:
return 0
return game_object.opacity
<|end_body_1|>
<|body_start_2|>
if game... | Utilities for manipulating the visibility and persistence of Objects. | CommonObjectVisibilityUtils | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonObjectVisibilityUtils:
"""Utilities for manipulating the visibility and persistence of Objects."""
def set_opacity(game_object: GameObject, opacity: int) -> bool:
"""set_opacity(game_object, opacity) Set the opacity of an Object. :param game_object: An instance of an Object. :t... | stack_v2_sparse_classes_36k_train_024350 | 2,726 | permissive | [
{
"docstring": "set_opacity(game_object, opacity) Set the opacity of an Object. :param game_object: An instance of an Object. :type game_object: GameObject :param opacity: Determines how opaque the Object will be. :type opacity: int :return: True, if successful. False, if not. :rtype: bool",
"name": "set_op... | 4 | null | Implement the Python class `CommonObjectVisibilityUtils` described below.
Class description:
Utilities for manipulating the visibility and persistence of Objects.
Method signatures and docstrings:
- def set_opacity(game_object: GameObject, opacity: int) -> bool: set_opacity(game_object, opacity) Set the opacity of an... | Implement the Python class `CommonObjectVisibilityUtils` described below.
Class description:
Utilities for manipulating the visibility and persistence of Objects.
Method signatures and docstrings:
- def set_opacity(game_object: GameObject, opacity: int) -> bool: set_opacity(game_object, opacity) Set the opacity of an... | 58e7beb30b9c818b294d35abd2436a0192cd3e82 | <|skeleton|>
class CommonObjectVisibilityUtils:
"""Utilities for manipulating the visibility and persistence of Objects."""
def set_opacity(game_object: GameObject, opacity: int) -> bool:
"""set_opacity(game_object, opacity) Set the opacity of an Object. :param game_object: An instance of an Object. :t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonObjectVisibilityUtils:
"""Utilities for manipulating the visibility and persistence of Objects."""
def set_opacity(game_object: GameObject, opacity: int) -> bool:
"""set_opacity(game_object, opacity) Set the opacity of an Object. :param game_object: An instance of an Object. :type game_obje... | the_stack_v2_python_sparse | Scripts/sims4communitylib/utils/objects/common_object_visibility_utils.py | ColonolNutty/Sims4CommunityLibrary | train | 183 |
eb093c8cbaad67b73aff00ef78a78daf1c8363db | [
"lists = {key: val for key, val in dict1.items()}\ndict1.update(dict2)\nfor key, val in lists.items():\n if key in dict2:\n dict1[key] = lists[key] + dict2[key]\nreturn dict1",
"global _CODEBOOK_CODE_VALUES\nif code_id is None:\n return None\nif not os.environ.get('UNITTEST_FLAG', 0) == 1 and _CODEBO... | <|body_start_0|>
lists = {key: val for key, val in dict1.items()}
dict1.update(dict2)
for key, val in lists.items():
if key in dict2:
dict1[key] = lists[key] + dict2[key]
return dict1
<|end_body_0|>
<|body_start_1|>
global _CODEBOOK_CODE_VALUES
... | Base class for generating Resource data JSON. | BaseGenerator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseGenerator:
"""Base class for generating Resource data JSON."""
def _merge_schema_dicts(self, dict1, dict2):
"""Safely merge dict2 schema into dict1 schema :param dict1: dict object :param dict2: dict object :return: dict"""
<|body_0|>
def _lookup_code_value(self, cod... | stack_v2_sparse_classes_36k_train_024351 | 14,523 | permissive | [
{
"docstring": "Safely merge dict2 schema into dict1 schema :param dict1: dict object :param dict2: dict object :return: dict",
"name": "_merge_schema_dicts",
"signature": "def _merge_schema_dicts(self, dict1, dict2)"
},
{
"docstring": "Return the code id string value from the code table. :param... | 4 | null | Implement the Python class `BaseGenerator` described below.
Class description:
Base class for generating Resource data JSON.
Method signatures and docstrings:
- def _merge_schema_dicts(self, dict1, dict2): Safely merge dict2 schema into dict1 schema :param dict1: dict object :param dict2: dict object :return: dict
- ... | Implement the Python class `BaseGenerator` described below.
Class description:
Base class for generating Resource data JSON.
Method signatures and docstrings:
- def _merge_schema_dicts(self, dict1, dict2): Safely merge dict2 schema into dict1 schema :param dict1: dict object :param dict2: dict object :return: dict
- ... | 461ae46aeda21d54de8a91aa5ef677676d5db541 | <|skeleton|>
class BaseGenerator:
"""Base class for generating Resource data JSON."""
def _merge_schema_dicts(self, dict1, dict2):
"""Safely merge dict2 schema into dict1 schema :param dict1: dict object :param dict2: dict object :return: dict"""
<|body_0|>
def _lookup_code_value(self, cod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseGenerator:
"""Base class for generating Resource data JSON."""
def _merge_schema_dicts(self, dict1, dict2):
"""Safely merge dict2 schema into dict1 schema :param dict1: dict object :param dict2: dict object :return: dict"""
lists = {key: val for key, val in dict1.items()}
dict... | the_stack_v2_python_sparse | rdr_service/resource/generators/_base.py | all-of-us/raw-data-repository | train | 46 |
eabacd9593b6f5fec7e607502323623a45fcfdb5 | [
"super(AttentionNet_MLP, self).__init__()\nencoder_layer = torch.nn.TransformerEncoderLayer(d_model=HIDDEN_NODES, nhead=num_head, dim_feedforward=dim_feedforward, dropout=p_dropout)\nself.net = nn.Sequential(nn.Linear(num_in, HIDDEN_NODES), nn.TransformerEncoder(encoder_layer, num_layers=num_layers, norm=torch.nn.L... | <|body_start_0|>
super(AttentionNet_MLP, self).__init__()
encoder_layer = torch.nn.TransformerEncoderLayer(d_model=HIDDEN_NODES, nhead=num_head, dim_feedforward=dim_feedforward, dropout=p_dropout)
self.net = nn.Sequential(nn.Linear(num_in, HIDDEN_NODES), nn.TransformerEncoder(encoder_layer, num_... | AttentionNet_MLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionNet_MLP:
def __init__(self, num_in, num_head=8, num_layers=2, dim_feedforward=HIDDEN_NODES, p_dropout=0.1):
"""Constructor method. Set up NN :param num_in: number of zip codes in the region"""
<|body_0|>
def forward(self, x):
"""Defines forward pass through ... | stack_v2_sparse_classes_36k_train_024352 | 1,188 | no_license | [
{
"docstring": "Constructor method. Set up NN :param num_in: number of zip codes in the region",
"name": "__init__",
"signature": "def __init__(self, num_in, num_head=8, num_layers=2, dim_feedforward=HIDDEN_NODES, p_dropout=0.1)"
},
{
"docstring": "Defines forward pass through the network on inp... | 2 | stack_v2_sparse_classes_30k_train_019691 | Implement the Python class `AttentionNet_MLP` described below.
Class description:
Implement the AttentionNet_MLP class.
Method signatures and docstrings:
- def __init__(self, num_in, num_head=8, num_layers=2, dim_feedforward=HIDDEN_NODES, p_dropout=0.1): Constructor method. Set up NN :param num_in: number of zip code... | Implement the Python class `AttentionNet_MLP` described below.
Class description:
Implement the AttentionNet_MLP class.
Method signatures and docstrings:
- def __init__(self, num_in, num_head=8, num_layers=2, dim_feedforward=HIDDEN_NODES, p_dropout=0.1): Constructor method. Set up NN :param num_in: number of zip code... | bd2a6544b7a3745067692cec80c1a84b15c0f86d | <|skeleton|>
class AttentionNet_MLP:
def __init__(self, num_in, num_head=8, num_layers=2, dim_feedforward=HIDDEN_NODES, p_dropout=0.1):
"""Constructor method. Set up NN :param num_in: number of zip codes in the region"""
<|body_0|>
def forward(self, x):
"""Defines forward pass through ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttentionNet_MLP:
def __init__(self, num_in, num_head=8, num_layers=2, dim_feedforward=HIDDEN_NODES, p_dropout=0.1):
"""Constructor method. Set up NN :param num_in: number of zip codes in the region"""
super(AttentionNet_MLP, self).__init__()
encoder_layer = torch.nn.TransformerEncoder... | the_stack_v2_python_sparse | AttentionNet.py | jinqiuzhao/ambulance-dispatch-DDQN | train | 0 | |
ef64e050d7b7f83d1b63d30b76e2e3a057cd7ac0 | [
"from apysc import EventType\nfrom apysc import MouseEvent\nfrom apysc.event.handler import append_handler_expression\nfrom apysc.event.handler import get_handler_name\nfrom apysc.type.variable_name_interface import VariableNameInterface\nself_instance: VariableNameInterface = self._validate_self_is_variable_name_i... | <|body_start_0|>
from apysc import EventType
from apysc import MouseEvent
from apysc.event.handler import append_handler_expression
from apysc.event.handler import get_handler_name
from apysc.type.variable_name_interface import VariableNameInterface
self_instance: Variabl... | MouseDownInterface | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MouseDownInterface:
def mousedown(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str:
"""Add mouse down event listener setting. Parameters ---------- handler : Handler Callable that called when mouse is downed on this instance. options : dict or None, default None Opt... | stack_v2_sparse_classes_36k_train_024353 | 3,053 | permissive | [
{
"docstring": "Add mouse down event listener setting. Parameters ---------- handler : Handler Callable that called when mouse is downed on this instance. options : dict or None, default None Optional arguments dictionary to be passed to handler. Returns ------- name : str Handler's name.",
"name": "mousedo... | 4 | null | Implement the Python class `MouseDownInterface` described below.
Class description:
Implement the MouseDownInterface class.
Method signatures and docstrings:
- def mousedown(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str: Add mouse down event listener setting. Parameters ---------- handler : H... | Implement the Python class `MouseDownInterface` described below.
Class description:
Implement the MouseDownInterface class.
Method signatures and docstrings:
- def mousedown(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str: Add mouse down event listener setting. Parameters ---------- handler : H... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class MouseDownInterface:
def mousedown(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str:
"""Add mouse down event listener setting. Parameters ---------- handler : Handler Callable that called when mouse is downed on this instance. options : dict or None, default None Opt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MouseDownInterface:
def mousedown(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str:
"""Add mouse down event listener setting. Parameters ---------- handler : Handler Callable that called when mouse is downed on this instance. options : dict or None, default None Optional argument... | the_stack_v2_python_sparse | apysc/event/mouse_down_interface.py | TrendingTechnology/apysc | train | 0 | |
074be7e710f7ca2e3ee8b89c07db8236049ab5b8 | [
"if hydra_targets and unit.type_id == UnitTypeId.HYDRALISK:\n close_hydra_targets = hydra_targets.closer_than(15, unit.position)\n if close_hydra_targets:\n if self.retreat_unit(unit, close_hydra_targets):\n return True\n if self.microing_hydras(hydra_targets, unit):\n retu... | <|body_start_0|>
if hydra_targets and unit.type_id == UnitTypeId.HYDRALISK:
close_hydra_targets = hydra_targets.closer_than(15, unit.position)
if close_hydra_targets:
if self.retreat_unit(unit, close_hydra_targets):
return True
if self.... | Ok for now | SpecificUnitsBehaviors | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecificUnitsBehaviors:
"""Ok for now"""
def specific_hydra_behavior(self, hydra_targets, unit):
"""Group everything related to hydras behavior on attack Parameters ---------- hydra_targets: Targets that hydras can reach(almost everything) unit: One hydra from the attacking force Ret... | stack_v2_sparse_classes_36k_train_024354 | 1,854 | permissive | [
{
"docstring": "Group everything related to hydras behavior on attack Parameters ---------- hydra_targets: Targets that hydras can reach(almost everything) unit: One hydra from the attacking force Returns ------- Actions(micro or retreat) if conditions are met False if not",
"name": "specific_hydra_behavior... | 2 | stack_v2_sparse_classes_30k_train_017894 | Implement the Python class `SpecificUnitsBehaviors` described below.
Class description:
Ok for now
Method signatures and docstrings:
- def specific_hydra_behavior(self, hydra_targets, unit): Group everything related to hydras behavior on attack Parameters ---------- hydra_targets: Targets that hydras can reach(almost... | Implement the Python class `SpecificUnitsBehaviors` described below.
Class description:
Ok for now
Method signatures and docstrings:
- def specific_hydra_behavior(self, hydra_targets, unit): Group everything related to hydras behavior on attack Parameters ---------- hydra_targets: Targets that hydras can reach(almost... | 1b45ce782df666dd21996011a04c92211c0e6368 | <|skeleton|>
class SpecificUnitsBehaviors:
"""Ok for now"""
def specific_hydra_behavior(self, hydra_targets, unit):
"""Group everything related to hydras behavior on attack Parameters ---------- hydra_targets: Targets that hydras can reach(almost everything) unit: One hydra from the attacking force Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecificUnitsBehaviors:
"""Ok for now"""
def specific_hydra_behavior(self, hydra_targets, unit):
"""Group everything related to hydras behavior on attack Parameters ---------- hydra_targets: Targets that hydras can reach(almost everything) unit: One hydra from the attacking force Returns ------- ... | the_stack_v2_python_sparse | actions/micro/specific_units_behaviors.py | Matuiss2/JackBot | train | 6 |
69dc22baa6e75bca504755e69f3fc4f537c0362a | [
"super().__init__()\nself.conv1 = nn.Conv2d(1, dim, 4, 2, 1)\nself.bn1 = nn.BatchNorm2d(dim)\nself.conv2 = nn.Conv2d(dim, dim, 4, 2, 1)\nself.bn2 = nn.BatchNorm2d(dim)\nself.conv3 = nn.Conv2d(dim, dim, 4, 2, 1)\nself.bn3 = nn.BatchNorm2d(dim)\nself.conv4 = nn.Conv2d(dim, dim, 4, 2, 1)\nself.bn4 = nn.BatchNorm2d(dim... | <|body_start_0|>
super().__init__()
self.conv1 = nn.Conv2d(1, dim, 4, 2, 1)
self.bn1 = nn.BatchNorm2d(dim)
self.conv2 = nn.Conv2d(dim, dim, 4, 2, 1)
self.bn2 = nn.BatchNorm2d(dim)
self.conv3 = nn.Conv2d(dim, dim, 4, 2, 1)
self.bn3 = nn.BatchNorm2d(dim)
sel... | This class implements a convolutional encoder to extract classification embeddings from logspectra. Arguments --------- dim : int Number of channels of the extracted embeddings. Returns -------- Latent representations to feed inside classifier and/or intepreter. Example: -------- >>> inputs = torch.ones(3, 431, 513) >>... | Conv2dEncoder_v2 | [
"Apache-2.0",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2dEncoder_v2:
"""This class implements a convolutional encoder to extract classification embeddings from logspectra. Arguments --------- dim : int Number of channels of the extracted embeddings. Returns -------- Latent representations to feed inside classifier and/or intepreter. Example: ----... | stack_v2_sparse_classes_36k_train_024355 | 19,449 | permissive | [
{
"docstring": "Extracts embeddings from logspectrograms.",
"name": "__init__",
"signature": "def __init__(self, dim=256)"
},
{
"docstring": "Computes forward pass. Arguments -------- x : torch.Tensor Log-power spectrogram. Expected shape `torch.Size([B, T, F])`. Returns -------- Embeddings : to... | 2 | null | Implement the Python class `Conv2dEncoder_v2` described below.
Class description:
This class implements a convolutional encoder to extract classification embeddings from logspectra. Arguments --------- dim : int Number of channels of the extracted embeddings. Returns -------- Latent representations to feed inside clas... | Implement the Python class `Conv2dEncoder_v2` described below.
Class description:
This class implements a convolutional encoder to extract classification embeddings from logspectra. Arguments --------- dim : int Number of channels of the extracted embeddings. Returns -------- Latent representations to feed inside clas... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class Conv2dEncoder_v2:
"""This class implements a convolutional encoder to extract classification embeddings from logspectra. Arguments --------- dim : int Number of channels of the extracted embeddings. Returns -------- Latent representations to feed inside classifier and/or intepreter. Example: ----... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv2dEncoder_v2:
"""This class implements a convolutional encoder to extract classification embeddings from logspectra. Arguments --------- dim : int Number of channels of the extracted embeddings. Returns -------- Latent representations to feed inside classifier and/or intepreter. Example: -------- >>> inpu... | the_stack_v2_python_sparse | PyTorch/dev/perf/speechbrain-tdnn/speechbrain/lobes/models/PIQ.py | Ascend/ModelZoo-PyTorch | train | 23 |
8b68037389597d1fbe4e27317888710b74712935 | [
"self.tracks = []\nself.active_tracks = []\nself.iou_threshold = iou_threshold\nself.max_past_frames = max_past_frames\nself.track_index = 0\nself.frame_index = 0",
"result_tracks = []\nfor track in self.active_tracks:\n item = None\n if track.last_frame_index != self.frame_index:\n item = track.get_... | <|body_start_0|>
self.tracks = []
self.active_tracks = []
self.iou_threshold = iou_threshold
self.max_past_frames = max_past_frames
self.track_index = 0
self.frame_index = 0
<|end_body_0|>
<|body_start_1|>
result_tracks = []
for track in self.active_track... | Class for associating detections from the current frame with existing tracks. | TrackDetAssociation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrackDetAssociation:
"""Class for associating detections from the current frame with existing tracks."""
def __init__(self, iou_threshold=0.3, max_past_frames=30):
"""iou_threshold : threshold used in iou matching. max_past_frames : the max number of frames looked into the past when ... | stack_v2_sparse_classes_36k_train_024356 | 15,271 | no_license | [
{
"docstring": "iou_threshold : threshold used in iou matching. max_past_frames : the max number of frames looked into the past when trying to associate current detections with existing tracks.",
"name": "__init__",
"signature": "def __init__(self, iou_threshold=0.3, max_past_frames=30)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_013768 | Implement the Python class `TrackDetAssociation` described below.
Class description:
Class for associating detections from the current frame with existing tracks.
Method signatures and docstrings:
- def __init__(self, iou_threshold=0.3, max_past_frames=30): iou_threshold : threshold used in iou matching. max_past_fra... | Implement the Python class `TrackDetAssociation` described below.
Class description:
Class for associating detections from the current frame with existing tracks.
Method signatures and docstrings:
- def __init__(self, iou_threshold=0.3, max_past_frames=30): iou_threshold : threshold used in iou matching. max_past_fra... | 4d21f2b3a9e5171b6ea611f3d4f67ba8f31408a1 | <|skeleton|>
class TrackDetAssociation:
"""Class for associating detections from the current frame with existing tracks."""
def __init__(self, iou_threshold=0.3, max_past_frames=30):
"""iou_threshold : threshold used in iou matching. max_past_frames : the max number of frames looked into the past when ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrackDetAssociation:
"""Class for associating detections from the current frame with existing tracks."""
def __init__(self, iou_threshold=0.3, max_past_frames=30):
"""iou_threshold : threshold used in iou matching. max_past_frames : the max number of frames looked into the past when trying to ass... | the_stack_v2_python_sparse | analyzer/track.py | Zhangyeping/visual-vehicle-behavier-analyzer | train | 0 |
88d5991c97626355b1ed549915a34bf8198cbaab | [
"self.maxheap = []\nself.maxsize = 0\nself.minheap = []\nself.minsize = 0\nself.size = 0",
"if not self.size:\n heapq.heappush(self.maxheap, (-num, self.maxsize))\n self.maxsize = 1\n self.size = 1\n return\nif num <= -self.maxheap[0][0]:\n heapq.heappush(self.maxheap, (-num, self.maxsize))\n se... | <|body_start_0|>
self.maxheap = []
self.maxsize = 0
self.minheap = []
self.minsize = 0
self.size = 0
<|end_body_0|>
<|body_start_1|>
if not self.size:
heapq.heappush(self.maxheap, (-num, self.maxsize))
self.maxsize = 1
self.size = 1
... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_024357 | 2,913 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_006149 | 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): :type num: int :rtype: void
- def findMedian(self): :rtype: float | 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): :type num: int :rtype: void
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | 786e1597b18cf5f16df0a3d7dfa0b80c1435de4d | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.maxheap = []
self.maxsize = 0
self.minheap = []
self.minsize = 0
self.size = 0
def addNum(self, num):
""":type num: int :rtype: void"""
if not self.size:
... | the_stack_v2_python_sparse | No_295_Find_Median_from_Data_Stream.py | georgewashingturd/leetcode | train | 0 | |
8707cb81b2fdeea848921f87af2905db93c48710 | [
"predecessors = []\nfor idx in range(len(word)):\n predecessors.append(word[:idx] + word[idx + 1:])\nreturn predecessors",
"words.sort(key=lambda word: len(word))\nword_to_chain_length = {}\nmax_chain_length = 1\nfor word in words:\n word_to_chain_length[word] = 1\n predecessors = self.get_predecessors(w... | <|body_start_0|>
predecessors = []
for idx in range(len(word)):
predecessors.append(word[:idx] + word[idx + 1:])
return predecessors
<|end_body_0|>
<|body_start_1|>
words.sort(key=lambda word: len(word))
word_to_chain_length = {}
max_chain_length = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_predecessors(self, word):
"""Return a list of words with 1 character removed from the provided word"""
<|body_0|>
def longestStrChain(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_024358 | 1,544 | no_license | [
{
"docstring": "Return a list of words with 1 character removed from the provided word",
"name": "get_predecessors",
"signature": "def get_predecessors(self, word)"
},
{
"docstring": ":type words: List[str] :rtype: int",
"name": "longestStrChain",
"signature": "def longestStrChain(self, ... | 2 | stack_v2_sparse_classes_30k_train_007163 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_predecessors(self, word): Return a list of words with 1 character removed from the provided word
- def longestStrChain(self, words): :type words: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_predecessors(self, word): Return a list of words with 1 character removed from the provided word
- def longestStrChain(self, words): :type words: List[str] :rtype: int
<... | 52d71a93de7f002ac887a82c947e1e32a3e7255f | <|skeleton|>
class Solution:
def get_predecessors(self, word):
"""Return a list of words with 1 character removed from the provided word"""
<|body_0|>
def longestStrChain(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_predecessors(self, word):
"""Return a list of words with 1 character removed from the provided word"""
predecessors = []
for idx in range(len(word)):
predecessors.append(word[:idx] + word[idx + 1:])
return predecessors
def longestStrChain(self... | the_stack_v2_python_sparse | template/solution.py | code-in-public/leetcode | train | 3 | |
cfbb3e99d6a2bb48aa8f8cbf643127e85bb5aa2a | [
"super(Sim_Attn, self).__init__()\nself.encoder_size = encoder_size\nself.decoder_size = decoder_size\nself.num_labels = num_labels\nself.hidden_size = hidden_size\nself.e_mlp = nn.Sequential(nn.Linear(encoder_size, hidden_size), nn.SELU(), nn.Linear(hidden_size, K), nn.SELU()) if MLP_Layer == 2 else nn.Sequential(... | <|body_start_0|>
super(Sim_Attn, self).__init__()
self.encoder_size = encoder_size
self.decoder_size = decoder_size
self.num_labels = num_labels
self.hidden_size = hidden_size
self.e_mlp = nn.Sequential(nn.Linear(encoder_size, hidden_size), nn.SELU(), nn.Linear(hidden_siz... | Sim_Attn | [
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sim_Attn:
def __init__(self, encoder_size, decoder_size, num_labels=1, hidden_size=HIDDEN_SIZE):
"""num_labels 代表当前节点到各个节点之间做的 bi_affine attention 分配给各个节点的向量维度, 因为子句分割是分割点选择任务,所以每个分割点的维度设置为1即可,一组标量的 soft_max 概率即 为边界标签的选择结果。 if LAYER_NORM_USE: edus = self.edu_norm(edus)"""
<|body_... | stack_v2_sparse_classes_36k_train_024359 | 16,149 | permissive | [
{
"docstring": "num_labels 代表当前节点到各个节点之间做的 bi_affine attention 分配给各个节点的向量维度, 因为子句分割是分割点选择任务,所以每个分割点的维度设置为1即可,一组标量的 soft_max 概率即 为边界标签的选择结果。 if LAYER_NORM_USE: edus = self.edu_norm(edus)",
"name": "__init__",
"signature": "def __init__(self, encoder_size, decoder_size, num_labels=1, hidden_size=HIDDEN_SI... | 2 | stack_v2_sparse_classes_30k_train_001195 | Implement the Python class `Sim_Attn` described below.
Class description:
Implement the Sim_Attn class.
Method signatures and docstrings:
- def __init__(self, encoder_size, decoder_size, num_labels=1, hidden_size=HIDDEN_SIZE): num_labels 代表当前节点到各个节点之间做的 bi_affine attention 分配给各个节点的向量维度, 因为子句分割是分割点选择任务,所以每个分割点的维度设置为1即... | Implement the Python class `Sim_Attn` described below.
Class description:
Implement the Sim_Attn class.
Method signatures and docstrings:
- def __init__(self, encoder_size, decoder_size, num_labels=1, hidden_size=HIDDEN_SIZE): num_labels 代表当前节点到各个节点之间做的 bi_affine attention 分配给各个节点的向量维度, 因为子句分割是分割点选择任务,所以每个分割点的维度设置为1即... | fd71b353c59bcb82ec2cd0bebf943040756faa63 | <|skeleton|>
class Sim_Attn:
def __init__(self, encoder_size, decoder_size, num_labels=1, hidden_size=HIDDEN_SIZE):
"""num_labels 代表当前节点到各个节点之间做的 bi_affine attention 分配给各个节点的向量维度, 因为子句分割是分割点选择任务,所以每个分割点的维度设置为1即可,一组标量的 soft_max 概率即 为边界标签的选择结果。 if LAYER_NORM_USE: edus = self.edu_norm(edus)"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sim_Attn:
def __init__(self, encoder_size, decoder_size, num_labels=1, hidden_size=HIDDEN_SIZE):
"""num_labels 代表当前节点到各个节点之间做的 bi_affine attention 分配给各个节点的向量维度, 因为子句分割是分割点选择任务,所以每个分割点的维度设置为1即可,一组标量的 soft_max 概率即 为边界标签的选择结果。 if LAYER_NORM_USE: edus = self.edu_norm(edus)"""
super(Sim_Attn, self)... | the_stack_v2_python_sparse | CDTB_Seg/model/ENC_DEC_GCN/model.py | NLP-Discourse-SoochowU/segmenter2020 | train | 0 | |
9ca3adf43bd6d398de39d4cb662a00b5b7c5ed07 | [
"super().__init__(model, params)\nself._var_scope = 'decoder'\nself._lambda_dec_d = 1.0\nself._n_classes = 0\nself._n_channels = 1\nif 'n_classes' in params.keys():\n self._n_classes = params['n_classes']\nif 'lambda_d' in params.keys():\n self._lambda_dec_d = params['lambda_d']\nself._init_optimizer()",
"o... | <|body_start_0|>
super().__init__(model, params)
self._var_scope = 'decoder'
self._lambda_dec_d = 1.0
self._n_classes = 0
self._n_channels = 1
if 'n_classes' in params.keys():
self._n_classes = params['n_classes']
if 'lambda_d' in params.keys():
... | debug implementation | Decoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
<|body_0|>
def _network(self, input):
"""forward netwrok."""
<|body_1|>
def _loss(self, _data):
"""pr... | stack_v2_sparse_classes_36k_train_024360 | 9,168 | permissive | [
{
"docstring": "Args: model: parent model object. params: dict() of parameters.",
"name": "__init__",
"signature": "def __init__(self, model, params)"
},
{
"docstring": "forward netwrok.",
"name": "_network",
"signature": "def _network(self, input)"
},
{
"docstring": "prepare the... | 3 | stack_v2_sparse_classes_30k_train_003193 | Implement the Python class `Decoder` described below.
Class description:
debug implementation
Method signatures and docstrings:
- def __init__(self, model, params): Args: model: parent model object. params: dict() of parameters.
- def _network(self, input): forward netwrok.
- def _loss(self, _data): prepare the loss ... | Implement the Python class `Decoder` described below.
Class description:
debug implementation
Method signatures and docstrings:
- def __init__(self, model, params): Args: model: parent model object. params: dict() of parameters.
- def _network(self, input): forward netwrok.
- def _loss(self, _data): prepare the loss ... | 9546d7a01c2b3e17131f34aa1e916e514c052ea8 | <|skeleton|>
class Decoder:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
<|body_0|>
def _network(self, input):
"""forward netwrok."""
<|body_1|>
def _loss(self, _data):
"""pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
super().__init__(model, params)
self._var_scope = 'decoder'
self._lambda_dec_d = 1.0
self._n_classes = 0
self._n_cha... | the_stack_v2_python_sparse | networks/network_aae_v_lite.py | cosmoplankton-studio/cellular-probabilistic | train | 0 |
011241ab57547be3ce8b0ab58fb256e7c80156d2 | [
"queryset = Workshop.objects.filter(club=obj, date__gte=date.today()).order_by('date', 'time')\nserializer = WorkshopSerializer(queryset, many=True)\nreturn serializer.data",
"queryset = Workshop.objects.filter(club=obj, date__lt=date.today()).order_by('-date', '-time')\nserializer = WorkshopSerializer(queryset, ... | <|body_start_0|>
queryset = Workshop.objects.filter(club=obj, date__gte=date.today()).order_by('date', 'time')
serializer = WorkshopSerializer(queryset, many=True)
return serializer.data
<|end_body_0|>
<|body_start_1|>
queryset = Workshop.objects.filter(club=obj, date__lt=date.today()).... | ClubDetailWorkshopSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClubDetailWorkshopSerializer:
def get_active_workshops(self, obj):
"""Active Workshops of the Club"""
<|body_0|>
def get_past_workshops(self, obj):
"""Past Workshops of the Club"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queryset = Workshop.obj... | stack_v2_sparse_classes_36k_train_024361 | 18,006 | no_license | [
{
"docstring": "Active Workshops of the Club",
"name": "get_active_workshops",
"signature": "def get_active_workshops(self, obj)"
},
{
"docstring": "Past Workshops of the Club",
"name": "get_past_workshops",
"signature": "def get_past_workshops(self, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018952 | Implement the Python class `ClubDetailWorkshopSerializer` described below.
Class description:
Implement the ClubDetailWorkshopSerializer class.
Method signatures and docstrings:
- def get_active_workshops(self, obj): Active Workshops of the Club
- def get_past_workshops(self, obj): Past Workshops of the Club | Implement the Python class `ClubDetailWorkshopSerializer` described below.
Class description:
Implement the ClubDetailWorkshopSerializer class.
Method signatures and docstrings:
- def get_active_workshops(self, obj): Active Workshops of the Club
- def get_past_workshops(self, obj): Past Workshops of the Club
<|skele... | 7cd4eb5d82917dcc554331d3893108b809468505 | <|skeleton|>
class ClubDetailWorkshopSerializer:
def get_active_workshops(self, obj):
"""Active Workshops of the Club"""
<|body_0|>
def get_past_workshops(self, obj):
"""Past Workshops of the Club"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClubDetailWorkshopSerializer:
def get_active_workshops(self, obj):
"""Active Workshops of the Club"""
queryset = Workshop.objects.filter(club=obj, date__gte=date.today()).order_by('date', 'time')
serializer = WorkshopSerializer(queryset, many=True)
return serializer.data
d... | the_stack_v2_python_sparse | workshop/serializers.py | aishwary023/workshops-app-backend | train | 0 | |
47374b97313e5ba532b31c0ef3167d4a43dc64a7 | [
"try:\n strike = self.strike\nexcept:\n pass\npaths = self.underlying.get_instrument_values(fixed_seed=fixed_seed)\ntime_grid = self.underlying.time_grid\ntry:\n time_index = np.where(time_grid == self.maturity)[0]\n time_index = int(time_index)\nexcept:\n print('Maturity date not in time grid of und... | <|body_start_0|>
try:
strike = self.strike
except:
pass
paths = self.underlying.get_instrument_values(fixed_seed=fixed_seed)
time_grid = self.underlying.time_grid
try:
time_index = np.where(time_grid == self.maturity)[0]
time_index ... | Class to value European options with arbitrary payoff by single-factor Monte Carlo simulation. Methods ======= generate_payoff : returns payoffs given the paths and the payoff function present_value : returns present value (Monte Carlo estimator) | valuation_mcs_european | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class valuation_mcs_european:
"""Class to value European options with arbitrary payoff by single-factor Monte Carlo simulation. Methods ======= generate_payoff : returns payoffs given the paths and the payoff function present_value : returns present value (Monte Carlo estimator)"""
def generate_pa... | stack_v2_sparse_classes_36k_train_024362 | 30,293 | no_license | [
{
"docstring": "Parameters ========== fixed_seed : Boolean use same/fixed seed for valuation",
"name": "generate_payoff",
"signature": "def generate_payoff(self, fixed_seed=False)"
},
{
"docstring": "Parameters ========== accuracy : int number of decimals in returned result fixed_seed : Boolean ... | 2 | null | Implement the Python class `valuation_mcs_european` described below.
Class description:
Class to value European options with arbitrary payoff by single-factor Monte Carlo simulation. Methods ======= generate_payoff : returns payoffs given the paths and the payoff function present_value : returns present value (Monte C... | Implement the Python class `valuation_mcs_european` described below.
Class description:
Class to value European options with arbitrary payoff by single-factor Monte Carlo simulation. Methods ======= generate_payoff : returns payoffs given the paths and the payoff function present_value : returns present value (Monte C... | 2136958cf4560cc183b072d89b756fad60e306bb | <|skeleton|>
class valuation_mcs_european:
"""Class to value European options with arbitrary payoff by single-factor Monte Carlo simulation. Methods ======= generate_payoff : returns payoffs given the paths and the payoff function present_value : returns present value (Monte Carlo estimator)"""
def generate_pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class valuation_mcs_european:
"""Class to value European options with arbitrary payoff by single-factor Monte Carlo simulation. Methods ======= generate_payoff : returns payoffs given the paths and the payoff function present_value : returns present value (Monte Carlo estimator)"""
def generate_payoff(self, fi... | the_stack_v2_python_sparse | webdata/pyfin/back/finance.py | davischan3168/packages | train | 3 |
e9ee71490a9adedf56080c4fb337fe554becf3b7 | [
"permission = AdministerOrganizationPermission(orgname)\nif permission.can() or allow_if_superuser():\n try:\n org = model.organization.get_organization(orgname)\n except model.InvalidOrganizationException:\n raise NotFound()\n prototype = model.permission.delete_prototype_permission(org, pro... | <|body_start_0|>
permission = AdministerOrganizationPermission(orgname)
if permission.can() or allow_if_superuser():
try:
org = model.organization.get_organization(orgname)
except model.InvalidOrganizationException:
raise NotFound()
pro... | Resource for managinging individual permission prototypes. | PermissionPrototype | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionPrototype:
"""Resource for managinging individual permission prototypes."""
def delete(self, orgname, prototypeid):
"""Delete an existing permission prototype."""
<|body_0|>
def put(self, orgname, prototypeid):
"""Update the role of an existing permissi... | stack_v2_sparse_classes_36k_train_024363 | 10,847 | permissive | [
{
"docstring": "Delete an existing permission prototype.",
"name": "delete",
"signature": "def delete(self, orgname, prototypeid)"
},
{
"docstring": "Update the role of an existing permission prototype.",
"name": "put",
"signature": "def put(self, orgname, prototypeid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014723 | Implement the Python class `PermissionPrototype` described below.
Class description:
Resource for managinging individual permission prototypes.
Method signatures and docstrings:
- def delete(self, orgname, prototypeid): Delete an existing permission prototype.
- def put(self, orgname, prototypeid): Update the role of... | Implement the Python class `PermissionPrototype` described below.
Class description:
Resource for managinging individual permission prototypes.
Method signatures and docstrings:
- def delete(self, orgname, prototypeid): Delete an existing permission prototype.
- def put(self, orgname, prototypeid): Update the role of... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class PermissionPrototype:
"""Resource for managinging individual permission prototypes."""
def delete(self, orgname, prototypeid):
"""Delete an existing permission prototype."""
<|body_0|>
def put(self, orgname, prototypeid):
"""Update the role of an existing permissi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PermissionPrototype:
"""Resource for managinging individual permission prototypes."""
def delete(self, orgname, prototypeid):
"""Delete an existing permission prototype."""
permission = AdministerOrganizationPermission(orgname)
if permission.can() or allow_if_superuser():
... | the_stack_v2_python_sparse | endpoints/api/prototype.py | quay/quay | train | 2,363 |
8f35ac4386a7363fc0a493db01149b577b7aa836 | [
"project, network, phases = cls._parse_args(network=network, phases=phases)\nnetwork = network[0]\nif filename == '':\n filename = project.name\nfilename = cls._parse_filename(filename=filename, ext='mat')\nd = Dict.to_dict(network=network, phases=phases, interleave=True)\nd = FlatDict(d, delimiter='|')\nd = san... | <|body_start_0|>
project, network, phases = cls._parse_args(network=network, phases=phases)
network = network[0]
if filename == '':
filename = project.name
filename = cls._parse_filename(filename=filename, ext='mat')
d = Dict.to_dict(network=network, phases=phases, in... | MAT files are a format used by Matlab Notes ----- The 'mat' file must contain data formatted as follows: 1. The file can contain either or both pore and throat data. 2. The property names should be in the format of ``pore_volume`` or ``throat_surface_area``. In OpenPNM the first '_' will be replaced by a '.' to give ``... | MAT | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MAT:
"""MAT files are a format used by Matlab Notes ----- The 'mat' file must contain data formatted as follows: 1. The file can contain either or both pore and throat data. 2. The property names should be in the format of ``pore_volume`` or ``throat_surface_area``. In OpenPNM the first '_' will ... | stack_v2_sparse_classes_36k_train_024364 | 3,462 | permissive | [
{
"docstring": "Write Network to a Mat file for exporting to Matlab. Parameters ---------- network : GenericNetwork filename : str Desired file name, defaults to network name if not given phases : list of phase objects ([]) Phases that have properties we want to write to file",
"name": "export_data",
"s... | 2 | null | Implement the Python class `MAT` described below.
Class description:
MAT files are a format used by Matlab Notes ----- The 'mat' file must contain data formatted as follows: 1. The file can contain either or both pore and throat data. 2. The property names should be in the format of ``pore_volume`` or ``throat_surface... | Implement the Python class `MAT` described below.
Class description:
MAT files are a format used by Matlab Notes ----- The 'mat' file must contain data formatted as follows: 1. The file can contain either or both pore and throat data. 2. The property names should be in the format of ``pore_volume`` or ``throat_surface... | 5ddd7f7317dd9c6d82e6db5256ec1800dd6eef5d | <|skeleton|>
class MAT:
"""MAT files are a format used by Matlab Notes ----- The 'mat' file must contain data formatted as follows: 1. The file can contain either or both pore and throat data. 2. The property names should be in the format of ``pore_volume`` or ``throat_surface_area``. In OpenPNM the first '_' will ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MAT:
"""MAT files are a format used by Matlab Notes ----- The 'mat' file must contain data formatted as follows: 1. The file can contain either or both pore and throat data. 2. The property names should be in the format of ``pore_volume`` or ``throat_surface_area``. In OpenPNM the first '_' will be replaced b... | the_stack_v2_python_sparse | openpnm/io/_mat.py | ma-sadeghi/OpenPNM | train | 1 |
e5336e886b35016083020cacdfc62baca8759176 | [
"if not crvs:\n msg = 'Intrinsic mutual informations require a conditional variable.'\n raise ditException(msg)\nsuper().__init__(dist, rvs, crvs, rv_mode=rv_mode)\ntheoretical_bound_j = prod(self._shape)\nbound_j = min([bound_j, theoretical_bound_j]) if bound_j else theoretical_bound_j\nself._construct_auxva... | <|body_start_0|>
if not crvs:
msg = 'Intrinsic mutual informations require a conditional variable.'
raise ditException(msg)
super().__init__(dist, rvs, crvs, rv_mode=rv_mode)
theoretical_bound_j = prod(self._shape)
bound_j = min([bound_j, theoretical_bound_j]) if ... | Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|V] - I[U:Z|V] | BaseTwoPartIntrinsicMutualInformation | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseTwoPartIntrinsicMutualInformation:
"""Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|V] - I[U:Z|V]"""
def __init__(self... | stack_v2_sparse_classes_36k_train_024365 | 25,213 | permissive | [
{
"docstring": "Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to compute the intrinsic mutual information of. rvs : list, None A list of lists. Each inner list specifies the indexes of the random variables used to calculate the intrinsic mutual information. If None, then i... | 3 | null | Implement the Python class `BaseTwoPartIntrinsicMutualInformation` described below.
Class description:
Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|... | Implement the Python class `BaseTwoPartIntrinsicMutualInformation` described below.
Class description:
Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|... | b13c5020a2b8524527a4a0db5a81d8549142228c | <|skeleton|>
class BaseTwoPartIntrinsicMutualInformation:
"""Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|V] - I[U:Z|V]"""
def __init__(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseTwoPartIntrinsicMutualInformation:
"""Compute the two-part intrinsic mutual informations, an upper bound on the secret key agreement rate: .. math:: I[X : Y \\downarrow\\downarrow\\downarrow\\downarrow Z] = inf_{J} min_{V - U - XY - ZJ} I[X:Y|J] + I[U:J|V] - I[U:Z|V]"""
def __init__(self, dist, rvs=N... | the_stack_v2_python_sparse | dit/multivariate/secret_key_agreement/base_skar_optimizers.py | dit/dit | train | 468 |
cd51951988cc830caa77f03f2eeb40d2fcc4bf9b | [
"super(SelfAttention, self).__init__()\nself.in_channel = in_channel\nif out_channel is not None:\n self.out_channel = out_channel\nelse:\n self.out_channel = in_channel\nself.temperature = self.out_channel ** 0.5\nself.q_map = nn.Conv1d(in_channel, out_channel, 1, bias=False)\nself.k_map = nn.Conv1d(in_chann... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.in_channel = in_channel
if out_channel is not None:
self.out_channel = out_channel
else:
self.out_channel = in_channel
self.temperature = self.out_channel ** 0.5
self.q_map = nn.Conv1d(in_... | SelfAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
def __init__(self, in_channel, out_channel=None, attn_dropout=0.1):
""":param in_channel: previous layer's output feature dimension :param out_channel: size of output vector, defaults to in_channel"""
<|body_0|>
def forward(self, x):
""":param x: the f... | stack_v2_sparse_classes_36k_train_024366 | 1,662 | permissive | [
{
"docstring": ":param in_channel: previous layer's output feature dimension :param out_channel: size of output vector, defaults to in_channel",
"name": "__init__",
"signature": "def __init__(self, in_channel, out_channel=None, attn_dropout=0.1)"
},
{
"docstring": ":param x: the feature maps fro... | 2 | stack_v2_sparse_classes_30k_train_014763 | Implement the Python class `SelfAttention` described below.
Class description:
Implement the SelfAttention class.
Method signatures and docstrings:
- def __init__(self, in_channel, out_channel=None, attn_dropout=0.1): :param in_channel: previous layer's output feature dimension :param out_channel: size of output vect... | Implement the Python class `SelfAttention` described below.
Class description:
Implement the SelfAttention class.
Method signatures and docstrings:
- def __init__(self, in_channel, out_channel=None, attn_dropout=0.1): :param in_channel: previous layer's output feature dimension :param out_channel: size of output vect... | d046b36458a5b0c57b4783e597bb180fccc4ddb2 | <|skeleton|>
class SelfAttention:
def __init__(self, in_channel, out_channel=None, attn_dropout=0.1):
""":param in_channel: previous layer's output feature dimension :param out_channel: size of output vector, defaults to in_channel"""
<|body_0|>
def forward(self, x):
""":param x: the f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
def __init__(self, in_channel, out_channel=None, attn_dropout=0.1):
""":param in_channel: previous layer's output feature dimension :param out_channel: size of output vector, defaults to in_channel"""
super(SelfAttention, self).__init__()
self.in_channel = in_channel
... | the_stack_v2_python_sparse | models/attention.py | henghuiding/attMPTI | train | 1 | |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"name = read_unicode_string(fp)\nclassID = read_length_and_key(fp)\nvalue = read_unicode_string(fp)\nreturn cls(name, classID, value)",
"written = write_unicode_string(fp, self.name)\nwritten += write_length_and_key(fp, self.classID)\nwritten += write_unicode_string(fp, self.value)\nreturn written"
] | <|body_start_0|>
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
value = read_unicode_string(fp)
return cls(name, classID, value)
<|end_body_0|>
<|body_start_1|>
written = write_unicode_string(fp, self.name)
written += write_length_and_key(fp, self.class... | Name structure (Undocumented). | Name | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Name:
"""Name structure (Undocumented)."""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_024367 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000120 | Implement the Python class `Name` described below.
Class description:
Name structure (Undocumented).
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file-like object | Implement the Python class `Name` described below.
Class description:
Name structure (Undocumented).
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file-like object
... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class Name:
"""Name structure (Undocumented)."""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Name:
"""Name structure (Undocumented)."""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
value = read_unicode_string(fp)
return cls(name, classID, valu... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
3bd0351821970c475d87327494d672eeaa24358b | [
"if sys.version_info.major >= 3:\n if isinstance(recipients, abc.KeysView):\n recipients = [x for x in recipients]\nif isinstance(recipients, dict):\n recipients = [x for x in recipients]\nif not isinstance(recipients, list):\n recipients = recipients.split(',')\nif not len(recipients):\n raise V... | <|body_start_0|>
if sys.version_info.major >= 3:
if isinstance(recipients, abc.KeysView):
recipients = [x for x in recipients]
if isinstance(recipients, dict):
recipients = [x for x in recipients]
if not isinstance(recipients, list):
recipients... | ToolsOSD | [
"EFL-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
<|b... | stack_v2_sparse_classes_36k_train_024368 | 12,939 | permissive | [
{
"docstring": "Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())",
"name": "get_message_recipientgroups",
"signature": "def get_message_recipientgroups(bot... | 3 | stack_v2_sparse_classes_30k_test_000773 | Implement the Python class `ToolsOSD` described below.
Class description:
Implement the ToolsOSD class.
Method signatures and docstrings:
- def get_message_recipientgroups(bot, recipients, text_method): Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a com... | Implement the Python class `ToolsOSD` described below.
Class description:
Implement the ToolsOSD class.
Method signatures and docstrings:
- def get_message_recipientgroups(bot, recipients, text_method): Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a com... | 816dddc88943b9194f3f0aa6558759eedd585343 | <|skeleton|>
class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
if sys.version_in... | the_stack_v2_python_sparse | sopel_modules/SpiceBot/osd.py | SpiceBot/SpiceBot | train | 1 | |
29fff5538d81fc2a9d182ec7ff1592062e783825 | [
"self.pendulum_mass = pendulum_mass\nself.cart_mass = cart_mass\nself.length = length\nself.rot_friction = rot_friction\nself.gravity = gravity\nsuper().__init__(func=self._ode, step_size=step_size, dim_action=(1,), dim_state=(4,))",
"bk = get_backend(state)\npendulum_mass = self.pendulum_mass\ncart_mass = self.c... | <|body_start_0|>
self.pendulum_mass = pendulum_mass
self.cart_mass = cart_mass
self.length = length
self.rot_friction = rot_friction
self.gravity = gravity
super().__init__(func=self._ode, step_size=step_size, dim_action=(1,), dim_state=(4,))
<|end_body_0|>
<|body_start_... | Cart with mounted inverted pendulum. Parameters ---------- pendulum_mass : float cart_mass : float length : float rot_friction : float, optional gravity: float, optional step_size : float, optional | CartPole | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartPole:
"""Cart with mounted inverted pendulum. Parameters ---------- pendulum_mass : float cart_mass : float length : float rot_friction : float, optional gravity: float, optional step_size : float, optional"""
def __init__(self, pendulum_mass, cart_mass, length, rot_friction=0.0, gravity... | stack_v2_sparse_classes_36k_train_024369 | 2,902 | permissive | [
{
"docstring": "Initialization; see `CartPole`.",
"name": "__init__",
"signature": "def __init__(self, pendulum_mass, cart_mass, length, rot_friction=0.0, gravity=9.81, step_size=0.01)"
},
{
"docstring": "Compute the state time-derivative. Parameters ---------- state: ndarray or Tensor States. a... | 2 | null | Implement the Python class `CartPole` described below.
Class description:
Cart with mounted inverted pendulum. Parameters ---------- pendulum_mass : float cart_mass : float length : float rot_friction : float, optional gravity: float, optional step_size : float, optional
Method signatures and docstrings:
- def __init... | Implement the Python class `CartPole` described below.
Class description:
Cart with mounted inverted pendulum. Parameters ---------- pendulum_mass : float cart_mass : float length : float rot_friction : float, optional gravity: float, optional step_size : float, optional
Method signatures and docstrings:
- def __init... | c144aeecba5f35ccfb4ec943d29d7092c0fa20e3 | <|skeleton|>
class CartPole:
"""Cart with mounted inverted pendulum. Parameters ---------- pendulum_mass : float cart_mass : float length : float rot_friction : float, optional gravity: float, optional step_size : float, optional"""
def __init__(self, pendulum_mass, cart_mass, length, rot_friction=0.0, gravity... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CartPole:
"""Cart with mounted inverted pendulum. Parameters ---------- pendulum_mass : float cart_mass : float length : float rot_friction : float, optional gravity: float, optional step_size : float, optional"""
def __init__(self, pendulum_mass, cart_mass, length, rot_friction=0.0, gravity=9.81, step_s... | the_stack_v2_python_sparse | rllib/environment/systems/cart_pole.py | tzahishimkin/extended-hucrl | train | 0 |
796c97fa706620ae501f9414f89251b4409d38ea | [
"self.ensure_one()\nif self.communication_channel != 'email':\n return False\nif self.state in ('sent', 'done'):\n raise ValidationError(_('This communication is already sent.'))\nlines_2be_processed = self.credit_control_line_ids.filtered(lambda line: line.state != 'sent')\nif not lines_2be_processed:\n r... | <|body_start_0|>
self.ensure_one()
if self.communication_channel != 'email':
return False
if self.state in ('sent', 'done'):
raise ValidationError(_('This communication is already sent.'))
lines_2be_processed = self.credit_control_line_ids.filtered(lambda line: li... | CreditControlCommunication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreditControlCommunication:
def action_send_email(self):
"""Send account follow-up email to the customer. :return:"""
<|body_0|>
def _compute_credit_control_lines_html(self):
"""This method renders the qweb template and returns the result as HTML. :return: HTML strin... | stack_v2_sparse_classes_36k_train_024370 | 3,309 | no_license | [
{
"docstring": "Send account follow-up email to the customer. :return:",
"name": "action_send_email",
"signature": "def action_send_email(self)"
},
{
"docstring": "This method renders the qweb template and returns the result as HTML. :return: HTML string",
"name": "_compute_credit_control_li... | 4 | stack_v2_sparse_classes_30k_train_008611 | Implement the Python class `CreditControlCommunication` described below.
Class description:
Implement the CreditControlCommunication class.
Method signatures and docstrings:
- def action_send_email(self): Send account follow-up email to the customer. :return:
- def _compute_credit_control_lines_html(self): This metho... | Implement the Python class `CreditControlCommunication` described below.
Class description:
Implement the CreditControlCommunication class.
Method signatures and docstrings:
- def action_send_email(self): Send account follow-up email to the customer. :return:
- def _compute_credit_control_lines_html(self): This metho... | c04e2b9730db07848c153d8245d2df65ec4e2c8f | <|skeleton|>
class CreditControlCommunication:
def action_send_email(self):
"""Send account follow-up email to the customer. :return:"""
<|body_0|>
def _compute_credit_control_lines_html(self):
"""This method renders the qweb template and returns the result as HTML. :return: HTML strin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreditControlCommunication:
def action_send_email(self):
"""Send account follow-up email to the customer. :return:"""
self.ensure_one()
if self.communication_channel != 'email':
return False
if self.state in ('sent', 'done'):
raise ValidationError(_('Thi... | the_stack_v2_python_sparse | altinkaya_credit_control/models/credit_control_communication.py | aaltinisik/customaddons | train | 15 | |
8bb77ee804b8aa6e528df1580208304302f7516b | [
"validator = URLValidator()\nredirect_uris = self.cleaned_data.get('redirect_uris', '').split()\nerrors = []\nfor uri in redirect_uris:\n try:\n validator(uri)\n except ValidationError as e:\n errors.append(e)\nif errors:\n raise ValidationError(errors)\nreturn ' '.join(redirect_uris)",
"se... | <|body_start_0|>
validator = URLValidator()
redirect_uris = self.cleaned_data.get('redirect_uris', '').split()
errors = []
for uri in redirect_uris:
try:
validator(uri)
except ValidationError as e:
errors.append(e)
if errors... | The application configuration form. This form provides a more helpful user selection widget, as well as providing help text for all fields. | ApplicationForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationForm:
"""The application configuration form. This form provides a more helpful user selection widget, as well as providing help text for all fields."""
def clean_redirect_uris(self):
"""Clean the redirect_uris field. This method will ensure that all the URIs are valid by v... | stack_v2_sparse_classes_36k_train_024371 | 4,611 | permissive | [
{
"docstring": "Clean the redirect_uris field. This method will ensure that all the URIs are valid by validating each of them, as well as removing unnecessary whitespace. Returns: unicode: A space-separated list of URIs. Raises: django.core.exceptions.ValidationError: Raised when one or more URIs are invalid.",... | 2 | null | Implement the Python class `ApplicationForm` described below.
Class description:
The application configuration form. This form provides a more helpful user selection widget, as well as providing help text for all fields.
Method signatures and docstrings:
- def clean_redirect_uris(self): Clean the redirect_uris field.... | Implement the Python class `ApplicationForm` described below.
Class description:
The application configuration form. This form provides a more helpful user selection widget, as well as providing help text for all fields.
Method signatures and docstrings:
- def clean_redirect_uris(self): Clean the redirect_uris field.... | 02e1ef3a4e9a8117977b053805234a713c31a699 | <|skeleton|>
class ApplicationForm:
"""The application configuration form. This form provides a more helpful user selection widget, as well as providing help text for all fields."""
def clean_redirect_uris(self):
"""Clean the redirect_uris field. This method will ensure that all the URIs are valid by v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApplicationForm:
"""The application configuration form. This form provides a more helpful user selection widget, as well as providing help text for all fields."""
def clean_redirect_uris(self):
"""Clean the redirect_uris field. This method will ensure that all the URIs are valid by validating eac... | the_stack_v2_python_sparse | reviewboard/oauth/forms.py | parthyz/reviewboard | train | 1 |
60eecbc9886dc6e7e022d5c87830e49e1975c31f | [
"self.quark = quark\nself.nucleon = nucleon\nself.ip = input_dict",
"self.mN = (self.ip['mproton'] + self.ip['mneutron']) / 2\nif self.nucleon == 'p':\n if self.quark == 'u':\n return self.mN ** 2 * 2 * self.ip['gA']\n if self.quark == 'd':\n return -self.mN ** 2 * 2 * self.ip['gA']\n if se... | <|body_start_0|>
self.quark = quark
self.nucleon = nucleon
self.ip = input_dict
<|end_body_0|>
<|body_start_1|>
self.mN = (self.ip['mproton'] + self.ip['mneutron']) / 2
if self.nucleon == 'p':
if self.quark == 'u':
return self.mN ** 2 * 2 * self.ip['g... | FPprimed | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FPprimed:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (option... | stack_v2_sparse_classes_36k_train_024372 | 18,337 | permissive | [
{
"docstring": "The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictionary of hadronic input parameters (default is Num_inpu... | 3 | stack_v2_sparse_classes_30k_val_000394 | Implement the Python class `FPprimed` described below.
Class description:
Implement the FPprimed class.
Method signatures and docstrings:
- def __init__(self, quark, nucleon, input_dict): The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark fl... | Implement the Python class `FPprimed` described below.
Class description:
Implement the FPprimed class.
Method signatures and docstrings:
- def __init__(self, quark, nucleon, input_dict): The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark fl... | 4a714e4701f817fdc96e10e461eef7c4756ef71d | <|skeleton|>
class FPprimed:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (option... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FPprimed:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dicti... | the_stack_v2_python_sparse | directdm/num/single_nucleon_form_factors.py | DirectDM/directdm-py | train | 6 | |
394c26e9a45324310557d2d65c891077892be553 | [
"self.f = f\nself.memo = {}\nprint('Calling __init__()')",
"if args not in self.memo:\n self.memo[args] = self.f(*args)\nreturn self.memo[args]"
] | <|body_start_0|>
self.f = f
self.memo = {}
print('Calling __init__()')
<|end_body_0|>
<|body_start_1|>
if args not in self.memo:
self.memo[args] = self.f(*args)
return self.memo[args]
<|end_body_1|>
| Implements memoize functionality. | Memoize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Memoize:
"""Implements memoize functionality."""
def __init__(self, f):
"""Initializes dictionary to store factorials which can be used later. Args: f: Reference to called function."""
<|body_0|>
def __call__(self, *args):
"""Calls the actual function if output i... | stack_v2_sparse_classes_36k_train_024373 | 1,465 | no_license | [
{
"docstring": "Initializes dictionary to store factorials which can be used later. Args: f: Reference to called function.",
"name": "__init__",
"signature": "def __init__(self, f)"
},
{
"docstring": "Calls the actual function if output is not stored for a input. Args: args: Tuple of function ar... | 2 | stack_v2_sparse_classes_30k_train_003722 | Implement the Python class `Memoize` described below.
Class description:
Implements memoize functionality.
Method signatures and docstrings:
- def __init__(self, f): Initializes dictionary to store factorials which can be used later. Args: f: Reference to called function.
- def __call__(self, *args): Calls the actual... | Implement the Python class `Memoize` described below.
Class description:
Implements memoize functionality.
Method signatures and docstrings:
- def __init__(self, f): Initializes dictionary to store factorials which can be used later. Args: f: Reference to called function.
- def __call__(self, *args): Calls the actual... | 2d6e1a19365730ba98c544245140556d0df6a8af | <|skeleton|>
class Memoize:
"""Implements memoize functionality."""
def __init__(self, f):
"""Initializes dictionary to store factorials which can be used later. Args: f: Reference to called function."""
<|body_0|>
def __call__(self, *args):
"""Calls the actual function if output i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Memoize:
"""Implements memoize functionality."""
def __init__(self, f):
"""Initializes dictionary to store factorials which can be used later. Args: f: Reference to called function."""
self.f = f
self.memo = {}
print('Calling __init__()')
def __call__(self, *args):
... | the_stack_v2_python_sparse | python/memoization_using_class.py | hansrajdas/sample-programs | train | 0 |
5a64df55eec34a4d79ab704e71045c78a10e261b | [
"key = cache_key('friends', user.pk)\nfriends = cache.get(key)\nif friends is None:\n qs = Friend.objects.select_related('from_user', 'to_user').filter(to_user=user).all()\n friends = [u.from_user for u in qs]\n cache.set(key, friends)\nreturn friends",
"key = cache_key('requests', user.pk)\nrequests = c... | <|body_start_0|>
key = cache_key('friends', user.pk)
friends = cache.get(key)
if friends is None:
qs = Friend.objects.select_related('from_user', 'to_user').filter(to_user=user).all()
friends = [u.from_user for u in qs]
cache.set(key, friends)
return f... | Friendship manager | FriendshipManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FriendshipManager:
"""Friendship manager"""
def friends(self, user):
"""Return a list of all friends"""
<|body_0|>
def requests(self, user):
"""Return a list of friendship requests"""
<|body_1|>
def sent_requests(self, user):
"""Return a list... | stack_v2_sparse_classes_36k_train_024374 | 8,134 | no_license | [
{
"docstring": "Return a list of all friends",
"name": "friends",
"signature": "def friends(self, user)"
},
{
"docstring": "Return a list of friendship requests",
"name": "requests",
"signature": "def requests(self, user)"
},
{
"docstring": "Return a list of friendship requests f... | 6 | stack_v2_sparse_classes_30k_train_010368 | Implement the Python class `FriendshipManager` described below.
Class description:
Friendship manager
Method signatures and docstrings:
- def friends(self, user): Return a list of all friends
- def requests(self, user): Return a list of friendship requests
- def sent_requests(self, user): Return a list of friendship ... | Implement the Python class `FriendshipManager` described below.
Class description:
Friendship manager
Method signatures and docstrings:
- def friends(self, user): Return a list of all friends
- def requests(self, user): Return a list of friendship requests
- def sent_requests(self, user): Return a list of friendship ... | 2a1c64a2a1680913a68e97bbba980a4fde9a603e | <|skeleton|>
class FriendshipManager:
"""Friendship manager"""
def friends(self, user):
"""Return a list of all friends"""
<|body_0|>
def requests(self, user):
"""Return a list of friendship requests"""
<|body_1|>
def sent_requests(self, user):
"""Return a list... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FriendshipManager:
"""Friendship manager"""
def friends(self, user):
"""Return a list of all friends"""
key = cache_key('friends', user.pk)
friends = cache.get(key)
if friends is None:
qs = Friend.objects.select_related('from_user', 'to_user').filter(to_user=us... | the_stack_v2_python_sparse | connect/models.py | jordanSev/CS3398-Ferengi-Finaglers-S2019 | train | 0 |
ee8a32474724df8d9352932bf974c01dd2cd4051 | [
"self.on_cts = on_cts\nself.on_intvl = on_intvl\nself.off_cts = off_cts\nself.off_intvl = off_intvl\nself.cutoff = cutoff\nself.offset = slml_offset(on_cts, on_intvl, off_cts, off_intvl)\nself.p_signal = None",
"try:\n s = float(s)\n llike, nt, err = slmlike(s, self.on_cts, self.on_intvl, self.off_cts, self... | <|body_start_0|>
self.on_cts = on_cts
self.on_intvl = on_intvl
self.off_cts = off_cts
self.off_intvl = off_intvl
self.cutoff = cutoff
self.offset = slml_offset(on_cts, on_intvl, off_cts, off_intvl)
self.p_signal = None
<|end_body_0|>
<|body_start_1|>
try:... | Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (siglml); * The marginal posterior density for the signal rate (sigmp); * ... | OnOff | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnOff:
"""Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (siglml); * The marginal posterior densit... | stack_v2_sparse_classes_36k_train_024375 | 16,279 | no_license | [
{
"docstring": "Initialize an OnOff object. :Parameters: on_cts : int Counts observed on source (source + background) on_intvl: float Interval spanned on source off_cts: int Counts observed off source (background only) off_intvl : float Interval spanned off source :Keywords: cutoff : float Cutoff for truncation... | 4 | stack_v2_sparse_classes_30k_train_016365 | Implement the Python class `OnOff` described below.
Class description:
Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (s... | Implement the Python class `OnOff` described below.
Class description:
Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (s... | 215de4e93b5cf79a1e9f380047b4db92bfeaf45c | <|skeleton|>
class OnOff:
"""Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (siglml); * The marginal posterior densit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnOff:
"""Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (siglml); * The marginal posterior density for the sig... | the_stack_v2_python_sparse | package/inference/count/onoff.py | tloredo/inference | train | 3 |
38803b63e87eb5c83bf36cab94d1b3b7eb998017 | [
"self.driver.get(self.get_login_url())\nusername_input_id = 'id_username'\npassword_input_id = 'id_password'\ntry:\n element_present = EC.presence_of_element_located((By.ID, username_input_id))\n WebDriverWait(self.driver, self.pessimistic_wait).until(element_present)\nexcept TimeoutException:\n logger.war... | <|body_start_0|>
self.driver.get(self.get_login_url())
username_input_id = 'id_username'
password_input_id = 'id_password'
try:
element_present = EC.presence_of_element_located((By.ID, username_input_id))
WebDriverWait(self.driver, self.pessimistic_wait).until(ele... | Archivematica Authentication Ability: the ability of an Archivematica user to use a browser to login/out to/from Archivematica and/or the Storage Service. | ArchivematicaBrowserAuthenticationAbility | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArchivematicaBrowserAuthenticationAbility:
"""Archivematica Authentication Ability: the ability of an Archivematica user to use a browser to login/out to/from Archivematica and/or the Storage Service."""
def login(self):
"""Login to Archivematica."""
<|body_0|>
def login... | stack_v2_sparse_classes_36k_train_024376 | 2,398 | no_license | [
{
"docstring": "Login to Archivematica.",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "Login to Archivematica Storage Service.",
"name": "login_ss",
"signature": "def login_ss(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004832 | Implement the Python class `ArchivematicaBrowserAuthenticationAbility` described below.
Class description:
Archivematica Authentication Ability: the ability of an Archivematica user to use a browser to login/out to/from Archivematica and/or the Storage Service.
Method signatures and docstrings:
- def login(self): Log... | Implement the Python class `ArchivematicaBrowserAuthenticationAbility` described below.
Class description:
Archivematica Authentication Ability: the ability of an Archivematica user to use a browser to login/out to/from Archivematica and/or the Storage Service.
Method signatures and docstrings:
- def login(self): Log... | 96fe940a9e18f97aae5868fe4c7c6d0b389814d0 | <|skeleton|>
class ArchivematicaBrowserAuthenticationAbility:
"""Archivematica Authentication Ability: the ability of an Archivematica user to use a browser to login/out to/from Archivematica and/or the Storage Service."""
def login(self):
"""Login to Archivematica."""
<|body_0|>
def login... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArchivematicaBrowserAuthenticationAbility:
"""Archivematica Authentication Ability: the ability of an Archivematica user to use a browser to login/out to/from Archivematica and/or the Storage Service."""
def login(self):
"""Login to Archivematica."""
self.driver.get(self.get_login_url())
... | the_stack_v2_python_sparse | amuser/am_browser_auth_ability.py | artefactual-labs/archivematica-acceptance-tests | train | 3 |
32386b116366ad506499352b7802573b8a14b170 | [
"self._hass = hass\nself._recp_nrs = recp_nrs\nself._signal_cli_rest_api = signal_cli_rest_api",
"_LOGGER.debug('Sending signal message')\ndata = kwargs.get(ATTR_DATA)\ntry:\n data = DATA_SCHEMA(data)\nexcept vol.Invalid as ex:\n _LOGGER.error('Invalid message data: %s', ex)\n raise ex\nfilenames = self.... | <|body_start_0|>
self._hass = hass
self._recp_nrs = recp_nrs
self._signal_cli_rest_api = signal_cli_rest_api
<|end_body_0|>
<|body_start_1|>
_LOGGER.debug('Sending signal message')
data = kwargs.get(ATTR_DATA)
try:
data = DATA_SCHEMA(data)
except vol.... | Implement the notification service for SignalMessenger. | SignalNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalNotificationService:
"""Implement the notification service for SignalMessenger."""
def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None:
"""Initialize the service."""
<|body_0|>
def send_message(self, message: ... | stack_v2_sparse_classes_36k_train_024377 | 5,525 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None"
},
{
"docstring": "Send a message to a one or more recipients. Additionally a file can be attached.",
"name... | 4 | stack_v2_sparse_classes_30k_train_015029 | Implement the Python class `SignalNotificationService` described below.
Class description:
Implement the notification service for SignalMessenger.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None: Initialize the service.
- ... | Implement the Python class `SignalNotificationService` described below.
Class description:
Implement the notification service for SignalMessenger.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None: Initialize the service.
- ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SignalNotificationService:
"""Implement the notification service for SignalMessenger."""
def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None:
"""Initialize the service."""
<|body_0|>
def send_message(self, message: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignalNotificationService:
"""Implement the notification service for SignalMessenger."""
def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None:
"""Initialize the service."""
self._hass = hass
self._recp_nrs = recp_nrs
s... | the_stack_v2_python_sparse | homeassistant/components/signal_messenger/notify.py | home-assistant/core | train | 35,501 |
6f97c9fe59b491b3f585e4695249f63f1543559a | [
"super(MultiHeadedAttention, self).__init__()\nassert n_feat % n_head == 0\nself.d_k = n_feat // n_head\nself.h = n_head\nself.linear_q = nn.Linear(n_feat, n_feat)\nself.linear_k = nn.Linear(n_feat, n_feat)\nself.linear_v = nn.Linear(n_feat, n_feat)\nself.linear_out = nn.Linear(n_feat, n_feat)\nself.attn = None\nse... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert n_feat % n_head == 0
self.d_k = n_feat // n_head
self.h = n_head
self.linear_q = nn.Linear(n_feat, n_feat)
self.linear_k = nn.Linear(n_feat, n_feat)
self.linear_v = nn.Linear(n_feat, n_feat)
... | Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate. | MultiHeadedAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dropout_rate):
"""Construct an MultiHeadedAttention object."""
<|body_... | stack_v2_sparse_classes_36k_train_024378 | 11,646 | permissive | [
{
"docstring": "Construct an MultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_head, n_feat, dropout_rate)"
},
{
"docstring": "Transform query, key and value. Args: query (torch.Tensor): Query tensor (#batch, time1, size). key (torch.Tensor): Key tensor (#batc... | 4 | null | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.
Method signatures and docstrings:
- def __init__(self, n_head, n_feat, dropout_rate): Con... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.
Method signatures and docstrings:
- def __init__(self, n_head, n_feat, dropout_rate): Con... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class MultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dropout_rate):
"""Construct an MultiHeadedAttention object."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dropout_rate):
"""Construct an MultiHeadedAttention object."""
super(MultiHeadedAtt... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/attention.py | espnet/espnet | train | 7,242 |
88a8d28ca9bfadf87df1165a5f526f1aaabfcf56 | [
"target = sum\nmemo = {0: 1}\n\ndef dfs(node, cursum):\n if not node:\n return 0\n cursum += node.val\n count = memo.get(cursum - target, 0)\n memo[cursum] = memo.get(cursum, 0) + 1\n sub = dfs(node.left, cursum) + dfs(node.right, cursum)\n memo[cursum] -= 1\n return count + sub\nreturn ... | <|body_start_0|>
target = sum
memo = {0: 1}
def dfs(node, cursum):
if not node:
return 0
cursum += node.val
count = memo.get(cursum - target, 0)
memo[cursum] = memo.get(cursum, 0) + 1
sub = dfs(node.left, cursum) + dfs(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum1(self, root: TreeNode, sum: int) -> int:
"""前缀和+记忆优化,参考560题解"""
<|body_0|>
def pathSum2(self, root: TreeNode, sum: int) -> int:
"""https://leetcode-cn.com/problems/path-sum-iii/solution/437zhi-xu-yi-ci-di-gui-wu-xing-dai-ma-yong-lie-bia/"""
... | stack_v2_sparse_classes_36k_train_024379 | 1,916 | no_license | [
{
"docstring": "前缀和+记忆优化,参考560题解",
"name": "pathSum1",
"signature": "def pathSum1(self, root: TreeNode, sum: int) -> int"
},
{
"docstring": "https://leetcode-cn.com/problems/path-sum-iii/solution/437zhi-xu-yi-ci-di-gui-wu-xing-dai-ma-yong-lie-bia/",
"name": "pathSum2",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_000464 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum1(self, root: TreeNode, sum: int) -> int: 前缀和+记忆优化,参考560题解
- def pathSum2(self, root: TreeNode, sum: int) -> int: https://leetcode-cn.com/problems/path-sum-iii/solutio... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum1(self, root: TreeNode, sum: int) -> int: 前缀和+记忆优化,参考560题解
- def pathSum2(self, root: TreeNode, sum: int) -> int: https://leetcode-cn.com/problems/path-sum-iii/solutio... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def pathSum1(self, root: TreeNode, sum: int) -> int:
"""前缀和+记忆优化,参考560题解"""
<|body_0|>
def pathSum2(self, root: TreeNode, sum: int) -> int:
"""https://leetcode-cn.com/problems/path-sum-iii/solution/437zhi-xu-yi-ci-di-gui-wu-xing-dai-ma-yong-lie-bia/"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum1(self, root: TreeNode, sum: int) -> int:
"""前缀和+记忆优化,参考560题解"""
target = sum
memo = {0: 1}
def dfs(node, cursum):
if not node:
return 0
cursum += node.val
count = memo.get(cursum - target, 0)
... | the_stack_v2_python_sparse | 437_path-sum-iii.py | helloocc/algorithm | train | 1 | |
019f1141aafc7b72fcafb5e954970e316bcb1538 | [
"super().__init__(node, control, unique_id, description, device_info)\nself._memory_change_handler: EventListener | None = None\nself._attr_native_value = 0",
"await super().async_added_to_hass()\nif (last_state := (await self.async_get_last_state())) and (last_number_data := (await self.async_get_last_number_dat... | <|body_start_0|>
super().__init__(node, control, unique_id, description, device_info)
self._memory_change_handler: EventListener | None = None
self._attr_native_value = 0
<|end_body_0|>
<|body_start_1|>
await super().async_added_to_hass()
if (last_state := (await self.async_get_... | Representation of a ISY/IoX Backlight Number entity. | ISYBacklightNumberEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISYBacklightNumberEntity:
"""Representation of a ISY/IoX Backlight Number entity."""
def __init__(self, node: Node, control: str, unique_id: str, description: NumberEntityDescription, device_info: DeviceInfo | None) -> None:
"""Initialize the ISY Backlight number entity."""
<... | stack_v2_sparse_classes_36k_train_024380 | 10,460 | permissive | [
{
"docstring": "Initialize the ISY Backlight number entity.",
"name": "__init__",
"signature": "def __init__(self, node: Node, control: str, unique_id: str, description: NumberEntityDescription, device_info: DeviceInfo | None) -> None"
},
{
"docstring": "Load the last known state when added to h... | 4 | null | Implement the Python class `ISYBacklightNumberEntity` described below.
Class description:
Representation of a ISY/IoX Backlight Number entity.
Method signatures and docstrings:
- def __init__(self, node: Node, control: str, unique_id: str, description: NumberEntityDescription, device_info: DeviceInfo | None) -> None:... | Implement the Python class `ISYBacklightNumberEntity` described below.
Class description:
Representation of a ISY/IoX Backlight Number entity.
Method signatures and docstrings:
- def __init__(self, node: Node, control: str, unique_id: str, description: NumberEntityDescription, device_info: DeviceInfo | None) -> None:... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ISYBacklightNumberEntity:
"""Representation of a ISY/IoX Backlight Number entity."""
def __init__(self, node: Node, control: str, unique_id: str, description: NumberEntityDescription, device_info: DeviceInfo | None) -> None:
"""Initialize the ISY Backlight number entity."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ISYBacklightNumberEntity:
"""Representation of a ISY/IoX Backlight Number entity."""
def __init__(self, node: Node, control: str, unique_id: str, description: NumberEntityDescription, device_info: DeviceInfo | None) -> None:
"""Initialize the ISY Backlight number entity."""
super().__init... | the_stack_v2_python_sparse | homeassistant/components/isy994/number.py | home-assistant/core | train | 35,501 |
904ef3d679591c460965ec30cfe76dcc3a7a08fa | [
"super().__init__()\nself.batch_size = batch_size\nself.decoding_units = decoding_units\nself.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dimension)\nif gru:\n self.layer = tf.keras.layers.GRU(self.decoding_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')\n... | <|body_start_0|>
super().__init__()
self.batch_size = batch_size
self.decoding_units = decoding_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dimension)
if gru:
self.layer = tf.keras.layers.GRU(self.decoding_units, return_sequences=True, retur... | Decoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
def __init__(self, vocab_size, embedding_dimension, decoding_units, batch_size, gru: bool=True):
"""decoder for attention model"""
<|body_0|>
def call(self, x, hidden, enc_output):
"""given vector, hidden, and encoding, return new vector, state, and weights"... | stack_v2_sparse_classes_36k_train_024381 | 2,408 | permissive | [
{
"docstring": "decoder for attention model",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embedding_dimension, decoding_units, batch_size, gru: bool=True)"
},
{
"docstring": "given vector, hidden, and encoding, return new vector, state, and weights",
"name": "call",
... | 2 | stack_v2_sparse_classes_30k_test_001129 | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dimension, decoding_units, batch_size, gru: bool=True): decoder for attention model
- def call(self, x, hidden, enc_output): given vector, ... | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dimension, decoding_units, batch_size, gru: bool=True): decoder for attention model
- def call(self, x, hidden, enc_output): given vector, ... | d1d4d485d1fac8743cdbbc2996792db249dcf389 | <|skeleton|>
class Decoder:
def __init__(self, vocab_size, embedding_dimension, decoding_units, batch_size, gru: bool=True):
"""decoder for attention model"""
<|body_0|>
def call(self, x, hidden, enc_output):
"""given vector, hidden, and encoding, return new vector, state, and weights"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
def __init__(self, vocab_size, embedding_dimension, decoding_units, batch_size, gru: bool=True):
"""decoder for attention model"""
super().__init__()
self.batch_size = batch_size
self.decoding_units = decoding_units
self.embedding = tf.keras.layers.Embedding(vo... | the_stack_v2_python_sparse | assignment5/code/src/decoder.py | jschmidtnj/cs584 | train | 0 | |
4f359ac464a854cceb537dac85dff1cdb369c5b9 | [
"users = Users.objects.filter(business_group=request.session['user']['business_group']).order_by('-status', 'id')\nserializer = UsersSerializer(users, many=True)\nreturn Response({'status': True, 'message': '成功', 'data': serializer.data})",
"query = request.data.get('query')\nusers = Users.objects.filter(Q(userna... | <|body_start_0|>
users = Users.objects.filter(business_group=request.session['user']['business_group']).order_by('-status', 'id')
serializer = UsersSerializer(users, many=True)
return Response({'status': True, 'message': '成功', 'data': serializer.data})
<|end_body_0|>
<|body_start_1|>
qu... | 用户列表 | UserList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserList:
"""用户列表"""
def get(self, request):
"""获取所有用户列表(可用于开发人员,测试人员等)"""
<|body_0|>
def post(self, request):
"""根据用户名或姓名查询用户"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
users = Users.objects.filter(business_group=request.session['user']['b... | stack_v2_sparse_classes_36k_train_024382 | 7,374 | no_license | [
{
"docstring": "获取所有用户列表(可用于开发人员,测试人员等)",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "根据用户名或姓名查询用户",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `UserList` described below.
Class description:
用户列表
Method signatures and docstrings:
- def get(self, request): 获取所有用户列表(可用于开发人员,测试人员等)
- def post(self, request): 根据用户名或姓名查询用户 | Implement the Python class `UserList` described below.
Class description:
用户列表
Method signatures and docstrings:
- def get(self, request): 获取所有用户列表(可用于开发人员,测试人员等)
- def post(self, request): 根据用户名或姓名查询用户
<|skeleton|>
class UserList:
"""用户列表"""
def get(self, request):
"""获取所有用户列表(可用于开发人员,测试人员等)"""
... | 1621ee90681a7796da7ad7173cc2a9b67494ed03 | <|skeleton|>
class UserList:
"""用户列表"""
def get(self, request):
"""获取所有用户列表(可用于开发人员,测试人员等)"""
<|body_0|>
def post(self, request):
"""根据用户名或姓名查询用户"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserList:
"""用户列表"""
def get(self, request):
"""获取所有用户列表(可用于开发人员,测试人员等)"""
users = Users.objects.filter(business_group=request.session['user']['business_group']).order_by('-status', 'id')
serializer = UsersSerializer(users, many=True)
return Response({'status': True, 'mess... | the_stack_v2_python_sparse | at_server-master/userapp/views.py | xiaominwanglast/reactjs | train | 1 |
d01e4f7e3b3ee39208237293aaf6869aefbce9e5 | [
"label = 'a'\nbytes = [ord('a')]\nself.assertEqual(make_dafsa.encode_prefix(label), bytes)",
"label = 'ab'\nbytes = [ord('b'), ord('a')]\nself.assertEqual(make_dafsa.encode_prefix(label), bytes)"
] | <|body_start_0|>
label = 'a'
bytes = [ord('a')]
self.assertEqual(make_dafsa.encode_prefix(label), bytes)
<|end_body_0|>
<|body_start_1|>
label = 'ab'
bytes = [ord('b'), ord('a')]
self.assertEqual(make_dafsa.encode_prefix(label), bytes)
<|end_body_1|>
| EncodePrefixTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncodePrefixTest:
def testChar(self):
"""Tests to encode a single character prefix."""
<|body_0|>
def testChars(self):
"""Tests to encode a multi character prefix."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
label = 'a'
bytes = [ord('a')... | stack_v2_sparse_classes_36k_train_024383 | 20,781 | permissive | [
{
"docstring": "Tests to encode a single character prefix.",
"name": "testChar",
"signature": "def testChar(self)"
},
{
"docstring": "Tests to encode a multi character prefix.",
"name": "testChars",
"signature": "def testChars(self)"
}
] | 2 | null | Implement the Python class `EncodePrefixTest` described below.
Class description:
Implement the EncodePrefixTest class.
Method signatures and docstrings:
- def testChar(self): Tests to encode a single character prefix.
- def testChars(self): Tests to encode a multi character prefix. | Implement the Python class `EncodePrefixTest` described below.
Class description:
Implement the EncodePrefixTest class.
Method signatures and docstrings:
- def testChar(self): Tests to encode a single character prefix.
- def testChars(self): Tests to encode a multi character prefix.
<|skeleton|>
class EncodePrefixTe... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class EncodePrefixTest:
def testChar(self):
"""Tests to encode a single character prefix."""
<|body_0|>
def testChars(self):
"""Tests to encode a multi character prefix."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncodePrefixTest:
def testChar(self):
"""Tests to encode a single character prefix."""
label = 'a'
bytes = [ord('a')]
self.assertEqual(make_dafsa.encode_prefix(label), bytes)
def testChars(self):
"""Tests to encode a multi character prefix."""
label = 'ab'
... | the_stack_v2_python_sparse | tools/media_engagement_preload/make_dafsa_unittest.py | chromium/chromium | train | 17,408 | |
1439eb609cddb100c757ad56676c6951732d16f3 | [
"if sys.version_info > (3,):\n instance().info(txt)\nelse:\n try:\n instance().info(unicode(txt).encode('utf-8'))\n except:\n instance().info(txt)",
"if sys.version_info > (3,):\n instance().debug(txt)\nelse:\n try:\n instance().debug(unicode(txt).encode('utf-8'))\n except:\... | <|body_start_0|>
if sys.version_info > (3,):
instance().info(txt)
else:
try:
instance().info(unicode(txt).encode('utf-8'))
except:
instance().info(txt)
<|end_body_0|>
<|body_start_1|>
if sys.version_info > (3,):
ins... | Logger | ClassLogger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassLogger:
"""Logger"""
def info(self, txt):
"""Display message in the screen @param txt: message @type txt: string"""
<|body_0|>
def trace(self, txt):
"""Display message in the screen @param txt: message @type txt: string"""
<|body_1|>
def error(s... | stack_v2_sparse_classes_36k_train_024384 | 6,693 | permissive | [
{
"docstring": "Display message in the screen @param txt: message @type txt: string",
"name": "info",
"signature": "def info(self, txt)"
},
{
"docstring": "Display message in the screen @param txt: message @type txt: string",
"name": "trace",
"signature": "def trace(self, txt)"
},
{
... | 3 | null | Implement the Python class `ClassLogger` described below.
Class description:
Logger
Method signatures and docstrings:
- def info(self, txt): Display message in the screen @param txt: message @type txt: string
- def trace(self, txt): Display message in the screen @param txt: message @type txt: string
- def error(self,... | Implement the Python class `ClassLogger` described below.
Class description:
Logger
Method signatures and docstrings:
- def info(self, txt): Display message in the screen @param txt: message @type txt: string
- def trace(self, txt): Display message in the screen @param txt: message @type txt: string
- def error(self,... | 66f65dd6e4a48909120f63239f630147c733df3f | <|skeleton|>
class ClassLogger:
"""Logger"""
def info(self, txt):
"""Display message in the screen @param txt: message @type txt: string"""
<|body_0|>
def trace(self, txt):
"""Display message in the screen @param txt: message @type txt: string"""
<|body_1|>
def error(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassLogger:
"""Logger"""
def info(self, txt):
"""Display message in the screen @param txt: message @type txt: string"""
if sys.version_info > (3,):
instance().info(txt)
else:
try:
instance().info(unicode(txt).encode('utf-8'))
ex... | the_stack_v2_python_sparse | Libs/Logger.py | ExtensiveAutomation/extensiveautomation-appclient | train | 2 |
1b16ad67ef6a32b8ae52a07658e5d902da79c872 | [
"username = self.request.user.get_username()\nalbums = Album.objects.filter(user__username=username)\nphotos = Photo.objects.filter(user__username=username)\nreturn (albums, photos)",
"context = super().get_context_data(**kwargs)\nalbums = context['albums_and_photos'][0]\nphotos = context['albums_and_photos'][1]\... | <|body_start_0|>
username = self.request.user.get_username()
albums = Album.objects.filter(user__username=username)
photos = Photo.objects.filter(user__username=username)
return (albums, photos)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
... | Define the library view class. | LibraryView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryView:
"""Define the library view class."""
def get_queryset(self):
"""Get the context to display."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Filter the context for display."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
usern... | stack_v2_sparse_classes_36k_train_024385 | 4,522 | permissive | [
{
"docstring": "Get the context to display.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Filter the context for display.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000071 | Implement the Python class `LibraryView` described below.
Class description:
Define the library view class.
Method signatures and docstrings:
- def get_queryset(self): Get the context to display.
- def get_context_data(self, **kwargs): Filter the context for display. | Implement the Python class `LibraryView` described below.
Class description:
Define the library view class.
Method signatures and docstrings:
- def get_queryset(self): Get the context to display.
- def get_context_data(self, **kwargs): Filter the context for display.
<|skeleton|>
class LibraryView:
"""Define the... | bd78a0c7442d90db8af26bdd93f6170d36dd2385 | <|skeleton|>
class LibraryView:
"""Define the library view class."""
def get_queryset(self):
"""Get the context to display."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Filter the context for display."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LibraryView:
"""Define the library view class."""
def get_queryset(self):
"""Get the context to display."""
username = self.request.user.get_username()
albums = Album.objects.filter(user__username=username)
photos = Photo.objects.filter(user__username=username)
ret... | the_stack_v2_python_sparse | imagersite/imager_images/views.py | ShannonTully/django-imager | train | 1 |
d1996d89dfe707a7f259692889eb85139eaa28d0 | [
"ans = []\nfrom collections import deque\nqueue = deque()\nfor i in range(len(nums)):\n while queue and queue[0] < i - k + 1:\n queue.popleft()\n while queue and nums[i] > nums[queue[-1]]:\n queue.pop()\n queue.append(i)\n if i >= k - 1:\n ans.append(nums[queue[0]])\nreturn ans",
... | <|body_start_0|>
ans = []
from collections import deque
queue = deque()
for i in range(len(nums)):
while queue and queue[0] < i - k + 1:
queue.popleft()
while queue and nums[i] > nums[queue[-1]]:
queue.pop()
queue.append... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
"""Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0遍历到3的时候,由于3进来后,前面比3小的元素一定不可能是目标的元素,所以将其弹出,而遍历 到2的时候,2不大于3,并且不知道2后面的元素会不会比2更小,也就是2可能是一个候选的最大值,所以入队... | stack_v2_sparse_classes_36k_train_024386 | 3,046 | no_license | [
{
"docstring": "Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0遍历到3的时候,由于3进来后,前面比3小的元素一定不可能是目标的元素,所以将其弹出,而遍历 到2的时候,2不大于3,并且不知道2后面的元素会不会比2更小,也就是2可能是一个候选的最大值,所以入队列。如此 一来便可以在遍历到第i个元素时确认这个元素的留存状态,即它大于队列尾元素,队列尾弹出,然后第i元素入队列。... | 2 | stack_v2_sparse_classes_30k_train_010608 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0... | a1c074ff0d542f7ef0e5e01e280b16e52fa7a33d | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
"""Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0遍历到3的时候,由于3进来后,前面比3小的元素一定不可能是目标的元素,所以将其弹出,而遍历 到2的时候,2不大于3,并且不知道2后面的元素会不会比2更小,也就是2可能是一个候选的最大值,所以入队... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSlidingWindow(self, nums, k):
"""Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0遍历到3的时候,由于3进来后,前面比3小的元素一定不可能是目标的元素,所以将其弹出,而遍历 到2的时候,2不大于3,并且不知道2后面的元素会不会比2更小,也就是2可能是一个候选的最大值,所以入队列。如此 一来便可以在遍历到... | the_stack_v2_python_sparse | 239_Sliding Window Maximum.py | xhwupup/xhw_project | train | 0 | |
e91046afd7362c2a75232c702cb226dbc661d236 | [
"time = timezone.now() + datetime.timedelta(weeks=1664)\nfuture_question = Question(pub_date=time)\nself.assertIs(future_question.was_published_recently(), False)",
"time = timezone.now() - datetime.timedelta(days=1, seconds=1)\nold_question = Question(pub_date=time)\nself.assertIs(old_question.was_published_rece... | <|body_start_0|>
time = timezone.now() + datetime.timedelta(weeks=1664)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
<|end_body_0|>
<|body_start_1|>
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
old_ques... | Tests for Question Model | QuestionModelTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionModelTests:
"""Tests for Question Model"""
def test_was_published_recently_with_future_question(self):
"""If date is in future, was_published_recently() should return False"""
<|body_0|>
def test_was_published_recently_with_old_question(self):
"""If date ... | stack_v2_sparse_classes_36k_train_024387 | 5,109 | no_license | [
{
"docstring": "If date is in future, was_published_recently() should return False",
"name": "test_was_published_recently_with_future_question",
"signature": "def test_was_published_recently_with_future_question(self)"
},
{
"docstring": "If date is in past, was_published_recently() should return... | 3 | null | Implement the Python class `QuestionModelTests` described below.
Class description:
Tests for Question Model
Method signatures and docstrings:
- def test_was_published_recently_with_future_question(self): If date is in future, was_published_recently() should return False
- def test_was_published_recently_with_old_que... | Implement the Python class `QuestionModelTests` described below.
Class description:
Tests for Question Model
Method signatures and docstrings:
- def test_was_published_recently_with_future_question(self): If date is in future, was_published_recently() should return False
- def test_was_published_recently_with_old_que... | 7be49bb366ec6bb8b4f97575e54e007cd4317938 | <|skeleton|>
class QuestionModelTests:
"""Tests for Question Model"""
def test_was_published_recently_with_future_question(self):
"""If date is in future, was_published_recently() should return False"""
<|body_0|>
def test_was_published_recently_with_old_question(self):
"""If date ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionModelTests:
"""Tests for Question Model"""
def test_was_published_recently_with_future_question(self):
"""If date is in future, was_published_recently() should return False"""
time = timezone.now() + datetime.timedelta(weeks=1664)
future_question = Question(pub_date=time)
... | the_stack_v2_python_sparse | code/cory/Django/polls-tutorial/polls/tests.py | PdxCodeGuild/class_redmage | train | 0 |
72a5672a6bae08e14ece7c8a608b058e163012e6 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('cici_fyl', 'cici_fyl')\npropertydata = repo['cici_fyl.property'].find()\nrestaurantdata = repo['cici_fyl.restaurant'].find()\ncoor = methods.selectcoordinate(restaurantdata)\nx = methods.appendattribute(... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cici_fyl', 'cici_fyl')
propertydata = repo['cici_fyl.property'].find()
restaurantdata = repo['cici_fyl.restaurant'].find()
coor = methods.... | processrestaurant | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class processrestaurant:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyt... | stack_v2_sparse_classes_36k_train_024388 | 3,335 | permissive | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_020201 | Implement the Python class `processrestaurant` described below.
Class description:
Implement the processrestaurant class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime... | Implement the Python class `processrestaurant` described below.
Class description:
Implement the processrestaurant class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class processrestaurant:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class processrestaurant:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cici_fyl', 'cici_fyl')
pr... | the_stack_v2_python_sparse | cici_fyl/project/cici_fyl/processrestaurant.py | lingyigu/course-2017-spr-proj | train | 0 | |
24ca209ed8521ea936023e716fe4cd1531926e18 | [
"sentence = layer[wt.sentence]\nif len(sentence) < 2:\n return False\nif sentence[1] != wt.verb or sentence[0] != wt.questionWord:\n return False\nreturn (layer[wt.questionWord] in ['kes', 'keda'] and len(set(layer[wt.verb]).intersection({'olema', 'valima', 'on'}))) != 0 and sentence[2] == wt.about",
"answe... | <|body_start_0|>
sentence = layer[wt.sentence]
if len(sentence) < 2:
return False
if sentence[1] != wt.verb or sentence[0] != wt.questionWord:
return False
return (layer[wt.questionWord] in ['kes', 'keda'] and len(set(layer[wt.verb]).intersection({'olema', 'valima... | WhoIs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhoIs:
def canAnswer(self, layer):
"""checks if user asked WHO IS question :param currenLayer: currently used layer :return:return if client asked who question"""
<|body_0|>
def answer(self, layer):
"""Answers general who questions about UT :param word: Noun that the... | stack_v2_sparse_classes_36k_train_024389 | 1,194 | no_license | [
{
"docstring": "checks if user asked WHO IS question :param currenLayer: currently used layer :return:return if client asked who question",
"name": "canAnswer",
"signature": "def canAnswer(self, layer)"
},
{
"docstring": "Answers general who questions about UT :param word: Noun that the user ask... | 2 | stack_v2_sparse_classes_30k_train_018955 | Implement the Python class `WhoIs` described below.
Class description:
Implement the WhoIs class.
Method signatures and docstrings:
- def canAnswer(self, layer): checks if user asked WHO IS question :param currenLayer: currently used layer :return:return if client asked who question
- def answer(self, layer): Answers... | Implement the Python class `WhoIs` described below.
Class description:
Implement the WhoIs class.
Method signatures and docstrings:
- def canAnswer(self, layer): checks if user asked WHO IS question :param currenLayer: currently used layer :return:return if client asked who question
- def answer(self, layer): Answers... | f761909d3bcfb5651814cf5090e242f6bcad8ce0 | <|skeleton|>
class WhoIs:
def canAnswer(self, layer):
"""checks if user asked WHO IS question :param currenLayer: currently used layer :return:return if client asked who question"""
<|body_0|>
def answer(self, layer):
"""Answers general who questions about UT :param word: Noun that the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WhoIs:
def canAnswer(self, layer):
"""checks if user asked WHO IS question :param currenLayer: currently used layer :return:return if client asked who question"""
sentence = layer[wt.sentence]
if len(sentence) < 2:
return False
if sentence[1] != wt.verb or sentence[... | the_stack_v2_python_sparse | langprocessing/questions/WhoIsQuestion.py | Terminaator/chatbot | train | 0 | |
1e894d296ab14aadc1667d38ebeee560cb1fdc51 | [
"self.force_scale_x = 0.3\nself.force_scale_y = 0.1\nself.force_offset_x = 100.0\nself.force_offset_y = 10.0\nself.steering_p_gain = 1.0\nself.steering_d_gain = 0.1\nself.car_width = car_width\nself.scan_width = scan_width\nself.lidar_range = lidar_range\nself.turn_clearance = turn_clearance * (math.pi / 180.0)\nse... | <|body_start_0|>
self.force_scale_x = 0.3
self.force_scale_y = 0.1
self.force_offset_x = 100.0
self.force_offset_y = 10.0
self.steering_p_gain = 1.0
self.steering_d_gain = 0.1
self.car_width = car_width
self.scan_width = scan_width
self.lidar_range... | PotentialFieldController | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PotentialFieldController:
def __init__(self, car_width=0.5, scan_width=270.0, lidar_range=10.0, turn_clearance=0.35, max_turn_angle=34.0, min_speed=0.5, max_speed=3.0, min_dist=0.1, max_dist=3.0, no_obst_dist=10.0):
"""Todo: explanation of what is :param car_width: (float) Half the car's... | stack_v2_sparse_classes_36k_train_024390 | 8,441 | permissive | [
{
"docstring": "Todo: explanation of what is :param car_width: (float) Half the car's width with tolerance used for calculating todo Default=0.5 :param scan_width: (float) The arc width of the full Lidar scan in degrees. Default=270.0 for Hokuyo UST-10LX :param lidar_range: (float) Maximum range of the Lidar in... | 5 | stack_v2_sparse_classes_30k_val_000198 | Implement the Python class `PotentialFieldController` described below.
Class description:
Implement the PotentialFieldController class.
Method signatures and docstrings:
- def __init__(self, car_width=0.5, scan_width=270.0, lidar_range=10.0, turn_clearance=0.35, max_turn_angle=34.0, min_speed=0.5, max_speed=3.0, min_... | Implement the Python class `PotentialFieldController` described below.
Class description:
Implement the PotentialFieldController class.
Method signatures and docstrings:
- def __init__(self, car_width=0.5, scan_width=270.0, lidar_range=10.0, turn_clearance=0.35, max_turn_angle=34.0, min_speed=0.5, max_speed=3.0, min_... | 3ae3ab1cedd89e56db2fbabe24f1c6a79d3553d9 | <|skeleton|>
class PotentialFieldController:
def __init__(self, car_width=0.5, scan_width=270.0, lidar_range=10.0, turn_clearance=0.35, max_turn_angle=34.0, min_speed=0.5, max_speed=3.0, min_dist=0.1, max_dist=3.0, no_obst_dist=10.0):
"""Todo: explanation of what is :param car_width: (float) Half the car's... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PotentialFieldController:
def __init__(self, car_width=0.5, scan_width=270.0, lidar_range=10.0, turn_clearance=0.35, max_turn_angle=34.0, min_speed=0.5, max_speed=3.0, min_dist=0.1, max_dist=3.0, no_obst_dist=10.0):
"""Todo: explanation of what is :param car_width: (float) Half the car's width with to... | the_stack_v2_python_sparse | src/racecar/scripts/pfc.py | pmusau17/F1TenthHardware | train | 3 | |
1f2e8b9969e50c5531b35169fc84b89106403967 | [
"self.dict_lanelet_conf_point = {}\nfor i in range(len(cl.id)):\n self.dict_lanelet_conf_point[cl.id[i]] = cl.conf_point[i]\nself.dict_lanelet_agent = {}\nself.dict_parent_lanelet = {}\nself.dict_lanelet_potential_agent = {}\nself.sorted_lanelet = []\nself.i_ego = 0\nself.sorted_conf_agent = []\nself.dict_agent_... | <|body_start_0|>
self.dict_lanelet_conf_point = {}
for i in range(len(cl.id)):
self.dict_lanelet_conf_point[cl.id[i]] = cl.conf_point[i]
self.dict_lanelet_agent = {}
self.dict_parent_lanelet = {}
self.dict_lanelet_potential_agent = {}
self.sorted_lanelet = []
... | 提取交叉路口的冲突信息 | IntersectionInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntersectionInfo:
"""提取交叉路口的冲突信息"""
def __init__(self, cl) -> None:
"""params: cl: Conf_Lanelet类"""
<|body_0|>
def extend2list(self, lanelet_network):
"""为了适应接口。暂时修改"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dict_lanelet_conf_point = ... | stack_v2_sparse_classes_36k_train_024391 | 33,485 | no_license | [
{
"docstring": "params: cl: Conf_Lanelet类",
"name": "__init__",
"signature": "def __init__(self, cl) -> None"
},
{
"docstring": "为了适应接口。暂时修改",
"name": "extend2list",
"signature": "def extend2list(self, lanelet_network)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000788 | Implement the Python class `IntersectionInfo` described below.
Class description:
提取交叉路口的冲突信息
Method signatures and docstrings:
- def __init__(self, cl) -> None: params: cl: Conf_Lanelet类
- def extend2list(self, lanelet_network): 为了适应接口。暂时修改 | Implement the Python class `IntersectionInfo` described below.
Class description:
提取交叉路口的冲突信息
Method signatures and docstrings:
- def __init__(self, cl) -> None: params: cl: Conf_Lanelet类
- def extend2list(self, lanelet_network): 为了适应接口。暂时修改
<|skeleton|>
class IntersectionInfo:
"""提取交叉路口的冲突信息"""
def __init_... | 4d714b0d2f917b7f66e32ffc0083a3dd09d0bc72 | <|skeleton|>
class IntersectionInfo:
"""提取交叉路口的冲突信息"""
def __init__(self, cl) -> None:
"""params: cl: Conf_Lanelet类"""
<|body_0|>
def extend2list(self, lanelet_network):
"""为了适应接口。暂时修改"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntersectionInfo:
"""提取交叉路口的冲突信息"""
def __init__(self, cl) -> None:
"""params: cl: Conf_Lanelet类"""
self.dict_lanelet_conf_point = {}
for i in range(len(cl.id)):
self.dict_lanelet_conf_point[cl.id[i]] = cl.conf_point[i]
self.dict_lanelet_agent = {}
self... | the_stack_v2_python_sparse | intersection_planner.py | passengerxuhongli/commonroad_planner | train | 0 |
61328977615887b4958199dfd9744623844c780e | [
"super().__init__(name)\nself._sensitive_registry = set()\nself._lock = Lock()",
"if value:\n with self._lock:\n self._sensitive_registry.add(str(value))",
"record.msg = self.replace(record.getMessage())\nrecord.args = {}\nreturn True",
"with self._lock:\n for replacement in self._sensitive_regis... | <|body_start_0|>
super().__init__(name)
self._sensitive_registry = set()
self._lock = Lock()
<|end_body_0|>
<|body_start_1|>
if value:
with self._lock:
self._sensitive_registry.add(str(value))
<|end_body_1|>
<|body_start_2|>
record.msg = self.replace... | Sensitive Log Filter | SensitiveFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensitiveFilter:
"""Sensitive Log Filter"""
def __init__(self, name=''):
"""Plug in a new filter to an existing formatter"""
<|body_0|>
def add(self, value: str):
"""Add sensitive value to registry."""
<|body_1|>
def filter(self, record: logging.LogR... | stack_v2_sparse_classes_36k_train_024392 | 1,094 | permissive | [
{
"docstring": "Plug in a new filter to an existing formatter",
"name": "__init__",
"signature": "def __init__(self, name='')"
},
{
"docstring": "Add sensitive value to registry.",
"name": "add",
"signature": "def add(self, value: str)"
},
{
"docstring": "Filter the record",
... | 4 | null | Implement the Python class `SensitiveFilter` described below.
Class description:
Sensitive Log Filter
Method signatures and docstrings:
- def __init__(self, name=''): Plug in a new filter to an existing formatter
- def add(self, value: str): Add sensitive value to registry.
- def filter(self, record: logging.LogRecor... | Implement the Python class `SensitiveFilter` described below.
Class description:
Sensitive Log Filter
Method signatures and docstrings:
- def __init__(self, name=''): Plug in a new filter to an existing formatter
- def add(self, value: str): Add sensitive value to registry.
- def filter(self, record: logging.LogRecor... | 30dc147e40d63d1082ec2a5e6c62005b60c29c37 | <|skeleton|>
class SensitiveFilter:
"""Sensitive Log Filter"""
def __init__(self, name=''):
"""Plug in a new filter to an existing formatter"""
<|body_0|>
def add(self, value: str):
"""Add sensitive value to registry."""
<|body_1|>
def filter(self, record: logging.LogR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SensitiveFilter:
"""Sensitive Log Filter"""
def __init__(self, name=''):
"""Plug in a new filter to an existing formatter"""
super().__init__(name)
self._sensitive_registry = set()
self._lock = Lock()
def add(self, value: str):
"""Add sensitive value to regist... | the_stack_v2_python_sparse | tcex/logger/sensitive_filter.py | ThreatConnect-Inc/tcex | train | 24 |
8bf0eedabf05fb31f88926141b89399b19e0d6f7 | [
"super(LibraryPackage, self).__init__(name, helpText)\nself._LibName = libName\nself._Header = header\nself._Framework = framework\nreturn",
"if self._Framework == False:\n installed, self._CheckPipe = PackageUtil.TestLibrary(self._LibName, self._Header)\nelse:\n installed, self._CheckPipe = PackageUtil.Tes... | <|body_start_0|>
super(LibraryPackage, self).__init__(name, helpText)
self._LibName = libName
self._Header = header
self._Framework = framework
return
<|end_body_0|>
<|body_start_1|>
if self._Framework == False:
installed, self._CheckPipe = PackageUtil.TestLi... | For packages that are system wide libraries e.g. X11. | LibraryPackage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryPackage:
"""For packages that are system wide libraries e.g. X11."""
def __init__(self, name, helpText, libName, header=None, framework=False):
"""Initialise the package."""
<|body_0|>
def CheckState(self):
"""Need to test the library linking and inclusion... | stack_v2_sparse_classes_36k_train_024393 | 1,134 | no_license | [
{
"docstring": "Initialise the package.",
"name": "__init__",
"signature": "def __init__(self, name, helpText, libName, header=None, framework=False)"
},
{
"docstring": "Need to test the library linking and inclusion of the header.",
"name": "CheckState",
"signature": "def CheckState(sel... | 2 | stack_v2_sparse_classes_30k_train_006506 | Implement the Python class `LibraryPackage` described below.
Class description:
For packages that are system wide libraries e.g. X11.
Method signatures and docstrings:
- def __init__(self, name, helpText, libName, header=None, framework=False): Initialise the package.
- def CheckState(self): Need to test the library ... | Implement the Python class `LibraryPackage` described below.
Class description:
For packages that are system wide libraries e.g. X11.
Method signatures and docstrings:
- def __init__(self, name, helpText, libName, header=None, framework=False): Initialise the package.
- def CheckState(self): Need to test the library ... | 33c6fcaf848e25303161e41bf4b5f73863a144f0 | <|skeleton|>
class LibraryPackage:
"""For packages that are system wide libraries e.g. X11."""
def __init__(self, name, helpText, libName, header=None, framework=False):
"""Initialise the package."""
<|body_0|>
def CheckState(self):
"""Need to test the library linking and inclusion... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LibraryPackage:
"""For packages that are system wide libraries e.g. X11."""
def __init__(self, name, helpText, libName, header=None, framework=False):
"""Initialise the package."""
super(LibraryPackage, self).__init__(name, helpText)
self._LibName = libName
self._Header = ... | the_stack_v2_python_sparse | core/LibraryPackage.py | mschwen/snoing | train | 0 |
0bd1808eecfc0c246b65e26d8ac90132f0da6860 | [
"model_properties = mall_models.ProductModelProperty.objects.filter(owner=request.manager, is_deleted=False)\nid2property = {}\nfor model_property in model_properties:\n model_property.property_values = []\n t_name = model_property.name\n model_property.shot_name = t_name[:6] + '...' if len(t_name) > 6 els... | <|body_start_0|>
model_properties = mall_models.ProductModelProperty.objects.filter(owner=request.manager, is_deleted=False)
id2property = {}
for model_property in model_properties:
model_property.property_values = []
t_name = model_property.name
model_propert... | ModelPropertyList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelPropertyList:
def get(request):
"""商品规格列表页面."""
<|body_0|>
def api_get(request):
"""获取全部规格属性集合 Return json: Example: [{ id: 1, name: "颜色", type: "text", values: [{ id: 1, full_id: "1:1", //full_id表示${property.id}:${value.id} name: "红", image: "" }, { id: 2, name... | stack_v2_sparse_classes_36k_train_024394 | 9,873 | no_license | [
{
"docstring": "商品规格列表页面.",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "获取全部规格属性集合 Return json: Example: [{ id: 1, name: \"颜色\", type: \"text\", values: [{ id: 1, full_id: \"1:1\", //full_id表示${property.id}:${value.id} name: \"红\", image: \"\" }, { id: 2, name: \"白\" image:... | 2 | null | Implement the Python class `ModelPropertyList` described below.
Class description:
Implement the ModelPropertyList class.
Method signatures and docstrings:
- def get(request): 商品规格列表页面.
- def api_get(request): 获取全部规格属性集合 Return json: Example: [{ id: 1, name: "颜色", type: "text", values: [{ id: 1, full_id: "1:1", //ful... | Implement the Python class `ModelPropertyList` described below.
Class description:
Implement the ModelPropertyList class.
Method signatures and docstrings:
- def get(request): 商品规格列表页面.
- def api_get(request): 获取全部规格属性集合 Return json: Example: [{ id: 1, name: "颜色", type: "text", values: [{ id: 1, full_id: "1:1", //ful... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class ModelPropertyList:
def get(request):
"""商品规格列表页面."""
<|body_0|>
def api_get(request):
"""获取全部规格属性集合 Return json: Example: [{ id: 1, name: "颜色", type: "text", values: [{ id: 1, full_id: "1:1", //full_id表示${property.id}:${value.id} name: "红", image: "" }, { id: 2, name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelPropertyList:
def get(request):
"""商品规格列表页面."""
model_properties = mall_models.ProductModelProperty.objects.filter(owner=request.manager, is_deleted=False)
id2property = {}
for model_property in model_properties:
model_property.property_values = []
... | the_stack_v2_python_sparse | weapp/mall/product/model_property.py | chengdg/weizoom | train | 1 | |
20eb97d6eebd246ed1ccce4410c85deb2748a8f7 | [
"super(MLP, self).__init__()\nself.linear_layers = nn.ModuleList()\nif len(n_hidden) == 0:\n self.linear_layers.append(nn.Linear(n_inputs, n_classes))\nelse:\n for i in range(len(n_hidden)):\n if i == 0:\n n_in = n_inputs\n else:\n n_in = n_hidden[i - 1]\n self.linea... | <|body_start_0|>
super(MLP, self).__init__()
self.linear_layers = nn.ModuleList()
if len(n_hidden) == 0:
self.linear_layers.append(nn.Linear(n_inputs, n_classes))
else:
for i in range(len(n_hidden)):
if i == 0:
n_in = n_inputs
... | This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward. | MLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_inputs, n_hidden, n_classes):
"""Initializes MLP object. Args: n_inputs: number ... | stack_v2_sparse_classes_36k_train_024395 | 2,665 | no_license | [
{
"docstring": "Initializes MLP object. Args: n_inputs: number of inputs. n_hidden: list of ints, specifies the number of units in each linear layer. If the list is empty, the MLP will not have any linear layers, and the model will simply perform a multinomial logistic regression. n_classes: number of classes o... | 2 | stack_v2_sparse_classes_30k_train_018379 | Implement the Python class `MLP` described below.
Class description:
This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward.
Method signatures and docstrings:
- def __init__(self, n_inputs, n_hidden, n_... | Implement the Python class `MLP` described below.
Class description:
This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward.
Method signatures and docstrings:
- def __init__(self, n_inputs, n_hidden, n_... | 7f56384b5dcb71d3c432cca47b65f25acf847208 | <|skeleton|>
class MLP:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_inputs, n_hidden, n_classes):
"""Initializes MLP object. Args: n_inputs: number ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLP:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_inputs, n_hidden, n_classes):
"""Initializes MLP object. Args: n_inputs: number of inputs. n_... | the_stack_v2_python_sparse | assignment_1/code/mlp_pytorch.py | MichelleAppel/deep-learning | train | 1 |
031f7932f060574d8950ad7bd22c64639b8b52c4 | [
"nassets = 3\nann_vol = AnnualizedVolatility()\ntoday = pd.Timestamp('2016', tz='utc')\nassets = np.arange(nassets, dtype=np.float64)\nreturns = np.full((ann_vol.window_length, nassets), 0.004, dtype=np.float64)\nout = np.empty(shape=(nassets,), dtype=np.float64)\nann_vol.compute(today, assets, out, returns, 252)\n... | <|body_start_0|>
nassets = 3
ann_vol = AnnualizedVolatility()
today = pd.Timestamp('2016', tz='utc')
assets = np.arange(nassets, dtype=np.float64)
returns = np.full((ann_vol.window_length, nassets), 0.004, dtype=np.float64)
out = np.empty(shape=(nassets,), dtype=np.float6... | Test Annualized Volatility | AnnualizedVolatilityTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnualizedVolatilityTestCase:
"""Test Annualized Volatility"""
def test_simple_volatility(self):
"""Simple test for uniform returns should generate 0 volatility"""
<|body_0|>
def test_volatility(self):
"""Check volatility results against values calculated manuall... | stack_v2_sparse_classes_36k_train_024396 | 20,639 | permissive | [
{
"docstring": "Simple test for uniform returns should generate 0 volatility",
"name": "test_simple_volatility",
"signature": "def test_simple_volatility(self)"
},
{
"docstring": "Check volatility results against values calculated manually",
"name": "test_volatility",
"signature": "def t... | 2 | null | Implement the Python class `AnnualizedVolatilityTestCase` described below.
Class description:
Test Annualized Volatility
Method signatures and docstrings:
- def test_simple_volatility(self): Simple test for uniform returns should generate 0 volatility
- def test_volatility(self): Check volatility results against valu... | Implement the Python class `AnnualizedVolatilityTestCase` described below.
Class description:
Test Annualized Volatility
Method signatures and docstrings:
- def test_simple_volatility(self): Simple test for uniform returns should generate 0 volatility
- def test_volatility(self): Check volatility results against valu... | d08d1a9a343232e37d9e5767cae64af799067b45 | <|skeleton|>
class AnnualizedVolatilityTestCase:
"""Test Annualized Volatility"""
def test_simple_volatility(self):
"""Simple test for uniform returns should generate 0 volatility"""
<|body_0|>
def test_volatility(self):
"""Check volatility results against values calculated manuall... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnnualizedVolatilityTestCase:
"""Test Annualized Volatility"""
def test_simple_volatility(self):
"""Simple test for uniform returns should generate 0 volatility"""
nassets = 3
ann_vol = AnnualizedVolatility()
today = pd.Timestamp('2016', tz='utc')
assets = np.arang... | the_stack_v2_python_sparse | zipline/_tests/pipeline/test_technical.py | quantrocket-llc/zipline | train | 17 |
3fc027822bc4b20546b08fb940bf5de65ad5b0bd | [
"if self.error_message:\n return '%s: %s' % (self.__class__.__name__, self.messageFormat(self.error_message))\nelse:\n return '%s: %s' % (self.__class__.__name__, self.messageFormat())",
"if template is None:\n template = self.DEFAULTTEMPLATE\nline, lineChar = self.getLineCoordinate()\nvariables = {'prod... | <|body_start_0|>
if self.error_message:
return '%s: %s' % (self.__class__.__name__, self.messageFormat(self.error_message))
else:
return '%s: %s' % (self.__class__.__name__, self.messageFormat())
<|end_body_0|>
<|body_start_1|>
if template is None:
template =... | Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the production which failed expected -- string (currently taken from grammar) describing what p... | ParserSyntaxError | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParserSyntaxError:
"""Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the production which failed expected -- string (cu... | stack_v2_sparse_classes_36k_train_024397 | 2,101 | permissive | [
{
"docstring": "Create a string representation of the error",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Create a default message for this syntax error",
"name": "messageFormat",
"signature": "def messageFormat(self, template=None)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_012751 | Implement the Python class `ParserSyntaxError` described below.
Class description:
Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the product... | Implement the Python class `ParserSyntaxError` described below.
Class description:
Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the product... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class ParserSyntaxError:
"""Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the production which failed expected -- string (cu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParserSyntaxError:
"""Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the production which failed expected -- string (currently taken... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/simpleparse/error.py | alexus37/AugmentedRealityChess | train | 1 |
a4d8ebce16b692324de7677a8d0d7343a64d5885 | [
"self.receiver_mock.add_mock('volumeset', MockResponse(responses=[(200, VolumeCase.VOLUME_STATUS)], path='/goform/formiPhoneAppVolume.xml'))\ncode, payload = self.open_jrpc('Application.SetVolume', {'volume': 66})\nself.assertEqual(code, 200)\nself.assertPayloadEqual(payload, 75)\nself.assertEqual(self.receiver_moc... | <|body_start_0|>
self.receiver_mock.add_mock('volumeset', MockResponse(responses=[(200, VolumeCase.VOLUME_STATUS)], path='/goform/formiPhoneAppVolume.xml'))
code, payload = self.open_jrpc('Application.SetVolume', {'volume': 66})
self.assertEqual(code, 200)
self.assertPayloadEqual(payload... | VolumeCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeCase:
def test_set_volume(self):
"""Setting the volume targets the receiver"""
<|body_0|>
def test_incr_volume(self):
"""Incrementing the volume targets the receiver"""
<|body_1|>
def test_get_properties_volume(self):
"""Getting the volume ... | stack_v2_sparse_classes_36k_train_024398 | 3,037 | no_license | [
{
"docstring": "Setting the volume targets the receiver",
"name": "test_set_volume",
"signature": "def test_set_volume(self)"
},
{
"docstring": "Incrementing the volume targets the receiver",
"name": "test_incr_volume",
"signature": "def test_incr_volume(self)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_018688 | Implement the Python class `VolumeCase` described below.
Class description:
Implement the VolumeCase class.
Method signatures and docstrings:
- def test_set_volume(self): Setting the volume targets the receiver
- def test_incr_volume(self): Incrementing the volume targets the receiver
- def test_get_properties_volume... | Implement the Python class `VolumeCase` described below.
Class description:
Implement the VolumeCase class.
Method signatures and docstrings:
- def test_set_volume(self): Setting the volume targets the receiver
- def test_incr_volume(self): Incrementing the volume targets the receiver
- def test_get_properties_volume... | 987a13298f289997d89a8ba25a05691f2e947efb | <|skeleton|>
class VolumeCase:
def test_set_volume(self):
"""Setting the volume targets the receiver"""
<|body_0|>
def test_incr_volume(self):
"""Incrementing the volume targets the receiver"""
<|body_1|>
def test_get_properties_volume(self):
"""Getting the volume ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VolumeCase:
def test_set_volume(self):
"""Setting the volume targets the receiver"""
self.receiver_mock.add_mock('volumeset', MockResponse(responses=[(200, VolumeCase.VOLUME_STATUS)], path='/goform/formiPhoneAppVolume.xml'))
code, payload = self.open_jrpc('Application.SetVolume', {'vol... | the_stack_v2_python_sparse | kp/regression/volume_cases.py | Schwartzmorn/kodiproxy | train | 0 | |
b6f5886e709f7280402502c116ab72683f777af3 | [
"super(MySQLNotificationsTable, self).__init__(db_dict, dbtype, verbose)\nself.connectdb(db_dict, verbose)\nself._load_table()",
"start_date, end_date = compute_startend_dates(start_date, end_date=end_date, number_of_days=number_of_days)\ncursor = self.connection.cursor()\ntry:\n if target_id is None:\n ... | <|body_start_0|>
super(MySQLNotificationsTable, self).__init__(db_dict, dbtype, verbose)
self.connectdb(db_dict, verbose)
self._load_table()
<|end_body_0|>
<|body_start_1|>
start_date, end_date = compute_startend_dates(start_date, end_date=end_date, number_of_days=number_of_days)
... | Class representing the connection with a mysql database | MySQLNotificationsTable | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLNotificationsTable:
"""Class representing the connection with a mysql database"""
def __init__(self, db_dict, dbtype, verbose):
"""Read the input file into a dictionary."""
<|body_0|>
def select_by_daterange(self, start_date, end_date=None, number_of_days=None, targ... | stack_v2_sparse_classes_36k_train_024399 | 9,652 | permissive | [
{
"docstring": "Read the input file into a dictionary.",
"name": "__init__",
"signature": "def __init__(self, db_dict, dbtype, verbose)"
},
{
"docstring": "Select records between two timestamps and return the set of records selected Parameters: start_date(:class:`py:datetime.datetime` or `None`)... | 4 | stack_v2_sparse_classes_30k_val_001015 | Implement the Python class `MySQLNotificationsTable` described below.
Class description:
Class representing the connection with a mysql database
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Read the input file into a dictionary.
- def select_by_daterange(self, start_date, end_date... | Implement the Python class `MySQLNotificationsTable` described below.
Class description:
Class representing the connection with a mysql database
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Read the input file into a dictionary.
- def select_by_daterange(self, start_date, end_date... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class MySQLNotificationsTable:
"""Class representing the connection with a mysql database"""
def __init__(self, db_dict, dbtype, verbose):
"""Read the input file into a dictionary."""
<|body_0|>
def select_by_daterange(self, start_date, end_date=None, number_of_days=None, targ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySQLNotificationsTable:
"""Class representing the connection with a mysql database"""
def __init__(self, db_dict, dbtype, verbose):
"""Read the input file into a dictionary."""
super(MySQLNotificationsTable, self).__init__(db_dict, dbtype, verbose)
self.connectdb(db_dict, verbose... | the_stack_v2_python_sparse | smipyping/_notificationstable.py | KSchopmeyer/smipyping | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.