blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d04000bbfd7b31da67ec881d1b5c193611892ad | [
"self.args = args = self.args.strip().lower()\nrecipe, ingredients, tools = ('', '', '')\nif 'from' in args:\n recipe, *rest = args.split(' from ', 1)\n rest = rest[0] if rest else ''\n ingredients, *tools = rest.split(' using ', 1)\nelif 'using' in args:\n recipe, *tools = args.split(' using ', 1)\ntoo... | <|body_start_0|>
self.args = args = self.args.strip().lower()
recipe, ingredients, tools = ('', '', '')
if 'from' in args:
recipe, *rest = args.split(' from ', 1)
rest = rest[0] if rest else ''
ingredients, *tools = rest.split(' using ', 1)
elif 'using... | Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, spellbook Notes: Ingredients must be... | CmdCraft | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdCraft:
"""Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, ... | stack_v2_sparse_classes_10k_train_006000 | 41,597 | permissive | [
{
"docstring": "Handle parsing of: :: <recipe> [FROM <ingredients>] [USING <tools>] Examples: :: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, spellbook",
"name": "parse",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_001897 | Implement the Python class `CmdCraft` described below.
Class description:
Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, b... | Implement the Python class `CmdCraft` described below.
Class description:
Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, b... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class CmdCraft:
"""Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CmdCraft:
"""Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, spellbook Not... | the_stack_v2_python_sparse | evennia/contrib/game_systems/crafting/crafting.py | evennia/evennia | train | 1,781 |
4b612ccddcca123d374e51540159ac2215f18f3c | [
"ability = Ability.query.get(id)\nif not ability:\n api.abort(code=404, message='Ability not found')\nreturn {'data': ability.__jsonapi__()}",
"ability = Ability.query.get(id)\ndata = request.get_json()['data']\ntry:\n if len(data['relationships']['groups']['data']) >= 0:\n ability.groups = list((id[... | <|body_start_0|>
ability = Ability.query.get(id)
if not ability:
api.abort(code=404, message='Ability not found')
return {'data': ability.__jsonapi__()}
<|end_body_0|>
<|body_start_1|>
ability = Ability.query.get(id)
data = request.get_json()['data']
try:
... | Abilities | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Abilities:
def get(self, id):
"""Get ability"""
<|body_0|>
def put(self, id):
"""Update ability"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ability = Ability.query.get(id)
if not ability:
api.abort(code=404, message='Ability ... | stack_v2_sparse_classes_10k_train_006001 | 46,738 | permissive | [
{
"docstring": "Get ability",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update ability",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005721 | Implement the Python class `Abilities` described below.
Class description:
Implement the Abilities class.
Method signatures and docstrings:
- def get(self, id): Get ability
- def put(self, id): Update ability | Implement the Python class `Abilities` described below.
Class description:
Implement the Abilities class.
Method signatures and docstrings:
- def get(self, id): Get ability
- def put(self, id): Update ability
<|skeleton|>
class Abilities:
def get(self, id):
"""Get ability"""
<|body_0|>
def ... | 3439a2dd0bd527c5d604801fec3a5aac904a72e2 | <|skeleton|>
class Abilities:
def get(self, id):
"""Get ability"""
<|body_0|>
def put(self, id):
"""Update ability"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Abilities:
def get(self, id):
"""Get ability"""
ability = Ability.query.get(id)
if not ability:
api.abort(code=404, message='Ability not found')
return {'data': ability.__jsonapi__()}
def put(self, id):
"""Update ability"""
ability = Ability.que... | the_stack_v2_python_sparse | app/views.py | taidos/lxc-rest | train | 0 | |
4c8a10ece7f2349ce117d535e4e7090da2150d20 | [
"fields = OrderedDict()\nvalidator_functions = {}\noptions_members = {}\nfor base in reversed(bases):\n if hasattr(base, '_schema'):\n fields.update(deepcopy(base._schema.fields))\n options_members.update(dict(base._schema.options))\n validator_functions.update(base._schema.validators)\nfor ... | <|body_start_0|>
fields = OrderedDict()
validator_functions = {}
options_members = {}
for base in reversed(bases):
if hasattr(base, '_schema'):
fields.update(deepcopy(base._schema.fields))
options_members.update(dict(base._schema.options))
... | Metaclass for Models. | ModelMeta | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelMeta:
"""Metaclass for Models."""
def __new__(mcs, name, bases, attrs):
"""This metaclass parses the declarative Model into a corresponding Schema, then adding it as the `_schema` attribute to the host class."""
<|body_0|>
def _read_options(mcs, name, bases, attrs, ... | stack_v2_sparse_classes_10k_train_006002 | 15,133 | permissive | [
{
"docstring": "This metaclass parses the declarative Model into a corresponding Schema, then adding it as the `_schema` attribute to the host class.",
"name": "__new__",
"signature": "def __new__(mcs, name, bases, attrs)"
},
{
"docstring": "Parses model `Options` class into a `SchemaOptions` in... | 2 | stack_v2_sparse_classes_30k_train_004225 | Implement the Python class `ModelMeta` described below.
Class description:
Metaclass for Models.
Method signatures and docstrings:
- def __new__(mcs, name, bases, attrs): This metaclass parses the declarative Model into a corresponding Schema, then adding it as the `_schema` attribute to the host class.
- def _read_o... | Implement the Python class `ModelMeta` described below.
Class description:
Metaclass for Models.
Method signatures and docstrings:
- def __new__(mcs, name, bases, attrs): This metaclass parses the declarative Model into a corresponding Schema, then adding it as the `_schema` attribute to the host class.
- def _read_o... | 5c0edaac0bc8b040fda638845f24e39b6c324888 | <|skeleton|>
class ModelMeta:
"""Metaclass for Models."""
def __new__(mcs, name, bases, attrs):
"""This metaclass parses the declarative Model into a corresponding Schema, then adding it as the `_schema` attribute to the host class."""
<|body_0|>
def _read_options(mcs, name, bases, attrs, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelMeta:
"""Metaclass for Models."""
def __new__(mcs, name, bases, attrs):
"""This metaclass parses the declarative Model into a corresponding Schema, then adding it as the `_schema` attribute to the host class."""
fields = OrderedDict()
validator_functions = {}
options_... | the_stack_v2_python_sparse | bin/jamf_pro_addon_for_splunk/aob_py3/solnlib/packages/schematics/models.py | jamf/SplunkBase | train | 5 |
7ef910140a9d2f63ef34668f89c8462a3792b35d | [
"self.prefix_sums = []\nprefix_sum = 0\nfor weight in w:\n prefix_sum += weight\n self.prefix_sums.append(prefix_sum)\nself.total_sum = prefix_sum",
"target = self.total_sum * random()\nlow, high = (0, len(self.prefix_sums))\nwhile low < high:\n mid = low + (high - low) // 2\n if target > self.prefix_... | <|body_start_0|>
self.prefix_sums = []
prefix_sum = 0
for weight in w:
prefix_sum += weight
self.prefix_sums.append(prefix_sum)
self.total_sum = prefix_sum
<|end_body_0|>
<|body_start_1|>
target = self.total_sum * random()
low, high = (0, len(self... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self) -> int:
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.prefix_sums = []
prefix_sum = 0
for weight in w:
... | stack_v2_sparse_classes_10k_train_006003 | 4,170 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w: List[int])"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_004182 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w: List[int]): :type w: List[int]
- def pickIndex(self) -> int: :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w: List[int]): :type w: List[int]
- def pickIndex(self) -> int: :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":ty... | 3c0943ee9b373e4297aa43a4813f0033c284a5b2 | <|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self) -> int:
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
self.prefix_sums = []
prefix_sum = 0
for weight in w:
prefix_sum += weight
self.prefix_sums.append(prefix_sum)
self.total_sum = prefix_sum
def pickIndex(self) -> int:
... | the_stack_v2_python_sparse | 528.random-pick-with-weight.py | Joecth/leetcode_3rd_vscode | train | 0 | |
317b9ce5345b881dee08757ac31de25088eb556d | [
"self.pokemon = pokemon\nself.action = None\nentries = []\nfor pokemon in self.pokemon.getTrainer().beltPokemon:\n entries.append(PokemonMenuEntry(pokemon, self.setAction))\nself.menu = Menu(entries, columns=2)\nscreen = SwitchMenuScreen(self.menu)\ncmds = {commands.UP: self.menu.up, commands.DOWN: self.menu.dow... | <|body_start_0|>
self.pokemon = pokemon
self.action = None
entries = []
for pokemon in self.pokemon.getTrainer().beltPokemon:
entries.append(PokemonMenuEntry(pokemon, self.setAction))
self.menu = Menu(entries, columns=2)
screen = SwitchMenuScreen(self.menu)
... | Controller for Switch Menu | SwitchMenuController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwitchMenuController:
"""Controller for Switch Menu"""
def __init__(self, pokemon, cancellable=True):
"""Initialize the Switch Menu"""
<|body_0|>
def setAction(self, entry):
"""Set the Chosen Action"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_006004 | 1,988 | no_license | [
{
"docstring": "Initialize the Switch Menu",
"name": "__init__",
"signature": "def __init__(self, pokemon, cancellable=True)"
},
{
"docstring": "Set the Chosen Action",
"name": "setAction",
"signature": "def setAction(self, entry)"
}
] | 2 | null | Implement the Python class `SwitchMenuController` described below.
Class description:
Controller for Switch Menu
Method signatures and docstrings:
- def __init__(self, pokemon, cancellable=True): Initialize the Switch Menu
- def setAction(self, entry): Set the Chosen Action | Implement the Python class `SwitchMenuController` described below.
Class description:
Controller for Switch Menu
Method signatures and docstrings:
- def __init__(self, pokemon, cancellable=True): Initialize the Switch Menu
- def setAction(self, entry): Set the Chosen Action
<|skeleton|>
class SwitchMenuController:
... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class SwitchMenuController:
"""Controller for Switch Menu"""
def __init__(self, pokemon, cancellable=True):
"""Initialize the Switch Menu"""
<|body_0|>
def setAction(self, entry):
"""Set the Chosen Action"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SwitchMenuController:
"""Controller for Switch Menu"""
def __init__(self, pokemon, cancellable=True):
"""Initialize the Switch Menu"""
self.pokemon = pokemon
self.action = None
entries = []
for pokemon in self.pokemon.getTrainer().beltPokemon:
entries.a... | the_stack_v2_python_sparse | src/Screen/Pygame/Menu/ActionMenu/SwitchMenu/switch_menu_controller.py | sgtnourry/Pokemon-Project | train | 0 |
70126b46623a972aef6c2521d99e89f61095442e | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file | RDAPServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RDAPServicer:
"""Missing associated documentation comment in .proto file"""
def DomainLookup(self, request, context):
"""Missing associated documentation comment in .proto file"""
<|body_0|>
def EntityLookup(self, request, context):
"""Missing associated document... | stack_v2_sparse_classes_10k_train_006005 | 9,591 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "DomainLookup",
"signature": "def DomainLookup(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "EntityLookup",
"signature": "def EntityLookup(se... | 6 | stack_v2_sparse_classes_30k_train_000275 | Implement the Python class `RDAPServicer` described below.
Class description:
Missing associated documentation comment in .proto file
Method signatures and docstrings:
- def DomainLookup(self, request, context): Missing associated documentation comment in .proto file
- def EntityLookup(self, request, context): Missin... | Implement the Python class `RDAPServicer` described below.
Class description:
Missing associated documentation comment in .proto file
Method signatures and docstrings:
- def DomainLookup(self, request, context): Missing associated documentation comment in .proto file
- def EntityLookup(self, request, context): Missin... | eaf76d8a8215e5f43d25f4cd6aa5b178d26da549 | <|skeleton|>
class RDAPServicer:
"""Missing associated documentation comment in .proto file"""
def DomainLookup(self, request, context):
"""Missing associated documentation comment in .proto file"""
<|body_0|>
def EntityLookup(self, request, context):
"""Missing associated document... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RDAPServicer:
"""Missing associated documentation comment in .proto file"""
def DomainLookup(self, request, context):
"""Missing associated documentation comment in .proto file"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | domains/rdap_grpc/rdap_pb2_grpc.py | 8nty/domains | train | 0 |
662b8a407c6d6b1050f1a85a54564417cc339699 | [
"cfac = np.sqrt(2) / 2\nself.pnt = cfac * np.array([[0.5, 0.5, 0.0], [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [-0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [-0.5, 0.0, -0.5], [-0.5, 0.0, 0.5], [0.5, 0.0, -0.5], [0.0, 0.5, 0.5], [0.0, -0.5, -0.5], [0.0, 0.5, -0.5], [0.0, -0.5, 0.5], [1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.... | <|body_start_0|>
cfac = np.sqrt(2) / 2
self.pnt = cfac * np.array([[0.5, 0.5, 0.0], [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [-0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [-0.5, 0.0, -0.5], [-0.5, 0.0, 0.5], [0.5, 0.0, -0.5], [0.0, 0.5, 0.5], [0.0, -0.5, -0.5], [0.0, 0.5, -0.5], [0.0, -0.5, 0.5], [1.0, 0.0, 0.0], [-1.... | Defines points that fall within the unit cell of a fcc lattice | NanoFcc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NanoFcc:
"""Defines points that fall within the unit cell of a fcc lattice"""
def __init__(self, radius):
"""The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of unit cell"""
<|body_0|>
def check_point(self... | stack_v2_sparse_classes_10k_train_006006 | 4,924 | no_license | [
{
"docstring": "The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of unit cell",
"name": "__init__",
"signature": "def __init__(self, radius)"
},
{
"docstring": "Checks whether a point is within the unit cell :param pnt: given poin... | 2 | stack_v2_sparse_classes_30k_train_001595 | Implement the Python class `NanoFcc` described below.
Class description:
Defines points that fall within the unit cell of a fcc lattice
Method signatures and docstrings:
- def __init__(self, radius): The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of ... | Implement the Python class `NanoFcc` described below.
Class description:
Defines points that fall within the unit cell of a fcc lattice
Method signatures and docstrings:
- def __init__(self, radius): The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of ... | 351fde195f54d9af205e8abad217751121b25e6c | <|skeleton|>
class NanoFcc:
"""Defines points that fall within the unit cell of a fcc lattice"""
def __init__(self, radius):
"""The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of unit cell"""
<|body_0|>
def check_point(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NanoFcc:
"""Defines points that fall within the unit cell of a fcc lattice"""
def __init__(self, radius):
"""The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of unit cell"""
cfac = np.sqrt(2) / 2
self.pnt = cfac * n... | the_stack_v2_python_sparse | build/particles/nanoparticle_core.py | nathanhorst/MD | train | 0 |
f601805f857b6297fc9105263e68618298551a31 | [
"ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)\nsuper(FillPlot, self).__init__(**kwargs)\nself.color = kwargs.get('color', 'b')\nself.lineColor = kwargs.get('lineColor', 'none')\nself.data = kwargs.get('data', [])\nself.isLog = kwargs.get('isLog', False)",
"if not self.xLimits or not len(self.xLimits) == ... | <|body_start_0|>
ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)
super(FillPlot, self).__init__(**kwargs)
self.color = kwargs.get('color', 'b')
self.lineColor = kwargs.get('lineColor', 'none')
self.data = kwargs.get('data', [])
self.isLog = kwargs.get('isLog', False... | A class for... | FillPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FillPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of FillPlot."""
<|body_0|>
def shaveDataToXLimits(self):
"""shaveData doc..."""
<|body_1|>
def _plot(self):
"""_plot doc..."""
<|body_2|>
def ... | stack_v2_sparse_classes_10k_train_006007 | 3,050 | no_license | [
{
"docstring": "Creates a new instance of FillPlot.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "shaveData doc...",
"name": "shaveDataToXLimits",
"signature": "def shaveDataToXLimits(self)"
},
{
"docstring": "_plot doc...",
"name": "_pl... | 4 | stack_v2_sparse_classes_30k_train_006915 | Implement the Python class `FillPlot` described below.
Class description:
A class for...
Method signatures and docstrings:
- def __init__(self, **kwargs): Creates a new instance of FillPlot.
- def shaveDataToXLimits(self): shaveData doc...
- def _plot(self): _plot doc...
- def _dataItemToValue(cls, value): _dataItemT... | Implement the Python class `FillPlot` described below.
Class description:
A class for...
Method signatures and docstrings:
- def __init__(self, **kwargs): Creates a new instance of FillPlot.
- def shaveDataToXLimits(self): shaveData doc...
- def _plot(self): _plot doc...
- def _dataItemToValue(cls, value): _dataItemT... | bcd0d80077c68cf4bb515d643e51f62dd6c4caaa | <|skeleton|>
class FillPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of FillPlot."""
<|body_0|>
def shaveDataToXLimits(self):
"""shaveData doc..."""
<|body_1|>
def _plot(self):
"""_plot doc..."""
<|body_2|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FillPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of FillPlot."""
ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)
super(FillPlot, self).__init__(**kwargs)
self.color = kwargs.get('color', 'b')
self.lineColor = kwargs.get('... | the_stack_v2_python_sparse | src/cadence/analysis/shared/plotting/FillPlot.py | sernst/Cadence | train | 2 |
6008284ce3f73614a1a2bc5ec2f0e692476b8616 | [
"if not self.key.id():\n logging.error('Key id does not exist.')\n return None\nif self.size < 1:\n return None\nstring_id = self.key.string_id()\nlog_part_keys = [ndb.Key('QuickLog', string_id, 'QuickLogPart', i + 1) for i in xrange(self.size)]\nlog_parts = ndb.get_multi(log_part_keys)\nserialized = ''.jo... | <|body_start_0|>
if not self.key.id():
logging.error('Key id does not exist.')
return None
if self.size < 1:
return None
string_id = self.key.string_id()
log_part_keys = [ndb.Key('QuickLog', string_id, 'QuickLogPart', i + 1) for i in xrange(self.size)]... | Represents a log entity. | QuickLog | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuickLog:
"""Represents a log entity."""
def GetRecords(self):
"""Gets records store in multiple entities. Combines and deserializes the data stored in QuickLogPart for this log. Returns: List of Record object."""
<|body_0|>
def SetRecords(self, records):
"""Sets... | stack_v2_sparse_classes_10k_train_006008 | 8,298 | permissive | [
{
"docstring": "Gets records store in multiple entities. Combines and deserializes the data stored in QuickLogPart for this log. Returns: List of Record object.",
"name": "GetRecords",
"signature": "def GetRecords(self)"
},
{
"docstring": "Sets records for this log and put into datastore. Serial... | 2 | stack_v2_sparse_classes_30k_train_004244 | Implement the Python class `QuickLog` described below.
Class description:
Represents a log entity.
Method signatures and docstrings:
- def GetRecords(self): Gets records store in multiple entities. Combines and deserializes the data stored in QuickLogPart for this log. Returns: List of Record object.
- def SetRecords... | Implement the Python class `QuickLog` described below.
Class description:
Represents a log entity.
Method signatures and docstrings:
- def GetRecords(self): Gets records store in multiple entities. Combines and deserializes the data stored in QuickLogPart for this log. Returns: List of Record object.
- def SetRecords... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class QuickLog:
"""Represents a log entity."""
def GetRecords(self):
"""Gets records store in multiple entities. Combines and deserializes the data stored in QuickLogPart for this log. Returns: List of Record object."""
<|body_0|>
def SetRecords(self, records):
"""Sets... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QuickLog:
"""Represents a log entity."""
def GetRecords(self):
"""Gets records store in multiple entities. Combines and deserializes the data stored in QuickLogPart for this log. Returns: List of Record object."""
if not self.key.id():
logging.error('Key id does not exist.')
... | the_stack_v2_python_sparse | third_party/catapult/dashboard/dashboard/quick_logger.py | metux/chromium-suckless | train | 5 |
706e065d5a7f1fe0b5b92beff9432613340340a9 | [
"scheduler_name = 'api_auto_create_schedulers_once' + str(random.randint(0, 99999))\nflow_table = load_workbook(abs_dir('flow_dataset_info.xlsx'))\ninfo_sheet = flow_table.get_sheet_by_name('flow_info')\nflow_id = info_sheet.cell(row=2, column=2).value\nflow_name = info_sheet.cell(row=2, column=3).value\ndata = {'n... | <|body_start_0|>
scheduler_name = 'api_auto_create_schedulers_once' + str(random.randint(0, 99999))
flow_table = load_workbook(abs_dir('flow_dataset_info.xlsx'))
info_sheet = flow_table.get_sheet_by_name('flow_info')
flow_id = info_sheet.cell(row=2, column=2).value
flow_name = in... | 用来测试创建schedulers | CreateSchedulers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateSchedulers:
"""用来测试创建schedulers"""
def test_case01(self):
"""创建schedulers,单次执行"""
<|body_0|>
def test_case02(self):
"""创建schedulers,周期执行"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
scheduler_name = 'api_auto_create_schedulers_once' + s... | stack_v2_sparse_classes_10k_train_006009 | 15,511 | no_license | [
{
"docstring": "创建schedulers,单次执行",
"name": "test_case01",
"signature": "def test_case01(self)"
},
{
"docstring": "创建schedulers,周期执行",
"name": "test_case02",
"signature": "def test_case02(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000298 | Implement the Python class `CreateSchedulers` described below.
Class description:
用来测试创建schedulers
Method signatures and docstrings:
- def test_case01(self): 创建schedulers,单次执行
- def test_case02(self): 创建schedulers,周期执行 | Implement the Python class `CreateSchedulers` described below.
Class description:
用来测试创建schedulers
Method signatures and docstrings:
- def test_case01(self): 创建schedulers,单次执行
- def test_case02(self): 创建schedulers,周期执行
<|skeleton|>
class CreateSchedulers:
"""用来测试创建schedulers"""
def test_case01(self):
... | fc41513af3063169ff1b17d6f01f7074057ceb1f | <|skeleton|>
class CreateSchedulers:
"""用来测试创建schedulers"""
def test_case01(self):
"""创建schedulers,单次执行"""
<|body_0|>
def test_case02(self):
"""创建schedulers,周期执行"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreateSchedulers:
"""用来测试创建schedulers"""
def test_case01(self):
"""创建schedulers,单次执行"""
scheduler_name = 'api_auto_create_schedulers_once' + str(random.randint(0, 99999))
flow_table = load_workbook(abs_dir('flow_dataset_info.xlsx'))
info_sheet = flow_table.get_sheet_by_nam... | the_stack_v2_python_sparse | singl_api/api_test_cases/cases_for_schedulers_api.py | bingjiegu/For_API | train | 0 |
0a46b07d6f1f6dc98c41ac3e0368bc092a5178fb | [
"nums = sorted(nums)\nans = []\ni = 0\nwhile i < len(nums) - 1:\n if nums[i] == nums[i + 1]:\n ans.append(nums[i])\n i += 2\n else:\n i += 1\nreturn ans",
"ans = []\nelem2count = {}\nfor num in nums:\n elem2count[num] = elem2count.get(num, 0) + 1\n if elem2count[num] == 2:\n ... | <|body_start_0|>
nums = sorted(nums)
ans = []
i = 0
while i < len(nums) - 1:
if nums[i] == nums[i + 1]:
ans.append(nums[i])
i += 2
else:
i += 1
return ans
<|end_body_0|>
<|body_start_1|>
ans = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicates(self, nums):
"""Sort the array then linear scan. Time: O(NlogN) :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDuplicates2(self, nums):
"""Map element to its count and pick those with count of 2. Time: O(N) Space: O(N) :typ... | stack_v2_sparse_classes_10k_train_006010 | 1,942 | no_license | [
{
"docstring": "Sort the array then linear scan. Time: O(NlogN) :type nums: List[int] :rtype: List[int]",
"name": "findDuplicates",
"signature": "def findDuplicates(self, nums)"
},
{
"docstring": "Map element to its count and pick those with count of 2. Time: O(N) Space: O(N) :type nums: List[in... | 3 | stack_v2_sparse_classes_30k_train_007134 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicates(self, nums): Sort the array then linear scan. Time: O(NlogN) :type nums: List[int] :rtype: List[int]
- def findDuplicates2(self, nums): Map element to its coun... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicates(self, nums): Sort the array then linear scan. Time: O(NlogN) :type nums: List[int] :rtype: List[int]
- def findDuplicates2(self, nums): Map element to its coun... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def findDuplicates(self, nums):
"""Sort the array then linear scan. Time: O(NlogN) :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDuplicates2(self, nums):
"""Map element to its count and pick those with count of 2. Time: O(N) Space: O(N) :typ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicates(self, nums):
"""Sort the array then linear scan. Time: O(NlogN) :type nums: List[int] :rtype: List[int]"""
nums = sorted(nums)
ans = []
i = 0
while i < len(nums) - 1:
if nums[i] == nums[i + 1]:
ans.append(nums[i])... | the_stack_v2_python_sparse | py/leetcode_py/442.py | imsure/tech-interview-prep | train | 0 | |
0838fe0644dbea49ad40052a6fd8d130db3c8c01 | [
"hashmap = db_api.get_instance()\ntry:\n group_db = hashmap.get_group_from_threshold(uuid=threshold_id)\n return group_models.Group(**group_db.export_model())\nexcept db_api.ThresholdHasNoGroup as e:\n pecan.abort(404, e.args[0])",
"hashmap = db_api.get_instance()\nthreshold_list = []\nsearch_opts = dict... | <|body_start_0|>
hashmap = db_api.get_instance()
try:
group_db = hashmap.get_group_from_threshold(uuid=threshold_id)
return group_models.Group(**group_db.export_model())
except db_api.ThresholdHasNoGroup as e:
pecan.abort(404, e.args[0])
<|end_body_0|>
<|body... | Controller responsible of thresholds management. | HashMapThresholdsController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashMapThresholdsController:
"""Controller responsible of thresholds management."""
def group(self, threshold_id):
"""Get the group attached to the threshold. :param threshold_id: UUID of the threshold to filter on."""
<|body_0|>
def get_all(self, service_id=None, field_... | stack_v2_sparse_classes_10k_train_006011 | 6,844 | permissive | [
{
"docstring": "Get the group attached to the threshold. :param threshold_id: UUID of the threshold to filter on.",
"name": "group",
"signature": "def group(self, threshold_id)"
},
{
"docstring": "Get the threshold list :param service_id: Service UUID to filter on. :param field_id: Field UUID to... | 6 | stack_v2_sparse_classes_30k_train_000087 | Implement the Python class `HashMapThresholdsController` described below.
Class description:
Controller responsible of thresholds management.
Method signatures and docstrings:
- def group(self, threshold_id): Get the group attached to the threshold. :param threshold_id: UUID of the threshold to filter on.
- def get_a... | Implement the Python class `HashMapThresholdsController` described below.
Class description:
Controller responsible of thresholds management.
Method signatures and docstrings:
- def group(self, threshold_id): Get the group attached to the threshold. :param threshold_id: UUID of the threshold to filter on.
- def get_a... | 94630b97cd1fb4bdd9a638070ffbbe3625de8aa2 | <|skeleton|>
class HashMapThresholdsController:
"""Controller responsible of thresholds management."""
def group(self, threshold_id):
"""Get the group attached to the threshold. :param threshold_id: UUID of the threshold to filter on."""
<|body_0|>
def get_all(self, service_id=None, field_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HashMapThresholdsController:
"""Controller responsible of thresholds management."""
def group(self, threshold_id):
"""Get the group attached to the threshold. :param threshold_id: UUID of the threshold to filter on."""
hashmap = db_api.get_instance()
try:
group_db = ha... | the_stack_v2_python_sparse | cloudkitty/rating/hash/controllers/threshold.py | openstack/cloudkitty | train | 103 |
eda8de8ccada37bedd3845bd948fc30cfa7d0ad1 | [
"cube1 = Cube('red', 6)\ncube2 = Cube('blue', 5)\nstacked_list = [cube1, cube2]\nself.assertEqual(calc_height(stacked_list), 'The maximum tower height is 11')",
"cube1 = Cube('red', 5)\ncube2 = Cube('red', 5)\ncube_list = [cube1, cube2]\nwith self.assertRaises(ValueError):\n stack_cubes(cube_list)",
"cube1 =... | <|body_start_0|>
cube1 = Cube('red', 6)
cube2 = Cube('blue', 5)
stacked_list = [cube1, cube2]
self.assertEqual(calc_height(stacked_list), 'The maximum tower height is 11')
<|end_body_0|>
<|body_start_1|>
cube1 = Cube('red', 5)
cube2 = Cube('red', 5)
cube_list = [... | UnitTest | UnitTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitTest:
"""UnitTest"""
def test_calc_height(self):
"""test_calc_height: Testing calculate_height function"""
<|body_0|>
def test_failure(self):
"""test_failure: Make sure a ValueError is raised if you cannot stack the cubes"""
<|body_1|>
def test_w... | stack_v2_sparse_classes_10k_train_006012 | 1,393 | no_license | [
{
"docstring": "test_calc_height: Testing calculate_height function",
"name": "test_calc_height",
"signature": "def test_calc_height(self)"
},
{
"docstring": "test_failure: Make sure a ValueError is raised if you cannot stack the cubes",
"name": "test_failure",
"signature": "def test_fai... | 3 | stack_v2_sparse_classes_30k_train_003596 | Implement the Python class `UnitTest` described below.
Class description:
UnitTest
Method signatures and docstrings:
- def test_calc_height(self): test_calc_height: Testing calculate_height function
- def test_failure(self): test_failure: Make sure a ValueError is raised if you cannot stack the cubes
- def test_wides... | Implement the Python class `UnitTest` described below.
Class description:
UnitTest
Method signatures and docstrings:
- def test_calc_height(self): test_calc_height: Testing calculate_height function
- def test_failure(self): test_failure: Make sure a ValueError is raised if you cannot stack the cubes
- def test_wides... | 78f8f8d575e69da8d0c48929a562b0e9f64ab68d | <|skeleton|>
class UnitTest:
"""UnitTest"""
def test_calc_height(self):
"""test_calc_height: Testing calculate_height function"""
<|body_0|>
def test_failure(self):
"""test_failure: Make sure a ValueError is raised if you cannot stack the cubes"""
<|body_1|>
def test_w... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UnitTest:
"""UnitTest"""
def test_calc_height(self):
"""test_calc_height: Testing calculate_height function"""
cube1 = Cube('red', 6)
cube2 = Cube('blue', 5)
stacked_list = [cube1, cube2]
self.assertEqual(calc_height(stacked_list), 'The maximum tower height is 11')... | the_stack_v2_python_sparse | task3/unit_test.py | jamesl33/210CT-Course-Work | train | 0 |
7e72497d7fa22ff6596bb6ffbb3acbffb32f970e | [
"def partition(p, r):\n x = nums[r]\n i = p - 1\n for j in range(p, r):\n if nums[j] < x:\n i += 1\n nums[i], nums[j] = (nums[j], nums[i])\n nums[i + 1], nums[r] = (nums[r], nums[i + 1])\n return i + 1\n\ndef random_partition(p, r):\n ri = randint(p, r)\n nums[ri], ... | <|body_start_0|>
def partition(p, r):
x = nums[r]
i = p - 1
for j in range(p, r):
if nums[j] < x:
i += 1
nums[i], nums[j] = (nums[j], nums[i])
nums[i + 1], nums[r] = (nums[r], nums[i + 1])
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
<|body_0|>
def findKthLargestPQ(self, nums, k):
"""Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-he... | stack_v2_sparse_classes_10k_train_006013 | 2,164 | no_license | [
{
"docstring": "Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": "Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-heap. :rtype: int",
... | 2 | stack_v2_sparse_classes_30k_train_004049 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int
- def findKthLargestPQ(self, nums, k): Algorithm: * Heap O(n lg k),... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int
- def findKthLargestPQ(self, nums, k): Algorithm: * Heap O(n lg k),... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
<|body_0|>
def findKthLargestPQ(self, nums, k):
"""Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-he... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
def partition(p, r):
x = nums[r]
i = p - 1
for j in range(p, r):
if nums[j] < x:
i += 1
... | the_stack_v2_python_sparse | K/KthLargestElementinanArray.py | bssrdf/pyleet | train | 2 | |
435f48322403ca8e571f3bccfe8cc3a0a1677b7e | [
"super().__init__()\ncheck_boundaries(boundaries)\nself.boundaries = boundaries\nself.frequencies = frequencies\nself.fraction = fraction",
"self.randomize(None)\nself.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])\nself.fracs = self.R.uniform(low=self.fraction[0], high=self.fraction[... | <|body_start_0|>
super().__init__()
check_boundaries(boundaries)
self.boundaries = boundaries
self.frequencies = frequencies
self.fraction = fraction
<|end_body_0|>
<|body_start_1|>
self.randomize(None)
self.magnitude = self.R.uniform(low=self.boundaries[0], high... | Add a random partial sinusoidal signal to the input signal | SignalRandAddSinePartial | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalRandAddSinePartial:
"""Add a random partial sinusoidal signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.01, 0.2)) -> None:
"""Args: boundaries: list defining lower a... | stack_v2_sparse_classes_10k_train_006014 | 16,322 | permissive | [
{
"docstring": "Args: boundaries: list defining lower and upper boundaries for the sinusoidal magnitude, lower and upper values need to be positive , default : ``[0.1, 0.3]`` frequencies: list defining lower and upper frequencies for sinusoidal signal generation , default : ``[0.001, 0.02]`` fraction: list defi... | 2 | stack_v2_sparse_classes_30k_train_007194 | Implement the Python class `SignalRandAddSinePartial` described below.
Class description:
Add a random partial sinusoidal signal to the input signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.0... | Implement the Python class `SignalRandAddSinePartial` described below.
Class description:
Add a random partial sinusoidal signal to the input signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.0... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SignalRandAddSinePartial:
"""Add a random partial sinusoidal signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.01, 0.2)) -> None:
"""Args: boundaries: list defining lower a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SignalRandAddSinePartial:
"""Add a random partial sinusoidal signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.01, 0.2)) -> None:
"""Args: boundaries: list defining lower and upper boun... | the_stack_v2_python_sparse | monai/transforms/signal/array.py | Project-MONAI/MONAI | train | 4,805 |
7acd232d92de0770395fea7265cbb4028c011344 | [
"self.log_file = log_file\nself.data = []\nself.ip_regex = {}",
"self.data = []\ntry:\n with open(self.log_file, encoding='utf-8') as file_data:\n self.data = self.ip_regex[jail].findall(file_data.read())\nexcept (IndexError, FileNotFoundError, IsADirectoryError, UnboundLocalError):\n _LOGGER.warning... | <|body_start_0|>
self.log_file = log_file
self.data = []
self.ip_regex = {}
<|end_body_0|>
<|body_start_1|>
self.data = []
try:
with open(self.log_file, encoding='utf-8') as file_data:
self.data = self.ip_regex[jail].findall(file_data.read())
... | Class to parse fail2ban logs. | BanLogParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BanLogParser:
"""Class to parse fail2ban logs."""
def __init__(self, log_file):
"""Initialize the parser."""
<|body_0|>
def read_log(self, jail):
"""Read the fail2ban log and find entries for jail."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_006015 | 4,292 | permissive | [
{
"docstring": "Initialize the parser.",
"name": "__init__",
"signature": "def __init__(self, log_file)"
},
{
"docstring": "Read the fail2ban log and find entries for jail.",
"name": "read_log",
"signature": "def read_log(self, jail)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001435 | Implement the Python class `BanLogParser` described below.
Class description:
Class to parse fail2ban logs.
Method signatures and docstrings:
- def __init__(self, log_file): Initialize the parser.
- def read_log(self, jail): Read the fail2ban log and find entries for jail. | Implement the Python class `BanLogParser` described below.
Class description:
Class to parse fail2ban logs.
Method signatures and docstrings:
- def __init__(self, log_file): Initialize the parser.
- def read_log(self, jail): Read the fail2ban log and find entries for jail.
<|skeleton|>
class BanLogParser:
"""Cla... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BanLogParser:
"""Class to parse fail2ban logs."""
def __init__(self, log_file):
"""Initialize the parser."""
<|body_0|>
def read_log(self, jail):
"""Read the fail2ban log and find entries for jail."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BanLogParser:
"""Class to parse fail2ban logs."""
def __init__(self, log_file):
"""Initialize the parser."""
self.log_file = log_file
self.data = []
self.ip_regex = {}
def read_log(self, jail):
"""Read the fail2ban log and find entries for jail."""
sel... | the_stack_v2_python_sparse | homeassistant/components/fail2ban/sensor.py | home-assistant/core | train | 35,501 |
3232b3ee62cd5600d1a8b7ddb4e81a415b91930e | [
"self.max_madays = max_mean_days\nif trange.is_inf:\n self.trange = self.trange_ensure_not_inf(days_collected, trange, tzinfo)\n self.trange.set_start_day_offset(-max_mean_days)\nelse:\n self.trange = trange\nself.dates = self.date_list(days_collected, tzinfo, start=self.trange.start, end=self.trange.end)\... | <|body_start_0|>
self.max_madays = max_mean_days
if trange.is_inf:
self.trange = self.trange_ensure_not_inf(days_collected, trange, tzinfo)
self.trange.set_start_day_offset(-max_mean_days)
else:
self.trange = trange
self.dates = self.date_list(days_col... | Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-classes** :class:`MeanMessageResult` Generated result by calling ``generate_result()``. Check ... | MeanMessageResultGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeanMessageResultGenerator:
"""Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-classes** :class:`MeanMessageResult` Gen... | stack_v2_sparse_classes_10k_train_006016 | 25,000 | permissive | [
{
"docstring": "Initializing method of :class:`MeanMessageResultGenerator`. :param cursor: cursor of the aggregated data :param days_collected: \"claimed\" days collected on the data :param tzinfo: timezone info to separate the data by their date :param trange: time range of the data :param max_mean_days: maxim... | 2 | null | Implement the Python class `MeanMessageResultGenerator` described below.
Class description:
Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-c... | Implement the Python class `MeanMessageResultGenerator` described below.
Class description:
Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-c... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class MeanMessageResultGenerator:
"""Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-classes** :class:`MeanMessageResult` Gen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MeanMessageResultGenerator:
"""Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-classes** :class:`MeanMessageResult` Generated result... | the_stack_v2_python_sparse | models/stats/msg.py | RxJellyBot/Jelly-Bot | train | 5 |
a552a58f10b432411abec7012eba9003a34930ad | [
"paddle.set_default_dtype(np.float64)\nsuper(Conv2DNet, self).__init__()\nself._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', weight_attr=paddle.nn.initializer.Constant(value=0.5), bias_attr=paddle.nn.initializer.Constant(val... | <|body_start_0|>
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
self._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', weight_attr=paddle.nn.initializer.Constant(value=0.5), bias_attr=... | model | Conv2DNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self, inputs):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
sel... | stack_v2_sparse_classes_10k_train_006017 | 1,731 | no_license | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, inputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004894 | Implement the Python class `Conv2DNet` described below.
Class description:
model
Method signatures and docstrings:
- def __init__(self): __init__
- def forward(self, inputs): forward | Implement the Python class `Conv2DNet` described below.
Class description:
model
Method signatures and docstrings:
- def __init__(self): __init__
- def forward(self, inputs): forward
<|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self, inputs):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
self._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', w... | the_stack_v2_python_sparse | framework/api/optimizer/conv2d_dygraph_model.py | PaddlePaddle/PaddleTest | train | 42 |
df14c2c069f5f8b9cde8c3ffdc05492e8294cb72 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Schema()",
"from ..entity import Entity\nfrom .property_ import Property_\nfrom ..entity import Entity\nfrom .property_ import Property_\nfields: Dict[str, Callable[[Any], None]] = {'baseType': lambda n: setattr(self, 'base_type', n.ge... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Schema()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from .property_ import Property_
from ..entity import Entity
from .property_ import Property_
... | Schema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Schema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Schema"""
... | stack_v2_sparse_classes_10k_train_006018 | 2,452 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Schema",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(parse_... | 3 | null | Implement the Python class `Schema` described below.
Class description:
Implement the Schema class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | Implement the Python class `Schema` described below.
Class description:
Implement the Schema class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Schema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Schema"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Schema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Schema:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Schema"""
if not p... | the_stack_v2_python_sparse | msgraph/generated/models/external_connectors/schema.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b95b7494671c6bef9c9541cf8c9e691a02b2d87c | [
"self.params = {}\nself.reg = reg\nself.dtype = dtype\nC, H, W = input_dim\nself.params['W1'] = np.random.normal(0, weight_scale, (num_filters, C, filter_size, filter_size))\nself.params['b1'] = np.zeros(num_filters)\nself.params['W2'] = np.random.normal(0, weight_scale, (num_filters * H / 2 * W / 2, hidden_dim))\n... | <|body_start_0|>
self.params = {}
self.reg = reg
self.dtype = dtype
C, H, W = input_dim
self.params['W1'] = np.random.normal(0, weight_scale, (num_filters, C, filter_size, filter_size))
self.params['b1'] = np.zeros(num_filters)
self.params['W2'] = np.random.normal... | A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C input channels. | CustomLayerConvNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomLayerConvNet:
"""A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C inpu... | stack_v2_sparse_classes_10k_train_006019 | 8,901 | no_license | [
{
"docstring": "Initialize a new network. Inputs: - input_dim: Tuple (C, H, W) giving size of input data - num_filters: Number of filters to use in the convolutional layer - filter_size: Size of filters to use in the convolutional layer - hidden_dim: Number of units to use in the fully-connected hidden layer - ... | 2 | stack_v2_sparse_classes_30k_train_002346 | Implement the Python class `CustomLayerConvNet` described below.
Class description:
A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each wi... | Implement the Python class `CustomLayerConvNet` described below.
Class description:
A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each wi... | c885a43d6181ff62c595f3d41823f112219e61db | <|skeleton|>
class CustomLayerConvNet:
"""A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C inpu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomLayerConvNet:
"""A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C input channels.""... | the_stack_v2_python_sparse | assignment2/cs231n/classifiers/NormalConvNet.py | EllieLily/cs213n | train | 0 |
ea95cbc9f7155276329779b065c7482863de34ca | [
"if User.objects.filter(email__iexact=self.cleaned_data['email']):\n raise forms.ValidationError(_('This email address is already in use. Please supply a different email address.'))\nreturn self.cleaned_data['email']",
"if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:\n if self.clea... | <|body_start_0|>
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_('This email address is already in use. Please supply a different email address.'))
return self.cleaned_data['email']
<|end_body_0|>
<|body_start_1|>
if 'password1' in sel... | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
def clean_email(self):
"""Validate that the supplied email address is unique for the site."""
<|body_0|>
def clean(self):
"""Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_error... | stack_v2_sparse_classes_10k_train_006020 | 3,948 | no_license | [
{
"docstring": "Validate that the supplied email address is unique for the site.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` beca... | 2 | stack_v2_sparse_classes_30k_train_004268 | Implement the Python class `RegistrationForm` described below.
Class description:
Implement the RegistrationForm class.
Method signatures and docstrings:
- def clean_email(self): Validate that the supplied email address is unique for the site.
- def clean(self): Verifiy that the values entered into the two password f... | Implement the Python class `RegistrationForm` described below.
Class description:
Implement the RegistrationForm class.
Method signatures and docstrings:
- def clean_email(self): Validate that the supplied email address is unique for the site.
- def clean(self): Verifiy that the values entered into the two password f... | 3031a38a88a96d1ade8e2391cb455fa9921e7549 | <|skeleton|>
class RegistrationForm:
def clean_email(self):
"""Validate that the supplied email address is unique for the site."""
<|body_0|>
def clean(self):
"""Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_error... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
def clean_email(self):
"""Validate that the supplied email address is unique for the site."""
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_('This email address is already in use. Please supply a different email add... | the_stack_v2_python_sparse | accaunt/forms.py | MaratFM/Djanym | train | 0 | |
b66e4b55e67bb7998cd7bc882caaf58a9e15e8dd | [
"envelopes.sort(key=lambda x: (x[0], -x[1]))\ndoll = [0] * len(envelopes)\nmaxLen = 0\nfor envelope in envelopes:\n i = bisect_left(doll, envelope[1], 0, maxLen)\n doll[i] = envelope[1]\n if i == maxLen:\n maxLen += 1\nreturn maxLen",
"n = len(envelopes)\nif n < 1:\n return 0\nenvelopes.sort()\... | <|body_start_0|>
envelopes.sort(key=lambda x: (x[0], -x[1]))
doll = [0] * len(envelopes)
maxLen = 0
for envelope in envelopes:
i = bisect_left(doll, envelope[1], 0, maxLen)
doll[i] = envelope[1]
if i == maxLen:
maxLen += 1
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes2(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
envelopes.... | stack_v2_sparse_classes_10k_train_006021 | 2,260 | no_license | [
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes",
"signature": "def maxEnvelopes(self, envelopes)"
},
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes2",
"signature": "def maxEnvelopes2(self, envelopes)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes2(self, envelopes): :type envelopes: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes2(self, envelopes): :type envelopes: List[List[int]] :rtype: int
<|skeleton|>
c... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes2(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
envelopes.sort(key=lambda x: (x[0], -x[1]))
doll = [0] * len(envelopes)
maxLen = 0
for envelope in envelopes:
i = bisect_left(doll, envelope[1], 0, maxLen)
... | the_stack_v2_python_sparse | code354RussianDollEnvelopes.py | cybelewang/leetcode-python | train | 0 | |
2b718cd6dbb5d396e2c566ce23abf2c9bf2de137 | [
"n = len(array)\ni, j = (0, 0)\ncurr_ones = 0\nmax_ones = 0\nwhile j < n:\n if array[j]:\n curr_ones += 1\n j += 1\n max_ones = max(max_ones, curr_ones)\n elif not array[j] and m > 0:\n curr_ones += 1\n m -= 1\n j += 1\n max_ones = max(max_ones, curr_ones)\n ... | <|body_start_0|>
n = len(array)
i, j = (0, 0)
curr_ones = 0
max_ones = 0
while j < n:
if array[j]:
curr_ones += 1
j += 1
max_ones = max(max_ones, curr_ones)
elif not array[j] and m > 0:
curr_o... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_ones_length(self, array, m):
"""Returns count of maximum consecutive ones that can be achieved by flipping m zeroes. Time complexity: O(n). Space complexity: O(1), n is len(array)."""
<|body_0|>
def max_ones_seq(self, array, m):
"""Returns indices o... | stack_v2_sparse_classes_10k_train_006022 | 2,867 | no_license | [
{
"docstring": "Returns count of maximum consecutive ones that can be achieved by flipping m zeroes. Time complexity: O(n). Space complexity: O(1), n is len(array).",
"name": "max_ones_length",
"signature": "def max_ones_length(self, array, m)"
},
{
"docstring": "Returns indices of longest seque... | 2 | stack_v2_sparse_classes_30k_train_005029 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_ones_length(self, array, m): Returns count of maximum consecutive ones that can be achieved by flipping m zeroes. Time complexity: O(n). Space complexity: O(1), n is len(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_ones_length(self, array, m): Returns count of maximum consecutive ones that can be achieved by flipping m zeroes. Time complexity: O(n). Space complexity: O(1), n is len(... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def max_ones_length(self, array, m):
"""Returns count of maximum consecutive ones that can be achieved by flipping m zeroes. Time complexity: O(n). Space complexity: O(1), n is len(array)."""
<|body_0|>
def max_ones_seq(self, array, m):
"""Returns indices o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def max_ones_length(self, array, m):
"""Returns count of maximum consecutive ones that can be achieved by flipping m zeroes. Time complexity: O(n). Space complexity: O(1), n is len(array)."""
n = len(array)
i, j = (0, 0)
curr_ones = 0
max_ones = 0
whil... | the_stack_v2_python_sparse | Arrays/max_consecutive_ones.py | vladn90/Algorithms | train | 0 | |
1a78ab721be7adabb9212886a3225b6d6ff9a979 | [
"self.host = host\nself.port = port\nself.username = username\nself.password = password\nself.private_key = private_key\nself.private_key_passphrase = private_key_passphrase\nself.private_key_algorithm = private_key_algorithm\nself.sftp_handler = None\nself.ssh_connection = None",
"try:\n self.ssh_connection =... | <|body_start_0|>
self.host = host
self.port = port
self.username = username
self.password = password
self.private_key = private_key
self.private_key_passphrase = private_key_passphrase
self.private_key_algorithm = private_key_algorithm
self.sftp_handler = ... | SFTP Connection object. | SftpConnection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SftpConnection:
"""SFTP Connection object."""
def __init__(self, host: str, port: int, username: str, password: str=None, private_key: str=None, private_key_passphrase: str=None, private_key_algorithm: str=PublicKeyAlgorithms.ED25519.value):
"""Initialize the SFTP Connection object. ... | stack_v2_sparse_classes_10k_train_006023 | 5,271 | permissive | [
{
"docstring": "Initialize the SFTP Connection object. Args: host (str): The hostname of the SFTP server. port (int): The port of the SFTP server. username (str): The username to use for the SFTP connection. password (str): The password to use for the SFTP connection. private_key (str): The private key to use f... | 5 | stack_v2_sparse_classes_30k_train_003282 | Implement the Python class `SftpConnection` described below.
Class description:
SFTP Connection object.
Method signatures and docstrings:
- def __init__(self, host: str, port: int, username: str, password: str=None, private_key: str=None, private_key_passphrase: str=None, private_key_algorithm: str=PublicKeyAlgorithm... | Implement the Python class `SftpConnection` described below.
Class description:
SFTP Connection object.
Method signatures and docstrings:
- def __init__(self, host: str, port: int, username: str, password: str=None, private_key: str=None, private_key_passphrase: str=None, private_key_algorithm: str=PublicKeyAlgorithm... | af1a4458bb78c16ecca484514d4bd0d1d8c24b5d | <|skeleton|>
class SftpConnection:
"""SFTP Connection object."""
def __init__(self, host: str, port: int, username: str, password: str=None, private_key: str=None, private_key_passphrase: str=None, private_key_algorithm: str=PublicKeyAlgorithms.ED25519.value):
"""Initialize the SFTP Connection object. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SftpConnection:
"""SFTP Connection object."""
def __init__(self, host: str, port: int, username: str, password: str=None, private_key: str=None, private_key_passphrase: str=None, private_key_algorithm: str=PublicKeyAlgorithms.ED25519.value):
"""Initialize the SFTP Connection object. Args: host (s... | the_stack_v2_python_sparse | services/document-delivery-service/src/document_delivery_service/services/sftp.py | bcgov/ppr | train | 4 |
033bb7383df651ef12719da6fa9c1b1ed4c3cb70 | [
"self.mode = kwargs.pop('mode', 'markdown')\nself.addons = kwargs.pop('addons', [])\nself.theme = kwargs.pop('theme', 'default')\nself.theme_path = kwargs.pop('theme_path', 's_markdown/codemirror/theme/%s.css' % self.theme)\nself.keymap = kwargs.pop('keymap', None)\nself.options = kwargs.pop('options', {})\nself.ad... | <|body_start_0|>
self.mode = kwargs.pop('mode', 'markdown')
self.addons = kwargs.pop('addons', [])
self.theme = kwargs.pop('theme', 'default')
self.theme_path = kwargs.pop('theme_path', 's_markdown/codemirror/theme/%s.css' % self.theme)
self.keymap = kwargs.pop('keymap', None)
... | CodeMirror | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeMirror:
def __init__(self, *args, **kwargs):
"""Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to the addon, without `.js` extension. Example: `mode/overlay`) :param theme: Theme name. :param them... | stack_v2_sparse_classes_10k_train_006024 | 3,381 | permissive | [
{
"docstring": "Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to the addon, without `.js` extension. Example: `mode/overlay`) :param theme: Theme name. :param theme_path: Path to the theme file. Default is `s_markdown/codem... | 3 | stack_v2_sparse_classes_30k_train_003148 | Implement the Python class `CodeMirror` described below.
Class description:
Implement the CodeMirror class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to... | Implement the Python class `CodeMirror` described below.
Class description:
Implement the CodeMirror class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to... | 9bf040faac43feae08b33900e30bf7d17b817ae4 | <|skeleton|>
class CodeMirror:
def __init__(self, *args, **kwargs):
"""Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to the addon, without `.js` extension. Example: `mode/overlay`) :param theme: Theme name. :param them... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CodeMirror:
def __init__(self, *args, **kwargs):
"""Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to the addon, without `.js` extension. Example: `mode/overlay`) :param theme: Theme name. :param theme_path: Path t... | the_stack_v2_python_sparse | s_markdown/widgets.py | AmatanHead/collective-blog | train | 0 | |
23050faaaaca4daad88eb1029b3ac34fd2f90920 | [
"plot_key = metrics_for_slice_pb2.PlotKey()\nif self.name:\n plot_key.name = self.name\nif self.model_name:\n plot_key.model_name = self.model_name\nif self.output_name:\n plot_key.output_name = self.output_name\nif self.sub_key:\n plot_key.sub_key.CopyFrom(self.sub_key.to_proto())\nif self.example_weig... | <|body_start_0|>
plot_key = metrics_for_slice_pb2.PlotKey()
if self.name:
plot_key.name = self.name
if self.model_name:
plot_key.model_name = self.model_name
if self.output_name:
plot_key.output_name = self.output_name
if self.sub_key:
... | A PlotKey is a metric key that uniquely identifies a plot. | PlotKey | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotKey:
"""A PlotKey is a metric key that uniquely identifies a plot."""
def to_proto(self) -> metrics_for_slice_pb2.PlotKey:
"""Converts key to proto."""
<|body_0|>
def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey':
"""Configures class from proto."... | stack_v2_sparse_classes_10k_train_006025 | 44,385 | permissive | [
{
"docstring": "Converts key to proto.",
"name": "to_proto",
"signature": "def to_proto(self) -> metrics_for_slice_pb2.PlotKey"
},
{
"docstring": "Configures class from proto.",
"name": "from_proto",
"signature": "def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey'"
}
] | 2 | stack_v2_sparse_classes_30k_train_005935 | Implement the Python class `PlotKey` described below.
Class description:
A PlotKey is a metric key that uniquely identifies a plot.
Method signatures and docstrings:
- def to_proto(self) -> metrics_for_slice_pb2.PlotKey: Converts key to proto.
- def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey': Configur... | Implement the Python class `PlotKey` described below.
Class description:
A PlotKey is a metric key that uniquely identifies a plot.
Method signatures and docstrings:
- def to_proto(self) -> metrics_for_slice_pb2.PlotKey: Converts key to proto.
- def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey': Configur... | ee0d8eff562bfe068a3ffdc4da0472cc90adaf41 | <|skeleton|>
class PlotKey:
"""A PlotKey is a metric key that uniquely identifies a plot."""
def to_proto(self) -> metrics_for_slice_pb2.PlotKey:
"""Converts key to proto."""
<|body_0|>
def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey':
"""Configures class from proto."... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PlotKey:
"""A PlotKey is a metric key that uniquely identifies a plot."""
def to_proto(self) -> metrics_for_slice_pb2.PlotKey:
"""Converts key to proto."""
plot_key = metrics_for_slice_pb2.PlotKey()
if self.name:
plot_key.name = self.name
if self.model_name:
... | the_stack_v2_python_sparse | tensorflow_model_analysis/metrics/metric_types.py | tensorflow/model-analysis | train | 1,200 |
34758b74c20c1808fa799542d45298d54c82e1f4 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('chuci_yfch_yuwan_zhurh', 'chuci_yfch_yuwan_zhurh')\n\ndef select(R, s):\n return [t for t in R if s(t)]\n\ndef product(R, S):\n return [(t, u) for t in R for u in S]\n\ndef project(R, p):\n retu... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('chuci_yfch_yuwan_zhurh', 'chuci_yfch_yuwan_zhurh')
def select(R, s):
return [t for t in R if s(t)]
def product(R, S):
re... | unemploy_gov_sparkgov__output | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unemploy_gov_sparkgov__output:
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 descr... | stack_v2_sparse_classes_10k_train_006026 | 5,978 | no_license | [
{
"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 | null | Implement the Python class `unemploy_gov_sparkgov__output` described below.
Class description:
Implement the unemploy_gov_sparkgov__output 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.P... | Implement the Python class `unemploy_gov_sparkgov__output` described below.
Class description:
Implement the unemploy_gov_sparkgov__output 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.P... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class unemploy_gov_sparkgov__output:
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 descr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class unemploy_gov_sparkgov__output:
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('chuci_yfch_yuwan_zhur... | the_stack_v2_python_sparse | chuci_yfch_yuwan_zhurh/unemploy_gov_sparkgov__output.py | maximega/course-2019-spr-proj | train | 2 | |
2955a24ef7d61ddce4e07a01bdd518262cab889f | [
"differentiator.refresh()\nop = differentiator.generate_differentiable_op(sampled_op=op)\nqubit = cirq.GridQubit(0, 0)\ncircuit = util.convert_to_tensor([cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('alpha'))])\npsums = util.convert_to_tensor([[cirq.Z(qubit)]])\nsymbol_values_array = np.array([[0.123]], dtype=np.floa... | <|body_start_0|>
differentiator.refresh()
op = differentiator.generate_differentiable_op(sampled_op=op)
qubit = cirq.GridQubit(0, 0)
circuit = util.convert_to_tensor([cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('alpha'))])
psums = util.convert_to_tensor([[cirq.Z(qubit)]])
... | Test approximate correctness of noisy methods. | NoisyGradientCorrectnessTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoisyGradientCorrectnessTest:
"""Test approximate correctness of noisy methods."""
def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples):
"""Test the value of sampled differentiator with simple circuit."""
<|body_0|>
def test_approx_equality_s... | stack_v2_sparse_classes_10k_train_006027 | 22,303 | permissive | [
{
"docstring": "Test the value of sampled differentiator with simple circuit.",
"name": "test_sampled_value_with_simple_circuit",
"signature": "def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples)"
},
{
"docstring": "Test small circuits with limited depth.",
"nam... | 3 | stack_v2_sparse_classes_30k_val_000062 | Implement the Python class `NoisyGradientCorrectnessTest` described below.
Class description:
Test approximate correctness of noisy methods.
Method signatures and docstrings:
- def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples): Test the value of sampled differentiator with simple circu... | Implement the Python class `NoisyGradientCorrectnessTest` described below.
Class description:
Test approximate correctness of noisy methods.
Method signatures and docstrings:
- def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples): Test the value of sampled differentiator with simple circu... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class NoisyGradientCorrectnessTest:
"""Test approximate correctness of noisy methods."""
def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples):
"""Test the value of sampled differentiator with simple circuit."""
<|body_0|>
def test_approx_equality_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NoisyGradientCorrectnessTest:
"""Test approximate correctness of noisy methods."""
def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples):
"""Test the value of sampled differentiator with simple circuit."""
differentiator.refresh()
op = differentiator.ge... | the_stack_v2_python_sparse | tensorflow_quantum/python/differentiators/gradient_test.py | tensorflow/quantum | train | 1,799 |
74454f487b399c1d06e3245182b84481425b4fa5 | [
"render = self.scene.render\ncamera = render.camera\nnp.random.seed(3421)\nR = np.random.permutation(range(camera.imageHeight))\nC = np.random.permutation(range(camera.imageWidth))\nNPixels = 100\nPixels = np.empty((NPixels, 2))\nPixels[:, 0] = C[:NPixels]\nPixels[:, 1] = R[:NPixels]\nfor pixel in Pixels:\n ray ... | <|body_start_0|>
render = self.scene.render
camera = render.camera
np.random.seed(3421)
R = np.random.permutation(range(camera.imageHeight))
C = np.random.permutation(range(camera.imageWidth))
NPixels = 100
Pixels = np.empty((NPixels, 2))
Pixels[:, 0] = C[... | Base class for all test cases. The derived classes override the default setUp method. Tests performed for create_ray(pixel) are: Test if the ray origin in correct Test if the ray is going towards the general direction of lookat Test if the ray going through the center of the image passes through the lookat point in the... | RayCreationFromPixelBaseTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RayCreationFromPixelBaseTests:
"""Base class for all test cases. The derived classes override the default setUp method. Tests performed for create_ray(pixel) are: Test if the ray origin in correct Test if the ray is going towards the general direction of lookat Test if the ray going through the c... | stack_v2_sparse_classes_10k_train_006028 | 8,575 | no_license | [
{
"docstring": "Test if the ray origin is set correctly",
"name": "test_ray_through_center_eyePoint",
"signature": "def test_ray_through_center_eyePoint(self)"
},
{
"docstring": "ray direction should be towards the lookat direction",
"name": "test_ray_through_center_towards_neg_z_direction",... | 5 | stack_v2_sparse_classes_30k_train_000655 | Implement the Python class `RayCreationFromPixelBaseTests` described below.
Class description:
Base class for all test cases. The derived classes override the default setUp method. Tests performed for create_ray(pixel) are: Test if the ray origin in correct Test if the ray is going towards the general direction of loo... | Implement the Python class `RayCreationFromPixelBaseTests` described below.
Class description:
Base class for all test cases. The derived classes override the default setUp method. Tests performed for create_ray(pixel) are: Test if the ray origin in correct Test if the ray is going towards the general direction of loo... | 43cf6e7c7c1851c725252a7b6684edaef432bc29 | <|skeleton|>
class RayCreationFromPixelBaseTests:
"""Base class for all test cases. The derived classes override the default setUp method. Tests performed for create_ray(pixel) are: Test if the ray origin in correct Test if the ray is going towards the general direction of lookat Test if the ray going through the c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RayCreationFromPixelBaseTests:
"""Base class for all test cases. The derived classes override the default setUp method. Tests performed for create_ray(pixel) are: Test if the ray origin in correct Test if the ray is going towards the general direction of lookat Test if the ray going through the center of the ... | the_stack_v2_python_sparse | asses/557/3/Daniel Pham 260526252/TestCreateRay.py | danhp/socs | train | 0 |
ef9f95557d67947839d44312021f7fcf007b1fc0 | [
"if not settings.DEBUG:\n return {}\nreturn {'athlete': {'name': 'Domen Blenkuš', 'age': '28', 'weight': 74.5}, 'measurements': [{'power': 120, 'heart_rate': 128}, {'power': 140, 'heart_rate': 135}, {'power': 160, 'heart_rate': 145}, {'power': 180, 'heart_rate': 143}, {'power': 200, 'heart_rate': 147}, {'power':... | <|body_start_0|>
if not settings.DEBUG:
return {}
return {'athlete': {'name': 'Domen Blenkuš', 'age': '28', 'weight': 74.5}, 'measurements': [{'power': 120, 'heart_rate': 128}, {'power': 140, 'heart_rate': 135}, {'power': 160, 'heart_rate': 145}, {'power': 180, 'heart_rate': 143}, {'power': ... | Conconi Test view. | ConconiTestView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConconiTestView:
"""Conconi Test view."""
def get_initial(self):
"""Return initial values if ``DEBUG`` setting is set to ``True``."""
<|body_0|>
def _save_data(self, forms):
"""Save data."""
<|body_1|>
def forms_valid(self, forms):
"""Save da... | stack_v2_sparse_classes_10k_train_006029 | 3,198 | permissive | [
{
"docstring": "Return initial values if ``DEBUG`` setting is set to ``True``.",
"name": "get_initial",
"signature": "def get_initial(self)"
},
{
"docstring": "Save data.",
"name": "_save_data",
"signature": "def _save_data(self, forms)"
},
{
"docstring": "Save data, make report ... | 3 | stack_v2_sparse_classes_30k_train_003037 | Implement the Python class `ConconiTestView` described below.
Class description:
Conconi Test view.
Method signatures and docstrings:
- def get_initial(self): Return initial values if ``DEBUG`` setting is set to ``True``.
- def _save_data(self, forms): Save data.
- def forms_valid(self, forms): Save data, make report... | Implement the Python class `ConconiTestView` described below.
Class description:
Conconi Test view.
Method signatures and docstrings:
- def get_initial(self): Return initial values if ``DEBUG`` setting is set to ``True``.
- def _save_data(self, forms): Save data.
- def forms_valid(self, forms): Save data, make report... | bae6105812c2f2414d0c10ddd465bf589503f61a | <|skeleton|>
class ConconiTestView:
"""Conconi Test view."""
def get_initial(self):
"""Return initial values if ``DEBUG`` setting is set to ``True``."""
<|body_0|>
def _save_data(self, forms):
"""Save data."""
<|body_1|>
def forms_valid(self, forms):
"""Save da... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConconiTestView:
"""Conconi Test view."""
def get_initial(self):
"""Return initial values if ``DEBUG`` setting is set to ``True``."""
if not settings.DEBUG:
return {}
return {'athlete': {'name': 'Domen Blenkuš', 'age': '28', 'weight': 74.5}, 'measurements': [{'power': ... | the_stack_v2_python_sparse | src/lactolyse/views/conconi_test.py | dblenkus/lactolyse | train | 2 |
1c09e2ced8ed33aaf69f92e353bcdee1631818af | [
"self.github_repo_obj = github_repo_obj\nself.git_repo_obj = git_repo_obj\nself.run_id = run_id",
"for pr in self.github_repo_obj.get_pulls(state='open', sort='created', base=BASE):\n print(f'{t.yellow}Looking on pr number [{pr.number}]: last updated: {str(pr.updated_at)}, branch={pr.head.ref}')\n condition... | <|body_start_0|>
self.github_repo_obj = github_repo_obj
self.git_repo_obj = git_repo_obj
self.run_id = run_id
<|end_body_0|>
<|body_start_1|>
for pr in self.github_repo_obj.get_pulls(state='open', sort='created', base=BASE):
print(f'{t.yellow}Looking on pr number [{pr.number... | AutoBumperManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoBumperManager:
def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str):
"""Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo object. run_id: GitHub action run id."""
<|body_0|>
def manage(self):
"""Iterates over al... | stack_v2_sparse_classes_10k_train_006030 | 11,815 | permissive | [
{
"docstring": "Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo object. run_id: GitHub action run id.",
"name": "__init__",
"signature": "def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str)"
},
{
"docstring": "Iterates over all PR's in the r... | 2 | null | Implement the Python class `AutoBumperManager` described below.
Class description:
Implement the AutoBumperManager class.
Method signatures and docstrings:
- def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str): Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo obje... | Implement the Python class `AutoBumperManager` described below.
Class description:
Implement the AutoBumperManager class.
Method signatures and docstrings:
- def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str): Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo obje... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class AutoBumperManager:
def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str):
"""Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo object. run_id: GitHub action run id."""
<|body_0|>
def manage(self):
"""Iterates over al... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AutoBumperManager:
def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str):
"""Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo object. run_id: GitHub action run id."""
self.github_repo_obj = github_repo_obj
self.git_repo_obj = git_repo... | the_stack_v2_python_sparse | Utils/github_workflow_scripts/autobump_release_notes/autobump_rn.py | demisto/content | train | 1,023 | |
b9214029d439a4adbb3ccc25e22d7118d47dcdc5 | [
"Dialog.__init__(self, text, screen, False)\nself.choices = [str(choice) for choice in choices]\nself.scriptEngine = script_engine.ScriptEngine()\nmaxWidth = max(list(map(self.font.calcWidth, self.choices)))\nsize = (maxWidth + self.xBorder * 2 + self.sideCursor.get_width(), (self.font.height + LINEBUFFER) * len(se... | <|body_start_0|>
Dialog.__init__(self, text, screen, False)
self.choices = [str(choice) for choice in choices]
self.scriptEngine = script_engine.ScriptEngine()
maxWidth = max(list(map(self.font.calcWidth, self.choices)))
size = (maxWidth + self.xBorder * 2 + self.sideCursor.get_w... | Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable. | ChoiceDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, screen, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font ... | stack_v2_sparse_classes_10k_train_006031 | 7,179 | no_license | [
{
"docstring": "Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font with which to write the text. screen - the surface to draw the dialog onto. scriptEngine - the engine to return the option chosen to. choices - the possible options to choose from... | 3 | stack_v2_sparse_classes_30k_train_002155 | Implement the Python class `ChoiceDialog` described below.
Class description:
Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable.
Method signatures and docstrings:
- def __init__(self, text, screen, choices): Initialize the dialog and create the choice box. text - a li... | Implement the Python class `ChoiceDialog` described below.
Class description:
Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable.
Method signatures and docstrings:
- def __init__(self, text, screen, choices): Initialize the dialog and create the choice box. text - a li... | 72841fc503c716ac3b524e42f2311cbd9d18a092 | <|skeleton|>
class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, screen, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, screen, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font with which to... | the_stack_v2_python_sparse | eng/dialog.py | andrew-turner/Ditto | train | 0 |
767bdb1f5d36e4adf2109c0e5e3496fb049c52f9 | [
"count, self.dp = (0, [0])\nfor i in nums:\n count += i\n self.dp.append(count)",
"n = len(self.dp)\nl = 0 if i < 0 else i\nr = n - 1 if j > n - 1 else j\nreturn self.dp[j + 1] - self.dp[i]"
] | <|body_start_0|>
count, self.dp = (0, [0])
for i in nums:
count += i
self.dp.append(count)
<|end_body_0|>
<|body_start_1|>
n = len(self.dp)
l = 0 if i < 0 else i
r = n - 1 if j > n - 1 else j
return self.dp[j + 1] - self.dp[i]
<|end_body_1|>
| Solution description | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution description"""
def __init__(self, nums):
"""type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count, self.dp = (0, [0])
... | stack_v2_sparse_classes_10k_train_006032 | 743 | permissive | [
{
"docstring": "type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000524 | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def __init__(self, nums): type nums: List[int]
- def sumRange(self, i, j): type i: int :type j: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def __init__(self, nums): type nums: List[int]
- def sumRange(self, i, j): type i: int :type j: int :rtype: int
<|skeleton|>
class Solution:
"""Solution description"""
def __ini... | 869ee24c50c08403b170e8f7868699185e9dfdd1 | <|skeleton|>
class Solution:
"""Solution description"""
def __init__(self, nums):
"""type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution description"""
def __init__(self, nums):
"""type nums: List[int]"""
count, self.dp = (0, [0])
for i in nums:
count += i
self.dp.append(count)
def sumRange(self, i, j):
"""type i: int :type j: int :rtype: int"""
n =... | the_stack_v2_python_sparse | Range Sum Query-Immutable/2.py | cerebrumaize/leetcode | train | 0 |
8541d3164920d4a53c67dc90f41ed4f4144cd48c | [
"if not root:\n return ''\ndata = '['\ndata += str(root.val)\nfor child in root.children:\n data += self.serialize(child)\ndata += ']'\nreturn data",
"stack = list()\ni = 0\nroot = None\nwhile i < len(data):\n if data[i] == ']':\n root = stack[-1]\n stack.pop()\n elif data[i].isdigit():\... | <|body_start_0|>
if not root:
return ''
data = '['
data += str(root.val)
for child in root.children:
data += self.serialize(child)
data += ']'
return data
<|end_body_0|>
<|body_start_1|>
stack = list()
i = 0
root = None
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_006033 | 1,498 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 178546686aa3ae8f5da1ae845417f86fab9a644d | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
data = '['
data += str(root.val)
for child in root.children:
data += self.serialize(child)
data ... | the_stack_v2_python_sparse | 428. Serialize and Deserialize N-ary Tree.py | JaylenZhang19/Leetcode | train | 0 | |
f3843e3cd179431ad2c5039df69d357a0c7d0421 | [
"if not value:\n return []\nreturn value.split('\\r\\n')",
"super(MultiEmailField, self).validate(value)\nfor email in value:\n validate_email(email)"
] | <|body_start_0|>
if not value:
return []
return value.split('\r\n')
<|end_body_0|>
<|body_start_1|>
super(MultiEmailField, self).validate(value)
for email in value:
validate_email(email)
<|end_body_1|>
| MultiEmailField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not value:
... | stack_v2_sparse_classes_10k_train_006034 | 1,940 | no_license | [
{
"docstring": "Normalize data to a list of strings.",
"name": "to_python",
"signature": "def to_python(self, value)"
},
{
"docstring": "Check if value consists only of valid emails.",
"name": "validate",
"signature": "def validate(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000319 | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails. | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails.
<|skeleton|>
class Mult... | 43874528bb09bb79180fe380ecfa05795bc94e4d | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
if not value:
return []
return value.split('\r\n')
def validate(self, value):
"""Check if value consists only of valid emails."""
super(MultiEmailField, self).valida... | the_stack_v2_python_sparse | programacion/python/django/t4uAdmin/workflowCodeManager/form.py | adrianlzt/cerebro | train | 19 | |
5629ad020469bb4f0749842a5e0a615cc8c15d4c | [
"Frame.__init__(self, master)\nself.pack()\nself.createArtistWidgets()",
"top_frame = Frame(self)\nself.labelInput = Label(top_frame, text='Artist Name')\nself.text_in = Entry(top_frame)\nself.labelResult = Label(top_frame, text='Result')\nself.labelInput.pack()\nself.text_in.pack()\nself.labelResult.pack()\ntop_... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createArtistWidgets()
<|end_body_0|>
<|body_start_1|>
top_frame = Frame(self)
self.labelInput = Label(top_frame, text='Artist Name')
self.text_in = Entry(top_frame)
self.labelResult = Label(top_frame,... | Application main window class. | getArtist_UI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getArtist_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):... | stack_v2_sparse_classes_10k_train_006035 | 10,077 | no_license | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createArtistWidgets",
"signature": "def createArtistWidgets(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_004917 | Implement the Python class `getArtist_UI` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Han... | Implement the Python class `getArtist_UI` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Han... | 2dba11861f91e4bdc1ef28279132a6d8dd4ccf54 | <|skeleton|>
class getArtist_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class getArtist_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createArtistWidgets()
def createArtistWidgets(self):
"""Add all the widgets to ... | the_stack_v2_python_sparse | Mux_src/Fix_All_Music_Guis.py | rduvalwa5/Mux | train | 0 |
97a367d4cdb88faaccf67b56591dd958245f9850 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn FileEvidence()",
"from .alert_evidence import AlertEvidence\nfrom .detection_status import DetectionStatus\nfrom .file_details import FileDetails\nfrom .alert_evidence import AlertEvidence\nfrom .detection_status import DetectionStatus... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return FileEvidence()
<|end_body_0|>
<|body_start_1|>
from .alert_evidence import AlertEvidence
from .detection_status import DetectionStatus
from .file_details import FileDetails
... | FileEvidence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileEvidence:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_10k_train_006036 | 2,997 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: FileEvidence",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | stack_v2_sparse_classes_30k_train_003863 | Implement the Python class `FileEvidence` described below.
Class description:
Implement the FileEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileEvidence: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `FileEvidence` described below.
Class description:
Implement the FileEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileEvidence: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class FileEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileEvidence:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileEvidence:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: FileEvidence""... | the_stack_v2_python_sparse | msgraph/generated/models/security/file_evidence.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
2668a678747c3cca786a8d71f654860df92968b3 | [
"try:\n DeleteAnnotationLayerCommand(pk).run()\n return self.response(200, message='OK')\nexcept AnnotationLayerNotFoundError:\n return self.response_404()\nexcept AnnotationLayerDeleteIntegrityError as ex:\n return self.response_422(message=str(ex))\nexcept AnnotationLayerDeleteFailedError as ex:\n ... | <|body_start_0|>
try:
DeleteAnnotationLayerCommand(pk).run()
return self.response(200, message='OK')
except AnnotationLayerNotFoundError:
return self.response_404()
except AnnotationLayerDeleteIntegrityError as ex:
return self.response_422(message=... | AnnotationLayerRestApi | [
"Apache-2.0",
"OFL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnotationLayerRestApi:
def delete(self, pk: int) -> Response:
"""Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema: type: integer name: pk description: The annotation layer pk for this annotation responses: 200: description: ... | stack_v2_sparse_classes_10k_train_006037 | 12,412 | permissive | [
{
"docstring": "Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema: type: integer name: pk description: The annotation layer pk for this annotation responses: 200: description: Item deleted content: application/json: schema: type: object properties: m... | 4 | null | Implement the Python class `AnnotationLayerRestApi` described below.
Class description:
Implement the AnnotationLayerRestApi class.
Method signatures and docstrings:
- def delete(self, pk: int) -> Response: Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema... | Implement the Python class `AnnotationLayerRestApi` described below.
Class description:
Implement the AnnotationLayerRestApi class.
Method signatures and docstrings:
- def delete(self, pk: int) -> Response: Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema... | 0945d4a2f46667aebb9b93d0d7685215627ad237 | <|skeleton|>
class AnnotationLayerRestApi:
def delete(self, pk: int) -> Response:
"""Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema: type: integer name: pk description: The annotation layer pk for this annotation responses: 200: description: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AnnotationLayerRestApi:
def delete(self, pk: int) -> Response:
"""Delete an annotation layer --- delete: description: >- Delete an annotation layer parameters: - in: path schema: type: integer name: pk description: The annotation layer pk for this annotation responses: 200: description: Item deleted c... | the_stack_v2_python_sparse | superset/annotation_layers/api.py | apache-superset/incubator-superset | train | 21 | |
ff9ddca5f5fcae922243d5a07ca737197b28eb38 | [
"self.bridgeRotation = None\nself.rotatedLoopLayers = []\nself.sliceDictionary = None\nself.stopProcessing = False\nself.z = 0.0",
"for loop in rotatedLoopLayer.loops:\n for pointIndex, point in enumerate(loop):\n loop[pointIndex] = complex(point.real, -point.imag)\ntriangle_mesh.sortLoopsInOrderOfArea(... | <|body_start_0|>
self.bridgeRotation = None
self.rotatedLoopLayers = []
self.sliceDictionary = None
self.stopProcessing = False
self.z = 0.0
<|end_body_0|>
<|body_start_1|>
for loop in rotatedLoopLayer.loops:
for pointIndex, point in enumerate(loop):
... | An svg carving. | SVGReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVGReader:
"""An svg carving."""
def __init__(self):
"""Add empty lists."""
<|body_0|>
def flipDirectLayer(self, rotatedLoopLayer):
"""Flip the y coordinate of the layer and direct the loops."""
<|body_1|>
def getRotatedLoopLayer(self):
"""Re... | stack_v2_sparse_classes_10k_train_006038 | 39,231 | no_license | [
{
"docstring": "Add empty lists.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Flip the y coordinate of the layer and direct the loops.",
"name": "flipDirectLayer",
"signature": "def flipDirectLayer(self, rotatedLoopLayer)"
},
{
"docstring": "Return t... | 6 | stack_v2_sparse_classes_30k_val_000399 | Implement the Python class `SVGReader` described below.
Class description:
An svg carving.
Method signatures and docstrings:
- def __init__(self): Add empty lists.
- def flipDirectLayer(self, rotatedLoopLayer): Flip the y coordinate of the layer and direct the loops.
- def getRotatedLoopLayer(self): Return the rotate... | Implement the Python class `SVGReader` described below.
Class description:
An svg carving.
Method signatures and docstrings:
- def __init__(self): Add empty lists.
- def flipDirectLayer(self, rotatedLoopLayer): Flip the y coordinate of the layer and direct the loops.
- def getRotatedLoopLayer(self): Return the rotate... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class SVGReader:
"""An svg carving."""
def __init__(self):
"""Add empty lists."""
<|body_0|>
def flipDirectLayer(self, rotatedLoopLayer):
"""Flip the y coordinate of the layer and direct the loops."""
<|body_1|>
def getRotatedLoopLayer(self):
"""Re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SVGReader:
"""An svg carving."""
def __init__(self):
"""Add empty lists."""
self.bridgeRotation = None
self.rotatedLoopLayers = []
self.sliceDictionary = None
self.stopProcessing = False
self.z = 0.0
def flipDirectLayer(self, rotatedLoopLayer):
... | the_stack_v2_python_sparse | fabmetheus_utilities/svg_reader.py | amsler/skeinforge | train | 10 |
737e6736fba9eca295117d03131560384f7c1f89 | [
"self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\nself.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')\nself.plugin_dir = directory\nself.log = None\nself.database = None\nself.noa = None\nself.thread = None\nself.thread_clock = None\nself.javaProcessObject = None\nself.pixmap_w... | <|body_start_0|>
self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
self.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
self.plugin_dir = directory
self.log = None
self.database = None
self.noa = None
self.thread = None
s... | Resources used by the process & interface Objects | Resources | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
<|body_0|>
def loadAppResources(self):
"""load interface graphical resources"""
<|body_1|>
def releaseResources(self, planHeatDMM):
... | stack_v2_sparse_classes_10k_train_006039 | 5,429 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, directory)"
},
{
"docstring": "load interface graphical resources",
"name": "loadAppResources",
"signature": "def loadAppResources(self)"
},
{
"docstring": "Release application resources",
"nam... | 3 | null | Implement the Python class `Resources` described below.
Class description:
Resources used by the process & interface Objects
Method signatures and docstrings:
- def __init__(self, directory): Constructor
- def loadAppResources(self): load interface graphical resources
- def releaseResources(self, planHeatDMM): Releas... | Implement the Python class `Resources` described below.
Class description:
Resources used by the process & interface Objects
Method signatures and docstrings:
- def __init__(self, directory): Constructor
- def loadAppResources(self): load interface graphical resources
- def releaseResources(self, planHeatDMM): Releas... | 9764fcb86d3898b232c4cc333dab75ebe41cd421 | <|skeleton|>
class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
<|body_0|>
def loadAppResources(self):
"""load interface graphical resources"""
<|body_1|>
def releaseResources(self, planHeatDMM):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
self.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
self.plugin_dir = d... | the_stack_v2_python_sparse | PlanheatMappingModule/PlanHeatDMM/src/resources.py | Planheat/Planheat-Tool | train | 2 |
6932fb4f94e7ff377c04f16b4c5410e511a1fde6 | [
"length = len(words)\nif length < 1:\n return 0\nmaxProduct = 0\nlstWord = []\nfor word in words:\n lstWord.append(set(word))\nfor i in xrange(length):\n for j in xrange(length):\n if i != j:\n if lstWord[i] & lstWord[j] == set([]):\n maxProduct = max(maxProduct, len(words[... | <|body_start_0|>
length = len(words)
if length < 1:
return 0
maxProduct = 0
lstWord = []
for word in words:
lstWord.append(set(word))
for i in xrange(length):
for j in xrange(length):
if i != j:
if ls... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct(self, words):
""":type words: List[str] :rtype: int"""
<|body_0|>
def maxProduct2(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(words)
if length < 1:... | stack_v2_sparse_classes_10k_train_006040 | 2,119 | no_license | [
{
"docstring": ":type words: List[str] :rtype: int",
"name": "maxProduct",
"signature": "def maxProduct(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: int",
"name": "maxProduct2",
"signature": "def maxProduct2(self, words)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005209 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, words): :type words: List[str] :rtype: int
- def maxProduct2(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 maxProduct(self, words): :type words: List[str] :rtype: int
- def maxProduct2(self, words): :type words: List[str] :rtype: int
<|skeleton|>
class Solution:
def maxProdu... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def maxProduct(self, words):
""":type words: List[str] :rtype: int"""
<|body_0|>
def maxProduct2(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProduct(self, words):
""":type words: List[str] :rtype: int"""
length = len(words)
if length < 1:
return 0
maxProduct = 0
lstWord = []
for word in words:
lstWord.append(set(word))
for i in xrange(length):
... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00318.Maximum Product of Word Lengths.py | roger6blog/LeetCode | train | 0 | |
3b04049720fe498660852dba601dd009fd91e225 | [
"d = {}\nmaxl = 0\nfor n in nums:\n if n not in d:\n l = n if n - 1 not in d else d[n - 1][0]\n r = n if n + 1 not in d else d[n + 1][1]\n d[l] = (l, r)\n d[r] = (l, r)\n d[n] = (l, r)\n tmp_l = r - l + 1\n if tmp_l > maxl:\n maxl = tmp_l\nreturn maxl",... | <|body_start_0|>
d = {}
maxl = 0
for n in nums:
if n not in d:
l = n if n - 1 not in d else d[n - 1][0]
r = n if n + 1 not in d else d[n + 1][1]
d[l] = (l, r)
d[r] = (l, r)
d[n] = (l, r)
t... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive_v1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = {}
maxl = 0
... | stack_v2_sparse_classes_10k_train_006041 | 1,360 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive_v1",
"signature": "def longestConsecutive_v1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003187 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive_v1(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive_v1(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 2a29426be1d690b6f90bc45b437900deee46d832 | <|skeleton|>
class Solution:
def longestConsecutive_v1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestConsecutive_v1(self, nums):
""":type nums: List[int] :rtype: int"""
d = {}
maxl = 0
for n in nums:
if n not in d:
l = n if n - 1 not in d else d[n - 1][0]
r = n if n + 1 not in d else d[n + 1][1]
d... | the_stack_v2_python_sparse | src/leet/Longest Consecutive Sequence.py | sevenseablue/leetcode | train | 0 | |
3e0fa2e54938d72afe0ee795890c28920402d6dc | [
"wx.Menu.__init__(self)\nself._callbacks = {}\nfor i in menu:\n menuid = wx.NewId()\n item = wx.MenuItem(self, menuid, i[0])\n self._callbacks[menuid] = i[1]\n self.Append(item)\n self.Bind(wx.EVT_MENU, self.on_callback, item)",
"menuid = event.GetId()\nself._callbacks[menuid](event)\nevent.Skip()"... | <|body_start_0|>
wx.Menu.__init__(self)
self._callbacks = {}
for i in menu:
menuid = wx.NewId()
item = wx.MenuItem(self, menuid, i[0])
self._callbacks[menuid] = i[1]
self.Append(item)
self.Bind(wx.EVT_MENU, self.on_callback, item)
<|end... | Context Menu. | ContextMenu | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContextMenu:
"""Context Menu."""
def __init__(self, menu):
"""Attach the context menu to to the parent with the defined items."""
<|body_0|>
def on_callback(self, event):
"""Execute the menu item callback."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_006042 | 9,581 | permissive | [
{
"docstring": "Attach the context menu to to the parent with the defined items.",
"name": "__init__",
"signature": "def __init__(self, menu)"
},
{
"docstring": "Execute the menu item callback.",
"name": "on_callback",
"signature": "def on_callback(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001316 | Implement the Python class `ContextMenu` described below.
Class description:
Context Menu.
Method signatures and docstrings:
- def __init__(self, menu): Attach the context menu to to the parent with the defined items.
- def on_callback(self, event): Execute the menu item callback. | Implement the Python class `ContextMenu` described below.
Class description:
Context Menu.
Method signatures and docstrings:
- def __init__(self, menu): Attach the context menu to to the parent with the defined items.
- def on_callback(self, event): Execute the menu item callback.
<|skeleton|>
class ContextMenu:
... | 95129ca054384a4c59a4effdb3fe32a7a66af6ff | <|skeleton|>
class ContextMenu:
"""Context Menu."""
def __init__(self, menu):
"""Attach the context menu to to the parent with the defined items."""
<|body_0|>
def on_callback(self, event):
"""Execute the menu item callback."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ContextMenu:
"""Context Menu."""
def __init__(self, menu):
"""Attach the context menu to to the parent with the defined items."""
wx.Menu.__init__(self)
self._callbacks = {}
for i in menu:
menuid = wx.NewId()
item = wx.MenuItem(self, menuid, i[0])
... | the_stack_v2_python_sparse | rummage/lib/gui/controls/custom_statusbar.py | facelessuser/Rummage | train | 70 |
b0d16aed31e0c7fd3471d26d640ecc5a720dc494 | [
"if logging_config_path is not None:\n config_path = logging_config_path\nelse:\n config_path = DEFAULT_LOGGING_CONFIG_PATH\nlog_config = load_resource(config_path, 'utf-8')\nif log_config:\n with log_config:\n fileConfig(log_config, disable_existing_loggers=False)\nelse:\n logging.basicConfig(le... | <|body_start_0|>
if logging_config_path is not None:
config_path = logging_config_path
else:
config_path = DEFAULT_LOGGING_CONFIG_PATH
log_config = load_resource(config_path, 'utf-8')
if log_config:
with log_config:
fileConfig(log_confi... | Utility class used to configure logging and print an informative start banner. | LoggingConfigurator | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggingConfigurator:
"""Utility class used to configure logging and print an informative start banner."""
def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None):
"""Configure logger. :param logging_config_path: str: (Default value = None) Optional ... | stack_v2_sparse_classes_10k_train_006043 | 21,957 | permissive | [
{
"docstring": "Configure logger. :param logging_config_path: str: (Default value = None) Optional path to custom logging config :param log_level: str: (Default value = None)",
"name": "configure",
"signature": "def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None)"
... | 3 | stack_v2_sparse_classes_30k_train_000426 | Implement the Python class `LoggingConfigurator` described below.
Class description:
Utility class used to configure logging and print an informative start banner.
Method signatures and docstrings:
- def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None): Configure logger. :param l... | Implement the Python class `LoggingConfigurator` described below.
Class description:
Utility class used to configure logging and print an informative start banner.
Method signatures and docstrings:
- def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None): Configure logger. :param l... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class LoggingConfigurator:
"""Utility class used to configure logging and print an informative start banner."""
def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None):
"""Configure logger. :param logging_config_path: str: (Default value = None) Optional ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LoggingConfigurator:
"""Utility class used to configure logging and print an informative start banner."""
def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None):
"""Configure logger. :param logging_config_path: str: (Default value = None) Optional path to custo... | the_stack_v2_python_sparse | aries_cloudagent/config/logging.py | hyperledger/aries-cloudagent-python | train | 370 |
a66a8fa0c65d15d3deee74c28f19e9858f16ee66 | [
"super(PsortAnalysisReportQueueConsumer, self).__init__(queue_object)\nself._filter_string = filter_string\nself._preferred_encoding = preferred_encoding\nself._storage_file = storage_file\nself.anomalies = []\nself.counter = collections.Counter()\nself.tags = []",
"self.counter[u'Total Reports'] += 1\nself.count... | <|body_start_0|>
super(PsortAnalysisReportQueueConsumer, self).__init__(queue_object)
self._filter_string = filter_string
self._preferred_encoding = preferred_encoding
self._storage_file = storage_file
self.anomalies = []
self.counter = collections.Counter()
self.... | Class that implements an analysis report queue consumer for psort. | PsortAnalysisReportQueueConsumer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PsortAnalysisReportQueueConsumer:
"""Class that implements an analysis report queue consumer for psort."""
def __init__(self, queue_object, storage_file, filter_string, preferred_encoding=u'utf-8'):
"""Initializes the queue consumer. Args: queue_object: the queue object (instance of ... | stack_v2_sparse_classes_10k_train_006044 | 25,291 | permissive | [
{
"docstring": "Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue). storage_file: the storage file (instance of StorageFile). filter_string: the filter string. preferred_encoding: optional preferred encoding.",
"name": "__init__",
"signature": "def __init__(self, qu... | 2 | stack_v2_sparse_classes_30k_train_005790 | Implement the Python class `PsortAnalysisReportQueueConsumer` described below.
Class description:
Class that implements an analysis report queue consumer for psort.
Method signatures and docstrings:
- def __init__(self, queue_object, storage_file, filter_string, preferred_encoding=u'utf-8'): Initializes the queue con... | Implement the Python class `PsortAnalysisReportQueueConsumer` described below.
Class description:
Class that implements an analysis report queue consumer for psort.
Method signatures and docstrings:
- def __init__(self, queue_object, storage_file, filter_string, preferred_encoding=u'utf-8'): Initializes the queue con... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class PsortAnalysisReportQueueConsumer:
"""Class that implements an analysis report queue consumer for psort."""
def __init__(self, queue_object, storage_file, filter_string, preferred_encoding=u'utf-8'):
"""Initializes the queue consumer. Args: queue_object: the queue object (instance of ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PsortAnalysisReportQueueConsumer:
"""Class that implements an analysis report queue consumer for psort."""
def __init__(self, queue_object, storage_file, filter_string, preferred_encoding=u'utf-8'):
"""Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue). stora... | the_stack_v2_python_sparse | plaso/frontend/psort.py | CNR-ITTIG/plasodfaxp | train | 1 |
2f0cfa672d6a1069d0647c0dd3593ccaa8527330 | [
"self.SetTitle('This is an example Dialog')\nself.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)\nreturn True",
"if messageId == c4d.DLG_OK:\n print('User Click on Ok')\n return True\nelif messageId == c4d.DLG_CANCEL:\n print('User Click on Cancel')\n self.Close()\n return True\nreturn True"
] | <|body_start_0|>
self.SetTitle('This is an example Dialog')
self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)
return True
<|end_body_0|>
<|body_start_1|>
if messageId == c4d.DLG_OK:
print('User Click on Ok')
return True
elif messageId == c4d.DLG_CANCEL:
... | ExampleDialog | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automat... | stack_v2_sparse_classes_10k_train_006045 | 7,074 | permissive | [
{
"docstring": "This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True.",
"name": "CreateLayout",
"signature": "def CreateLayout(self)"
},
{
"docstring": "This Method is called automatically when the user cl... | 2 | stack_v2_sparse_classes_30k_train_007024 | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True.... | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True.... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True."""
self.SetTitle('This is an example Dialog')
self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)
... | the_stack_v2_python_sparse | plugins/py-ies_meta_r12/py-ies-meta_loader.pyp | PluginCafe/cinema4d_py_sdk_extended | train | 112 | |
c7494cc4c831641cde1c4925294590910d37b971 | [
"rqst = Request('GET', '/resource/watcher')\nrqst.set_json({'agent_id': agent_id})\nasync with rqst.fetch() as resp:\n data = await resp.json()\n if 'message' in data:\n return data['message']\n else:\n return data",
"rqst = Request('POST', '/resource/watcher/agent/start')\nrqst.set_json({'... | <|body_start_0|>
rqst = Request('GET', '/resource/watcher')
rqst.set_json({'agent_id': agent_id})
async with rqst.fetch() as resp:
data = await resp.json()
if 'message' in data:
return data['message']
else:
return data
<|end_bod... | Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege. | AgentWatcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentWatcher:
"""Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege."""
async def get_status(cls, agent_id: str) -> dict:
"""Get a... | stack_v2_sparse_classes_10k_train_006046 | 4,810 | permissive | [
{
"docstring": "Get agent and watcher status.",
"name": "get_status",
"signature": "async def get_status(cls, agent_id: str) -> dict"
},
{
"docstring": "Start agent.",
"name": "agent_start",
"signature": "async def agent_start(cls, agent_id: str) -> dict"
},
{
"docstring": "Stop ... | 4 | stack_v2_sparse_classes_30k_train_005710 | Implement the Python class `AgentWatcher` described below.
Class description:
Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege.
Method signatures and docstrings:
... | Implement the Python class `AgentWatcher` described below.
Class description:
Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege.
Method signatures and docstrings:
... | afc831fedb59f791cdf4201e7f617b201d820074 | <|skeleton|>
class AgentWatcher:
"""Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege."""
async def get_status(cls, agent_id: str) -> dict:
"""Get a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AgentWatcher:
"""Provides a shortcut of :func:`Admin.query() <ai.backend.client.admin.Admin.query>` that manipulate agent status. .. note:: All methods in this function class require you to have the *superadmin* privilege."""
async def get_status(cls, agent_id: str) -> dict:
"""Get agent and watc... | the_stack_v2_python_sparse | src/ai/backend/client/func/agent.py | lablup/backend.ai-client-py | train | 7 |
707224378ed0cd849660f38f9bacfca1cd411f1a | [
"article = request.data.get('article', {})\narticle['author'] = request.user.pk\narticle_instance = get_object_or_404(Article, slug=slug)\nslug = slugify(article['title']).replace('_', '-')\nslug = slug + '-' + str(uuid.uuid4()).split('-')[-1]\narticle['slug'] = slug\nthe_full_sentence = '{} {}'.format(article['tit... | <|body_start_0|>
article = request.data.get('article', {})
article['author'] = request.user.pk
article_instance = get_object_or_404(Article, slug=slug)
slug = slugify(article['title']).replace('_', '-')
slug = slug + '-' + str(uuid.uuid4()).split('-')[-1]
article['slug'] ... | UpdateDestroyArticleAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestroyArticleAPIView:
def update(self, request, slug):
"""This method updates a user article"""
<|body_0|>
def destroy(self, request, slug):
"""This method allows a user to delete his article"""
<|body_1|>
def retrieve(self, request, slug):
... | stack_v2_sparse_classes_10k_train_006047 | 16,404 | permissive | [
{
"docstring": "This method updates a user article",
"name": "update",
"signature": "def update(self, request, slug)"
},
{
"docstring": "This method allows a user to delete his article",
"name": "destroy",
"signature": "def destroy(self, request, slug)"
},
{
"docstring": "This me... | 3 | stack_v2_sparse_classes_30k_train_006320 | Implement the Python class `UpdateDestroyArticleAPIView` described below.
Class description:
Implement the UpdateDestroyArticleAPIView class.
Method signatures and docstrings:
- def update(self, request, slug): This method updates a user article
- def destroy(self, request, slug): This method allows a user to delete ... | Implement the Python class `UpdateDestroyArticleAPIView` described below.
Class description:
Implement the UpdateDestroyArticleAPIView class.
Method signatures and docstrings:
- def update(self, request, slug): This method updates a user article
- def destroy(self, request, slug): This method allows a user to delete ... | 0e9ef1a10c8a3f6736999a5111736f7bd7236689 | <|skeleton|>
class UpdateDestroyArticleAPIView:
def update(self, request, slug):
"""This method updates a user article"""
<|body_0|>
def destroy(self, request, slug):
"""This method allows a user to delete his article"""
<|body_1|>
def retrieve(self, request, slug):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateDestroyArticleAPIView:
def update(self, request, slug):
"""This method updates a user article"""
article = request.data.get('article', {})
article['author'] = request.user.pk
article_instance = get_object_or_404(Article, slug=slug)
slug = slugify(article['title'])... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/ah-backend-odin | train | 0 | |
f697311ca21da3da40e323f7d20fe2ab8fa97dd7 | [
"with db.connection as connection:\n service = CitiesService(connection)\n cities = service.read_all()\n return (jsonify(cities), 200)",
"name = request.json.get('name')\nwith db.connection as connection:\n city = CitiesService(connection)\n try:\n return (jsonify(city.read(name)), 200)\n ... | <|body_start_0|>
with db.connection as connection:
service = CitiesService(connection)
cities = service.read_all()
return (jsonify(cities), 200)
<|end_body_0|>
<|body_start_1|>
name = request.json.get('name')
with db.connection as connection:
city... | CitiesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CitiesView:
def get(self):
"""Получение списка всех городов"""
<|body_0|>
def post(self):
"""Создание нового города"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with db.connection as connection:
service = CitiesService(connection)
... | stack_v2_sparse_classes_10k_train_006048 | 1,079 | no_license | [
{
"docstring": "Получение списка всех городов",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Создание нового города",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004510 | Implement the Python class `CitiesView` described below.
Class description:
Implement the CitiesView class.
Method signatures and docstrings:
- def get(self): Получение списка всех городов
- def post(self): Создание нового города | Implement the Python class `CitiesView` described below.
Class description:
Implement the CitiesView class.
Method signatures and docstrings:
- def get(self): Получение списка всех городов
- def post(self): Создание нового города
<|skeleton|>
class CitiesView:
def get(self):
"""Получение списка всех гор... | 79b0563f654016f7d56d988988ddc4bfdb0f1474 | <|skeleton|>
class CitiesView:
def get(self):
"""Получение списка всех городов"""
<|body_0|>
def post(self):
"""Создание нового города"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CitiesView:
def get(self):
"""Получение списка всех городов"""
with db.connection as connection:
service = CitiesService(connection)
cities = service.read_all()
return (jsonify(cities), 200)
def post(self):
"""Создание нового города"""
n... | the_stack_v2_python_sparse | Lesson 13/final v 2.0/src/blueprints/cities.py | Alexey7953/antida-school | train | 0 | |
c7ab036e7d928189048cbd35300c7eddde959387 | [
"if not root:\n return '^$'\nelse:\n return '^' + str(root.val) + self.serialize(root.left) + self.serialize(root.right) + '$'",
"if data == '^$':\n return None\nelse:\n p1 = data[1:].index('^') + 1\n cnt, p2 = (1, p1 + 1)\n while cnt > 0:\n if data[p2] == '^':\n cnt += 1\n ... | <|body_start_0|>
if not root:
return '^$'
else:
return '^' + str(root.val) + self.serialize(root.left) + self.serialize(root.right) + '$'
<|end_body_0|>
<|body_start_1|>
if data == '^$':
return None
else:
p1 = data[1:].index('^') + 1
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006049 | 1,265 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002772 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0d2e7f9b26e34c9b5964484563c597c3da296d15 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '^$'
else:
return '^' + str(root.val) + self.serialize(root.left) + self.serialize(root.right) + '$'
def deserialize(self, data):... | the_stack_v2_python_sparse | 297SerializeAndDeserializeBinaryTree.py | yanlinf/LeetCode | train | 0 | |
538a88b28cb8897e8d2856e1a86945dfdc48fce0 | [
"ns = len(s)\nnp = len(p)\ndp = [[False] * (np + 1) for _ in range(ns + 1)]\ndp[0][0] = True\nfor i in range(np):\n if p[i] == '*' and dp[0][i - 1]:\n dp[0][i + 1] = True\nfor i in range(1, ns + 1):\n for j in range(1, np + 1):\n if p[j - 1] == s[i - 1] or p[j - 1] == '.':\n dp[i][j] ... | <|body_start_0|>
ns = len(s)
np = len(p)
dp = [[False] * (np + 1) for _ in range(ns + 1)]
dp[0][0] = True
for i in range(np):
if p[i] == '*' and dp[0][i - 1]:
dp[0][i + 1] = True
for i in range(1, ns + 1):
for j in range(1, np + 1):... | 给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010 | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010"""
def isMatch(self, s: str, p: str) -> bool:
... | stack_v2_sparse_classes_10k_train_006050 | 4,476 | permissive | [
{
"docstring": "dp[i][j] 表示 s 的前 i 个是否能被 p 的前 j 个匹配 p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1] If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1]; If p.charAt(j) == '*': here are two sub conditions: //in this case, a* only counts as empty, otherwise is not match - if p.charAt(j-1) != s.charAt(i) : dp[i][... | 2 | stack_v2_sparse_classes_30k_train_003281 | Implement the Python class `Solution` described below.
Class description:
给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010
Method signatures... | Implement the Python class `Solution` described below.
Class description:
给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010
Method signatures... | 9f49766a2b375a6c65f7bfa96df513875ddd772d | <|skeleton|>
class Solution:
"""给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010"""
def isMatch(self, s: str, p: str) -> bool:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010"""
def isMatch(self, s: str, p: str) -> bool:
"""dp[i][j]... | the_stack_v2_python_sparse | Leetcode/10.isMatch.py | Song2017/Leetcode_python | train | 1 |
db95b3aea68197823ccc068736545fbfa12ff048 | [
"self.weight_keep_drop = weight_keep_drop\nself.mode = mode\nsuper(WeightDropLSTMCell, self).__init__(num_units, forget_bias, state_is_tuple, activation, reuse)",
"sigmoid = tf.sigmoid\nif self._state_is_tuple:\n c, h = state\nelse:\n c, h = tf.split(value=state, num_or_size_splits=2, axis=1)\nif self._line... | <|body_start_0|>
self.weight_keep_drop = weight_keep_drop
self.mode = mode
super(WeightDropLSTMCell, self).__init__(num_units, forget_bias, state_is_tuple, activation, reuse)
<|end_body_0|>
<|body_start_1|>
sigmoid = tf.sigmoid
if self._state_is_tuple:
c, h = state
... | WeightDropLSTMCell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightDropLSTMCell:
def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None):
"""Initialize the parameters for an LSTM cell."""
<|body_0|>
def call(self, inputs, state):
"... | stack_v2_sparse_classes_10k_train_006051 | 2,572 | permissive | [
{
"docstring": "Initialize the parameters for an LSTM cell.",
"name": "__init__",
"signature": "def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None)"
},
{
"docstring": "Long short-term memory cell... | 2 | stack_v2_sparse_classes_30k_train_006835 | Implement the Python class `WeightDropLSTMCell` described below.
Class description:
Implement the WeightDropLSTMCell class.
Method signatures and docstrings:
- def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None): Init... | Implement the Python class `WeightDropLSTMCell` described below.
Class description:
Implement the WeightDropLSTMCell class.
Method signatures and docstrings:
- def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None): Init... | de8095ecef9300e0f670062c2779459c19c2d49d | <|skeleton|>
class WeightDropLSTMCell:
def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None):
"""Initialize the parameters for an LSTM cell."""
<|body_0|>
def call(self, inputs, state):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WeightDropLSTMCell:
def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None):
"""Initialize the parameters for an LSTM cell."""
self.weight_keep_drop = weight_keep_drop
self.mode = mode
... | the_stack_v2_python_sparse | utils/weight_drop_lstm.py | Johnnytjn/RNN_classify | train | 0 | |
7ee6386eea2a69af1484816b2f2194df7680bbe6 | [
"queryset = Article.objects.all()\nusername = self.request.query_params.get('username', None)\nif username is not None:\n queryset = queryset.filter(author__username__iexact=username)\ntag = self.request.query_params.get('tag', None)\nif tag is not None:\n queryset = queryset.filter(tags__tag_name__iexact=tag... | <|body_start_0|>
queryset = Article.objects.all()
username = self.request.query_params.get('username', None)
if username is not None:
queryset = queryset.filter(author__username__iexact=username)
tag = self.request.query_params.get('tag', None)
if tag is not None:
... | A user can post an artcle once they have an account in the application params: ['title', 'description', 'body'] | ArticleAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleAPIView:
"""A user can post an artcle once they have an account in the application params: ['title', 'description', 'body']"""
def get_queryset(self):
"""Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL."... | stack_v2_sparse_classes_10k_train_006052 | 12,242 | permissive | [
{
"docstring": "Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Create a new article in the application",
"name": "post",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_001756 | Implement the Python class `ArticleAPIView` described below.
Class description:
A user can post an artcle once they have an account in the application params: ['title', 'description', 'body']
Method signatures and docstrings:
- def get_queryset(self): Optionally restricts the returned purchases to a given user, by fi... | Implement the Python class `ArticleAPIView` described below.
Class description:
A user can post an artcle once they have an account in the application params: ['title', 'description', 'body']
Method signatures and docstrings:
- def get_queryset(self): Optionally restricts the returned purchases to a given user, by fi... | e8438b78b88c52d108520429d0b67cd3d13e0824 | <|skeleton|>
class ArticleAPIView:
"""A user can post an artcle once they have an account in the application params: ['title', 'description', 'body']"""
def get_queryset(self):
"""Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL."... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArticleAPIView:
"""A user can post an artcle once they have an account in the application params: ['title', 'description', 'body']"""
def get_queryset(self):
"""Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL."""
qu... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/ah-sealteam | train | 1 |
405b5c41d8264945db2d199eaab9bc43661cd4d9 | [
"if sys.platform == 'win32':\n return QWinSplitterHandle(self.orientation(), self)\nreturn QSplitterHandle(self.orientation(), self)",
"old = self.orientation()\nif old != orientation:\n super(QCustomSplitter, self).setOrientation(orientation)\n if sys.platform == 'win32':\n for idx in xrange(self... | <|body_start_0|>
if sys.platform == 'win32':
return QWinSplitterHandle(self.orientation(), self)
return QSplitterHandle(self.orientation(), self)
<|end_body_0|>
<|body_start_1|>
old = self.orientation()
if old != orientation:
super(QCustomSplitter, self).setOrien... | A custom QSplitter which handles children of type QSplitItem. | QCustomSplitter | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCustomSplitter:
"""A custom QSplitter which handles children of type QSplitItem."""
def createHandle(self):
"""A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterHandle which works around an issue with handle not drawing... | stack_v2_sparse_classes_10k_train_006053 | 8,068 | permissive | [
{
"docstring": "A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterHandle which works around an issue with handle not drawing nicely. On all other platforms, a normal QSplitterHandler widget.",
"name": "createHandle",
"signature": "def creat... | 3 | null | Implement the Python class `QCustomSplitter` described below.
Class description:
A custom QSplitter which handles children of type QSplitItem.
Method signatures and docstrings:
- def createHandle(self): A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterH... | Implement the Python class `QCustomSplitter` described below.
Class description:
A custom QSplitter which handles children of type QSplitItem.
Method signatures and docstrings:
- def createHandle(self): A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterH... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class QCustomSplitter:
"""A custom QSplitter which handles children of type QSplitItem."""
def createHandle(self):
"""A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterHandle which works around an issue with handle not drawing... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QCustomSplitter:
"""A custom QSplitter which handles children of type QSplitItem."""
def createHandle(self):
"""A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterHandle which works around an issue with handle not drawing nicely. On a... | the_stack_v2_python_sparse | enaml/qt/qt_splitter.py | enthought/enaml | train | 17 |
3ab1113c546bc7a99aea7b355fbc03f64f397463 | [
"self.type = typ\nself.rootobj = rootobject\nself.islead = islead\nself.obj = None\nif self.type == 'excel':\n self._findexcel(field)\nelse:\n self._findword(field)",
"found = False\nfor sheet in self.rootobj:\n r = sheet.min_row\n for c in range(sheet.min_column, sheet.max_column + 1):\n if st... | <|body_start_0|>
self.type = typ
self.rootobj = rootobject
self.islead = islead
self.obj = None
if self.type == 'excel':
self._findexcel(field)
else:
self._findword(field)
<|end_body_0|>
<|body_start_1|>
found = False
for sheet in ... | Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (Workbook) self.islead - чи є поле прові... | SourceItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (W... | stack_v2_sparse_classes_10k_train_006054 | 5,367 | no_license | [
{
"docstring": "Конструктор. Здійснює під'єднання до джерела даних. rootobject - об'єкт, де розташовано відповідні дані: документ (Document) або робоча книга (Workbook), в залежності від типу. islead - чи є параметр провідним.",
"name": "__init__",
"signature": "def __init__(self, field, typ, rootobject... | 4 | stack_v2_sparse_classes_30k_train_001325 | Implement the Python class `SourceItem` described below.
Class description:
Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт ... | Implement the Python class `SourceItem` described below.
Class description:
Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт ... | e44bf2b535b34bc31fb323c20901a77b0b3072f2 | <|skeleton|>
class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (W... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (Workbook) self... | the_stack_v2_python_sparse | dz_others/subject23_MS/merge/t23_22_sourceitem.py | davendiy/ads_course2 | train | 0 |
af788f1b33b24a6c2c3e80cb974c69b73c94106a | [
"request_json = request.get_json()\nvalid_format, errors = schema_utils.validate(request_json, 'affiliation')\nbearer_token = request.headers['Authorization'].replace('Bearer ', '')\nis_new_business = request.args.get('newBusiness', 'false').lower() == 'true'\nif not valid_format:\n return ({'message': schema_ut... | <|body_start_0|>
request_json = request.get_json()
valid_format, errors = schema_utils.validate(request_json, 'affiliation')
bearer_token = request.headers['Authorization'].replace('Bearer ', '')
is_new_business = request.args.get('newBusiness', 'false').lower() == 'true'
if not ... | Resource for managing affiliations for an org. | OrgAffiliations | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrgAffiliations:
"""Resource for managing affiliations for an org."""
def post(org_id):
"""Post a new Affiliation for an org using the request body."""
<|body_0|>
def get(org_id):
"""Get all affiliated entities for the given org."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k_train_006055 | 30,185 | permissive | [
{
"docstring": "Post a new Affiliation for an org using the request body.",
"name": "post",
"signature": "def post(org_id)"
},
{
"docstring": "Get all affiliated entities for the given org.",
"name": "get",
"signature": "def get(org_id)"
}
] | 2 | null | Implement the Python class `OrgAffiliations` described below.
Class description:
Resource for managing affiliations for an org.
Method signatures and docstrings:
- def post(org_id): Post a new Affiliation for an org using the request body.
- def get(org_id): Get all affiliated entities for the given org. | Implement the Python class `OrgAffiliations` described below.
Class description:
Resource for managing affiliations for an org.
Method signatures and docstrings:
- def post(org_id): Post a new Affiliation for an org using the request body.
- def get(org_id): Get all affiliated entities for the given org.
<|skeleton|... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class OrgAffiliations:
"""Resource for managing affiliations for an org."""
def post(org_id):
"""Post a new Affiliation for an org using the request body."""
<|body_0|>
def get(org_id):
"""Get all affiliated entities for the given org."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrgAffiliations:
"""Resource for managing affiliations for an org."""
def post(org_id):
"""Post a new Affiliation for an org using the request body."""
request_json = request.get_json()
valid_format, errors = schema_utils.validate(request_json, 'affiliation')
bearer_token ... | the_stack_v2_python_sparse | auth-api/src/auth_api/resources/org.py | bcgov/sbc-auth | train | 13 |
07015697a309763c9dd62e212fb8a48856c6a5bf | [
"if len(arr.shape) == 1:\n arr = np.expand_dims(arr, axis=0)\nif arr.shape[-1] != 599 and arr.shape[-1] != 603:\n raise RuntimeError('This is not an array valid with all classes defined!')\nelif arr.shape[-1] == 599:\n return arr[:, list(CATEGORIES_MAP.values())]\nelse:\n return arr[:, list(CATEGORIES_M... | <|body_start_0|>
if len(arr.shape) == 1:
arr = np.expand_dims(arr, axis=0)
if arr.shape[-1] != 599 and arr.shape[-1] != 603:
raise RuntimeError('This is not an array valid with all classes defined!')
elif arr.shape[-1] == 599:
return arr[:, list(CATEGORIES_MAP... | CategoryEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryEncoder:
def transform(arr: np.array) -> np.array:
"""Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array"""
<|body_0|>
def invert_transform(arr: np.array) -> np.array:
"""Returns all categories, tranfor... | stack_v2_sparse_classes_10k_train_006056 | 2,046 | no_license | [
{
"docstring": "Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array",
"name": "transform",
"signature": "def transform(arr: np.array) -> np.array"
},
{
"docstring": "Returns all categories, tranforming back from useful categories Args: arr:... | 2 | stack_v2_sparse_classes_30k_test_000120 | Implement the Python class `CategoryEncoder` described below.
Class description:
Implement the CategoryEncoder class.
Method signatures and docstrings:
- def transform(arr: np.array) -> np.array: Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array
- def invert_t... | Implement the Python class `CategoryEncoder` described below.
Class description:
Implement the CategoryEncoder class.
Method signatures and docstrings:
- def transform(arr: np.array) -> np.array: Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array
- def invert_t... | af685a136a6303b56af857bf70011b222db46fe5 | <|skeleton|>
class CategoryEncoder:
def transform(arr: np.array) -> np.array:
"""Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array"""
<|body_0|>
def invert_transform(arr: np.array) -> np.array:
"""Returns all categories, tranfor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CategoryEncoder:
def transform(arr: np.array) -> np.array:
"""Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array"""
if len(arr.shape) == 1:
arr = np.expand_dims(arr, axis=0)
if arr.shape[-1] != 599 and arr.shape[-1] !... | the_stack_v2_python_sparse | project/utils/category_encoder.py | BAlmeidaS/capstone-udacity-mle | train | 1 | |
772983b8a117cd6885490e4147740dc1164f2f7b | [
"ParticleFilter.__init__(self, number_of_particles, limits, process_noise, measurement_noise)\nself.resolutions = resolutions\nself.epsilon = epsilon\nself.upper_quantile = upper_quantile\nself.minimum_number_of_particles = int(min_number_particles)\nself.maximum_number_of_particles = int(max_number_particles)",
... | <|body_start_0|>
ParticleFilter.__init__(self, number_of_particles, limits, process_noise, measurement_noise)
self.resolutions = resolutions
self.epsilon = epsilon
self.upper_quantile = upper_quantile
self.minimum_number_of_particles = int(min_number_particles)
self.maxim... | Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min) | AdaptiveParticleFilterKld | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaptiveParticleFilterKld:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, proces... | stack_v2_sparse_classes_10k_train_006057 | 6,194 | no_license | [
{
"docstring": "Initialize the adaptive particle filter using Kullback-Leibler divergence (KLD) sampling proposed in [1]. [1] Fox, Dieter. \"Adapting the sample size in particle filters through KLD-sampling.\" The international Journal of robotics research 22.12 (2003): 985-1003. :param number_of_particles: Num... | 2 | stack_v2_sparse_classes_30k_train_006168 | Implement the Python class `AdaptiveParticleFilterKld` described below.
Class description:
Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)
Method signatures and ... | Implement the Python class `AdaptiveParticleFilterKld` described below.
Class description:
Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)
Method signatures and ... | 4e5197c38a9d241d9ea06c06ab9fc893ffb8c70b | <|skeleton|>
class AdaptiveParticleFilterKld:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, proces... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdaptiveParticleFilterKld:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, process_noise, meas... | the_stack_v2_python_sparse | core/particle_filters/adaptive_particle_filter_kld.py | eternalamit5/Learning-Nuggets | train | 0 |
f35fed08f143761fe680b809b2a5573cbd5f4dbc | [
"if not root:\n return 0\nif not root.left:\n return self.minDepth_MK1(root.right) + 1\nif not root.right:\n return self.minDepth_MK1(root.left) + 1\nreturn min(self.minDepth_MK1(root.left), self.minDepth_MK1(root.right)) + 1",
"if not root:\n return 0\ndeq = deque([(root, 1)])\nwhile deq:\n node, ... | <|body_start_0|>
if not root:
return 0
if not root.left:
return self.minDepth_MK1(root.right) + 1
if not root.right:
return self.minDepth_MK1(root.left) + 1
return min(self.minDepth_MK1(root.left), self.minDepth_MK1(root.right)) + 1
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth_MK1(self, root: TreeNode) -> int:
"""DFS"""
<|body_0|>
def minDepth_MK2(self, root: TreeNode) -> int:
"""BFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
if not root.left:
... | stack_v2_sparse_classes_10k_train_006058 | 1,001 | no_license | [
{
"docstring": "DFS",
"name": "minDepth_MK1",
"signature": "def minDepth_MK1(self, root: TreeNode) -> int"
},
{
"docstring": "BFS",
"name": "minDepth_MK2",
"signature": "def minDepth_MK2(self, root: TreeNode) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_000975 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth_MK1(self, root: TreeNode) -> int: DFS
- def minDepth_MK2(self, root: TreeNode) -> int: BFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth_MK1(self, root: TreeNode) -> int: DFS
- def minDepth_MK2(self, root: TreeNode) -> int: BFS
<|skeleton|>
class Solution:
def minDepth_MK1(self, root: TreeNode) ... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def minDepth_MK1(self, root: TreeNode) -> int:
"""DFS"""
<|body_0|>
def minDepth_MK2(self, root: TreeNode) -> int:
"""BFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth_MK1(self, root: TreeNode) -> int:
"""DFS"""
if not root:
return 0
if not root.left:
return self.minDepth_MK1(root.right) + 1
if not root.right:
return self.minDepth_MK1(root.left) + 1
return min(self.minDepth_MK... | the_stack_v2_python_sparse | 0111. Minimum Depth of Binary Tree/Solution.py | faterazer/LeetCode | train | 4 | |
62e5a501a1d62b366038b9a0a3695f1bcfc8cef0 | [
"if not root:\n return root\nroot.left, root.right = (root.right, root.left)\nself.invertTree(root.left)\nself.invertTree(root.right)\nreturn root",
"if not root:\n return root\nself.invertTree(root.left)\nroot.left, root.right = (root.right, root.left)\nself.invertTree(root.right)\nreturn root"
] | <|body_start_0|>
if not root:
return root
root.left, root.right = (root.right, root.left)
self.invertTree(root.left)
self.invertTree(root.right)
return root
<|end_body_0|>
<|body_start_1|>
if not root:
return root
self.invertTree(root.left... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:先序遍历 关键:将每个点的左右子节点交换"""
<|body_0|>
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:中序遍历 关键:将每个点的左右子节点交换"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_10k_train_006059 | 1,754 | no_license | [
{
"docstring": "思路:先序遍历 关键:将每个点的左右子节点交换",
"name": "invertTree",
"signature": "def invertTree(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "思路:中序遍历 关键:将每个点的左右子节点交换",
"name": "invertTree",
"signature": "def invertTree(self, root: TreeNode) -> TreeNode"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root: TreeNode) -> TreeNode: 思路:先序遍历 关键:将每个点的左右子节点交换
- def invertTree(self, root: TreeNode) -> TreeNode: 思路:中序遍历 关键:将每个点的左右子节点交换 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root: TreeNode) -> TreeNode: 思路:先序遍历 关键:将每个点的左右子节点交换
- def invertTree(self, root: TreeNode) -> TreeNode: 思路:中序遍历 关键:将每个点的左右子节点交换
<|skeleton|>
class Solution... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:先序遍历 关键:将每个点的左右子节点交换"""
<|body_0|>
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:中序遍历 关键:将每个点的左右子节点交换"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:先序遍历 关键:将每个点的左右子节点交换"""
if not root:
return root
root.left, root.right = (root.right, root.left)
self.invertTree(root.left)
self.invertTree(root.right)
return root
def invertTree(... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/226. 翻转二叉树.py | yiming1012/MyLeetCode | train | 2 | |
544d20a2eaab38d949ad8814f04420c79b50925b | [
"sql = \" select a.id, pbf.full_name as authorize_name, pbf.take_photo, a.mobile_number, a.relation_student from info_authorize a join info_people_basic_facts pbf on a.basic_id = pbf.id join info_student s on a.student_id = s.id join info_guardian g on g.student_id = s.id where g.login_user_id = :login_user_id ... | <|body_start_0|>
sql = " select a.id, pbf.full_name as authorize_name, pbf.take_photo, a.mobile_number, a.relation_student from info_authorize a join info_people_basic_facts pbf on a.basic_id = pbf.id join info_student s on a.student_id = s.id join info_guardian g on g.student_id = s.id where g.login_user_id... | InfoAuthorize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfoAuthorize:
def query_auth_info(self, login_user_id):
"""获取授权人列表 :param login_user_id :return:"""
<|body_0|>
def query_sa_auth_tooltips(self, login_user_id, create_dt):
"""获取有无学生变更授权人 :param login_user_id :param create_dt :return:"""
<|body_1|>
def de... | stack_v2_sparse_classes_10k_train_006060 | 3,640 | no_license | [
{
"docstring": "获取授权人列表 :param login_user_id :return:",
"name": "query_auth_info",
"signature": "def query_auth_info(self, login_user_id)"
},
{
"docstring": "获取有无学生变更授权人 :param login_user_id :param create_dt :return:",
"name": "query_sa_auth_tooltips",
"signature": "def query_sa_auth_too... | 4 | stack_v2_sparse_classes_30k_val_000133 | Implement the Python class `InfoAuthorize` described below.
Class description:
Implement the InfoAuthorize class.
Method signatures and docstrings:
- def query_auth_info(self, login_user_id): 获取授权人列表 :param login_user_id :return:
- def query_sa_auth_tooltips(self, login_user_id, create_dt): 获取有无学生变更授权人 :param login_u... | Implement the Python class `InfoAuthorize` described below.
Class description:
Implement the InfoAuthorize class.
Method signatures and docstrings:
- def query_auth_info(self, login_user_id): 获取授权人列表 :param login_user_id :return:
- def query_sa_auth_tooltips(self, login_user_id, create_dt): 获取有无学生变更授权人 :param login_u... | a7cf5a0b6daa372ed860dc43d92c55fcde764eb9 | <|skeleton|>
class InfoAuthorize:
def query_auth_info(self, login_user_id):
"""获取授权人列表 :param login_user_id :return:"""
<|body_0|>
def query_sa_auth_tooltips(self, login_user_id, create_dt):
"""获取有无学生变更授权人 :param login_user_id :param create_dt :return:"""
<|body_1|>
def de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InfoAuthorize:
def query_auth_info(self, login_user_id):
"""获取授权人列表 :param login_user_id :return:"""
sql = " select a.id, pbf.full_name as authorize_name, pbf.take_photo, a.mobile_number, a.relation_student from info_authorize a join info_people_basic_facts pbf on a.basic_id = pbf.id join in... | the_stack_v2_python_sparse | python_project/smart_schoolBus_project/app/schoolbus_situation/models/info_authorize_model.py | malqch/aibus | train | 0 | |
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_10k_train_006061 | 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_006027 | 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_10k | 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 | |
12d3e8d3bc847d62d42bea392d6a722bf9834b23 | [
"self.batch_url = batch_url\nself.compute = compute\nself.http = http\nself.project = project\nself.resources = resources\nself.resource_type = None",
"http = context['http']\ncompute_utils.UpdateContextEndpointEntries(context, http)\nbatch_url = context['batch-url']\ncompute = context['compute']\nresources = con... | <|body_start_0|>
self.batch_url = batch_url
self.compute = compute
self.http = http
self.project = project
self.resources = resources
self.resource_type = None
<|end_body_0|>
<|body_start_1|>
http = context['http']
compute_utils.UpdateContextEndpointEntri... | Helper that uses compute component logic to build GceConfiguration. | ConfigurationHelper | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationHelper:
"""Helper that uses compute component logic to build GceConfiguration."""
def __init__(self, batch_url, compute, http, project, resources):
"""Sets fields expected by ScopePrompter."""
<|body_0|>
def FromContext(cls, context):
"""Updates requ... | stack_v2_sparse_classes_10k_train_006062 | 3,978 | permissive | [
{
"docstring": "Sets fields expected by ScopePrompter.",
"name": "__init__",
"signature": "def __init__(self, batch_url, compute, http, project, resources)"
},
{
"docstring": "Updates required global state and constructs ConfigurationHelper.",
"name": "FromContext",
"signature": "def Fro... | 5 | null | Implement the Python class `ConfigurationHelper` described below.
Class description:
Helper that uses compute component logic to build GceConfiguration.
Method signatures and docstrings:
- def __init__(self, batch_url, compute, http, project, resources): Sets fields expected by ScopePrompter.
- def FromContext(cls, c... | Implement the Python class `ConfigurationHelper` described below.
Class description:
Helper that uses compute component logic to build GceConfiguration.
Method signatures and docstrings:
- def __init__(self, batch_url, compute, http, project, resources): Sets fields expected by ScopePrompter.
- def FromContext(cls, c... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class ConfigurationHelper:
"""Helper that uses compute component logic to build GceConfiguration."""
def __init__(self, batch_url, compute, http, project, resources):
"""Sets fields expected by ScopePrompter."""
<|body_0|>
def FromContext(cls, context):
"""Updates requ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConfigurationHelper:
"""Helper that uses compute component logic to build GceConfiguration."""
def __init__(self, batch_url, compute, http, project, resources):
"""Sets fields expected by ScopePrompter."""
self.batch_url = batch_url
self.compute = compute
self.http = http
... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/dataproc/lib/compute_helpers.py | twistedpair/google-cloud-sdk | train | 58 |
852592373ddb19250e93c83ea058f0521ed99b8c | [
"for idx in range(len(nums)):\n high = min(len(nums), idx + k + 1)\n demoset = set(nums[idx + 1:high])\n if nums[idx] in demoset:\n return True\nreturn False",
"\"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\nnumDict = {}\nfor i in range(len(nums)... | <|body_start_0|>
for idx in range(len(nums)):
high = min(len(nums), idx + k + 1)
demoset = set(nums[idx + 1:high])
if nums[idx] in demoset:
return True
return False
<|end_body_0|>
<|body_start_1|>
"""
:type nums: List[int]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_10k_train_006063 | 843 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate2",
"signature": "def contai... | 2 | stack_v2_sparse_classes_30k_train_005779 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rty... | 829f918a0d4d94da5fd3004768421974fbe056e7 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
for idx in range(len(nums)):
high = min(len(nums), idx + k + 1)
demoset = set(nums[idx + 1:high])
if nums[idx] in demoset:
return True... | the_stack_v2_python_sparse | leetcode/easy/easy 201-400/219_存在重复元素 II.py | Weikoi/OJ_Python | train | 0 | |
76ae676219453fdcbc8218dbc8a0ee6f98e8eee0 | [
"if not isinstance(data, np.ndarray):\n raise TypeError('data must be a 2D numpy.ndarray')\nelif len(data.shape) is not 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nelif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nelse:\n X = data.T\n d = data.shape[0]... | <|body_start_0|>
if not isinstance(data, np.ndarray):
raise TypeError('data must be a 2D numpy.ndarray')
elif len(data.shape) is not 2:
raise TypeError('data must be a 2D numpy.ndarray')
elif data.shape[1] < 2:
raise ValueError('data must contain multiple data... | Class Multivariate Normal distribution | MultiNormal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""Class Multivariate Normal distribution"""
def __init__(self, data):
"""Constructor"""
<|body_0|>
def pdf(self, x):
"""Function calculate PDF Probability Density Function x is a numpy.ndarray of shape (d, 1) containing the data point whose PDF shou... | stack_v2_sparse_classes_10k_train_006064 | 2,625 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Function calculate PDF Probability Density Function x is a numpy.ndarray of shape (d, 1) containing the data point whose PDF should be calculated d is the number of dimensions of the Mult... | 2 | null | Implement the Python class `MultiNormal` described below.
Class description:
Class Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): Constructor
- def pdf(self, x): Function calculate PDF Probability Density Function x is a numpy.ndarray of shape (d, 1) containing the data... | Implement the Python class `MultiNormal` described below.
Class description:
Class Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): Constructor
- def pdf(self, x): Function calculate PDF Probability Density Function x is a numpy.ndarray of shape (d, 1) containing the data... | eaf23423ec0f412f103f5931d6610fdd67bcc5be | <|skeleton|>
class MultiNormal:
"""Class Multivariate Normal distribution"""
def __init__(self, data):
"""Constructor"""
<|body_0|>
def pdf(self, x):
"""Function calculate PDF Probability Density Function x is a numpy.ndarray of shape (d, 1) containing the data point whose PDF shou... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""Class Multivariate Normal distribution"""
def __init__(self, data):
"""Constructor"""
if not isinstance(data, np.ndarray):
raise TypeError('data must be a 2D numpy.ndarray')
elif len(data.shape) is not 2:
raise TypeError('data must be a 2D n... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | ledbagholberton/holbertonschool-machine_learning | train | 1 |
24946af70bd19f4df06148cc31a255e1e471b47b | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_route_map_entry_by_search(self.search)\n objects = obj_model['query_set']\n only_main_property = False\nelse:\n ids = kwargs.get('obj_ids').split(';')\n objects = facade.get_route_map_entry_by_ids(ids)\n only_main_property = True\n obj_mod... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_entry_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
else:
ids = kwargs.get('obj_ids').split(';')
objects = facade.get_route_map... | RouteMapView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouteMapView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMapEntry."""
<|body_1|>
def put(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_10k_train_006065 | 9,414 | permissive | [
{
"docstring": "Returns a list of RouteMapEntries by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Create new RouteMapEntry.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Upda... | 4 | null | Implement the Python class `RouteMapView` described below.
Class description:
Implement the RouteMapView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMapEntries by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMapEntry.
- def put... | Implement the Python class `RouteMapView` described below.
Class description:
Implement the RouteMapView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMapEntries by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMapEntry.
- def put... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class RouteMapView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMapEntry."""
<|body_1|>
def put(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RouteMapView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_entry_by_search(self.search)
objects = obj_model['query_set']
only_main_property = F... | the_stack_v2_python_sparse | networkapi/api_route_map/v4/views.py | globocom/GloboNetworkAPI | train | 86 | |
c389b1c27dacbd2abfa06685f1fece2cacede9be | [
"super().__init__(data, device)\nself._sensor_type = sensor_type\nself._attr_name = f'{device.name} {SENSOR_TYPES[sensor_type][0]}'\nself._attr_device_class = SENSOR_TYPES[self._sensor_type][1]\nself._attr_unique_id = f'{device.device_uuid}-{sensor_type}'\nif self._sensor_type == CONST.TEMP_STATUS_KEY:\n self._a... | <|body_start_0|>
super().__init__(data, device)
self._sensor_type = sensor_type
self._attr_name = f'{device.name} {SENSOR_TYPES[sensor_type][0]}'
self._attr_device_class = SENSOR_TYPES[self._sensor_type][1]
self._attr_unique_id = f'{device.device_uuid}-{sensor_type}'
if s... | A sensor implementation for Abode devices. | AbodeSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data, device, sensor_type):
"""Initialize a sensor for an Abode device."""
<|body_0|>
def state(self):
"""Return the state of the sensor."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_006066 | 2,256 | permissive | [
{
"docstring": "Initialize a sensor for an Abode device.",
"name": "__init__",
"signature": "def __init__(self, data, device, sensor_type)"
},
{
"docstring": "Return the state of the sensor.",
"name": "state",
"signature": "def state(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002512 | Implement the Python class `AbodeSensor` described below.
Class description:
A sensor implementation for Abode devices.
Method signatures and docstrings:
- def __init__(self, data, device, sensor_type): Initialize a sensor for an Abode device.
- def state(self): Return the state of the sensor. | Implement the Python class `AbodeSensor` described below.
Class description:
A sensor implementation for Abode devices.
Method signatures and docstrings:
- def __init__(self, data, device, sensor_type): Initialize a sensor for an Abode device.
- def state(self): Return the state of the sensor.
<|skeleton|>
class Abo... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data, device, sensor_type):
"""Initialize a sensor for an Abode device."""
<|body_0|>
def state(self):
"""Return the state of the sensor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data, device, sensor_type):
"""Initialize a sensor for an Abode device."""
super().__init__(data, device)
self._sensor_type = sensor_type
self._attr_name = f'{device.name} {SENSOR_TYPES[sensor... | the_stack_v2_python_sparse | homeassistant/components/abode/sensor.py | BenWoodford/home-assistant | train | 11 |
b3982c3bd84d5ac12aee017be09a5378b5867719 | [
"\"\"\"\n In this problem, one should compare the left and right subtree of a root, but only got one root. use root.left and root.right will make the recursive process difficult, so we can compare root and root.\n \"\"\"\nif not root:\n return True\nreturn self.isMirror(root.left, root.right)",
... | <|body_start_0|>
"""
In this problem, one should compare the left and right subtree of a root, but only got one root. use root.left and root.right will make the recursive process difficult, so we can compare root and root.
"""
if not root:
return True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isMirror(self, left, right):
""":type tN1, tN2: TreeNode : rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
In this problem,... | stack_v2_sparse_classes_10k_train_006067 | 1,103 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
},
{
"docstring": ":type tN1, tN2: TreeNode : rtype: bool",
"name": "isMirror",
"signature": "def isMirror(self, left, right)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isMirror(self, left, right): :type tN1, tN2: TreeNode : rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isMirror(self, left, right): :type tN1, tN2: TreeNode : rtype: bool
<|skeleton|>
class Solution:
def is... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isMirror(self, left, right):
""":type tN1, tN2: TreeNode : rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
"""
In this problem, one should compare the left and right subtree of a root, but only got one root. use root.left and root.right will make the recursive process difficult, so we can compare root an... | the_stack_v2_python_sparse | Python/SymmetricTree.py | here0009/LeetCode | train | 1 | |
e06972728f124a062bb6bfa5cc9e3e229bb5d43a | [
"if coins == [] or amount == 0:\n return 0\ncoins = sorted(coins)\ndp = [-1 for i in range(amount + 1)]\nfor i in range(coins[0], amount + 1):\n if i in coins:\n dp[i] = 1\n else:\n for k in range(1, i // 2 + 1):\n print(k, i)\n if dp[i - k] != -1 and dp[k] != -1:\n ... | <|body_start_0|>
if coins == [] or amount == 0:
return 0
coins = sorted(coins)
dp = [-1 for i in range(amount + 1)]
for i in range(coins[0], amount + 1):
if i in coins:
dp[i] = 1
else:
for k in range(1, i // 2 + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange_1(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int 572ms bfs"""
<|body_1|>
def coinChange_2(s... | stack_v2_sparse_classes_10k_train_006068 | 3,462 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int 572ms bfs",
"name": "coinChange_1",
"signature": "def coinChange_1(self,... | 4 | stack_v2_sparse_classes_30k_train_003962 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange_1(self, coins, amount): :type coins: List[int] :type amount: int :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange_1(self, coins, amount): :type coins: List[int] :type amount: int :rtype... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange_1(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int 572ms bfs"""
<|body_1|>
def coinChange_2(s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
if coins == [] or amount == 0:
return 0
coins = sorted(coins)
dp = [-1 for i in range(amount + 1)]
for i in range(coins[0], amount + 1):
if ... | the_stack_v2_python_sparse | CoinChange_MID_322.py | 953250587/leetcode-python | train | 2 | |
f4428aebd34569c6ad3347bcfc05b7b4d4df778f | [
"self.head = None\nself.tail = None\nreturn",
"currentNode = self.head\nwhile currentNode is not None:\n print(currentNode.getData())\n currentNode = currentNode.getNext()\nreturn",
"if isinstance(item, ListNode):\n if self.head is None:\n self.head = item\n else:\n tail = self.tail\n ... | <|body_start_0|>
self.head = None
self.tail = None
return
<|end_body_0|>
<|body_start_1|>
currentNode = self.head
while currentNode is not None:
print(currentNode.getData())
currentNode = currentNode.getNext()
return
<|end_body_1|>
<|body_start_2... | SingleLinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleLinkedList:
def __init__(self):
"""constructor to initiate this object"""
<|body_0|>
def outputList(self):
"""outputs the list (the value of the node, actually)"""
<|body_1|>
def addListitem(self, item):
"""add an item at the end of the lis... | stack_v2_sparse_classes_10k_train_006069 | 1,208 | no_license | [
{
"docstring": "constructor to initiate this object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "outputs the list (the value of the node, actually)",
"name": "outputList",
"signature": "def outputList(self)"
},
{
"docstring": "add an item at the end ... | 4 | stack_v2_sparse_classes_30k_train_004545 | Implement the Python class `SingleLinkedList` described below.
Class description:
Implement the SingleLinkedList class.
Method signatures and docstrings:
- def __init__(self): constructor to initiate this object
- def outputList(self): outputs the list (the value of the node, actually)
- def addListitem(self, item): ... | Implement the Python class `SingleLinkedList` described below.
Class description:
Implement the SingleLinkedList class.
Method signatures and docstrings:
- def __init__(self): constructor to initiate this object
- def outputList(self): outputs the list (the value of the node, actually)
- def addListitem(self, item): ... | f4c08170bef3b841f3dac7a1a05c741ccfe8cfb9 | <|skeleton|>
class SingleLinkedList:
def __init__(self):
"""constructor to initiate this object"""
<|body_0|>
def outputList(self):
"""outputs the list (the value of the node, actually)"""
<|body_1|>
def addListitem(self, item):
"""add an item at the end of the lis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SingleLinkedList:
def __init__(self):
"""constructor to initiate this object"""
self.head = None
self.tail = None
return
def outputList(self):
"""outputs the list (the value of the node, actually)"""
currentNode = self.head
while currentNode is not ... | the_stack_v2_python_sparse | listen/einfacheliste.py | hofmannedv/python-kurs-gfn | train | 1 | |
6b914d2d05aa8965de3cb9676c420d51a2758717 | [
"super().__init__(*args, **kwargs)\nself.full_model_name = full_model_name\nself.app_name, self.related_model_name = full_model_name.split('.')\nself.label = full_model_name\nself.known_models = RegisteredModels()",
"if isinstance(value, Model):\n return value\nif isinstance(value, int):\n model_class = sel... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.full_model_name = full_model_name
self.app_name, self.related_model_name = full_model_name.split('.')
self.label = full_model_name
self.known_models = RegisteredModels()
<|end_body_0|>
<|body_start_1|>
if isinstance... | Field representing a model. ForeignKey relation is modeled with this field. | ModelField | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelField:
"""Field representing a model. ForeignKey relation is modeled with this field."""
def __init__(self, full_model_name: str, *args, **kwargs):
"""Initialize."""
<|body_0|>
def to_python(self, value):
"""Return the python object representing the field.""... | stack_v2_sparse_classes_10k_train_006070 | 19,131 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, full_model_name: str, *args, **kwargs)"
},
{
"docstring": "Return the python object representing the field.",
"name": "to_python",
"signature": "def to_python(self, value)"
},
{
"docstring": "Conve... | 3 | stack_v2_sparse_classes_30k_train_004580 | Implement the Python class `ModelField` described below.
Class description:
Field representing a model. ForeignKey relation is modeled with this field.
Method signatures and docstrings:
- def __init__(self, full_model_name: str, *args, **kwargs): Initialize.
- def to_python(self, value): Return the python object repr... | Implement the Python class `ModelField` described below.
Class description:
Field representing a model. ForeignKey relation is modeled with this field.
Method signatures and docstrings:
- def __init__(self, full_model_name: str, *args, **kwargs): Initialize.
- def to_python(self, value): Return the python object repr... | 25c0c45235ef37beb45c1af4c917fbbae6282016 | <|skeleton|>
class ModelField:
"""Field representing a model. ForeignKey relation is modeled with this field."""
def __init__(self, full_model_name: str, *args, **kwargs):
"""Initialize."""
<|body_0|>
def to_python(self, value):
"""Return the python object representing the field.""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelField:
"""Field representing a model. ForeignKey relation is modeled with this field."""
def __init__(self, full_model_name: str, *args, **kwargs):
"""Initialize."""
super().__init__(*args, **kwargs)
self.full_model_name = full_model_name
self.app_name, self.related_m... | the_stack_v2_python_sparse | resolwe/process/models.py | genialis/resolwe | train | 35 |
4b277afb0a635aed4d246f16c0b95ad6c8ccd3e1 | [
"for index, value in enumerate(sequence):\n print(index, value)\n if destination_value == value:\n return index",
"sequence_length = len(sequence)\nif not sequence_length:\n return -1\nindex = sequence_length - 1\nif sequence[index] == destination_value:\n return index\nreturn self.linearSearch... | <|body_start_0|>
for index, value in enumerate(sequence):
print(index, value)
if destination_value == value:
return index
<|end_body_0|>
<|body_start_1|>
sequence_length = len(sequence)
if not sequence_length:
return -1
index = sequenc... | 传统查找方法总结 | TraditionalSearch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraditionalSearch:
"""传统查找方法总结"""
def linearSearchTraditional(self, destination_value, sequence):
"""传统线行查找"""
<|body_0|>
def linearSearchRecursion(self, destination_value, sequence):
"""递归式线性查找"""
<|body_1|>
def binarySearchRecursion(self, value, so... | stack_v2_sparse_classes_10k_train_006071 | 2,239 | permissive | [
{
"docstring": "传统线行查找",
"name": "linearSearchTraditional",
"signature": "def linearSearchTraditional(self, destination_value, sequence)"
},
{
"docstring": "递归式线性查找",
"name": "linearSearchRecursion",
"signature": "def linearSearchRecursion(self, destination_value, sequence)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_003032 | Implement the Python class `TraditionalSearch` described below.
Class description:
传统查找方法总结
Method signatures and docstrings:
- def linearSearchTraditional(self, destination_value, sequence): 传统线行查找
- def linearSearchRecursion(self, destination_value, sequence): 递归式线性查找
- def binarySearchRecursion(self, value, sorted... | Implement the Python class `TraditionalSearch` described below.
Class description:
传统查找方法总结
Method signatures and docstrings:
- def linearSearchTraditional(self, destination_value, sequence): 传统线行查找
- def linearSearchRecursion(self, destination_value, sequence): 递归式线性查找
- def binarySearchRecursion(self, value, sorted... | ec385235f56b2ca42974f2f6067f708ab4f693fc | <|skeleton|>
class TraditionalSearch:
"""传统查找方法总结"""
def linearSearchTraditional(self, destination_value, sequence):
"""传统线行查找"""
<|body_0|>
def linearSearchRecursion(self, destination_value, sequence):
"""递归式线性查找"""
<|body_1|>
def binarySearchRecursion(self, value, so... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TraditionalSearch:
"""传统查找方法总结"""
def linearSearchTraditional(self, destination_value, sequence):
"""传统线行查找"""
for index, value in enumerate(sequence):
print(index, value)
if destination_value == value:
return index
def linearSearchRecursion(se... | the_stack_v2_python_sparse | DataStructure/12_线性查找与二分查找.py | xiaopingzhong/AlgorithmAndDataStructure | train | 0 |
46e1b6040e5c41d9cd5760ec9902fce4a5acda80 | [
"if not self.username:\n raise RuntimeError('Please supply a valid user name.')\nif self.use_tsk:\n self.path_type = rdfvalue.PathSpec.PathType.TSK\nelse:\n self.path_type = rdfvalue.PathSpec.PathType.OS\nclient = aff4.FACTORY.Open(self.client_id, token=self.token)\nself.user_pb = flow_utils.GetUserInfo(cl... | <|body_start_0|>
if not self.username:
raise RuntimeError('Please supply a valid user name.')
if self.use_tsk:
self.path_type = rdfvalue.PathSpec.PathType.TSK
else:
self.path_type = rdfvalue.PathSpec.PathType.OS
client = aff4.FACTORY.Open(self.client_i... | Do the initial work for a user investigation. | WinUserActivityInvestigation | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WinUserActivityInvestigation:
"""Do the initial work for a user investigation."""
def Start(self):
"""Validate parameters and do the actual work."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for each flow finishing."""
... | stack_v2_sparse_classes_10k_train_006072 | 10,734 | permissive | [
{
"docstring": "Validate parameters and do the actual work.",
"name": "Start",
"signature": "def Start(self)"
},
{
"docstring": "Complete anything we need to do for each flow finishing.",
"name": "FinishFlow",
"signature": "def FinishFlow(self, responses)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001464 | Implement the Python class `WinUserActivityInvestigation` described below.
Class description:
Do the initial work for a user investigation.
Method signatures and docstrings:
- def Start(self): Validate parameters and do the actual work.
- def FinishFlow(self, responses): Complete anything we need to do for each flow ... | Implement the Python class `WinUserActivityInvestigation` described below.
Class description:
Do the initial work for a user investigation.
Method signatures and docstrings:
- def Start(self): Validate parameters and do the actual work.
- def FinishFlow(self, responses): Complete anything we need to do for each flow ... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class WinUserActivityInvestigation:
"""Do the initial work for a user investigation."""
def Start(self):
"""Validate parameters and do the actual work."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for each flow finishing."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WinUserActivityInvestigation:
"""Do the initial work for a user investigation."""
def Start(self):
"""Validate parameters and do the actual work."""
if not self.username:
raise RuntimeError('Please supply a valid user name.')
if self.use_tsk:
self.path_type... | the_stack_v2_python_sparse | lib/flows/general/automation.py | defaultnamehere/grr | train | 3 |
cbed140c4cafb6636d33109c7fe2e76fa4895f2c | [
"if not meshRelax:\n return\nif not mc.objExists(meshRelax):\n raise UserInputError('IkaMeshRelax ' + meshRelax + ' does not exists! No influence data recorded!!')\nobjType = mc.objectType(meshRelax)\nif objType != 'ikaMeshRelax':\n raise UserInputError('Object ' + meshRelax + ' is not a vaild ikaMeshRelax... | <|body_start_0|>
if not meshRelax:
return
if not mc.objExists(meshRelax):
raise UserInputError('IkaMeshRelax ' + meshRelax + ' does not exists! No influence data recorded!!')
objType = mc.objectType(meshRelax)
if objType != 'ikaMeshRelax':
raise UserIn... | IkaMeshRelaxData class object. | IkaMeshRelaxData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IkaMeshRelaxData:
"""IkaMeshRelaxData class object."""
def __init__(self, meshRelax=''):
"""IkaMeshRelaxData class initilizer."""
<|body_0|>
def rebuild(self):
"""Rebuild surfaceSkin deformer from saved deformer data"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_006073 | 1,916 | no_license | [
{
"docstring": "IkaMeshRelaxData class initilizer.",
"name": "__init__",
"signature": "def __init__(self, meshRelax='')"
},
{
"docstring": "Rebuild surfaceSkin deformer from saved deformer data",
"name": "rebuild",
"signature": "def rebuild(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003952 | Implement the Python class `IkaMeshRelaxData` described below.
Class description:
IkaMeshRelaxData class object.
Method signatures and docstrings:
- def __init__(self, meshRelax=''): IkaMeshRelaxData class initilizer.
- def rebuild(self): Rebuild surfaceSkin deformer from saved deformer data | Implement the Python class `IkaMeshRelaxData` described below.
Class description:
IkaMeshRelaxData class object.
Method signatures and docstrings:
- def __init__(self, meshRelax=''): IkaMeshRelaxData class initilizer.
- def rebuild(self): Rebuild surfaceSkin deformer from saved deformer data
<|skeleton|>
class IkaMe... | 16337badb6d1b4266f31008ceb17cfd70fec3623 | <|skeleton|>
class IkaMeshRelaxData:
"""IkaMeshRelaxData class object."""
def __init__(self, meshRelax=''):
"""IkaMeshRelaxData class initilizer."""
<|body_0|>
def rebuild(self):
"""Rebuild surfaceSkin deformer from saved deformer data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IkaMeshRelaxData:
"""IkaMeshRelaxData class object."""
def __init__(self, meshRelax=''):
"""IkaMeshRelaxData class initilizer."""
if not meshRelax:
return
if not mc.objExists(meshRelax):
raise UserInputError('IkaMeshRelax ' + meshRelax + ' does not exists! ... | the_stack_v2_python_sparse | glTools-master/data/ikaMeshRelaxData.py | moChen0607/pubTool | train | 0 |
7b8536b5c1cc104cbaa84c457546908475149060 | [
"self.cap = capacity\nself.dic = {}\nself.cacahe = []",
"if key in self.dic:\n self.set(key, self.dic[key])\n return self.dic[key]\nelse:\n return -1",
"if key in self.dic:\n self.cacahe.remove(key)\nelif len(self.cacahe) >= self.cap:\n self.dic.pop(self.cacahe.pop(-1))\nself.dic[key] = value\nse... | <|body_start_0|>
self.cap = capacity
self.dic = {}
self.cacahe = []
<|end_body_0|>
<|body_start_1|>
if key in self.dic:
self.set(key, self.dic[key])
return self.dic[key]
else:
return -1
<|end_body_1|>
<|body_start_2|>
if key in self.d... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_006074 | 1,350 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_train_004567 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | cb70fc9ddc410923cc1dae6015a821d4e52c1c14 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.dic = {}
self.cacahe = []
def get(self, key):
""":rtype: int"""
if key in self.dic:
self.set(key, self.dic[key])
return self.dic[key]
... | the_stack_v2_python_sparse | 146LRU Cache.py | zingzheng/LeetCode_py | train | 0 | |
c793207626c423bbf2cc159ffc8d8a5e88c08c86 | [
"output = []\nfor rate in rates:\n _rate, created = Rate.objects.get_or_create(base_currency=base_currency, currency=rate.get('currency'), value_date=rate.get('date'), user=None, key=None)\n _rate.value = rate.get('value')\n _rate.save()\n output.append(_rate)\nreturn output",
"service_name = rate_ser... | <|body_start_0|>
output = []
for rate in rates:
_rate, created = Rate.objects.get_or_create(base_currency=base_currency, currency=rate.get('currency'), value_date=rate.get('date'), user=None, key=None)
_rate.value = rate.get('value')
_rate.save()
output.ap... | Manager for Rate model | RateManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateManager:
"""Manager for Rate model"""
def __sync_rates__(rates: [], base_currency: str):
"""Sync rates to the database :param rates: array of dict of rates from service :param base_currency: base currency to fetch"""
<|body_0|>
def fetch_rates(self, base_currency: st... | stack_v2_sparse_classes_10k_train_006075 | 16,208 | permissive | [
{
"docstring": "Sync rates to the database :param rates: array of dict of rates from service :param base_currency: base currency to fetch",
"name": "__sync_rates__",
"signature": "def __sync_rates__(rates: [], base_currency: str)"
},
{
"docstring": "Get rates from a service for a base currency a... | 5 | stack_v2_sparse_classes_30k_val_000301 | Implement the Python class `RateManager` described below.
Class description:
Manager for Rate model
Method signatures and docstrings:
- def __sync_rates__(rates: [], base_currency: str): Sync rates to the database :param rates: array of dict of rates from service :param base_currency: base currency to fetch
- def fet... | Implement the Python class `RateManager` described below.
Class description:
Manager for Rate model
Method signatures and docstrings:
- def __sync_rates__(rates: [], base_currency: str): Sync rates to the database :param rates: array of dict of rates from service :param base_currency: base currency to fetch
- def fet... | 23cc075377d47ac631634cd71fd0e7d6b0a57bad | <|skeleton|>
class RateManager:
"""Manager for Rate model"""
def __sync_rates__(rates: [], base_currency: str):
"""Sync rates to the database :param rates: array of dict of rates from service :param base_currency: base currency to fetch"""
<|body_0|>
def fetch_rates(self, base_currency: st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RateManager:
"""Manager for Rate model"""
def __sync_rates__(rates: [], base_currency: str):
"""Sync rates to the database :param rates: array of dict of rates from service :param base_currency: base currency to fetch"""
output = []
for rate in rates:
_rate, created = ... | the_stack_v2_python_sparse | src/geocurrency/rates/models.py | fmeurou/geocurrency | train | 5 |
bb52941cf047374e96790e03d6d0108ab0dc7e61 | [
"wf_service = netsvc.LocalService('workflow')\nsuper(stock_picking, self).action_done(cr, uid, ids, context=context)\npicking_obj = self.pool.get('stock.picking')\nfor picking_record in self.browse(cr, uid, ids):\n if picking_record.type == 'in':\n if picking_record.purchase_id:\n if picking_re... | <|body_start_0|>
wf_service = netsvc.LocalService('workflow')
super(stock_picking, self).action_done(cr, uid, ids, context=context)
picking_obj = self.pool.get('stock.picking')
for picking_record in self.browse(cr, uid, ids):
if picking_record.type == 'in':
if... | stock_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_picking:
def action_done(self, cr, uid, ids, context=None):
"""Checks if Goods avaiable in stock after Purchases Procedure done @return: True"""
<|body_0|>
def goods_recieved(self, cr, uid, ids, context=None):
"""Change State To Picking confirmed"""
<|b... | stack_v2_sparse_classes_10k_train_006076 | 3,934 | no_license | [
{
"docstring": "Checks if Goods avaiable in stock after Purchases Procedure done @return: True",
"name": "action_done",
"signature": "def action_done(self, cr, uid, ids, context=None)"
},
{
"docstring": "Change State To Picking confirmed",
"name": "goods_recieved",
"signature": "def good... | 2 | null | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def action_done(self, cr, uid, ids, context=None): Checks if Goods avaiable in stock after Purchases Procedure done @return: True
- def goods_recieved(self, cr, uid, id... | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def action_done(self, cr, uid, ids, context=None): Checks if Goods avaiable in stock after Purchases Procedure done @return: True
- def goods_recieved(self, cr, uid, id... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_picking:
def action_done(self, cr, uid, ids, context=None):
"""Checks if Goods avaiable in stock after Purchases Procedure done @return: True"""
<|body_0|>
def goods_recieved(self, cr, uid, ids, context=None):
"""Change State To Picking confirmed"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class stock_picking:
def action_done(self, cr, uid, ids, context=None):
"""Checks if Goods avaiable in stock after Purchases Procedure done @return: True"""
wf_service = netsvc.LocalService('workflow')
super(stock_picking, self).action_done(cr, uid, ids, context=context)
picking_obj ... | the_stack_v2_python_sparse | v_7/Dongola/ntc/purchase_ntc/wizard/stock_partial_picking.py | musabahmed/baba | train | 0 | |
4d9c5447d5c09557490f1a6f16236ecb19bf0b34 | [
"self.expert = MagicMock(spec=Expert, userbase=MagicMock(id=1))\nself.expert.profiles.all.return_value = []\nself.content = MagicMock(spec=Content, id=1)\nself.push_admin_feeds = PushSuperAdminFeeds(self.expert.userbase)\nself.expert_profile_ids = [2]\nself.tag_ids = [1, 2, 3, 4]",
"result = self.push_admin_feeds... | <|body_start_0|>
self.expert = MagicMock(spec=Expert, userbase=MagicMock(id=1))
self.expert.profiles.all.return_value = []
self.content = MagicMock(spec=Content, id=1)
self.push_admin_feeds = PushSuperAdminFeeds(self.expert.userbase)
self.expert_profile_ids = [2]
self.tag... | Test case for PushFeeds | TestPushSuperAdminFeeds | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPushSuperAdminFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
<|body_0|>
def test_push_super_admin_feeds(self, mock_expert_publish_content):
"""test case for testing the mocked method is getting called with exact argumen... | stack_v2_sparse_classes_10k_train_006077 | 20,391 | no_license | [
{
"docstring": "SetUp method for test case",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test case for testing the mocked method is getting called with exact arguments",
"name": "test_push_super_admin_feeds",
"signature": "def test_push_super_admin_feeds(self, mock... | 2 | stack_v2_sparse_classes_30k_train_001668 | Implement the Python class `TestPushSuperAdminFeeds` described below.
Class description:
Test case for PushFeeds
Method signatures and docstrings:
- def setUp(self): SetUp method for test case
- def test_push_super_admin_feeds(self, mock_expert_publish_content): test case for testing the mocked method is getting call... | Implement the Python class `TestPushSuperAdminFeeds` described below.
Class description:
Test case for PushFeeds
Method signatures and docstrings:
- def setUp(self): SetUp method for test case
- def test_push_super_admin_feeds(self, mock_expert_publish_content): test case for testing the mocked method is getting call... | 248a7b406686c0c98e944319a6eca08485104f5d | <|skeleton|>
class TestPushSuperAdminFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
<|body_0|>
def test_push_super_admin_feeds(self, mock_expert_publish_content):
"""test case for testing the mocked method is getting called with exact argumen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestPushSuperAdminFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
self.expert = MagicMock(spec=Expert, userbase=MagicMock(id=1))
self.expert.profiles.all.return_value = []
self.content = MagicMock(spec=Content, id=1)
self.push... | the_stack_v2_python_sparse | common/feeds/tests.py | skshivammahajan/DRFChat | train | 0 |
8bf0b2c074e292878589c337b8c384268173e80f | [
"self.accounts: dict[str, RidwellAccount] = {}\nself.dashboard_url = ''\nself.user_id = ''\nsuper().__init__(hass, LOGGER, name=name, update_interval=UPDATE_INTERVAL)",
"data = {}\n\nasync def async_get_pickups(account: RidwellAccount) -> None:\n \"\"\"Get the latest pickups for an account.\"\"\"\n data[acc... | <|body_start_0|>
self.accounts: dict[str, RidwellAccount] = {}
self.dashboard_url = ''
self.user_id = ''
super().__init__(hass, LOGGER, name=name, update_interval=UPDATE_INTERVAL)
<|end_body_0|>
<|body_start_1|>
data = {}
async def async_get_pickups(account: RidwellAcco... | Class to manage fetching data from single endpoint. | RidwellDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RidwellDataUpdateCoordinator:
"""Class to manage fetching data from single endpoint."""
def __init__(self, hass: HomeAssistant, *, name: str) -> None:
"""Initialize."""
<|body_0|>
async def _async_update_data(self) -> dict[str, list[RidwellPickupEvent]]:
"""Fetch... | stack_v2_sparse_classes_10k_train_006078 | 3,010 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, name: str) -> None"
},
{
"docstring": "Fetch the latest data from the source.",
"name": "_async_update_data",
"signature": "async def _async_update_data(self) -> dict[str, list[Ridw... | 3 | stack_v2_sparse_classes_30k_val_000302 | Implement the Python class `RidwellDataUpdateCoordinator` described below.
Class description:
Class to manage fetching data from single endpoint.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, name: str) -> None: Initialize.
- async def _async_update_data(self) -> dict[str, list[Ridwel... | Implement the Python class `RidwellDataUpdateCoordinator` described below.
Class description:
Class to manage fetching data from single endpoint.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, name: str) -> None: Initialize.
- async def _async_update_data(self) -> dict[str, list[Ridwel... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RidwellDataUpdateCoordinator:
"""Class to manage fetching data from single endpoint."""
def __init__(self, hass: HomeAssistant, *, name: str) -> None:
"""Initialize."""
<|body_0|>
async def _async_update_data(self) -> dict[str, list[RidwellPickupEvent]]:
"""Fetch... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RidwellDataUpdateCoordinator:
"""Class to manage fetching data from single endpoint."""
def __init__(self, hass: HomeAssistant, *, name: str) -> None:
"""Initialize."""
self.accounts: dict[str, RidwellAccount] = {}
self.dashboard_url = ''
self.user_id = ''
super().... | the_stack_v2_python_sparse | homeassistant/components/ridwell/coordinator.py | home-assistant/core | train | 35,501 |
44a22f85050c3da60fd744e9ad5a8ba813d7c373 | [
"if not root:\n return\nq = [[root], []]\ni = 0\nj = (i + 1) % 2\nwhile q[0] or q[1]:\n while q[i]:\n node = q[i].pop(0)\n node.next = q[i][0] if q[i] else None\n if node.left:\n q[j].append(node.left)\n if node.right:\n q[j].append(node.right)\n i = j\n ... | <|body_start_0|>
if not root:
return
q = [[root], []]
i = 0
j = (i + 1) % 2
while q[0] or q[1]:
while q[i]:
node = q[i].pop(0)
node.next = q[i][0] if q[i] else None
if node.left:
q[j].appe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root):
"""05/06/2018 23:03"""
<|body_0|>
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
"""Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nodes"""
<|body_1|>
def connect(self, root: 'Option... | stack_v2_sparse_classes_10k_train_006079 | 3,713 | no_license | [
{
"docstring": "05/06/2018 23:03",
"name": "connect",
"signature": "def connect(self, root)"
},
{
"docstring": "Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nodes",
"name": "connect",
"signature": "def connect(self, root: 'Optional[Node]') -> 'Optional[Node]'"
},... | 3 | stack_v2_sparse_classes_30k_train_005575 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): 05/06/2018 23:03
- def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): 05/06/2018 23:03
- def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nod... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def connect(self, root):
"""05/06/2018 23:03"""
<|body_0|>
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
"""Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nodes"""
<|body_1|>
def connect(self, root: 'Option... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root):
"""05/06/2018 23:03"""
if not root:
return
q = [[root], []]
i = 0
j = (i + 1) % 2
while q[0] or q[1]:
while q[i]:
node = q[i].pop(0)
node.next = q[i][0] if q[i] else None
... | the_stack_v2_python_sparse | leetcode/solved/116_Populating_Next_Right_Pointers_in_Each_Node/solution.py | sungminoh/algorithms | train | 0 | |
82662211c6a35edc85fbd4c5cb5e1b9f699d9bff | [
"account = BaseAccount.get(accountId)\nif account:\n return self.make_response({'message': None, 'account': account.to_json(is_admin=True)})\nelse:\n return self.make_response({'message': 'Unable to find account', 'account': None}, HTTP.NOT_FOUND)",
"self.reqparse.add_argument('accountName', type=str, requi... | <|body_start_0|>
account = BaseAccount.get(accountId)
if account:
return self.make_response({'message': None, 'account': account.to_json(is_admin=True)})
else:
return self.make_response({'message': 'Unable to find account', 'account': None}, HTTP.NOT_FOUND)
<|end_body_0|>... | AccountDetail | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountDetail:
def get(self, accountId):
"""Fetch a single account"""
<|body_0|>
def put(self, accountId):
"""Update an account"""
<|body_1|>
def delete(self, accountId):
"""Delete an account"""
<|body_2|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_10k_train_006080 | 9,518 | permissive | [
{
"docstring": "Fetch a single account",
"name": "get",
"signature": "def get(self, accountId)"
},
{
"docstring": "Update an account",
"name": "put",
"signature": "def put(self, accountId)"
},
{
"docstring": "Delete an account",
"name": "delete",
"signature": "def delete(... | 3 | stack_v2_sparse_classes_30k_train_002257 | Implement the Python class `AccountDetail` described below.
Class description:
Implement the AccountDetail class.
Method signatures and docstrings:
- def get(self, accountId): Fetch a single account
- def put(self, accountId): Update an account
- def delete(self, accountId): Delete an account | Implement the Python class `AccountDetail` described below.
Class description:
Implement the AccountDetail class.
Method signatures and docstrings:
- def get(self, accountId): Fetch a single account
- def put(self, accountId): Update an account
- def delete(self, accountId): Delete an account
<|skeleton|>
class Acco... | 29a26c705381fdba3538b4efedb25b9e09b387ed | <|skeleton|>
class AccountDetail:
def get(self, accountId):
"""Fetch a single account"""
<|body_0|>
def put(self, accountId):
"""Update an account"""
<|body_1|>
def delete(self, accountId):
"""Delete an account"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccountDetail:
def get(self, accountId):
"""Fetch a single account"""
account = BaseAccount.get(accountId)
if account:
return self.make_response({'message': None, 'account': account.to_json(is_admin=True)})
else:
return self.make_response({'message': 'Un... | the_stack_v2_python_sparse | backend/cloud_inquisitor/plugins/views/accounts.py | RiotGames/cloud-inquisitor | train | 468 | |
f2d4f0df53102104b9e5a16cfe4d581144061d4a | [
"Gremlin().gremlin_post('graph.truncateBackend();', auth=auth)\nbody = {'group_name': 'gremlin', 'group_description': 'group can execute gremlin'}\ncode, res = Auth().post_groups(body, auth=auth)\nprint(code, res)\nbody = {'target_url': '%s:%d' % (_cfg.graph_host, _cfg.server_port), 'target_name': 'gremlin', 'targe... | <|body_start_0|>
Gremlin().gremlin_post('graph.truncateBackend();', auth=auth)
body = {'group_name': 'gremlin', 'group_description': 'group can execute gremlin'}
code, res = Auth().post_groups(body, auth=auth)
print(code, res)
body = {'target_url': '%s:%d' % (_cfg.graph_host, _cf... | 绑定资源和用户组 | Access | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Access:
"""绑定资源和用户组"""
def setUp(self):
"""测试case开始 :resurn:"""
<|body_0|>
def test_access_create(self):
"""创建 access"""
<|body_1|>
def test_access_delete(self):
"""删除 access"""
<|body_2|>
def test_access_list(self):
"""获... | stack_v2_sparse_classes_10k_train_006081 | 17,517 | no_license | [
{
"docstring": "测试case开始 :resurn:",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "创建 access",
"name": "test_access_create",
"signature": "def test_access_create(self)"
},
{
"docstring": "删除 access",
"name": "test_access_delete",
"signature": "def test... | 6 | stack_v2_sparse_classes_30k_train_005012 | Implement the Python class `Access` described below.
Class description:
绑定资源和用户组
Method signatures and docstrings:
- def setUp(self): 测试case开始 :resurn:
- def test_access_create(self): 创建 access
- def test_access_delete(self): 删除 access
- def test_access_list(self): 获取 access
- def test_access_one(self): 获取 access
- d... | Implement the Python class `Access` described below.
Class description:
绑定资源和用户组
Method signatures and docstrings:
- def setUp(self): 测试case开始 :resurn:
- def test_access_create(self): 创建 access
- def test_access_delete(self): 删除 access
- def test_access_list(self): 获取 access
- def test_access_one(self): 获取 access
- d... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class Access:
"""绑定资源和用户组"""
def setUp(self):
"""测试case开始 :resurn:"""
<|body_0|>
def test_access_create(self):
"""创建 access"""
<|body_1|>
def test_access_delete(self):
"""删除 access"""
<|body_2|>
def test_access_list(self):
"""获... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Access:
"""绑定资源和用户组"""
def setUp(self):
"""测试case开始 :resurn:"""
Gremlin().gremlin_post('graph.truncateBackend();', auth=auth)
body = {'group_name': 'gremlin', 'group_description': 'group can execute gremlin'}
code, res = Auth().post_groups(body, auth=auth)
print(co... | the_stack_v2_python_sparse | src/graph_function_test/server/auth/test_auth_api.py | hugegraph/hugegraph-test | train | 1 |
e57bd5b1c83a97d32364399c502c8686a7c0dce3 | [
"dict = Counter(nums)\nnum = len(nums) // 3\nres = []\nfor key in dict.keys():\n if dict[key] > num:\n res.append(key)\nreturn res",
"num1, num2 = (nums[0], nums[0])\ncount1 = count2 = 0\nres = []\nfor i in range(len(nums)):\n if nums[i] == num1:\n count1 += 1\n elif nums[i] == num2:\n ... | <|body_start_0|>
dict = Counter(nums)
num = len(nums) // 3
res = []
for key in dict.keys():
if dict[key] > num:
res.append(key)
return res
<|end_body_0|>
<|body_start_1|>
num1, num2 = (nums[0], nums[0])
count1 = count2 = 0
res ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def majorityElement2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dict = Counter(nums)
... | stack_v2_sparse_classes_10k_train_006082 | 1,537 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "majorityElement2",
"signature": "def majorityElement2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002995 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: List[int]
- def majorityElement2(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: List[int]
- def majorityElement2(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solution:... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def majorityElement2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: List[int]"""
dict = Counter(nums)
num = len(nums) // 3
res = []
for key in dict.keys():
if dict[key] > num:
res.append(key)
return res
def majorityElemen... | the_stack_v2_python_sparse | 229. Majority Element II/majority.py | Macielyoung/LeetCode | train | 1 | |
a46fd4c1c4ad085c0da0fbb28fbfbd97e7652ad4 | [
"found = False\nseedlist = self.get_Value()\nfor iseed in seedlist:\n found = iseed.startswith(name + ' ')\n if found:\n break\nreturn found",
"offset = jobproperties.RandomFlags.RandomSeedOffset.get_Value()\nnewseed = name + ' OFFSET ' + str(offset) + ' ' + str(seed1) + ' ' + str(seed2)\nlogRandomFl... | <|body_start_0|>
found = False
seedlist = self.get_Value()
for iseed in seedlist:
found = iseed.startswith(name + ' ')
if found:
break
return found
<|end_body_0|>
<|body_start_1|>
offset = jobproperties.RandomFlags.RandomSeedOffset.get_Val... | Random number stream seeds | RandomSeedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSeedList:
"""Random number stream seeds"""
def checkForExistingSeed(self, name):
"""Ensure that each stream is only initialized once"""
<|body_0|>
def addSeed(self, name, seed1, seed2):
"""Add seeds to internal seedlist. Seeds will be incremented by offset ... | stack_v2_sparse_classes_10k_train_006083 | 6,803 | no_license | [
{
"docstring": "Ensure that each stream is only initialized once",
"name": "checkForExistingSeed",
"signature": "def checkForExistingSeed(self, name)"
},
{
"docstring": "Add seeds to internal seedlist. Seeds will be incremented by offset values",
"name": "addSeed",
"signature": "def addS... | 5 | null | Implement the Python class `RandomSeedList` described below.
Class description:
Random number stream seeds
Method signatures and docstrings:
- def checkForExistingSeed(self, name): Ensure that each stream is only initialized once
- def addSeed(self, name, seed1, seed2): Add seeds to internal seedlist. Seeds will be i... | Implement the Python class `RandomSeedList` described below.
Class description:
Random number stream seeds
Method signatures and docstrings:
- def checkForExistingSeed(self, name): Ensure that each stream is only initialized once
- def addSeed(self, name, seed1, seed2): Add seeds to internal seedlist. Seeds will be i... | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | <|skeleton|>
class RandomSeedList:
"""Random number stream seeds"""
def checkForExistingSeed(self, name):
"""Ensure that each stream is only initialized once"""
<|body_0|>
def addSeed(self, name, seed1, seed2):
"""Add seeds to internal seedlist. Seeds will be incremented by offset ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomSeedList:
"""Random number stream seeds"""
def checkForExistingSeed(self, name):
"""Ensure that each stream is only initialized once"""
found = False
seedlist = self.get_Value()
for iseed in seedlist:
found = iseed.startswith(name + ' ')
if fo... | the_stack_v2_python_sparse | athena/Control/RngComps/python/RandomFlags.py | rushioda/PIXELVALID_athena | train | 1 |
6a55778884f01902814ae792c7eaf01e9a3206ec | [
"s1, s2 = ([], [])\nfor v1 in S:\n if v1 != '#':\n s1.append(v1)\n elif len(s1) != 0:\n s1.pop()\nfor v2 in T:\n if v2 != '#':\n s2.append(v2)\n elif len(s2) != 0:\n s2.pop()\nreturn ''.join(s1) == ''.join(s2)",
"def f(input_str):\n skip = 0\n for s in reversed(input_... | <|body_start_0|>
s1, s2 = ([], [])
for v1 in S:
if v1 != '#':
s1.append(v1)
elif len(s1) != 0:
s1.pop()
for v2 in T:
if v2 != '#':
s2.append(v2)
elif len(s2) != 0:
s2.pop()
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def backspaceCompare2(self, S, T):
""":type S: str :type T: str :rtype: bool"""
<|body_0|>
def backspaceCompare(self, S, T):
""":type S: str :type T: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s1, s2 = ([], [])
... | stack_v2_sparse_classes_10k_train_006084 | 954 | no_license | [
{
"docstring": ":type S: str :type T: str :rtype: bool",
"name": "backspaceCompare2",
"signature": "def backspaceCompare2(self, S, T)"
},
{
"docstring": ":type S: str :type T: str :rtype: bool",
"name": "backspaceCompare",
"signature": "def backspaceCompare(self, S, T)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003469 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backspaceCompare2(self, S, T): :type S: str :type T: str :rtype: bool
- def backspaceCompare(self, S, T): :type S: str :type T: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backspaceCompare2(self, S, T): :type S: str :type T: str :rtype: bool
- def backspaceCompare(self, S, T): :type S: str :type T: str :rtype: bool
<|skeleton|>
class Solution:... | 77ee7186a918cf865a038d9da5ae71e0aa6b64dc | <|skeleton|>
class Solution:
def backspaceCompare2(self, S, T):
""":type S: str :type T: str :rtype: bool"""
<|body_0|>
def backspaceCompare(self, S, T):
""":type S: str :type T: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def backspaceCompare2(self, S, T):
""":type S: str :type T: str :rtype: bool"""
s1, s2 = ([], [])
for v1 in S:
if v1 != '#':
s1.append(v1)
elif len(s1) != 0:
s1.pop()
for v2 in T:
if v2 != '#':
... | the_stack_v2_python_sparse | 874-backspace-string-compare/solution.py | GoingMyWay/LeetCode | train | 2 | |
c8d2327ba45c30d7f94e5db69adb649ece479fc4 | [
"test = test_method()\ninput_str = 'test'\nself.assertEqual(test.check_palindrome(input_str), False)",
"test = test_method()\ninput_str = 'racecar'\nself.assertEqual(test.check_palindrome(input_str), True)",
"test = test_method()\ninput_str = 'deed'\nself.assertEqual(test.check_palindrome(input_str), True)",
... | <|body_start_0|>
test = test_method()
input_str = 'test'
self.assertEqual(test.check_palindrome(input_str), False)
<|end_body_0|>
<|body_start_1|>
test = test_method()
input_str = 'racecar'
self.assertEqual(test.check_palindrome(input_str), True)
<|end_body_1|>
<|body_s... | Test_Cases_ArraySet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Cases_ArraySet:
def test_1(self):
"""Test to verify working check_palindrome method"""
<|body_0|>
def test_2(self):
"""Test to verify working check_palindrome method"""
<|body_1|>
def test_3(self):
"""Test to verify working check_palindrome ... | stack_v2_sparse_classes_10k_train_006085 | 1,775 | no_license | [
{
"docstring": "Test to verify working check_palindrome method",
"name": "test_1",
"signature": "def test_1(self)"
},
{
"docstring": "Test to verify working check_palindrome method",
"name": "test_2",
"signature": "def test_2(self)"
},
{
"docstring": "Test to verify working check... | 5 | stack_v2_sparse_classes_30k_train_004391 | Implement the Python class `Test_Cases_ArraySet` described below.
Class description:
Implement the Test_Cases_ArraySet class.
Method signatures and docstrings:
- def test_1(self): Test to verify working check_palindrome method
- def test_2(self): Test to verify working check_palindrome method
- def test_3(self): Test... | Implement the Python class `Test_Cases_ArraySet` described below.
Class description:
Implement the Test_Cases_ArraySet class.
Method signatures and docstrings:
- def test_1(self): Test to verify working check_palindrome method
- def test_2(self): Test to verify working check_palindrome method
- def test_3(self): Test... | 31b182184e00dda5efba515824a6a3551fbd5870 | <|skeleton|>
class Test_Cases_ArraySet:
def test_1(self):
"""Test to verify working check_palindrome method"""
<|body_0|>
def test_2(self):
"""Test to verify working check_palindrome method"""
<|body_1|>
def test_3(self):
"""Test to verify working check_palindrome ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_Cases_ArraySet:
def test_1(self):
"""Test to verify working check_palindrome method"""
test = test_method()
input_str = 'test'
self.assertEqual(test.check_palindrome(input_str), False)
def test_2(self):
"""Test to verify working check_palindrome method"""
... | the_stack_v2_python_sparse | Lab 5/Test Cases.py | bryanee23/Advanced-Python-Programming | train | 0 | |
fc0d6d958c34b9beeaf7f86695d049be16db6a3f | [
"if not is_all(eids):\n g = g.edge_subgraph(eids.long())\nn_nodes = g.number_of_nodes()\nn_edges = g.number_of_edges()\nscore_context = utils.to_dgl_context(score.device)\nif isinstance(g, DGLGraph):\n gidx = g._graph.get_immutable_gidx(score_context)\nelif isinstance(g, DGLHeteroGraph):\n assert g._graph.... | <|body_start_0|>
if not is_all(eids):
g = g.edge_subgraph(eids.long())
n_nodes = g.number_of_nodes()
n_edges = g.number_of_edges()
score_context = utils.to_dgl_context(score.device)
if isinstance(g, DGLGraph):
gidx = g._graph.get_immutable_gidx(score_conte... | Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in the context of softmax. :math:`\\mathca... | EdgeSoftmax | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeSoftmax:
"""Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in ... | stack_v2_sparse_classes_10k_train_006086 | 6,424 | permissive | [
{
"docstring": "Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of type dgl.NData score = score - score_max # edge_sub_dst, ret dgl.EData score_sum = score.dst_sum() # of type dgl.NData out = score / score_sum # edge_div_dst, ret dgl.EData return out.dat... | 2 | stack_v2_sparse_classes_30k_train_002140 | Implement the Python class `EdgeSoftmax` described below.
Class description:
Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j... | Implement the Python class `EdgeSoftmax` described below.
Class description:
Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j... | 170c2ed46fde29271246fe6600948b2864534ca3 | <|skeleton|>
class EdgeSoftmax:
"""Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EdgeSoftmax:
"""Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in the context o... | the_stack_v2_python_sparse | python/dgl/nn/pytorch/softmax.py | Menooker/dgl | train | 3 |
56960237bbfa972b0867a7ec72430d459a3bf0e7 | [
"f = partial(rk4, t0=t0, tf=tf)\nF = np.empty((3, 3))\na = np.zeros(6)\nh = 0.0005\na[0] = h\nF[:, 0] = (f(s + a) - f(s - a))[0:3] / 2 / h\na[0], a[1] = (0, h)\nF[:, 1] = (f(s + a) - f(s - a))[0:3] / 2 / h\na[1], a[2] = (0, h)\nF[:, 2] = (f(s + a) - f(s - a))[0:3] / 2 / h\nreturn F",
"self.s = s\nself.t0 = t0\nse... | <|body_start_0|>
f = partial(rk4, t0=t0, tf=tf)
F = np.empty((3, 3))
a = np.zeros(6)
h = 0.0005
a[0] = h
F[:, 0] = (f(s + a) - f(s - a))[0:3] / 2 / h
a[0], a[1] = (0, h)
F[:, 1] = (f(s + a) - f(s - a))[0:3] / 2 / h
a[1], a[2] = (0, h)
F[:, ... | Kalman Filter class wrapper. | KalmanFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KalmanFilter:
"""Kalman Filter class wrapper."""
def __Jacobian(s, t0, tf):
"""Numerically computes the Jacobian of rk4(s,t0,tf). Args: s(1x6 numpy array): the state vector at t0 [rx,ry,rz,vx,vy,vz] t0(float): the intial time tf(float): the final time Returns: 3x3 numpy matrix: the t... | stack_v2_sparse_classes_10k_train_006087 | 2,932 | permissive | [
{
"docstring": "Numerically computes the Jacobian of rk4(s,t0,tf). Args: s(1x6 numpy array): the state vector at t0 [rx,ry,rz,vx,vy,vz] t0(float): the intial time tf(float): the final time Returns: 3x3 numpy matrix: the topleft half of the Jacobian of rk4(s,t0,tf)",
"name": "__Jacobian",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_002077 | Implement the Python class `KalmanFilter` described below.
Class description:
Kalman Filter class wrapper.
Method signatures and docstrings:
- def __Jacobian(s, t0, tf): Numerically computes the Jacobian of rk4(s,t0,tf). Args: s(1x6 numpy array): the state vector at t0 [rx,ry,rz,vx,vy,vz] t0(float): the intial time t... | Implement the Python class `KalmanFilter` described below.
Class description:
Kalman Filter class wrapper.
Method signatures and docstrings:
- def __Jacobian(s, t0, tf): Numerically computes the Jacobian of rk4(s,t0,tf). Args: s(1x6 numpy array): the state vector at t0 [rx,ry,rz,vx,vy,vz] t0(float): the intial time t... | 1aec8919ba42978e73aab4eaefe407adeb6287e9 | <|skeleton|>
class KalmanFilter:
"""Kalman Filter class wrapper."""
def __Jacobian(s, t0, tf):
"""Numerically computes the Jacobian of rk4(s,t0,tf). Args: s(1x6 numpy array): the state vector at t0 [rx,ry,rz,vx,vy,vz] t0(float): the intial time tf(float): the final time Returns: 3x3 numpy matrix: the t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KalmanFilter:
"""Kalman Filter class wrapper."""
def __Jacobian(s, t0, tf):
"""Numerically computes the Jacobian of rk4(s,t0,tf). Args: s(1x6 numpy array): the state vector at t0 [rx,ry,rz,vx,vy,vz] t0(float): the intial time tf(float): the final time Returns: 3x3 numpy matrix: the topleft half o... | the_stack_v2_python_sparse | orbitdeterminator/propagation/kalman_filter.py | aerospaceresearch/orbitdeterminator | train | 179 |
33ef1fffcfec905b8f6068d382f5aeb94a0ad81a | [
"context = {}\ncotizacion = CotizacionOrdenDeTrabajo.objects.get(id=kwargs['pk'])\nif cotizacion.es_valida():\n info_repuestos_faltantes = self.verificar_inventario_sucursal(cotizacion)\n if info_repuestos_faltantes:\n self.cargar_mensajes_de_errores(info_repuestos_faltantes)\n return HttpRespon... | <|body_start_0|>
context = {}
cotizacion = CotizacionOrdenDeTrabajo.objects.get(id=kwargs['pk'])
if cotizacion.es_valida():
info_repuestos_faltantes = self.verificar_inventario_sucursal(cotizacion)
if info_repuestos_faltantes:
self.cargar_mensajes_de_error... | FacturaOrdenDeTrabajoCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacturaOrdenDeTrabajoCreateView:
def get(self, request, *args, **kwargs):
"""Documentacion get Permite generar la factura que es el paso siguiente a una cotización de una orden de trabajo, antes de generarse la factura, se comprueba si la cotización no esta vencida, luego se verifica que... | stack_v2_sparse_classes_10k_train_006088 | 7,599 | no_license | [
{
"docstring": "Documentacion get Permite generar la factura que es el paso siguiente a una cotización de una orden de trabajo, antes de generarse la factura, se comprueba si la cotización no esta vencida, luego se verifica que en inventario de la sucursal esten todos los repuestos necesarios para reparar el ve... | 4 | stack_v2_sparse_classes_30k_train_004795 | Implement the Python class `FacturaOrdenDeTrabajoCreateView` described below.
Class description:
Implement the FacturaOrdenDeTrabajoCreateView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Documentacion get Permite generar la factura que es el paso siguiente a una cotización de u... | Implement the Python class `FacturaOrdenDeTrabajoCreateView` described below.
Class description:
Implement the FacturaOrdenDeTrabajoCreateView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Documentacion get Permite generar la factura que es el paso siguiente a una cotización de u... | 3e74310b47c82d2dc420e6aaa743a2bc077fd635 | <|skeleton|>
class FacturaOrdenDeTrabajoCreateView:
def get(self, request, *args, **kwargs):
"""Documentacion get Permite generar la factura que es el paso siguiente a una cotización de una orden de trabajo, antes de generarse la factura, se comprueba si la cotización no esta vencida, luego se verifica que... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FacturaOrdenDeTrabajoCreateView:
def get(self, request, *args, **kwargs):
"""Documentacion get Permite generar la factura que es el paso siguiente a una cotización de una orden de trabajo, antes de generarse la factura, se comprueba si la cotización no esta vencida, luego se verifica que en inventario... | the_stack_v2_python_sparse | concesionario/apps/factura_orden_de_trabajo/forms.py | DonAurelio/SIGIA | train | 2 | |
11de44ea3610d5822b17c150fc766336eb61c8db | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingStaffMember()",
"from .booking_staff_member_base import BookingStaffMemberBase\nfrom .booking_staff_role import BookingStaffRole\nfrom .booking_work_hours import BookingWorkHours\nfrom .booking_staff_member_base import BookingSt... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BookingStaffMember()
<|end_body_0|>
<|body_start_1|>
from .booking_staff_member_base import BookingStaffMemberBase
from .booking_staff_role import BookingStaffRole
from .booking_... | Represents a staff member who provides services in a business. | BookingStaffMember | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookingStaffMember:
"""Represents a staff member who provides services in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: ... | stack_v2_sparse_classes_10k_train_006089 | 5,421 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: BookingStaffMember",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_test_000226 | Implement the Python class `BookingStaffMember` described below.
Class description:
Represents a staff member who provides services in a business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember: Creates a new instance of the appropri... | Implement the Python class `BookingStaffMember` described below.
Class description:
Represents a staff member who provides services in a business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember: Creates a new instance of the appropri... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BookingStaffMember:
"""Represents a staff member who provides services in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BookingStaffMember:
"""Represents a staff member who provides services in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse nod... | the_stack_v2_python_sparse | msgraph/generated/models/booking_staff_member.py | microsoftgraph/msgraph-sdk-python | train | 135 |
400d77524b00c0a9275ca1e13dde331d67c20c0d | [
"standard_hmm = HMM.DishonestCasino()\nmissing_hmm = DishonestCasino()\nobservations = [1, 2, 6, 6, 1, 2, 3, 4, 5, 6]\ndistances = [1] * (len(observations) - 1)\nstandard_distributions = standard_hmm.scaled_posterior_durbin(observations)\nmissing_distributions = missing_hmm.scaled_posterior_durbin(observations, dis... | <|body_start_0|>
standard_hmm = HMM.DishonestCasino()
missing_hmm = DishonestCasino()
observations = [1, 2, 6, 6, 1, 2, 3, 4, 5, 6]
distances = [1] * (len(observations) - 1)
standard_distributions = standard_hmm.scaled_posterior_durbin(observations)
missing_distributions ... | TestMissingHMM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMissingHMM:
def test_scaled_posterior_durbin_compatibility(self):
"""Test the missing observation model when no observation is missing."""
<|body_0|>
def test_scaled_posterior_durbin_general(self):
"""This test is not strict but just checks some inequalities."""
... | stack_v2_sparse_classes_10k_train_006090 | 8,288 | no_license | [
{
"docstring": "Test the missing observation model when no observation is missing.",
"name": "test_scaled_posterior_durbin_compatibility",
"signature": "def test_scaled_posterior_durbin_compatibility(self)"
},
{
"docstring": "This test is not strict but just checks some inequalities.",
"name... | 2 | null | Implement the Python class `TestMissingHMM` described below.
Class description:
Implement the TestMissingHMM class.
Method signatures and docstrings:
- def test_scaled_posterior_durbin_compatibility(self): Test the missing observation model when no observation is missing.
- def test_scaled_posterior_durbin_general(se... | Implement the Python class `TestMissingHMM` described below.
Class description:
Implement the TestMissingHMM class.
Method signatures and docstrings:
- def test_scaled_posterior_durbin_compatibility(self): Test the missing observation model when no observation is missing.
- def test_scaled_posterior_durbin_general(se... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class TestMissingHMM:
def test_scaled_posterior_durbin_compatibility(self):
"""Test the missing observation model when no observation is missing."""
<|body_0|>
def test_scaled_posterior_durbin_general(self):
"""This test is not strict but just checks some inequalities."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestMissingHMM:
def test_scaled_posterior_durbin_compatibility(self):
"""Test the missing observation model when no observation is missing."""
standard_hmm = HMM.DishonestCasino()
missing_hmm = DishonestCasino()
observations = [1, 2, 6, 6, 1, 2, 3, 4, 5, 6]
distances = ... | the_stack_v2_python_sparse | MissingHMM.py | argriffing/xgcode | train | 1 | |
4d0009d949d754816d61d31782da11b8b1344c53 | [
"@lru_cache(None)\ndef dfs(cur: int) -> int:\n res = 0\n for next in adjList[cur]:\n res = max(res, dfs(next))\n return res + 1\nreturn max((dfs(i) for i in range(len(adjList)))) - 1",
"n = len(adjList)\ndeg = [0] * n\nfor i in range(n):\n for j in adjList[i]:\n deg[j] += 1\nqueue = dequ... | <|body_start_0|>
@lru_cache(None)
def dfs(cur: int) -> int:
res = 0
for next in adjList[cur]:
res = max(res, dfs(next))
return res + 1
return max((dfs(i) for i in range(len(adjList)))) - 1
<|end_body_0|>
<|body_start_1|>
n = len(adjLis... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_0|>
def solve2(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
@lru_cache(None)
def dfs(cur... | stack_v2_sparse_classes_10k_train_006091 | 1,503 | no_license | [
{
"docstring": "DAG中最长路径只和当前位置有关",
"name": "solve",
"signature": "def solve(self, adjList: List[List[int]]) -> int"
},
{
"docstring": "DAG中最长路径只和当前位置有关",
"name": "solve2",
"signature": "def solve2(self, adjList: List[List[int]]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_001267 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
- def solve2(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
- def solve2(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
<|skeleton|>
class Solution:
def so... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_0|>
def solve2(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
@lru_cache(None)
def dfs(cur: int) -> int:
res = 0
for next in adjList[cur]:
res = max(res, dfs(next))
return res + 1
return max((dfs(i) for i ... | the_stack_v2_python_sparse | 7_graph/拓扑排序/DAG最长路/DAG中的最长路径.py | 981377660LMT/algorithm-study | train | 225 | |
d3d1b10a2cf47e6226b8b6226cb53fe0879bfcfc | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.attenuation_lambda = torch.nn.Parameter(torch.tensor(attenuation_lambda, requires_grad=True))\nself.linears = clones(nn.Linear(d_model, d_model), 5)\nself.message = None\nself.leaky_relu_slope = leaky_r... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.attenuation_lambda = torch.nn.Parameter(torch.tensor(attenuation_lambda, requires_grad=True))
self.linears = clones(nn.Linear(d_model, d_model), 5... | MultiHeadedAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, leaky_relu_slope=0.1, dropout=0.1, attenuation_lambda=0.1, distance_matrix_kernel='softmax'):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query_node, value_node, key_edge, adj_matrix, mask=No... | stack_v2_sparse_classes_10k_train_006092 | 18,947 | permissive | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, leaky_relu_slope=0.1, dropout=0.1, attenuation_lambda=0.1, distance_matrix_kernel='softmax')"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_000873 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, leaky_relu_slope=0.1, dropout=0.1, attenuation_lambda=0.1, distance_matrix_kernel='softmax'): Take in model size and number... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, leaky_relu_slope=0.1, dropout=0.1, attenuation_lambda=0.1, distance_matrix_kernel='softmax'): Take in model size and number... | 11a36843a83ddc93748c5437f5a21f2507b66c77 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, leaky_relu_slope=0.1, dropout=0.1, attenuation_lambda=0.1, distance_matrix_kernel='softmax'):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query_node, value_node, key_edge, adj_matrix, mask=No... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
def __init__(self, h, d_model, leaky_relu_slope=0.1, dropout=0.1, attenuation_lambda=0.1, distance_matrix_kernel='softmax'):
"""Take in model size and number of heads."""
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_mod... | the_stack_v2_python_sparse | MolRep/Models/sequence_based/CoMPT.py | biomed-AI/MolRep | train | 104 | |
21c04defb8f361da7720357494063b243f68f190 | [
"super().__init__()\nimport sklearn\nimport sklearn.multiclass\nself.model = sklearn.multiclass.OneVsRestClassifier",
"specs = super().getInputSpecification()\nspecs.description = 'The \\\\xmlNode{OneVsRestClassifier} (\\\\textit{One-vs-the-rest (OvR) multiclass strategy})\\n Also known as ... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.multiclass
self.model = sklearn.multiclass.OneVsRestClassifier
<|end_body_0|>
<|body_start_1|>
specs = super().getInputSpecification()
specs.description = 'The \\xmlNode{OneVsRestClassifier} (\\textit{One-... | One-vs-the-rest (OvR) multiclass strategy classifer | OneVsRestClassifier | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneVsRestClassifier:
"""One-vs-the-rest (OvR) multiclass strategy classifer"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get... | stack_v2_sparse_classes_10k_train_006093 | 5,730 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 4 | stack_v2_sparse_classes_30k_train_006239 | Implement the Python class `OneVsRestClassifier` described below.
Class description:
One-vs-the-rest (OvR) multiclass strategy classifer
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecificatio... | Implement the Python class `OneVsRestClassifier` described below.
Class description:
One-vs-the-rest (OvR) multiclass strategy classifer
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecificatio... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class OneVsRestClassifier:
"""One-vs-the-rest (OvR) multiclass strategy classifer"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OneVsRestClassifier:
"""One-vs-the-rest (OvR) multiclass strategy classifer"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
import sklearn.multiclass
s... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/MultiClass/OneVsRestClassifier.py | idaholab/raven | train | 201 |
83dad2e11cc4c94614bdff547c2beef2e1b4d848 | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('CreatePrefetchTask', params, headers=headers)\n response = json.loads(body)\n model = models.CreatePrefetchTaskResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:\n ... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('CreatePrefetchTask', params, headers=headers)
response = json.loads(body)
model = models.CreatePrefetchTaskResponse()
model._deserialize(respons... | TeoClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeoClient:
def CreatePrefetchTask(self, request):
"""创建预热任务 :param request: Request instance for CreatePrefetchTask. :type request: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTaskRequest` :rtype: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTaskResponse`"""
... | stack_v2_sparse_classes_10k_train_006094 | 5,399 | permissive | [
{
"docstring": "创建预热任务 :param request: Request instance for CreatePrefetchTask. :type request: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTaskRequest` :rtype: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTaskResponse`",
"name": "CreatePrefetchTask",
"signature": "def CreatePrefet... | 5 | null | Implement the Python class `TeoClient` described below.
Class description:
Implement the TeoClient class.
Method signatures and docstrings:
- def CreatePrefetchTask(self, request): 创建预热任务 :param request: Request instance for CreatePrefetchTask. :type request: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTa... | Implement the Python class `TeoClient` described below.
Class description:
Implement the TeoClient class.
Method signatures and docstrings:
- def CreatePrefetchTask(self, request): 创建预热任务 :param request: Request instance for CreatePrefetchTask. :type request: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTa... | 6baf00a5a56ba58b6a1123423e0a1422d17a0201 | <|skeleton|>
class TeoClient:
def CreatePrefetchTask(self, request):
"""创建预热任务 :param request: Request instance for CreatePrefetchTask. :type request: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTaskRequest` :rtype: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTaskResponse`"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeoClient:
def CreatePrefetchTask(self, request):
"""创建预热任务 :param request: Request instance for CreatePrefetchTask. :type request: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTaskRequest` :rtype: :class:`tencentcloud.teo.v20220106.models.CreatePrefetchTaskResponse`"""
try:
... | the_stack_v2_python_sparse | tencentcloud/teo/v20220106/teo_client.py | TencentCloud/tencentcloud-sdk-python | train | 594 | |
e1775016c11651ce950d038615e399e3ad5e0df3 | [
"self.width = width\nself.height = height\nself.food = food\nself.food_index = 0\nself.shape = [(0, 0)]\nself.positions = set([(0, 0)])",
"curr = self.shape[-1]\nmapping = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}\ndelta = mapping[direction]\nnext_pos = (curr[0] + delta[0], curr[1] + delta[1])\nif ne... | <|body_start_0|>
self.width = width
self.height = height
self.food = food
self.food_index = 0
self.shape = [(0, 0)]
self.positions = set([(0, 0)])
<|end_body_0|>
<|body_start_1|>
curr = self.shape[-1]
mapping = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D... | SnakeGame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_10k_train_006095 | 1,921 | permissive | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 7ad7e5c1c040510b7b7bd225ed4297054464dbc6 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | questions/design-snake-game/Solution.py | franklingu/leetcode-solutions | train | 155 | |
f413c10154c22b1bf608fa618d1ca85f7482bb58 | [
"self.randomSampling = []\nself.dataRange = dataRange\nself.tot = tot\nself.len = len",
"try:\n isLegalNumList(self.dataRange)\nexcept Exception as err:\n print('An exception happened: ' + str(err))\n sys.exit()\nself.randomSampling = []\nwhile len(self.randomSampling) != self.tot:\n it = iter(self.da... | <|body_start_0|>
self.randomSampling = []
self.dataRange = dataRange
self.tot = tot
self.len = len
<|end_body_0|>
<|body_start_1|>
try:
isLegalNumList(self.dataRange)
except Exception as err:
print('An exception happened: ' + str(err))
... | elementSamplingFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class elementSamplingFactory:
def __init__(self, dataRange, tot, len=6):
""":param dataRange:数据范围 :param tot: 数据量 :param len: 若生成字符串,字符串长度"""
<|body_0|>
def randomIntSampling(self):
""":return: 生成数据"""
<|body_1|>
def randomFloatSampling(self):
""":retu... | stack_v2_sparse_classes_10k_train_006096 | 2,834 | no_license | [
{
"docstring": ":param dataRange:数据范围 :param tot: 数据量 :param len: 若生成字符串,字符串长度",
"name": "__init__",
"signature": "def __init__(self, dataRange, tot, len=6)"
},
{
"docstring": ":return: 生成数据",
"name": "randomIntSampling",
"signature": "def randomIntSampling(self)"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_train_005634 | Implement the Python class `elementSamplingFactory` described below.
Class description:
Implement the elementSamplingFactory class.
Method signatures and docstrings:
- def __init__(self, dataRange, tot, len=6): :param dataRange:数据范围 :param tot: 数据量 :param len: 若生成字符串,字符串长度
- def randomIntSampling(self): :return: 生成数据... | Implement the Python class `elementSamplingFactory` described below.
Class description:
Implement the elementSamplingFactory class.
Method signatures and docstrings:
- def __init__(self, dataRange, tot, len=6): :param dataRange:数据范围 :param tot: 数据量 :param len: 若生成字符串,字符串长度
- def randomIntSampling(self): :return: 生成数据... | 661dba7ea846859056fd6ee7a310d352ca178e98 | <|skeleton|>
class elementSamplingFactory:
def __init__(self, dataRange, tot, len=6):
""":param dataRange:数据范围 :param tot: 数据量 :param len: 若生成字符串,字符串长度"""
<|body_0|>
def randomIntSampling(self):
""":return: 生成数据"""
<|body_1|>
def randomFloatSampling(self):
""":retu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class elementSamplingFactory:
def __init__(self, dataRange, tot, len=6):
""":param dataRange:数据范围 :param tot: 数据量 :param len: 若生成字符串,字符串长度"""
self.randomSampling = []
self.dataRange = dataRange
self.tot = tot
self.len = len
def randomIntSampling(self):
""":return... | the_stack_v2_python_sparse | 林一夫2017012923/平时作业1/Factory.py | wanghan79/2020_Python | train | 4 | |
e0cf12f9fccfc16dc8c6c9ebeffc857869ab1f9f | [
"self.argument_spec = netapp_utils.na_ontap_host_argument_spec()\nself.argument_spec.update(dict(state=dict(required=False, choices=['present', 'absent'], default='present'), broadcast_domain=dict(required=True, type='str'), ipspace=dict(required=False, type='str'), mtu=dict(required=False, type='str'), ports=dict(... | <|body_start_0|>
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
self.argument_spec.update(dict(state=dict(required=False, choices=['present', 'absent'], default='present'), broadcast_domain=dict(required=True, type='str'), ipspace=dict(required=False, type='str'), mtu=dict(required=Fals... | Create, Modifies and Destroys a Broadcast domain | NetAppOntapBroadcastDomain | [
"MIT",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetAppOntapBroadcastDomain:
"""Create, Modifies and Destroys a Broadcast domain"""
def __init__(self):
"""Initialize the ONTAP Broadcast Domain class"""
<|body_0|>
def get_broadcast_domain(self):
"""Return details about the broadcast domain :param: name : broadca... | stack_v2_sparse_classes_10k_train_006097 | 9,431 | permissive | [
{
"docstring": "Initialize the ONTAP Broadcast Domain class",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return details about the broadcast domain :param: name : broadcast domain name :return: Details about the broadcas domain. None if not found. :rtype: dict",
... | 6 | stack_v2_sparse_classes_30k_train_001682 | Implement the Python class `NetAppOntapBroadcastDomain` described below.
Class description:
Create, Modifies and Destroys a Broadcast domain
Method signatures and docstrings:
- def __init__(self): Initialize the ONTAP Broadcast Domain class
- def get_broadcast_domain(self): Return details about the broadcast domain :... | Implement the Python class `NetAppOntapBroadcastDomain` described below.
Class description:
Create, Modifies and Destroys a Broadcast domain
Method signatures and docstrings:
- def __init__(self): Initialize the ONTAP Broadcast Domain class
- def get_broadcast_domain(self): Return details about the broadcast domain :... | 0cd0c003884155ac922e3e301305ac202de7028c | <|skeleton|>
class NetAppOntapBroadcastDomain:
"""Create, Modifies and Destroys a Broadcast domain"""
def __init__(self):
"""Initialize the ONTAP Broadcast Domain class"""
<|body_0|>
def get_broadcast_domain(self):
"""Return details about the broadcast domain :param: name : broadca... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NetAppOntapBroadcastDomain:
"""Create, Modifies and Destroys a Broadcast domain"""
def __init__(self):
"""Initialize the ONTAP Broadcast Domain class"""
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
self.argument_spec.update(dict(state=dict(required=False, choice... | the_stack_v2_python_sparse | ansible/my_env/lib/python2.7/site-packages/ansible/modules/storage/netapp/na_ontap_broadcast_domain.py | otus-devops-2019-02/yyashkin_infra | train | 0 |
0a48e14b6b283b777b9041049549529b10dbbe1d | [
"credentials = api_helpers.get_delegated_credential(global_configs.get('domain_super_admin_email'), REQUIRED_SCOPES)\nmax_calls, quota_period = api_helpers.get_ratelimiter_config(global_configs, API_NAME)\nself.repository = AdminDirectoryRepositoryClient(credentials=credentials, quota_max_calls=max_calls, quota_per... | <|body_start_0|>
credentials = api_helpers.get_delegated_credential(global_configs.get('domain_super_admin_email'), REQUIRED_SCOPES)
max_calls, quota_period = api_helpers.get_ratelimiter_config(global_configs, API_NAME)
self.repository = AdminDirectoryRepositoryClient(credentials=credentials, qu... | GSuite Admin Directory API Client. | AdminDirectoryClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminDirectoryClient:
"""GSuite Admin Directory API Client."""
def __init__(self, global_configs, **kwargs):
"""Initialize. Args: global_configs (dict): Global configurations. **kwargs (dict): The kwargs."""
<|body_0|>
def get_group_members(self, group_key):
"""G... | stack_v2_sparse_classes_10k_train_006098 | 9,750 | permissive | [
{
"docstring": "Initialize. Args: global_configs (dict): Global configurations. **kwargs (dict): The kwargs.",
"name": "__init__",
"signature": "def __init__(self, global_configs, **kwargs)"
},
{
"docstring": "Get all the members for specified groups. Args: group_key (str): The group's unique id... | 4 | stack_v2_sparse_classes_30k_train_006920 | Implement the Python class `AdminDirectoryClient` described below.
Class description:
GSuite Admin Directory API Client.
Method signatures and docstrings:
- def __init__(self, global_configs, **kwargs): Initialize. Args: global_configs (dict): Global configurations. **kwargs (dict): The kwargs.
- def get_group_member... | Implement the Python class `AdminDirectoryClient` described below.
Class description:
GSuite Admin Directory API Client.
Method signatures and docstrings:
- def __init__(self, global_configs, **kwargs): Initialize. Args: global_configs (dict): Global configurations. **kwargs (dict): The kwargs.
- def get_group_member... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class AdminDirectoryClient:
"""GSuite Admin Directory API Client."""
def __init__(self, global_configs, **kwargs):
"""Initialize. Args: global_configs (dict): Global configurations. **kwargs (dict): The kwargs."""
<|body_0|>
def get_group_members(self, group_key):
"""G... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdminDirectoryClient:
"""GSuite Admin Directory API Client."""
def __init__(self, global_configs, **kwargs):
"""Initialize. Args: global_configs (dict): Global configurations. **kwargs (dict): The kwargs."""
credentials = api_helpers.get_delegated_credential(global_configs.get('domain_sup... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_api/admin_directory.py | kevensen/forseti-security | train | 1 |
0717caac7c5339ec504a6557b87e848edc7b8832 | [
"self.pre = pre\nself._n = n\nself.top = Toplevel()\nself.top.focus_set()\nself.top.grab_set()\nself._make_widgets()",
"self._entries = []\nfor i in range(self._n):\n _frame = Frame(self.top)\n _frame.pack(side=TOP, fill=X)\n Label(_frame, text='a[{}]: '.format(i), font=('arial', '16', 'bold')).pack(side... | <|body_start_0|>
self.pre = pre
self._n = n
self.top = Toplevel()
self.top.focus_set()
self.top.grab_set()
self._make_widgets()
<|end_body_0|>
<|body_start_1|>
self._entries = []
for i in range(self._n):
_frame = Frame(self.top)
_f... | Діалогове вікно. Містить n полів для введення компонент вектора. | Dialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialog:
"""Діалогове вікно. Містить n полів для введення компонент вектора."""
def __init__(self, n, pre):
"""Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало"""
<|body_0|>
def _make_widgets(self):
"""Сворення віджетів"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_006099 | 5,953 | no_license | [
{
"docstring": "Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало",
"name": "__init__",
"signature": "def __init__(self, n, pre)"
},
{
"docstring": "Сворення віджетів",
"name": "_make_widgets",
"signature": "def _make_widgets(self)"
},
{
"docstring": "Обробка ... | 3 | stack_v2_sparse_classes_30k_train_003072 | Implement the Python class `Dialog` described below.
Class description:
Діалогове вікно. Містить n полів для введення компонент вектора.
Method signatures and docstrings:
- def __init__(self, n, pre): Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало
- def _make_widgets(self): Сворення віджетів
- ... | Implement the Python class `Dialog` described below.
Class description:
Діалогове вікно. Містить n полів для введення компонент вектора.
Method signatures and docstrings:
- def __init__(self, n, pre): Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало
- def _make_widgets(self): Сворення віджетів
- ... | e44bf2b535b34bc31fb323c20901a77b0b3072f2 | <|skeleton|>
class Dialog:
"""Діалогове вікно. Містить n полів для введення компонент вектора."""
def __init__(self, n, pre):
"""Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало"""
<|body_0|>
def _make_widgets(self):
"""Сворення віджетів"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dialog:
"""Діалогове вікно. Містить n полів для введення компонент вектора."""
def __init__(self, n, pre):
"""Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало"""
self.pre = pre
self._n = n
self.top = Toplevel()
self.top.focus_set()
self... | the_stack_v2_python_sparse | dz_others/subject24_gui/t24_7.py | davendiy/ads_course2 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.