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 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0ae6e7e9df1719abab515aefc60ecfbea54ea66e | [
"self.name = name\nself._address = address\nself._initialized = False\nself._led = SevenSegment.SevenSegment(address=self._address)\ntry:\n self._led.begin()\n self.clear()\n self._initialized = True\nexcept IOError:\n msg = 'Could not connect to %s LED at I2C address %s' % (self.name, hex(self._address... | <|body_start_0|>
self.name = name
self._address = address
self._initialized = False
self._led = SevenSegment.SevenSegment(address=self._address)
try:
self._led.begin()
self.clear()
self._initialized = True
except IOError:
ms... | Numeric display uses the Adafruit SevenSegment display with i2c backpack | Numeric_Display_Adapter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Numeric_Display_Adapter:
"""Numeric display uses the Adafruit SevenSegment display with i2c backpack"""
def __init__(self, name, address):
"""Initalize a seven segment display with i2c"""
<|body_0|>
def clear(self):
"""Clear the display"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_003800 | 1,232 | no_license | [
{
"docstring": "Initalize a seven segment display with i2c",
"name": "__init__",
"signature": "def __init__(self, name, address)"
},
{
"docstring": "Clear the display",
"name": "clear",
"signature": "def clear(self)"
},
{
"docstring": "Display value",
"name": "display",
"... | 4 | stack_v2_sparse_classes_30k_train_003520 | Implement the Python class `Numeric_Display_Adapter` described below.
Class description:
Numeric display uses the Adafruit SevenSegment display with i2c backpack
Method signatures and docstrings:
- def __init__(self, name, address): Initalize a seven segment display with i2c
- def clear(self): Clear the display
- def... | Implement the Python class `Numeric_Display_Adapter` described below.
Class description:
Numeric display uses the Adafruit SevenSegment display with i2c backpack
Method signatures and docstrings:
- def __init__(self, name, address): Initalize a seven segment display with i2c
- def clear(self): Clear the display
- def... | 35ef4d55155d7d60ab15113ff068276c29ace510 | <|skeleton|>
class Numeric_Display_Adapter:
"""Numeric display uses the Adafruit SevenSegment display with i2c backpack"""
def __init__(self, name, address):
"""Initalize a seven segment display with i2c"""
<|body_0|>
def clear(self):
"""Clear the display"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Numeric_Display_Adapter:
"""Numeric display uses the Adafruit SevenSegment display with i2c backpack"""
def __init__(self, name, address):
"""Initalize a seven segment display with i2c"""
self.name = name
self._address = address
self._initialized = False
self._led ... | the_stack_v2_python_sparse | liberty_bell/components/numeric_display_adapter.py | mattgrogan/liberty_bell | train | 0 |
22ddbb89149c68c000bc2a121bcc3a994b00ceab | [
"sys.path.append('./m4sc/')\nimport m4sc\ngdl.check_file_exists(kyber_file)\nself.__raw_data = []\ntry:\n with open(kyber_file, 'rb') as f:\n while True:\n try:\n self.__raw_data.append(pickle.load(f))\n except EOFError:\n break\nexcept:\n print(\"Err... | <|body_start_0|>
sys.path.append('./m4sc/')
import m4sc
gdl.check_file_exists(kyber_file)
self.__raw_data = []
try:
with open(kyber_file, 'rb') as f:
while True:
try:
self.__raw_data.append(pickle.load(f))
... | Kyber | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kyber:
def __load_from_file(self, kyber_file):
"""TODO: add description :param kyber_file: :return:"""
<|body_0|>
def __parse_data(self):
"""TODO: add description :return:"""
<|body_1|>
def __parse_data_no_zeros(self):
"""TODO: add description :r... | stack_v2_sparse_classes_75kplus_train_003801 | 3,700 | permissive | [
{
"docstring": "TODO: add description :param kyber_file: :return:",
"name": "__load_from_file",
"signature": "def __load_from_file(self, kyber_file)"
},
{
"docstring": "TODO: add description :return:",
"name": "__parse_data",
"signature": "def __parse_data(self)"
},
{
"docstring"... | 4 | null | Implement the Python class `Kyber` described below.
Class description:
Implement the Kyber class.
Method signatures and docstrings:
- def __load_from_file(self, kyber_file): TODO: add description :param kyber_file: :return:
- def __parse_data(self): TODO: add description :return:
- def __parse_data_no_zeros(self): TO... | Implement the Python class `Kyber` described below.
Class description:
Implement the Kyber class.
Method signatures and docstrings:
- def __load_from_file(self, kyber_file): TODO: add description :param kyber_file: :return:
- def __parse_data(self): TODO: add description :return:
- def __parse_data_no_zeros(self): TO... | 79985987a17bbc437c132a4d66ff1593dd374494 | <|skeleton|>
class Kyber:
def __load_from_file(self, kyber_file):
"""TODO: add description :param kyber_file: :return:"""
<|body_0|>
def __parse_data(self):
"""TODO: add description :return:"""
<|body_1|>
def __parse_data_no_zeros(self):
"""TODO: add description :r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Kyber:
def __load_from_file(self, kyber_file):
"""TODO: add description :param kyber_file: :return:"""
sys.path.append('./m4sc/')
import m4sc
gdl.check_file_exists(kyber_file)
self.__raw_data = []
try:
with open(kyber_file, 'rb') as f:
... | the_stack_v2_python_sparse | training_modules/f01_data_type/KYBER.py | MakRude/SCA-with-keras | train | 3 | |
e75f59f61526fff87bbd7f74ec86b342c5b3dc25 | [
"super(BasicDdRt, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)\ncontact_zone__width = self._length_factor * self.params['contact_zone__width']\nself.K_rock_sp = self.get_parameter_from_exponent('K_rock_sp')\nself.K_till_sp = self.get_parameter_from_exponent('K_ti... | <|body_start_0|>
super(BasicDdRt, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)
contact_zone__width = self._length_factor * self.params['contact_zone__width']
self.K_rock_sp = self.get_parameter_from_exponent('K_rock_sp')
self.K_till_sp... | A BasicDdRt computes erosion using linear diffusion, stream power with a smoothed threshold, Q~A, and two lithologies: rock and till. | BasicDdRt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicDdRt:
"""A BasicDdRt computes erosion using linear diffusion, stream power with a smoothed threshold, Q~A, and two lithologies: rock and till."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicDdRt."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_003802 | 9,836 | permissive | [
{
"docstring": "Initialize the BasicDdRt.",
"name": "__init__",
"signature": "def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None)"
},
{
"docstring": "Set up lithology handling for two layers with different erodibility. Parameters ---------- file_name : string Name of arc... | 5 | stack_v2_sparse_classes_30k_train_032646 | Implement the Python class `BasicDdRt` described below.
Class description:
A BasicDdRt computes erosion using linear diffusion, stream power with a smoothed threshold, Q~A, and two lithologies: rock and till.
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None, BaselevelHandlerClass=No... | Implement the Python class `BasicDdRt` described below.
Class description:
A BasicDdRt computes erosion using linear diffusion, stream power with a smoothed threshold, Q~A, and two lithologies: rock and till.
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None, BaselevelHandlerClass=No... | 1b756477b8a8ab6a8f1275b1b30ec84855c840ea | <|skeleton|>
class BasicDdRt:
"""A BasicDdRt computes erosion using linear diffusion, stream power with a smoothed threshold, Q~A, and two lithologies: rock and till."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicDdRt."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicDdRt:
"""A BasicDdRt computes erosion using linear diffusion, stream power with a smoothed threshold, Q~A, and two lithologies: rock and till."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicDdRt."""
super(BasicDdRt, self).__ini... | the_stack_v2_python_sparse | terrainbento/derived_models/model_808_basicDdRt/model_808_basicDdRt.py | mcflugen/terrainbento | train | 0 |
44570b410142774c8d88d774300dbe7d0b5a9b11 | [
"self._schema = schema\nself.namespaces = namespaces\nfor key, value in schema.items():\n if isinstance(value, basestring):\n schema[key] = self._init_param(value)\n else:\n schema[key] = self._init_param(*value)",
"if isinstance(selector, basestring):\n selector = etree.XPath(selector, nam... | <|body_start_0|>
self._schema = schema
self.namespaces = namespaces
for key, value in schema.items():
if isinstance(value, basestring):
schema[key] = self._init_param(value)
else:
schema[key] = self._init_param(*value)
<|end_body_0|>
<|bod... | Multi-purpose XML decoder. Applies a given schema to an XML tree node. | XMLDecoder | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XMLDecoder:
"""Multi-purpose XML decoder. Applies a given schema to an XML tree node."""
def __init__(self, schema, namespaces=None):
"""Initializes the XMLDecoder. :param schema: is a dict in the form 'key': (selector, [type[, multiplicity]]). *key* is the parameter name to be set o... | stack_v2_sparse_classes_75kplus_train_003803 | 5,481 | permissive | [
{
"docstring": "Initializes the XMLDecoder. :param schema: is a dict in the form 'key': (selector, [type[, multiplicity]]). *key* is the parameter name to be set on the result dictionary. *selector* is either an xpath string or a callable that accepts an :class:`etree.Element` and returns a list of objects (Ele... | 4 | null | Implement the Python class `XMLDecoder` described below.
Class description:
Multi-purpose XML decoder. Applies a given schema to an XML tree node.
Method signatures and docstrings:
- def __init__(self, schema, namespaces=None): Initializes the XMLDecoder. :param schema: is a dict in the form 'key': (selector, [type[,... | Implement the Python class `XMLDecoder` described below.
Class description:
Multi-purpose XML decoder. Applies a given schema to an XML tree node.
Method signatures and docstrings:
- def __init__(self, schema, namespaces=None): Initializes the XMLDecoder. :param schema: is a dict in the form 'key': (selector, [type[,... | 0b6b13f2bdfd11240e23537a92a03c33c7cde948 | <|skeleton|>
class XMLDecoder:
"""Multi-purpose XML decoder. Applies a given schema to an XML tree node."""
def __init__(self, schema, namespaces=None):
"""Initializes the XMLDecoder. :param schema: is a dict in the form 'key': (selector, [type[, multiplicity]]). *key* is the parameter name to be set o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XMLDecoder:
"""Multi-purpose XML decoder. Applies a given schema to an XML tree node."""
def __init__(self, schema, namespaces=None):
"""Initializes the XMLDecoder. :param schema: is a dict in the form 'key': (selector, [type[, multiplicity]]). *key* is the parameter name to be set on the result ... | the_stack_v2_python_sparse | ngeo_browse_server/decoding.py | EOX-A/ngeo-b | train | 4 |
34c94db1c1bd67f3345968dead180bf9ab2de5ab | [
"ret = {}\nflags_map = {'Desired': {'u': 'Unknown', 'i': 'Install', 'r': 'Remove/Deinstall', 'p': 'Purge', 'h': 'Hold'}, 'Current': {'n': 'Not-installed', 'i': 'Installed', 'c': 'Only config Files are Installed', 'u': 'Unpacked', 'f': 'Configuration Failed (Half-Configured)', 'h': 'Installlation Failed (Half-Instal... | <|body_start_0|>
ret = {}
flags_map = {'Desired': {'u': 'Unknown', 'i': 'Install', 'r': 'Remove/Deinstall', 'p': 'Purge', 'h': 'Hold'}, 'Current': {'n': 'Not-installed', 'i': 'Installed', 'c': 'Only config Files are Installed', 'u': 'Unpacked', 'f': 'Configuration Failed (Half-Configured)', 'h': 'Instal... | Package management class for Ubuntu. | Ubuntu1204PackageImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ubuntu1204PackageImpl:
"""Package management class for Ubuntu."""
def are_installed(cls, client_object, packages=None):
"""Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type packages... | stack_v2_sparse_classes_75kplus_train_003804 | 5,138 | no_license | [
{
"docstring": "Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type packages: list @param packages: List of package names to query. @rtype: dict @return: Map from the package name to a tuple of (bool status of i... | 4 | stack_v2_sparse_classes_30k_train_048652 | Implement the Python class `Ubuntu1204PackageImpl` described below.
Class description:
Package management class for Ubuntu.
Method signatures and docstrings:
- def are_installed(cls, client_object, packages=None): Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_... | Implement the Python class `Ubuntu1204PackageImpl` described below.
Class description:
Package management class for Ubuntu.
Method signatures and docstrings:
- def are_installed(cls, client_object, packages=None): Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class Ubuntu1204PackageImpl:
"""Package management class for Ubuntu."""
def are_installed(cls, client_object, packages=None):
"""Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type packages... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ubuntu1204PackageImpl:
"""Package management class for Ubuntu."""
def are_installed(cls, client_object, packages=None):
"""Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type packages: list @param... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/kvm/cmd/ubuntu1204_package_impl.py | Cloudxtreme/MyProject | train | 0 |
f3c12209910fcb6771468b9770dead888dfe37b3 | [
"sentence = s.split(' ')\nword_order = {}\nfor word in sentence:\n word_order[word[-1]] = word[:len(word) - 1]\nsort = word_order['1']\nfor i in range(2, len(sentence) + 1):\n sort += ' ' + word_order[f'{i}']\nreturn sort",
"sentence = s.split(' ')\nsort = [0] * len(sentence)\nfor i, word in enumerate(sente... | <|body_start_0|>
sentence = s.split(' ')
word_order = {}
for word in sentence:
word_order[word[-1]] = word[:len(word) - 1]
sort = word_order['1']
for i in range(2, len(sentence) + 1):
sort += ' ' + word_order[f'{i}']
return sort
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortSentence(self, s: str) -> str:
"""O(2n) where the time limiting step would be the first loop"""
<|body_0|>
def sortSentence(self, s: str) -> str:
"""O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sentence = s.split(' ')
... | stack_v2_sparse_classes_75kplus_train_003805 | 716 | no_license | [
{
"docstring": "O(2n) where the time limiting step would be the first loop",
"name": "sortSentence",
"signature": "def sortSentence(self, s: str) -> str"
},
{
"docstring": "O(n)",
"name": "sortSentence",
"signature": "def sortSentence(self, s: str) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_036374 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortSentence(self, s: str) -> str: O(2n) where the time limiting step would be the first loop
- def sortSentence(self, s: str) -> str: O(n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortSentence(self, s: str) -> str: O(2n) where the time limiting step would be the first loop
- def sortSentence(self, s: str) -> str: O(n)
<|skeleton|>
class Solution:
... | 6d6afba93d20665d033fe542c97e3eb50368bd3c | <|skeleton|>
class Solution:
def sortSentence(self, s: str) -> str:
"""O(2n) where the time limiting step would be the first loop"""
<|body_0|>
def sortSentence(self, s: str) -> str:
"""O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortSentence(self, s: str) -> str:
"""O(2n) where the time limiting step would be the first loop"""
sentence = s.split(' ')
word_order = {}
for word in sentence:
word_order[word[-1]] = word[:len(word) - 1]
sort = word_order['1']
for i i... | the_stack_v2_python_sparse | sorting_sentence.py | naomi397liu/AlgorithmPactice | train | 1 | |
88e40eb0db27fafa315cb79fae3c8ac392b0693e | [
"if len(password) < self.MIN_PASSWORD_LENGTH:\n raise exceptions.ValidationError(self.token, 'Password too short')\nif rank > 1 and rank > self.connection.level():\n raise exceptions.Unauthorized(self.token, 'Unauthorized to create user with rank %s' % rank)\npassword = hashlib.sha256(password.encode('utf-8')... | <|body_start_0|>
if len(password) < self.MIN_PASSWORD_LENGTH:
raise exceptions.ValidationError(self.token, 'Password too short')
if rank > 1 and rank > self.connection.level():
raise exceptions.Unauthorized(self.token, 'Unauthorized to create user with rank %s' % rank)
pa... | User class resource | UserResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserResource:
"""User class resource"""
def create(self, name, password, email=None, rank=1):
"""Create a new user"""
<|body_0|>
def login(self, name, password):
"""Login a new user in our database"""
<|body_1|>
def login_or_create(self, name, passwo... | stack_v2_sparse_classes_75kplus_train_003806 | 3,748 | permissive | [
{
"docstring": "Create a new user",
"name": "create",
"signature": "def create(self, name, password, email=None, rank=1)"
},
{
"docstring": "Login a new user in our database",
"name": "login",
"signature": "def login(self, name, password)"
},
{
"docstring": "Login or create a use... | 4 | stack_v2_sparse_classes_30k_train_020445 | Implement the Python class `UserResource` described below.
Class description:
User class resource
Method signatures and docstrings:
- def create(self, name, password, email=None, rank=1): Create a new user
- def login(self, name, password): Login a new user in our database
- def login_or_create(self, name, password):... | Implement the Python class `UserResource` described below.
Class description:
User class resource
Method signatures and docstrings:
- def create(self, name, password, email=None, rank=1): Create a new user
- def login(self, name, password): Login a new user in our database
- def login_or_create(self, name, password):... | cf20b363ed3d7bcb75101b17870e876a857ecd66 | <|skeleton|>
class UserResource:
"""User class resource"""
def create(self, name, password, email=None, rank=1):
"""Create a new user"""
<|body_0|>
def login(self, name, password):
"""Login a new user in our database"""
<|body_1|>
def login_or_create(self, name, passwo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserResource:
"""User class resource"""
def create(self, name, password, email=None, rank=1):
"""Create a new user"""
if len(password) < self.MIN_PASSWORD_LENGTH:
raise exceptions.ValidationError(self.token, 'Password too short')
if rank > 1 and rank > self.connection.... | the_stack_v2_python_sparse | smserver/resources/user_resource.py | Moutix/stepmania-server | train | 4 |
2b45e65c2848771686865bc1be2b63d2f0eb34da | [
"in_the_future = timezone.now() + datetime.timedelta(days=30)\na = Appointment(name='testappointment', start_time=in_the_future, end_time=timezone.now())\nwith self.assertRaises(ValidationError):\n a.full_clean()",
"a = Appointment(name='testappointment', start_time=timezone.now(), end_time=timezone.now() + da... | <|body_start_0|>
in_the_future = timezone.now() + datetime.timedelta(days=30)
a = Appointment(name='testappointment', start_time=in_the_future, end_time=timezone.now())
with self.assertRaises(ValidationError):
a.full_clean()
<|end_body_0|>
<|body_start_1|>
a = Appointment(na... | AppointmentModelTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppointmentModelTests:
def test_invalid_when_end_before_start(self):
"""Appointments with end_time before start_time are invalid"""
<|body_0|>
def test_autogenerate_room_name_when_empty(self):
"""Appointments without a room name get a random room name on save"""
... | stack_v2_sparse_classes_75kplus_train_003807 | 1,553 | permissive | [
{
"docstring": "Appointments with end_time before start_time are invalid",
"name": "test_invalid_when_end_before_start",
"signature": "def test_invalid_when_end_before_start(self)"
},
{
"docstring": "Appointments without a room name get a random room name on save",
"name": "test_autogenerate... | 3 | null | Implement the Python class `AppointmentModelTests` described below.
Class description:
Implement the AppointmentModelTests class.
Method signatures and docstrings:
- def test_invalid_when_end_before_start(self): Appointments with end_time before start_time are invalid
- def test_autogenerate_room_name_when_empty(self... | Implement the Python class `AppointmentModelTests` described below.
Class description:
Implement the AppointmentModelTests class.
Method signatures and docstrings:
- def test_invalid_when_end_before_start(self): Appointments with end_time before start_time are invalid
- def test_autogenerate_room_name_when_empty(self... | 63cd880d155bcf6549b5616be3c6d2a87d198106 | <|skeleton|>
class AppointmentModelTests:
def test_invalid_when_end_before_start(self):
"""Appointments with end_time before start_time are invalid"""
<|body_0|>
def test_autogenerate_room_name_when_empty(self):
"""Appointments without a room name get a random room name on save"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppointmentModelTests:
def test_invalid_when_end_before_start(self):
"""Appointments with end_time before start_time are invalid"""
in_the_future = timezone.now() + datetime.timedelta(days=30)
a = Appointment(name='testappointment', start_time=in_the_future, end_time=timezone.now())
... | the_stack_v2_python_sparse | rooms/tests.py | covid-videoplattform/django-webfrontend | train | 1 | |
75b91843c83e94bb16740c0dc597e2bfd21f3864 | [
"goods_id = request.POST.get('goods_id')\ngoods_lable = request.POST.get('goods_lable')\nu_login_name = request.session.get('u_login_name')\nuser = User.objects.get(u_login_name=u_login_name)\ngoods = Goods.objects.get(g_id=goods_id)\ngl = GoodsLable.objects.filter(gl_lable=goods_lable, gl_goods=goods)\nif len(gl) ... | <|body_start_0|>
goods_id = request.POST.get('goods_id')
goods_lable = request.POST.get('goods_lable')
u_login_name = request.session.get('u_login_name')
user = User.objects.get(u_login_name=u_login_name)
goods = Goods.objects.get(g_id=goods_id)
gl = GoodsLable.objects.fi... | 产品标签添加,删除 | GoodsLableHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoodsLableHandler:
"""产品标签添加,删除"""
def post(self, request):
"""添加"""
<|body_0|>
def get(self, request):
"""删除"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
goods_id = request.POST.get('goods_id')
goods_lable = request.POST.get('goods_l... | stack_v2_sparse_classes_75kplus_train_003808 | 21,132 | no_license | [
{
"docstring": "添加",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000070 | Implement the Python class `GoodsLableHandler` described below.
Class description:
产品标签添加,删除
Method signatures and docstrings:
- def post(self, request): 添加
- def get(self, request): 删除 | Implement the Python class `GoodsLableHandler` described below.
Class description:
产品标签添加,删除
Method signatures and docstrings:
- def post(self, request): 添加
- def get(self, request): 删除
<|skeleton|>
class GoodsLableHandler:
"""产品标签添加,删除"""
def post(self, request):
"""添加"""
<|body_0|>
de... | b6185fe5fb138a5a124e0efc9c266a249cce5459 | <|skeleton|>
class GoodsLableHandler:
"""产品标签添加,删除"""
def post(self, request):
"""添加"""
<|body_0|>
def get(self, request):
"""删除"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoodsLableHandler:
"""产品标签添加,删除"""
def post(self, request):
"""添加"""
goods_id = request.POST.get('goods_id')
goods_lable = request.POST.get('goods_lable')
u_login_name = request.session.get('u_login_name')
user = User.objects.get(u_login_name=u_login_name)
... | the_stack_v2_python_sparse | goods/views.py | bingfengxindong/goods_info | train | 0 |
42c785c4a9aec3d489f419a51908a0d75ad5f644 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn HostReputation()",
"from ..entity import Entity\nfrom .host_reputation_classification import HostReputationClassification\nfrom .host_reputation_rule import HostReputationRule\nfrom ..entity import Entity\nfrom .host_reputation_classif... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return HostReputation()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from .host_reputation_classification import HostReputationClassification
from .host_reputation_rule i... | HostReputation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostReputation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostReputation:
"""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 Retur... | stack_v2_sparse_classes_75kplus_train_003809 | 3,084 | 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: HostReputation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_047461 | Implement the Python class `HostReputation` described below.
Class description:
Implement the HostReputation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostReputation: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `HostReputation` described below.
Class description:
Implement the HostReputation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostReputation: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class HostReputation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostReputation:
"""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 Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HostReputation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostReputation:
"""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: HostReputa... | the_stack_v2_python_sparse | msgraph/generated/models/security/host_reputation.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
143f3d145b520c94c6caf7075ced005ba410afd5 | [
"if not self._check_project():\n return None\nasset = artellapipe.AssetsMgr().find_asset(asset_name)\nif not asset:\n LOGGER.warning('Impossible to return occurrences because asset \"{}\" does not exists!'.format(asset_name))\n return None\nshot = shots.ShotsManager().find_shot(shot_name)\nif not shot:\n ... | <|body_start_0|>
if not self._check_project():
return None
asset = artellapipe.AssetsMgr().find_asset(asset_name)
if not asset:
LOGGER.warning('Impossible to return occurrences because asset "{}" does not exists!'.format(asset_name))
return None
shot =... | ArtellaCastingManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArtellaCastingManager:
def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False):
"""Returns the number of ocurrences of given asset in given shot :param asset_name: str, name of the asset :param shot_name: str, name of the shot :return: int or None"""
... | stack_v2_sparse_classes_75kplus_train_003810 | 2,441 | permissive | [
{
"docstring": "Returns the number of ocurrences of given asset in given shot :param asset_name: str, name of the asset :param shot_name: str, name of the shot :return: int or None",
"name": "get_ocurrences_of_asset_in_shot",
"signature": "def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name,... | 3 | stack_v2_sparse_classes_30k_train_047763 | Implement the Python class `ArtellaCastingManager` described below.
Class description:
Implement the ArtellaCastingManager class.
Method signatures and docstrings:
- def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False): Returns the number of ocurrences of given asset in given shot :par... | Implement the Python class `ArtellaCastingManager` described below.
Class description:
Implement the ArtellaCastingManager class.
Method signatures and docstrings:
- def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False): Returns the number of ocurrences of given asset in given shot :par... | 3400f6a55f124f639143fe01c559059eaba23b22 | <|skeleton|>
class ArtellaCastingManager:
def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False):
"""Returns the number of ocurrences of given asset in given shot :param asset_name: str, name of the asset :param shot_name: str, name of the shot :return: int or None"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArtellaCastingManager:
def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False):
"""Returns the number of ocurrences of given asset in given shot :param asset_name: str, name of the asset :param shot_name: str, name of the shot :return: int or None"""
if not self._c... | the_stack_v2_python_sparse | artellapipe/managers/casting.py | ArtellaPipe/artellapipe | train | 8 | |
c2d80b623676d06bed2f2ee79d4791eb6e8033db | [
"Layer.__init__(self, name='approximated_smoothing')\nself.kernel_func = look_up_operations(type_str.lower(), SUPPORTED_KERNELS)\nself.sigma = sigma\nself.truncate = truncate",
"spatial_rank = infer_spatial_rank(image)\n_sigmas = expand_spatial_params(input_param=self.sigma, spatial_rank=spatial_rank, param_type=... | <|body_start_0|>
Layer.__init__(self, name='approximated_smoothing')
self.kernel_func = look_up_operations(type_str.lower(), SUPPORTED_KERNELS)
self.sigma = sigma
self.truncate = truncate
<|end_body_0|>
<|body_start_1|>
spatial_rank = infer_spatial_rank(image)
_sigmas = ... | computing 1d convolution one each spatial dimension of the input using one-dimensional filter. | SmoothingLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmoothingLayer:
"""computing 1d convolution one each spatial dimension of the input using one-dimensional filter."""
def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'):
""":param sigma: standard deviation :param truncate: Truncate the filter at this many standard deviatio... | stack_v2_sparse_classes_75kplus_train_003811 | 3,416 | permissive | [
{
"docstring": ":param sigma: standard deviation :param truncate: Truncate the filter at this many standard deviations :param type_str: type of kernels",
"name": "__init__",
"signature": "def __init__(self, sigma=1, truncate=3.0, type_str='gaussian')"
},
{
"docstring": ":param image: in shape `(... | 2 | stack_v2_sparse_classes_30k_test_000270 | Implement the Python class `SmoothingLayer` described below.
Class description:
computing 1d convolution one each spatial dimension of the input using one-dimensional filter.
Method signatures and docstrings:
- def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'): :param sigma: standard deviation :param tru... | Implement the Python class `SmoothingLayer` described below.
Class description:
computing 1d convolution one each spatial dimension of the input using one-dimensional filter.
Method signatures and docstrings:
- def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'): :param sigma: standard deviation :param tru... | 84dd0f85c9a1ab8a72f4c55fcf073379acf5ae1b | <|skeleton|>
class SmoothingLayer:
"""computing 1d convolution one each spatial dimension of the input using one-dimensional filter."""
def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'):
""":param sigma: standard deviation :param truncate: Truncate the filter at this many standard deviatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmoothingLayer:
"""computing 1d convolution one each spatial dimension of the input using one-dimensional filter."""
def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'):
""":param sigma: standard deviation :param truncate: Truncate the filter at this many standard deviations :param typ... | the_stack_v2_python_sparse | niftynet/layer/approximated_smoothing.py | 12SigmaTechnologies/NiftyNet-1 | train | 2 |
6806e0d3dcfae4849b8586447c1c77d7c28763f6 | [
"exp_value = 42\nicpw_obj = Int64(exp_value)\nself.assertEqual(exp_value, icpw_obj.icpw_value)",
"exp_value = 84\nobj0 = Int64(exp_value)\nobj1 = Int64(exp_value)\nself.assertEqual(obj0, obj1)",
"exp_value = 84\nobj0 = Int64(exp_value)\nobj1 = Int64(2 * exp_value + 1)\nself.assertNotEqual(obj0, obj1)",
"exp_v... | <|body_start_0|>
exp_value = 42
icpw_obj = Int64(exp_value)
self.assertEqual(exp_value, icpw_obj.icpw_value)
<|end_body_0|>
<|body_start_1|>
exp_value = 84
obj0 = Int64(exp_value)
obj1 = Int64(exp_value)
self.assertEqual(obj0, obj1)
<|end_body_1|>
<|body_start_2... | Int64Tester | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Int64Tester:
def test_value(self):
"""Test retrieving the value of an Int64."""
<|body_0|>
def test_eq(self):
"""Test that two Int64's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that two Int64's with different val... | stack_v2_sparse_classes_75kplus_train_003812 | 42,194 | permissive | [
{
"docstring": "Test retrieving the value of an Int64.",
"name": "test_value",
"signature": "def test_value(self)"
},
{
"docstring": "Test that two Int64's with the same value compare equal.",
"name": "test_eq",
"signature": "def test_eq(self)"
},
{
"docstring": "Test that two In... | 5 | stack_v2_sparse_classes_30k_train_022668 | Implement the Python class `Int64Tester` described below.
Class description:
Implement the Int64Tester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of an Int64.
- def test_eq(self): Test that two Int64's with the same value compare equal.
- def test_ne(self): Test that tw... | Implement the Python class `Int64Tester` described below.
Class description:
Implement the Int64Tester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of an Int64.
- def test_eq(self): Test that two Int64's with the same value compare equal.
- def test_ne(self): Test that tw... | a626f881d55c307bd857d0ff980cc526f2b18de2 | <|skeleton|>
class Int64Tester:
def test_value(self):
"""Test retrieving the value of an Int64."""
<|body_0|>
def test_eq(self):
"""Test that two Int64's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that two Int64's with different val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Int64Tester:
def test_value(self):
"""Test retrieving the value of an Int64."""
exp_value = 42
icpw_obj = Int64(exp_value)
self.assertEqual(exp_value, icpw_obj.icpw_value)
def test_eq(self):
"""Test that two Int64's with the same value compare equal."""
exp... | the_stack_v2_python_sparse | icypaw/test_types.py | sandialabs/IcyPaw | train | 0 | |
52a7257ed112050815550246671376a59e179777 | [
"feature = replace_default_to_nan(feature)\ny = y.astype('category') if self.target == 'classify' else y.astype('float')\ny = y.map(lambda x: int(x)) if self.target == 'classify' else y\nreturn (feature, y)",
"category_var = feature.select_dtypes(include='category').columns\nif self.cross:\n tag = None\n wh... | <|body_start_0|>
feature = replace_default_to_nan(feature)
y = y.astype('category') if self.target == 'classify' else y.astype('float')
y = y.map(lambda x: int(x)) if self.target == 'classify' else y
return (feature, y)
<|end_body_0|>
<|body_start_1|>
category_var = feature.sele... | 自定义预处理类函数封装 此处可以记录模型评估与调整过程 | Custom | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Custom:
"""自定义预处理类函数封装 此处可以记录模型评估与调整过程"""
def clean_data(self, feature, y):
"""基于单元格与行操作的数据清洗 Args: feature: 待清洗特征数据框 label: 待清洗标签序列 Returns: Feature: 已清洗特征数据框 Label: 已清洗标签序列"""
<|body_0|>
def feature_combination(self, feature, y):
"""基于列操作的数据清洗与特征构造 Args: featur... | stack_v2_sparse_classes_75kplus_train_003813 | 4,705 | permissive | [
{
"docstring": "基于单元格与行操作的数据清洗 Args: feature: 待清洗特征数据框 label: 待清洗标签序列 Returns: Feature: 已清洗特征数据框 Label: 已清洗标签序列",
"name": "clean_data",
"signature": "def clean_data(self, feature, y)"
},
{
"docstring": "基于列操作的数据清洗与特征构造 Args: feature: 待清洗特征数据框 Returns: feature_tmp: 已清洗特征数据框",
"name": "feature... | 2 | null | Implement the Python class `Custom` described below.
Class description:
自定义预处理类函数封装 此处可以记录模型评估与调整过程
Method signatures and docstrings:
- def clean_data(self, feature, y): 基于单元格与行操作的数据清洗 Args: feature: 待清洗特征数据框 label: 待清洗标签序列 Returns: Feature: 已清洗特征数据框 Label: 已清洗标签序列
- def feature_combination(self, feature, y): 基于列操作的数... | Implement the Python class `Custom` described below.
Class description:
自定义预处理类函数封装 此处可以记录模型评估与调整过程
Method signatures and docstrings:
- def clean_data(self, feature, y): 基于单元格与行操作的数据清洗 Args: feature: 待清洗特征数据框 label: 待清洗标签序列 Returns: Feature: 已清洗特征数据框 Label: 已清洗标签序列
- def feature_combination(self, feature, y): 基于列操作的数... | ede038b87b7a46c2872ac9ae744c4dbfe5d6fe48 | <|skeleton|>
class Custom:
"""自定义预处理类函数封装 此处可以记录模型评估与调整过程"""
def clean_data(self, feature, y):
"""基于单元格与行操作的数据清洗 Args: feature: 待清洗特征数据框 label: 待清洗标签序列 Returns: Feature: 已清洗特征数据框 Label: 已清洗标签序列"""
<|body_0|>
def feature_combination(self, feature, y):
"""基于列操作的数据清洗与特征构造 Args: featur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Custom:
"""自定义预处理类函数封装 此处可以记录模型评估与调整过程"""
def clean_data(self, feature, y):
"""基于单元格与行操作的数据清洗 Args: feature: 待清洗特征数据框 label: 待清洗标签序列 Returns: Feature: 已清洗特征数据框 Label: 已清洗标签序列"""
feature = replace_default_to_nan(feature)
y = y.astype('category') if self.target == 'classify' else y.... | the_stack_v2_python_sparse | mksc/template/custom.py | HelloCoyen/mksc2 | train | 1 |
18994b51f7d409c286b1600b094a69e335442a7d | [
"if x < 0:\n return False\nif self.successive_division(x) == list(reversed(self.successive_division(x))):\n return True\nreturn False",
"y = 10\nwhile True:\n if x // y == 0:\n break\n y *= 10\nz = math.log10(y)\nreturn int(z)",
"c = []\nfor i in range(self.get_count(x) - 1, -1, -1):\n con... | <|body_start_0|>
if x < 0:
return False
if self.successive_division(x) == list(reversed(self.successive_division(x))):
return True
return False
<|end_body_0|>
<|body_start_1|>
y = 10
while True:
if x // y == 0:
break
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def get_count(self, x):
""":param x: :return: x是几位数"""
<|body_1|>
def successive_division(self, x):
""":param x: :return: 辗转相除余数列表"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_003814 | 1,148 | no_license | [
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
},
{
"docstring": ":param x: :return: x是几位数",
"name": "get_count",
"signature": "def get_count(self, x)"
},
{
"docstring": ":param x: :return: 辗转相除余数列表",
"name": "succ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): :type x: int :rtype: bool
- def get_count(self, x): :param x: :return: x是几位数
- def successive_division(self, x): :param x: :return: 辗转相除余数列表 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): :type x: int :rtype: bool
- def get_count(self, x): :param x: :return: x是几位数
- def successive_division(self, x): :param x: :return: 辗转相除余数列表
<|skeleto... | fd745fc313052a301f927ed057964b593559188a | <|skeleton|>
class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def get_count(self, x):
""":param x: :return: x是几位数"""
<|body_1|>
def successive_division(self, x):
""":param x: :return: 辗转相除余数列表"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
if x < 0:
return False
if self.successive_division(x) == list(reversed(self.successive_division(x))):
return True
return False
def get_count(self, x):
""":param x: :return:... | the_stack_v2_python_sparse | leetcode/palindrome-number.py | huangyisan/lab | train | 0 | |
626f13e024481f7df32207f8483a6a8bd566bcc7 | [
"if H <= len(piles):\n return max(piles)\n\ndef is_affordable(k):\n return sum(((p - 1) // k + 1 for p in piles)) <= H\nlow, high = (1, max(piles))\nwhile low < high:\n mid = low + (high - low) // 2\n if is_affordable(mid):\n high = mid\n else:\n low = mid + 1\nreturn low",
"if H <= l... | <|body_start_0|>
if H <= len(piles):
return max(piles)
def is_affordable(k):
return sum(((p - 1) // k + 1 for p in piles)) <= H
low, high = (1, max(piles))
while low < high:
mid = low + (high - low) // 2
if is_affordable(mid):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 典型的type 2"""
<|body_0|>
def minEatingSpeedFailed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 我的版本,多做了 sort 但其實沒啥用 然後這個不是 type 2 type 2 不會有 == 的條件式... | stack_v2_sparse_classes_75kplus_train_003815 | 1,510 | no_license | [
{
"docstring": ":type piles: List[int] :type H: int :rtype: int 典型的type 2",
"name": "minEatingSpeed",
"signature": "def minEatingSpeed(self, piles, H)"
},
{
"docstring": ":type piles: List[int] :type H: int :rtype: int 我的版本,多做了 sort 但其實沒啥用 然後這個不是 type 2 type 2 不會有 == 的條件式 最後外面回傳 low",
"name"... | 2 | stack_v2_sparse_classes_30k_train_001831 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: int 典型的type 2
- def minEatingSpeedFailed(self, piles, H): :type piles: List[int] :type H: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: int 典型的type 2
- def minEatingSpeedFailed(self, piles, H): :type piles: List[int] :type H: int :rty... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 典型的type 2"""
<|body_0|>
def minEatingSpeedFailed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 我的版本,多做了 sort 但其實沒啥用 然後這個不是 type 2 type 2 不會有 == 的條件式... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 典型的type 2"""
if H <= len(piles):
return max(piles)
def is_affordable(k):
return sum(((p - 1) // k + 1 for p in piles)) <= H
low, high = (1, max(piles))
... | the_stack_v2_python_sparse | cs_notes/binary_search/koko_eating_bananas.py | hwc1824/LeetCodeSolution | train | 0 | |
d8598ab028196f1b3e3efbed76d414e20ac5075e | [
"body = jsonBinData.decode('utf-8')\nmd5_sig = hmac.new(secret.encode(), digestmod='md5').hexdigest()\nsha1_sig = hmac.new(secret.encode(), digestmod='sha1').hexdigest()\npayload_dict = {}\npayload_dict['body'], payload_dict['md5'], payload_dict['sha1'] = (body, md5_sig, sha1_sig)\nwith open(fname, 'w') as outFile:... | <|body_start_0|>
body = jsonBinData.decode('utf-8')
md5_sig = hmac.new(secret.encode(), digestmod='md5').hexdigest()
sha1_sig = hmac.new(secret.encode(), digestmod='sha1').hexdigest()
payload_dict = {}
payload_dict['body'], payload_dict['md5'], payload_dict['sha1'] = (body, md5_s... | Class that creates payload and verifies that they match | Hmac | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hmac:
"""Class that creates payload and verifies that they match"""
def wrap(self, jsonBinData):
"""creating json payload"""
<|body_0|>
def unwrap(self):
"""verifying they match"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
body = jsonBinData.... | stack_v2_sparse_classes_75kplus_train_003816 | 1,461 | no_license | [
{
"docstring": "creating json payload",
"name": "wrap",
"signature": "def wrap(self, jsonBinData)"
},
{
"docstring": "verifying they match",
"name": "unwrap",
"signature": "def unwrap(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001190 | Implement the Python class `Hmac` described below.
Class description:
Class that creates payload and verifies that they match
Method signatures and docstrings:
- def wrap(self, jsonBinData): creating json payload
- def unwrap(self): verifying they match | Implement the Python class `Hmac` described below.
Class description:
Class that creates payload and verifies that they match
Method signatures and docstrings:
- def wrap(self, jsonBinData): creating json payload
- def unwrap(self): verifying they match
<|skeleton|>
class Hmac:
"""Class that creates payload and ... | 860a59ee42190e13eabb62d10d6ad231a7bb6335 | <|skeleton|>
class Hmac:
"""Class that creates payload and verifies that they match"""
def wrap(self, jsonBinData):
"""creating json payload"""
<|body_0|>
def unwrap(self):
"""verifying they match"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hmac:
"""Class that creates payload and verifies that they match"""
def wrap(self, jsonBinData):
"""creating json payload"""
body = jsonBinData.decode('utf-8')
md5_sig = hmac.new(secret.encode(), digestmod='md5').hexdigest()
sha1_sig = hmac.new(secret.encode(), digestmod='... | the_stack_v2_python_sparse | classes/ianHmac.py | kmikus/dist-object-team4 | train | 0 |
59946f1490312e0c1ed3918729f00b8f94d51544 | [
"self.dataproc = dataproc\nself.batch_message_factory = batch_message_factory_override\nif not self.batch_message_factory:\n self.batch_message_factory = batch_message_factory.BatchMessageFactory(self.dataproc)",
"kwargs = {}\nkwargs['parent'] = args.CONCEPTS.region.Parse().RelativeName()\nkwargs['requestId'] ... | <|body_start_0|>
self.dataproc = dataproc
self.batch_message_factory = batch_message_factory_override
if not self.batch_message_factory:
self.batch_message_factory = batch_message_factory.BatchMessageFactory(self.dataproc)
<|end_body_0|>
<|body_start_1|>
kwargs = {}
... | Factory class handling BatchesCreateRequest message. Factory class for configure argument parser and create BatchesCreateRequest message from parsed argument. | BatchesCreateRequestFactory | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchesCreateRequestFactory:
"""Factory class handling BatchesCreateRequest message. Factory class for configure argument parser and create BatchesCreateRequest message from parsed argument."""
def __init__(self, dataproc, batch_message_factory_override=None):
"""Factory for BatchesC... | stack_v2_sparse_classes_75kplus_train_003817 | 5,240 | permissive | [
{
"docstring": "Factory for BatchesCreateRequest message. Only handles general submit flags added by this class. User needs to provide job specific message when creating the request message. Args: dataproc: A api_lib.dataproc.Dataproc instance. batch_message_factory_override: Override BatchMessageFactory instan... | 2 | stack_v2_sparse_classes_30k_train_044217 | Implement the Python class `BatchesCreateRequestFactory` described below.
Class description:
Factory class handling BatchesCreateRequest message. Factory class for configure argument parser and create BatchesCreateRequest message from parsed argument.
Method signatures and docstrings:
- def __init__(self, dataproc, b... | Implement the Python class `BatchesCreateRequestFactory` described below.
Class description:
Factory class handling BatchesCreateRequest message. Factory class for configure argument parser and create BatchesCreateRequest message from parsed argument.
Method signatures and docstrings:
- def __init__(self, dataproc, b... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class BatchesCreateRequestFactory:
"""Factory class handling BatchesCreateRequest message. Factory class for configure argument parser and create BatchesCreateRequest message from parsed argument."""
def __init__(self, dataproc, batch_message_factory_override=None):
"""Factory for BatchesC... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchesCreateRequestFactory:
"""Factory class handling BatchesCreateRequest message. Factory class for configure argument parser and create BatchesCreateRequest message from parsed argument."""
def __init__(self, dataproc, batch_message_factory_override=None):
"""Factory for BatchesCreateRequest ... | the_stack_v2_python_sparse | lib/googlecloudsdk/command_lib/dataproc/batches/batches_create_request_factory.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
0c9e90dc985dd8bee15a2f14b7f278a424975ade | [
"self.neurons = neurons\nself.n_outputs = n_outputs\nself.eta = eta\nself.lmbda = lmbda\nself.loss = loss\nself.metrics = metrics\nself.hidden_act = hidden_act\nself.output_act = output_act",
"model = Sequential()\nfor i in range(len(self.neurons)):\n model.add(Dense(self.neurons[i], activation=self.hidden_act... | <|body_start_0|>
self.neurons = neurons
self.n_outputs = n_outputs
self.eta = eta
self.lmbda = lmbda
self.loss = loss
self.metrics = metrics
self.hidden_act = hidden_act
self.output_act = output_act
<|end_body_0|>
<|body_start_1|>
model = Sequenti... | Keras | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Keras:
def __init__(self, neurons, n_outputs, eta, lmbda, loss, metrics, hidden_act, output_act):
"""Set up neural network using keras. Keyword arguments: neurons -- list with number of neurons in each hidden layer n_outputs -- number of outputs from the network eta -- learning rate lmbd... | stack_v2_sparse_classes_75kplus_train_003818 | 2,373 | no_license | [
{
"docstring": "Set up neural network using keras. Keyword arguments: neurons -- list with number of neurons in each hidden layer n_outputs -- number of outputs from the network eta -- learning rate lmbda -- regularization parameter loss -- loss function metrics -- metrics hidden_act -- activation function used... | 2 | stack_v2_sparse_classes_30k_train_009709 | Implement the Python class `Keras` described below.
Class description:
Implement the Keras class.
Method signatures and docstrings:
- def __init__(self, neurons, n_outputs, eta, lmbda, loss, metrics, hidden_act, output_act): Set up neural network using keras. Keyword arguments: neurons -- list with number of neurons ... | Implement the Python class `Keras` described below.
Class description:
Implement the Keras class.
Method signatures and docstrings:
- def __init__(self, neurons, n_outputs, eta, lmbda, loss, metrics, hidden_act, output_act): Set up neural network using keras. Keyword arguments: neurons -- list with number of neurons ... | f9fbe289ebe1e90dddf288a6e713cabc8d02b1f0 | <|skeleton|>
class Keras:
def __init__(self, neurons, n_outputs, eta, lmbda, loss, metrics, hidden_act, output_act):
"""Set up neural network using keras. Keyword arguments: neurons -- list with number of neurons in each hidden layer n_outputs -- number of outputs from the network eta -- learning rate lmbd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Keras:
def __init__(self, neurons, n_outputs, eta, lmbda, loss, metrics, hidden_act, output_act):
"""Set up neural network using keras. Keyword arguments: neurons -- list with number of neurons in each hidden layer n_outputs -- number of outputs from the network eta -- learning rate lmbda -- regulariz... | the_stack_v2_python_sparse | Project2/source/NN_keras.py | elinfi/FYS-STK4155 | train | 1 | |
ace1220af10d448fb80daf0b5e13b604368a01ef | [
"self.nRows = nRows\nself.nCols = nCols\nself.startSize = startSize\nself.sections = self.setup(self.nRows, self.nCols)\nfor _ in range(self.startSize):\n self.sections[0][0].individuals.append(ind(myLandscape=self, myCell=self.sections[0][0]))",
"land = []\nfor rowNum in range(nRows):\n row = []\n for c... | <|body_start_0|>
self.nRows = nRows
self.nCols = nCols
self.startSize = startSize
self.sections = self.setup(self.nRows, self.nCols)
for _ in range(self.startSize):
self.sections[0][0].individuals.append(ind(myLandscape=self, myCell=self.sections[0][0]))
<|end_body_0|... | This class holds all individuals across the landscape | landscape | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class landscape:
"""This class holds all individuals across the landscape"""
def __init__(self, nRows=5, nCols=5, startSize=50):
"""Creates a new grid-based with the number of rows, columns, and starting population size specified by the user."""
<|body_0|>
def setup(self, nRow... | stack_v2_sparse_classes_75kplus_train_003819 | 6,828 | no_license | [
{
"docstring": "Creates a new grid-based with the number of rows, columns, and starting population size specified by the user.",
"name": "__init__",
"signature": "def __init__(self, nRows=5, nCols=5, startSize=50)"
},
{
"docstring": "Sets up the landscape as a list of lists containing cells.",
... | 3 | stack_v2_sparse_classes_30k_train_003376 | Implement the Python class `landscape` described below.
Class description:
This class holds all individuals across the landscape
Method signatures and docstrings:
- def __init__(self, nRows=5, nCols=5, startSize=50): Creates a new grid-based with the number of rows, columns, and starting population size specified by ... | Implement the Python class `landscape` described below.
Class description:
This class holds all individuals across the landscape
Method signatures and docstrings:
- def __init__(self, nRows=5, nCols=5, startSize=50): Creates a new grid-based with the number of rows, columns, and starting population size specified by ... | fe30fac5c0f6632b8cc0ea2390738250d9508d11 | <|skeleton|>
class landscape:
"""This class holds all individuals across the landscape"""
def __init__(self, nRows=5, nCols=5, startSize=50):
"""Creates a new grid-based with the number of rows, columns, and starting population size specified by the user."""
<|body_0|>
def setup(self, nRow... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class landscape:
"""This class holds all individuals across the landscape"""
def __init__(self, nRows=5, nCols=5, startSize=50):
"""Creates a new grid-based with the number of rows, columns, and starting population size specified by the user."""
self.nRows = nRows
self.nCols = nCols
... | the_stack_v2_python_sparse | demographySim_orig.py | IntroToCompBioLSU/week10 | train | 0 |
2df042a3935a36de50235b743dbd0d6866562726 | [
"if self.memo.get((first, second), None) is None:\n if m.get(first + second, -1) == -1:\n res = 0\n else:\n res = 1 + self.recursion(second, first + second, m)\n self.memo[first, second] = res\nreturn self.memo[first, second]",
"self.memo = {}\nret = 0\nm = {}\nfor i, num in enumerate(A):\n... | <|body_start_0|>
if self.memo.get((first, second), None) is None:
if m.get(first + second, -1) == -1:
res = 0
else:
res = 1 + self.recursion(second, first + second, m)
self.memo[first, second] = res
return self.memo[first, second]
<|end... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recursion(self, first, second, m):
""":param first: :param second: :type m: dict :return:"""
<|body_0|>
def lenLongestFibSubseq1(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
def lenLongestFibSubseq(self, A):
""":type A:... | stack_v2_sparse_classes_75kplus_train_003820 | 10,775 | no_license | [
{
"docstring": ":param first: :param second: :type m: dict :return:",
"name": "recursion",
"signature": "def recursion(self, first, second, m)"
},
{
"docstring": ":type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq1",
"signature": "def lenLongestFibSubseq1(self, A)"
},
{
... | 3 | stack_v2_sparse_classes_30k_val_002145 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursion(self, first, second, m): :param first: :param second: :type m: dict :return:
- def lenLongestFibSubseq1(self, A): :type A: List[int] :rtype: int
- def lenLongestFib... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursion(self, first, second, m): :param first: :param second: :type m: dict :return:
- def lenLongestFibSubseq1(self, A): :type A: List[int] :rtype: int
- def lenLongestFib... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def recursion(self, first, second, m):
""":param first: :param second: :type m: dict :return:"""
<|body_0|>
def lenLongestFibSubseq1(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
def lenLongestFibSubseq(self, A):
""":type A:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def recursion(self, first, second, m):
""":param first: :param second: :type m: dict :return:"""
if self.memo.get((first, second), None) is None:
if m.get(first + second, -1) == -1:
res = 0
else:
res = 1 + self.recursion(second,... | the_stack_v2_python_sparse | python/leetcode/873_Length_of_Longest_Fibonacci_Subsequence.py | bobcaoge/my-code | train | 0 | |
34553c79d3ced37c5e55a96fe3eccb5b18c29ec5 | [
"self.Kd = Kd\nself.Kp = Kp\nself.Ki = Ki\nself.setpoint = setpoint\nself.output_limits = output_limits\nself.integral = 0\nself.last_error = 0\nself.last_value = 0\npass",
"self.integral = 0\nself.last_error = 0\nself.last_value = 0",
"error = self.setpoint - measurement\nderivative = error - self.last_error\n... | <|body_start_0|>
self.Kd = Kd
self.Kp = Kp
self.Ki = Ki
self.setpoint = setpoint
self.output_limits = output_limits
self.integral = 0
self.last_error = 0
self.last_value = 0
pass
<|end_body_0|>
<|body_start_1|>
self.integral = 0
se... | Useful reusable PID class | PID | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PID:
"""Useful reusable PID class"""
def __init__(self, Kd: float, Kp: float, Ki: float, setpoint=0.0, output_limits=None):
"""Initializes the PID controller :param Kd: The derivative portion of the PID controller :param Kp: The proportial portion of the PID controller :param Ki: The... | stack_v2_sparse_classes_75kplus_train_003821 | 1,854 | permissive | [
{
"docstring": "Initializes the PID controller :param Kd: The derivative portion of the PID controller :param Kp: The proportial portion of the PID controller :param Ki: The integral portion of the PID controller :param setpoint: The point that the PID is set to :param output_limits: Max and minimum setting for... | 3 | stack_v2_sparse_classes_30k_train_023881 | Implement the Python class `PID` described below.
Class description:
Useful reusable PID class
Method signatures and docstrings:
- def __init__(self, Kd: float, Kp: float, Ki: float, setpoint=0.0, output_limits=None): Initializes the PID controller :param Kd: The derivative portion of the PID controller :param Kp: Th... | Implement the Python class `PID` described below.
Class description:
Useful reusable PID class
Method signatures and docstrings:
- def __init__(self, Kd: float, Kp: float, Ki: float, setpoint=0.0, output_limits=None): Initializes the PID controller :param Kd: The derivative portion of the PID controller :param Kp: Th... | 5509c07931d85583b0d99606f66817afb6fbcbe1 | <|skeleton|>
class PID:
"""Useful reusable PID class"""
def __init__(self, Kd: float, Kp: float, Ki: float, setpoint=0.0, output_limits=None):
"""Initializes the PID controller :param Kd: The derivative portion of the PID controller :param Kp: The proportial portion of the PID controller :param Ki: The... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PID:
"""Useful reusable PID class"""
def __init__(self, Kd: float, Kp: float, Ki: float, setpoint=0.0, output_limits=None):
"""Initializes the PID controller :param Kd: The derivative portion of the PID controller :param Kp: The proportial portion of the PID controller :param Ki: The integral por... | the_stack_v2_python_sparse | soccer_common/src/soccer_common/pid.py | utra-robosoccer/soccerbot | train | 118 |
9e68a5f8d37cf8608b5dce569eafef6dd86496ad | [
"super().__init__()\ninputs = tf.keras.Input(shape=(state_dim,))\nself.embedding_dim = embedding_dim\nself.num_distributions = num_distributions\nassert not num_distributions or embedding_dim % num_distributions == 0\ndistribution_dim = (2 if not num_distributions else 1) * self.embedding_dim\nself.embedder = creat... | <|body_start_0|>
super().__init__()
inputs = tf.keras.Input(shape=(state_dim,))
self.embedding_dim = embedding_dim
self.num_distributions = num_distributions
assert not num_distributions or embedding_dim % num_distributions == 0
distribution_dim = (2 if not num_distributi... | A stochastic embed network. | StochasticEmbedNet | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StochasticEmbedNet:
"""A stochastic embed network."""
def __init__(self, state_dim, embedding_dim=256, hidden_dims=(256, 256), num_distributions=None, logvar_min=-4.0, logvar_max=15.0):
"""Creates a neural net. Args: state_dim: State size. embedding_dim: Embedding size. hidden_dims: ... | stack_v2_sparse_classes_75kplus_train_003822 | 26,038 | permissive | [
{
"docstring": "Creates a neural net. Args: state_dim: State size. embedding_dim: Embedding size. hidden_dims: List of hidden dimensions. num_distributions: Number of categorical distributions for discrete embedding. logvar_min: Minimum allowed logvar. logvar_max: Maximum allowed logvar.",
"name": "__init__... | 2 | null | Implement the Python class `StochasticEmbedNet` described below.
Class description:
A stochastic embed network.
Method signatures and docstrings:
- def __init__(self, state_dim, embedding_dim=256, hidden_dims=(256, 256), num_distributions=None, logvar_min=-4.0, logvar_max=15.0): Creates a neural net. Args: state_dim:... | Implement the Python class `StochasticEmbedNet` described below.
Class description:
A stochastic embed network.
Method signatures and docstrings:
- def __init__(self, state_dim, embedding_dim=256, hidden_dims=(256, 256), num_distributions=None, logvar_min=-4.0, logvar_max=15.0): Creates a neural net. Args: state_dim:... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class StochasticEmbedNet:
"""A stochastic embed network."""
def __init__(self, state_dim, embedding_dim=256, hidden_dims=(256, 256), num_distributions=None, logvar_min=-4.0, logvar_max=15.0):
"""Creates a neural net. Args: state_dim: State size. embedding_dim: Embedding size. hidden_dims: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StochasticEmbedNet:
"""A stochastic embed network."""
def __init__(self, state_dim, embedding_dim=256, hidden_dims=(256, 256), num_distributions=None, logvar_min=-4.0, logvar_max=15.0):
"""Creates a neural net. Args: state_dim: State size. embedding_dim: Embedding size. hidden_dims: List of hidde... | the_stack_v2_python_sparse | representation_batch_rl/representation_batch_rl/tf_utils.py | Jimmy-INL/google-research | train | 1 |
06526696370a81b601f219fb597e4e3a8edaa089 | [
"length = len(nums)\nsubsets = []\nnums.sort()\n\ndef dfs(index, subset):\n \"\"\"\n :type index: int\n :type subset: List[int]\n :rtype void\n \"\"\"\n subsets.append(subset)\n if index >= length:\n return\n for i in range(index, length):\n if i... | <|body_start_0|>
length = len(nums)
subsets = []
nums.sort()
def dfs(index, subset):
"""
:type index: int
:type subset: List[int]
:rtype void
"""
subsets.append(subset)
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
"""Implement with dfs :type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup(self, nums):
"""Implement with iteration. :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_003823 | 1,872 | no_license | [
{
"docstring": "Implement with dfs :type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums)"
},
{
"docstring": "Implement with iteration. :type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_044242 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): Implement with dfs :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup(self, nums): Implement with iteration. :type nums: List[int]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): Implement with dfs :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup(self, nums): Implement with iteration. :type nums: List[int]... | 052bd7915257679877dbe55b60ed1abb7528eaa2 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
"""Implement with dfs :type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup(self, nums):
"""Implement with iteration. :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def subsetsWithDup(self, nums):
"""Implement with dfs :type nums: List[int] :rtype: List[List[int]]"""
length = len(nums)
subsets = []
nums.sort()
def dfs(index, subset):
"""
:type index: int
:type subset: L... | the_stack_v2_python_sparse | python_solution/Backtracking/90_SubsetsII.py | Dimen61/leetcode | train | 4 | |
862c8250b34df1a532ee8a8bd5b21dfb8afda9e9 | [
"super().__init__()\nself.conv1 = SuperGATConv(in_dim, hidden_dim, num_heads, attn_type, neg_sample_ratio, feat_drop, attn_drop, negative_slope, F.elu)\nself.conv2 = SuperGATConv(num_heads * hidden_dim, out_dim, num_heads, attn_type, neg_sample_ratio, 0, attn_drop, negative_slope)",
"h = self.conv1(g, feat).flatt... | <|body_start_0|>
super().__init__()
self.conv1 = SuperGATConv(in_dim, hidden_dim, num_heads, attn_type, neg_sample_ratio, feat_drop, attn_drop, negative_slope, F.elu)
self.conv2 = SuperGATConv(num_heads * hidden_dim, out_dim, num_heads, attn_type, neg_sample_ratio, 0, attn_drop, negative_slope)
... | SuperGAT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperGAT:
def __init__(self, in_dim, hidden_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2):
"""两层SuperGAT模型 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param ... | stack_v2_sparse_classes_75kplus_train_003824 | 5,266 | no_license | [
{
"docstring": "两层SuperGAT模型 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param attn_type: str 注意力类型,可选择GO, DP, SD和MX :param neg_sample_ratio: float, optional 负样本边数量占正样本边数量的比例,默认0.5 :param feat_drop: float, optional 输入特征Dropout概率,默认为0 :param at... | 2 | stack_v2_sparse_classes_30k_val_001920 | Implement the Python class `SuperGAT` described below.
Class description:
Implement the SuperGAT class.
Method signatures and docstrings:
- def __init__(self, in_dim, hidden_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2): 两层SuperGAT模型 :param in_dim: int 输入特... | Implement the Python class `SuperGAT` described below.
Class description:
Implement the SuperGAT class.
Method signatures and docstrings:
- def __init__(self, in_dim, hidden_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2): 两层SuperGAT模型 :param in_dim: int 输入特... | b40071dc9f9fb20f081f4ed4944a7b65de919c18 | <|skeleton|>
class SuperGAT:
def __init__(self, in_dim, hidden_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2):
"""两层SuperGAT模型 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SuperGAT:
def __init__(self, in_dim, hidden_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2):
"""两层SuperGAT模型 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param attn_type: str... | the_stack_v2_python_sparse | gnn/supergat/model.py | deepdumbo/pytorch-tutorial-1 | train | 0 | |
4ab0af61520e83e07b22e6e422f5d74084912f33 | [
"entity = {'uuid': 'uuid', 'owner': '001'}\nprincipal = Principal({'roles': {'ROLE_ADMIN'}})\nprincipal.checkVisibility(entity, 'entity', 'code')",
"entity = {'uuid': 'uuid', 'owner': '001'}\nprincipal = Principal({'organizationId': '001', 'roles': {'ROLE_ENTITY_USER'}})\nprincipal.checkVisibility(entity, 'entity... | <|body_start_0|>
entity = {'uuid': 'uuid', 'owner': '001'}
principal = Principal({'roles': {'ROLE_ADMIN'}})
principal.checkVisibility(entity, 'entity', 'code')
<|end_body_0|>
<|body_start_1|>
entity = {'uuid': 'uuid', 'owner': '001'}
principal = Principal({'organizationId': '001... | PrincipalCheckVisibility | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrincipalCheckVisibility:
def testReturnsForAdmin(self):
"""Principal.checkVisibility() should return if principal is admin"""
<|body_0|>
def testReturnsForOwner(self):
"""Principal.checkVisibility() should return if principal is owner"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_003825 | 7,657 | no_license | [
{
"docstring": "Principal.checkVisibility() should return if principal is admin",
"name": "testReturnsForAdmin",
"signature": "def testReturnsForAdmin(self)"
},
{
"docstring": "Principal.checkVisibility() should return if principal is owner",
"name": "testReturnsForOwner",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_010556 | Implement the Python class `PrincipalCheckVisibility` described below.
Class description:
Implement the PrincipalCheckVisibility class.
Method signatures and docstrings:
- def testReturnsForAdmin(self): Principal.checkVisibility() should return if principal is admin
- def testReturnsForOwner(self): Principal.checkVis... | Implement the Python class `PrincipalCheckVisibility` described below.
Class description:
Implement the PrincipalCheckVisibility class.
Method signatures and docstrings:
- def testReturnsForAdmin(self): Principal.checkVisibility() should return if principal is admin
- def testReturnsForOwner(self): Principal.checkVis... | 70ac15f203af297b354ad89cfc38cf5572b3a19e | <|skeleton|>
class PrincipalCheckVisibility:
def testReturnsForAdmin(self):
"""Principal.checkVisibility() should return if principal is admin"""
<|body_0|>
def testReturnsForOwner(self):
"""Principal.checkVisibility() should return if principal is owner"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrincipalCheckVisibility:
def testReturnsForAdmin(self):
"""Principal.checkVisibility() should return if principal is admin"""
entity = {'uuid': 'uuid', 'owner': '001'}
principal = Principal({'roles': {'ROLE_ADMIN'}})
principal.checkVisibility(entity, 'entity', 'code')
def... | the_stack_v2_python_sparse | spec/unit/commons/principal.py | Neosperience/starter-serverless-python | train | 2 | |
94acb3fa4e7c2a22ed9d7abf6bb916c569c1d2df | [
"self.trackers = []\nself._id = 1\nself.max_age = kwargs.get('max_age', 3)\nself.cost_fn = kwargs.get('cost_fn', EuclideanDistance())\nself.cost_fn_min = kwargs.get('cost_fn_min', 0.0)\nself.cost_fn_max = kwargs.get('cost_fn_max', 10.0)",
"for trk in self.trackers:\n trk.predict()\nmatch_indices = matching(sel... | <|body_start_0|>
self.trackers = []
self._id = 1
self.max_age = kwargs.get('max_age', 3)
self.cost_fn = kwargs.get('cost_fn', EuclideanDistance())
self.cost_fn_min = kwargs.get('cost_fn_min', 0.0)
self.cost_fn_max = kwargs.get('cost_fn_max', 10.0)
<|end_body_0|>
<|body_s... | A simple multi-sensor multi-object tracking-fusion algorithm | SensorTracking | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensorTracking:
"""A simple multi-sensor multi-object tracking-fusion algorithm"""
def __init__(self, **kwargs):
"""Constructor parameters: - max_age: maximum number of frames a trackedobject can persist without being reassociated. default=3 - cost_fn: function or functor to compute ... | stack_v2_sparse_classes_75kplus_train_003826 | 9,887 | permissive | [
{
"docstring": "Constructor parameters: - max_age: maximum number of frames a trackedobject can persist without being reassociated. default=3 - cost_fn: function or functor to compute cost between two trackedobject. default=EuclideanDistance() - cost_fn_min: minimum value for the cost function to consider a mat... | 2 | stack_v2_sparse_classes_30k_train_011064 | Implement the Python class `SensorTracking` described below.
Class description:
A simple multi-sensor multi-object tracking-fusion algorithm
Method signatures and docstrings:
- def __init__(self, **kwargs): Constructor parameters: - max_age: maximum number of frames a trackedobject can persist without being reassocia... | Implement the Python class `SensorTracking` described below.
Class description:
A simple multi-sensor multi-object tracking-fusion algorithm
Method signatures and docstrings:
- def __init__(self, **kwargs): Constructor parameters: - max_age: maximum number of frames a trackedobject can persist without being reassocia... | d510f2ff779d5af508e83d8a6dc6e8de4ffe9995 | <|skeleton|>
class SensorTracking:
"""A simple multi-sensor multi-object tracking-fusion algorithm"""
def __init__(self, **kwargs):
"""Constructor parameters: - max_age: maximum number of frames a trackedobject can persist without being reassociated. default=3 - cost_fn: function or functor to compute ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SensorTracking:
"""A simple multi-sensor multi-object tracking-fusion algorithm"""
def __init__(self, **kwargs):
"""Constructor parameters: - max_age: maximum number of frames a trackedobject can persist without being reassociated. default=3 - cost_fn: function or functor to compute cost between ... | the_stack_v2_python_sparse | packages/asv_perception_tracking/src/smstf/tracking.py | MingiJeong/asv_perception | train | 0 |
d874df855c6ca80dad53d6eab17d883ffec24976 | [
"if len(json.loads(self.recommended_papers)) == RECOMMENDED_MAX_LENTH:\n return True\nelse:\n return False",
"papers_list = json.loads(self.recommended_papers)[RECOMMENDED_DAY_LENTH:]\nself.recommended_papers = json.dumps(papers_list)\nreturn None",
"papers_list = json.loads(self.recommended_papers)\npape... | <|body_start_0|>
if len(json.loads(self.recommended_papers)) == RECOMMENDED_MAX_LENTH:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
papers_list = json.loads(self.recommended_papers)[RECOMMENDED_DAY_LENTH:]
self.recommended_papers = json.dumps(pa... | 用户推荐类 | Recommended | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Recommended:
"""用户推荐类"""
def is_full(self):
"""返回推荐文章是否满队列"""
<|body_0|>
def clear(self):
"""在满队列情况下调用,压出最前每天的数量"""
<|body_1|>
def add(self, article_id):
"""为推荐队列添加文章,不判断是否超出长度 必须在外部清出空间"""
<|body_2|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_003827 | 2,640 | no_license | [
{
"docstring": "返回推荐文章是否满队列",
"name": "is_full",
"signature": "def is_full(self)"
},
{
"docstring": "在满队列情况下调用,压出最前每天的数量",
"name": "clear",
"signature": "def clear(self)"
},
{
"docstring": "为推荐队列添加文章,不判断是否超出长度 必须在外部清出空间",
"name": "add",
"signature": "def add(self, article... | 3 | stack_v2_sparse_classes_30k_train_012710 | Implement the Python class `Recommended` described below.
Class description:
用户推荐类
Method signatures and docstrings:
- def is_full(self): 返回推荐文章是否满队列
- def clear(self): 在满队列情况下调用,压出最前每天的数量
- def add(self, article_id): 为推荐队列添加文章,不判断是否超出长度 必须在外部清出空间 | Implement the Python class `Recommended` described below.
Class description:
用户推荐类
Method signatures and docstrings:
- def is_full(self): 返回推荐文章是否满队列
- def clear(self): 在满队列情况下调用,压出最前每天的数量
- def add(self, article_id): 为推荐队列添加文章,不判断是否超出长度 必须在外部清出空间
<|skeleton|>
class Recommended:
"""用户推荐类"""
def is_full(self... | d71140d4e6a1bfd4cd189dfb8ef46335b038ecde | <|skeleton|>
class Recommended:
"""用户推荐类"""
def is_full(self):
"""返回推荐文章是否满队列"""
<|body_0|>
def clear(self):
"""在满队列情况下调用,压出最前每天的数量"""
<|body_1|>
def add(self, article_id):
"""为推荐队列添加文章,不判断是否超出长度 必须在外部清出空间"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Recommended:
"""用户推荐类"""
def is_full(self):
"""返回推荐文章是否满队列"""
if len(json.loads(self.recommended_papers)) == RECOMMENDED_MAX_LENTH:
return True
else:
return False
def clear(self):
"""在满队列情况下调用,压出最前每天的数量"""
papers_list = json.loads(self.... | the_stack_v2_python_sparse | papers/models.py | Yiwozai/academiheadlines | train | 0 |
138c9d82c6be1895af94b7a9bff702e215b844fc | [
"self.project_parameters = project_parameters\nself.predict_object = Predict(project_parameters=project_parameters)\nself.data_path = None\nself.window = Tk()\nself.window.geometry('{}x{}'.format(self.window.winfo_screenwidth(), self.window.winfo_screenheight()))\nself.window.title('Demo GUI')\nself.load_image_butt... | <|body_start_0|>
self.project_parameters = project_parameters
self.predict_object = Predict(project_parameters=project_parameters)
self.data_path = None
self.window = Tk()
self.window.geometry('{}x{}'.format(self.window.winfo_screenwidth(), self.window.winfo_screenheight()))
... | Constructs a ProjectParameters class to store the parameters. | GUI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GUI:
"""Constructs a ProjectParameters class to store the parameters."""
def __init__(self, project_parameters):
"""Initialize the class. Args: project_parameters (argparse.Namespace): the parameters for this project."""
<|body_0|>
def _resize_image(self, image):
... | stack_v2_sparse_classes_75kplus_train_003828 | 3,953 | permissive | [
{
"docstring": "Initialize the class. Args: project_parameters (argparse.Namespace): the parameters for this project.",
"name": "__init__",
"signature": "def __init__(self, project_parameters)"
},
{
"docstring": "Resize the given image . Args: image (PIL.PngImagePlugin.PngImageFile): the image. ... | 5 | stack_v2_sparse_classes_30k_test_001266 | Implement the Python class `GUI` described below.
Class description:
Constructs a ProjectParameters class to store the parameters.
Method signatures and docstrings:
- def __init__(self, project_parameters): Initialize the class. Args: project_parameters (argparse.Namespace): the parameters for this project.
- def _re... | Implement the Python class `GUI` described below.
Class description:
Constructs a ProjectParameters class to store the parameters.
Method signatures and docstrings:
- def __init__(self, project_parameters): Initialize the class. Args: project_parameters (argparse.Namespace): the parameters for this project.
- def _re... | bdeee8efee6e172cfb1b9372ff52e85b44fa80f6 | <|skeleton|>
class GUI:
"""Constructs a ProjectParameters class to store the parameters."""
def __init__(self, project_parameters):
"""Initialize the class. Args: project_parameters (argparse.Namespace): the parameters for this project."""
<|body_0|>
def _resize_image(self, image):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GUI:
"""Constructs a ProjectParameters class to store the parameters."""
def __init__(self, project_parameters):
"""Initialize the class. Args: project_parameters (argparse.Namespace): the parameters for this project."""
self.project_parameters = project_parameters
self.predict_ob... | the_stack_v2_python_sparse | src/gui.py | fastyangmh/ImageClassificationArchive | train | 0 |
94558eea3b8d41d41e194423cf37729a16bdff7a | [
"if not nums:\n return -1\nl, r = (0, len(nums) - 1)\nwhile l < r - 1:\n mid = (l + r) / 2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n if nums[mid] < nums[r]:\n r = mid\n elif target < nums[l]:\n l = mid\n else:\n r = m... | <|body_start_0|>
if not nums:
return -1
l, r = (0, len(nums) - 1)
while l < r - 1:
mid = (l + r) / 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
if nums[mid] < nums[r]:
r = mid
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int 自己写的代码虽然很烂,但是速度beats 100. 不知道为何"""
<|body_0|>
def search(self, nums, target):
"""借鉴别人的代码。速度反而慢了。设计l < r-1是一个trick,可以让r l = mid, 然后跳出while。单独处理l r相邻的情况 The idea is that wh... | stack_v2_sparse_classes_75kplus_train_003829 | 2,532 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int 自己写的代码虽然很烂,但是速度beats 100. 不知道为何",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": "借鉴别人的代码。速度反而慢了。设计l < r-1是一个trick,可以让r l = mid, 然后跳出while。单独处理l r相邻的情况 The idea is that when rotating the array,... | 2 | stack_v2_sparse_classes_30k_train_012338 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int 自己写的代码虽然很烂,但是速度beats 100. 不知道为何
- def search(self, nums, target): 借鉴别人的代码。速度反而慢了。设计l < r-1是一个t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int 自己写的代码虽然很烂,但是速度beats 100. 不知道为何
- def search(self, nums, target): 借鉴别人的代码。速度反而慢了。设计l < r-1是一个t... | 22794e5e80f534c41ff81eb40072acaa1346a75c | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int 自己写的代码虽然很烂,但是速度beats 100. 不知道为何"""
<|body_0|>
def search(self, nums, target):
"""借鉴别人的代码。速度反而慢了。设计l < r-1是一个trick,可以让r l = mid, 然后跳出while。单独处理l r相邻的情况 The idea is that wh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int 自己写的代码虽然很烂,但是速度beats 100. 不知道为何"""
if not nums:
return -1
l, r = (0, len(nums) - 1)
while l < r - 1:
mid = (l + r) / 2
if nums[mid] == target:
... | the_stack_v2_python_sparse | 033.py | huosan0123/leetcode-py | train | 0 | |
659a1a455907f377e4199b9bb76eeb776649e65a | [
"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... | 定义服务 在服务中定义接口(指定请求和响应应类型) | TestServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestServicer:
"""定义服务 在服务中定义接口(指定请求和响应应类型)"""
def UnaryRPCs(self, request, context):
"""一元RPC示例"""
<|body_0|>
def ServerStreamingRPCs(self, request, context):
"""服务端流式RPC示例"""
<|body_1|>
def ClientStreamingRPCs(self, request_iterator, context):
... | stack_v2_sparse_classes_75kplus_train_003830 | 3,552 | no_license | [
{
"docstring": "一元RPC示例",
"name": "UnaryRPCs",
"signature": "def UnaryRPCs(self, request, context)"
},
{
"docstring": "服务端流式RPC示例",
"name": "ServerStreamingRPCs",
"signature": "def ServerStreamingRPCs(self, request, context)"
},
{
"docstring": "客户端流式RPC示例",
"name": "ClientStr... | 4 | stack_v2_sparse_classes_30k_train_046991 | Implement the Python class `TestServicer` described below.
Class description:
定义服务 在服务中定义接口(指定请求和响应应类型)
Method signatures and docstrings:
- def UnaryRPCs(self, request, context): 一元RPC示例
- def ServerStreamingRPCs(self, request, context): 服务端流式RPC示例
- def ClientStreamingRPCs(self, request_iterator, context): 客户端流式RPC示... | Implement the Python class `TestServicer` described below.
Class description:
定义服务 在服务中定义接口(指定请求和响应应类型)
Method signatures and docstrings:
- def UnaryRPCs(self, request, context): 一元RPC示例
- def ServerStreamingRPCs(self, request, context): 服务端流式RPC示例
- def ClientStreamingRPCs(self, request_iterator, context): 客户端流式RPC示... | 361868501c49cb0c5769b20f17688c81ef3f8aa8 | <|skeleton|>
class TestServicer:
"""定义服务 在服务中定义接口(指定请求和响应应类型)"""
def UnaryRPCs(self, request, context):
"""一元RPC示例"""
<|body_0|>
def ServerStreamingRPCs(self, request, context):
"""服务端流式RPC示例"""
<|body_1|>
def ClientStreamingRPCs(self, request_iterator, context):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestServicer:
"""定义服务 在服务中定义接口(指定请求和响应应类型)"""
def UnaryRPCs(self, request, context):
"""一元RPC示例"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ServerStreamingRP... | the_stack_v2_python_sparse | gRPC_demo/interface/test_pb2_grpc.py | Octopus-Ball/Demos | train | 0 |
bb7adfec0f2f54be78d0bbc11bde6923500b2cb0 | [
"if page_url is None or html_cont is None:\n return\nsoup = BeautifulSoup(html_cont, 'lxml', from_encoding='utf-8')\nnew_url = self._get_new_url(page_url, soup)\nnew_data = self._get_new_data(page_url, soup)\nreturn (new_url, new_data)",
"new_urls = set()\nlinks = soup.find_all('a', href=re.compile('/view/\\\\... | <|body_start_0|>
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'lxml', from_encoding='utf-8')
new_url = self._get_new_url(page_url, soup)
new_data = self._get_new_data(page_url, soup)
return (new_url, new_data)
<|end_body_0|>
<|body... | HtmlParse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParse:
def parse(self, page_url, html_cont):
"""解析页面内容,抽取URL和数据 :param page_url: 下面页面的url地址 :param html_cont: 下载页面的内容 :return:"""
<|body_0|>
def _get_new_url(self, page_url, soup):
"""爬取新的URL地址 :param page_url: :param soup: :return:"""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus_train_003831 | 1,601 | no_license | [
{
"docstring": "解析页面内容,抽取URL和数据 :param page_url: 下面页面的url地址 :param html_cont: 下载页面的内容 :return:",
"name": "parse",
"signature": "def parse(self, page_url, html_cont)"
},
{
"docstring": "爬取新的URL地址 :param page_url: :param soup: :return:",
"name": "_get_new_url",
"signature": "def _get_new_u... | 3 | null | Implement the Python class `HtmlParse` described below.
Class description:
Implement the HtmlParse class.
Method signatures and docstrings:
- def parse(self, page_url, html_cont): 解析页面内容,抽取URL和数据 :param page_url: 下面页面的url地址 :param html_cont: 下载页面的内容 :return:
- def _get_new_url(self, page_url, soup): 爬取新的URL地址 :param ... | Implement the Python class `HtmlParse` described below.
Class description:
Implement the HtmlParse class.
Method signatures and docstrings:
- def parse(self, page_url, html_cont): 解析页面内容,抽取URL和数据 :param page_url: 下面页面的url地址 :param html_cont: 下载页面的内容 :return:
- def _get_new_url(self, page_url, soup): 爬取新的URL地址 :param ... | 125afc91863e44868812ad16dbe03e2e4ede4038 | <|skeleton|>
class HtmlParse:
def parse(self, page_url, html_cont):
"""解析页面内容,抽取URL和数据 :param page_url: 下面页面的url地址 :param html_cont: 下载页面的内容 :return:"""
<|body_0|>
def _get_new_url(self, page_url, soup):
"""爬取新的URL地址 :param page_url: :param soup: :return:"""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HtmlParse:
def parse(self, page_url, html_cont):
"""解析页面内容,抽取URL和数据 :param page_url: 下面页面的url地址 :param html_cont: 下载页面的内容 :return:"""
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'lxml', from_encoding='utf-8')
new_url = self._get_... | the_stack_v2_python_sparse | 13-exec/05-scrapy/v01/HtmlParse.py | xrr314/python | train | 0 | |
9e69f1f4524c896ea7ca9842b32f0283c067e446 | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.select_one('h1.entry-title').text.strip()\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_cover = self.absolute_url(soup.select_one('div.elementor-image img')['data-src'])\nlogger.info('Novel co... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('h1.entry-title').text.strip()
logger.info('Novel title: %s', self.novel_title)
self.novel_cover = self.absolute_url(soup.select_one('div.elementor... | ReincarnationPalace | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReincarnationPalace:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_003832 | 2,691 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format.",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, c... | 2 | stack_v2_sparse_classes_30k_train_006901 | Implement the Python class `ReincarnationPalace` described below.
Class description:
Implement the ReincarnationPalace class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as cle... | Implement the Python class `ReincarnationPalace` described below.
Class description:
Implement the ReincarnationPalace class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as cle... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class ReincarnationPalace:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReincarnationPalace:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('h1.entry-title').text.strip()
logger.info('Novel title: %s', self... | the_stack_v2_python_sparse | lncrawl/sources/reincarnationpalace.py | NNTin/lightnovel-crawler | train | 2 | |
7947c74e9cb92355ede23c3756bea23ebb929baa | [
"self.condition_config = condition_config\nself.table_config = table_config\nself.extra_select = extra_select",
"values = []\nfor item in self.table_config:\n if item['q']:\n values.append(item['q'])\nreturn values",
"con_str = request.GET.get('condition', None)\nif not con_str:\n con_dict = {}\nel... | <|body_start_0|>
self.condition_config = condition_config
self.table_config = table_config
self.extra_select = extra_select
<|end_body_0|>
<|body_start_1|>
values = []
for item in self.table_config:
if item['q']:
values.append(item['q'])
retur... | BaseServiceList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseServiceList:
def __init__(self, condition_config, table_config, extra_select):
""":param condition_config: 查询条件配置 :param table_config: 表格配置 { 'q': 'title', # 用于数据库查询的字段,即Model.Tb.objects.xxx.values(*['v',]), None则表示不获取相应的数据库列 'title': '标题', # table表格显示的列名 'display': 0 # 实现在表格中显示 0,不显... | stack_v2_sparse_classes_75kplus_train_003833 | 2,147 | no_license | [
{
"docstring": ":param condition_config: 查询条件配置 :param table_config: 表格配置 { 'q': 'title', # 用于数据库查询的字段,即Model.Tb.objects.xxx.values(*['v',]), None则表示不获取相应的数据库列 'title': '标题', # table表格显示的列名 'display': 0 # 实现在表格中显示 0,不显示;1显示 'text': {'content': \"{id}\", 'kwargs': {'id': '@id'}}, # 表格的每一个td中显示的内容,一个@表示获取数据库查询字段,... | 3 | stack_v2_sparse_classes_30k_train_029559 | Implement the Python class `BaseServiceList` described below.
Class description:
Implement the BaseServiceList class.
Method signatures and docstrings:
- def __init__(self, condition_config, table_config, extra_select): :param condition_config: 查询条件配置 :param table_config: 表格配置 { 'q': 'title', # 用于数据库查询的字段,即Model.Tb.o... | Implement the Python class `BaseServiceList` described below.
Class description:
Implement the BaseServiceList class.
Method signatures and docstrings:
- def __init__(self, condition_config, table_config, extra_select): :param condition_config: 查询条件配置 :param table_config: 表格配置 { 'q': 'title', # 用于数据库查询的字段,即Model.Tb.o... | b44ad05f3341b18b2d8c3c64d47145c07f5ade51 | <|skeleton|>
class BaseServiceList:
def __init__(self, condition_config, table_config, extra_select):
""":param condition_config: 查询条件配置 :param table_config: 表格配置 { 'q': 'title', # 用于数据库查询的字段,即Model.Tb.objects.xxx.values(*['v',]), None则表示不获取相应的数据库列 'title': '标题', # table表格显示的列名 'display': 0 # 实现在表格中显示 0,不显... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseServiceList:
def __init__(self, condition_config, table_config, extra_select):
""":param condition_config: 查询条件配置 :param table_config: 表格配置 { 'q': 'title', # 用于数据库查询的字段,即Model.Tb.objects.xxx.values(*['v',]), None则表示不获取相应的数据库列 'title': '标题', # table表格显示的列名 'display': 0 # 实现在表格中显示 0,不显示;1显示 'text': ... | the_stack_v2_python_sparse | cmdb_web/service/base.py | jcdiy0601/EasyCmdb | train | 0 | |
c7da6610683f49360cc103496c8615a18111f96b | [
"if api_test_result_id == '':\n return response_failed({'status': 10102, 'message': 'api_test_task_id不能为空'})\nr = APITestResultAssociated.objects.filter(api_result_id=api_test_result_id)\ndata = []\nfor i in r:\n result = {'id': i.id, 'api_test_case_name': i.api_test_case_name, 'api_task_name': i.api_task.api... | <|body_start_0|>
if api_test_result_id == '':
return response_failed({'status': 10102, 'message': 'api_test_task_id不能为空'})
r = APITestResultAssociated.objects.filter(api_result_id=api_test_result_id)
data = []
for i in r:
result = {'id': i.id, 'api_test_case_name'... | CheckApiResult | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckApiResult:
def get(self, request, api_test_result_id, size_page, page, *args, **kwargs):
"""查看任务--测试报告列表--测试结果列表 :param size_page: 展示条数 :param page: 页数 :param request: :param api_test_result_id: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, ... | stack_v2_sparse_classes_75kplus_train_003834 | 15,228 | no_license | [
{
"docstring": "查看任务--测试报告列表--测试结果列表 :param size_page: 展示条数 :param page: 页数 :param request: :param api_test_result_id: :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, request, api_test_result_id, size_page, page, *args, **kwargs)"
},
{
"docstring": "查看任务--测试报告列表... | 3 | stack_v2_sparse_classes_30k_train_041396 | Implement the Python class `CheckApiResult` described below.
Class description:
Implement the CheckApiResult class.
Method signatures and docstrings:
- def get(self, request, api_test_result_id, size_page, page, *args, **kwargs): 查看任务--测试报告列表--测试结果列表 :param size_page: 展示条数 :param page: 页数 :param request: :param api_t... | Implement the Python class `CheckApiResult` described below.
Class description:
Implement the CheckApiResult class.
Method signatures and docstrings:
- def get(self, request, api_test_result_id, size_page, page, *args, **kwargs): 查看任务--测试报告列表--测试结果列表 :param size_page: 展示条数 :param page: 页数 :param request: :param api_t... | 730bbb7a048e0f41a2fb61c8cdf554bcc2bd042c | <|skeleton|>
class CheckApiResult:
def get(self, request, api_test_result_id, size_page, page, *args, **kwargs):
"""查看任务--测试报告列表--测试结果列表 :param size_page: 展示条数 :param page: 页数 :param request: :param api_test_result_id: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckApiResult:
def get(self, request, api_test_result_id, size_page, page, *args, **kwargs):
"""查看任务--测试报告列表--测试结果列表 :param size_page: 展示条数 :param page: 页数 :param request: :param api_test_result_id: :param args: :param kwargs: :return:"""
if api_test_result_id == '':
return respon... | the_stack_v2_python_sparse | automated_main/view/api_automation/api_test_task/api_test_task_view.py | a877429929/TestPlatformDjango | train | 0 | |
5853633f18162445981e5e3d7583c0253cdbb637 | [
"self.root = root\nself.write_root(root)\nfor p in root.subtree():\n if g.app.force_at_auto_sentinels:\n self.put_node_sentinel(p, '<!--', delim2='-->')\n self.write_headline(p)\n s = p.b.rstrip() + '\\n\\n'\n lines = s.splitlines(False)\n for s in lines:\n if not g.isDirective(s):\n ... | <|body_start_0|>
self.root = root
self.write_root(root)
for p in root.subtree():
if g.app.force_at_auto_sentinels:
self.put_node_sentinel(p, '<!--', delim2='-->')
self.write_headline(p)
s = p.b.rstrip() + '\n\n'
lines = s.splitlines... | The writer class for markdown files. | MarkdownWriter | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarkdownWriter:
"""The writer class for markdown files."""
def write(self, root: Position) -> None:
"""Write all the *descendants* of an @auto-markdown node."""
<|body_0|>
def write_headline(self, p: Position) -> None:
"""Write or skip the headline. New in Leo 5.... | stack_v2_sparse_classes_75kplus_train_003835 | 2,398 | permissive | [
{
"docstring": "Write all the *descendants* of an @auto-markdown node.",
"name": "write",
"signature": "def write(self, root: Position) -> None"
},
{
"docstring": "Write or skip the headline. New in Leo 5.5: Always write '#' sections. This will cause perfect import to fail. The alternatives are ... | 3 | stack_v2_sparse_classes_30k_train_018716 | Implement the Python class `MarkdownWriter` described below.
Class description:
The writer class for markdown files.
Method signatures and docstrings:
- def write(self, root: Position) -> None: Write all the *descendants* of an @auto-markdown node.
- def write_headline(self, p: Position) -> None: Write or skip the he... | Implement the Python class `MarkdownWriter` described below.
Class description:
The writer class for markdown files.
Method signatures and docstrings:
- def write(self, root: Position) -> None: Write all the *descendants* of an @auto-markdown node.
- def write_headline(self, p: Position) -> None: Write or skip the he... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class MarkdownWriter:
"""The writer class for markdown files."""
def write(self, root: Position) -> None:
"""Write all the *descendants* of an @auto-markdown node."""
<|body_0|>
def write_headline(self, p: Position) -> None:
"""Write or skip the headline. New in Leo 5.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MarkdownWriter:
"""The writer class for markdown files."""
def write(self, root: Position) -> None:
"""Write all the *descendants* of an @auto-markdown node."""
self.root = root
self.write_root(root)
for p in root.subtree():
if g.app.force_at_auto_sentinels:
... | the_stack_v2_python_sparse | leo/plugins/writers/markdown.py | leo-editor/leo-editor | train | 1,671 |
5055468924fa40be02902451f8716c95c3eca4ae | [
"self.max_cols = max_cols\nself.max_h_space = max_h_space\nself.max_fontsize = max_fontsize\nself.min_fontsize = min_fontsize\nself.total_fontsize = total_fontsize\nself.rows_per_col = rows_per_col\nself.space_scale = space_scale",
"if self.max_cols is not None:\n return int(max(min(ceil(num_plots / self.rows_... | <|body_start_0|>
self.max_cols = max_cols
self.max_h_space = max_h_space
self.max_fontsize = max_fontsize
self.min_fontsize = min_fontsize
self.total_fontsize = total_fontsize
self.rows_per_col = rows_per_col
self.space_scale = space_scale
<|end_body_0|>
<|body_s... | A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib) | LegendSize | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegendSize:
"""A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)"""
def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_col, space_scale):
"""Initialize a LegendSize instance :param... | stack_v2_sparse_classes_75kplus_train_003836 | 2,909 | permissive | [
{
"docstring": "Initialize a LegendSize instance :param max_cols: maximum allowed number of columns for the legend :param max_h_space: maximum proportion of horizontal space to be apportioned to the legend :param max_fontsize: maximum font size for legend labels :param min_fontsize: minimum font size for legend... | 4 | stack_v2_sparse_classes_30k_train_007977 | Implement the Python class `LegendSize` described below.
Class description:
A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)
Method signatures and docstrings:
- def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_c... | Implement the Python class `LegendSize` described below.
Class description:
A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)
Method signatures and docstrings:
- def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_c... | 4a03664f1cc9552787bd9cb39d1409b507f10777 | <|skeleton|>
class LegendSize:
"""A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)"""
def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_col, space_scale):
"""Initialize a LegendSize instance :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LegendSize:
"""A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)"""
def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_col, space_scale):
"""Initialize a LegendSize instance :param max_cols: ma... | the_stack_v2_python_sparse | src/LegendSize.py | dilynfullerton/tr-A_dependence_plots | train | 1 |
ed1f3c52344e0aa162b5f29dd054f661bd0e8e24 | [
"pygame.init()\nself.surface = pygame.display.set_mode((800, 600))\nself.running = True\nself.step_count = 0",
"clock = pygame.time.Clock()\nwhile self.running:\n self.step()\n clock.tick(60)",
"self.handle_events()\nself.handle_keyboard_events()\nself.draw_game()\nself.step_count += 1",
"for event in p... | <|body_start_0|>
pygame.init()
self.surface = pygame.display.set_mode((800, 600))
self.running = True
self.step_count = 0
<|end_body_0|>
<|body_start_1|>
clock = pygame.time.Clock()
while self.running:
self.step()
clock.tick(60)
<|end_body_1|>
<|... | MyGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyGame:
def __init__(self):
"""Initalizes the Game"""
<|body_0|>
def run(self):
"""Runs the Game until it ends"""
<|body_1|>
def step(self):
"""Moves Game one step forward"""
<|body_2|>
def handle_events(self):
"""Handles eve... | stack_v2_sparse_classes_75kplus_train_003837 | 1,544 | no_license | [
{
"docstring": "Initalizes the Game",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Runs the Game until it ends",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Moves Game one step forward",
"name": "step",
"signature": "def step... | 6 | stack_v2_sparse_classes_30k_train_027783 | Implement the Python class `MyGame` described below.
Class description:
Implement the MyGame class.
Method signatures and docstrings:
- def __init__(self): Initalizes the Game
- def run(self): Runs the Game until it ends
- def step(self): Moves Game one step forward
- def handle_events(self): Handles events
- def han... | Implement the Python class `MyGame` described below.
Class description:
Implement the MyGame class.
Method signatures and docstrings:
- def __init__(self): Initalizes the Game
- def run(self): Runs the Game until it ends
- def step(self): Moves Game one step forward
- def handle_events(self): Handles events
- def han... | dd8fec6f71b18aaa4a78e26a4afefc8c70327093 | <|skeleton|>
class MyGame:
def __init__(self):
"""Initalizes the Game"""
<|body_0|>
def run(self):
"""Runs the Game until it ends"""
<|body_1|>
def step(self):
"""Moves Game one step forward"""
<|body_2|>
def handle_events(self):
"""Handles eve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyGame:
def __init__(self):
"""Initalizes the Game"""
pygame.init()
self.surface = pygame.display.set_mode((800, 600))
self.running = True
self.step_count = 0
def run(self):
"""Runs the Game until it ends"""
clock = pygame.time.Clock()
while... | the_stack_v2_python_sparse | pygame4.py | bterwijn/python | train | 0 | |
8413b7d86917ba9e26b2fc6aba161653862e9457 | [
"if not self._errors:\n self._errors = ErrorDict()\nself._errors['upload_of_work'] = self.error_class([DEF_NO_UPLOAD])",
"cleaned_data = self.cleaned_data\nupload = cleaned_data.get('upload_of_work')\nif not upload:\n raise gci_forms.ValidationError(DEF_NO_UPLOAD)\nreturn upload"
] | <|body_start_0|>
if not self._errors:
self._errors = ErrorDict()
self._errors['upload_of_work'] = self.error_class([DEF_NO_UPLOAD])
<|end_body_0|>
<|body_start_1|>
cleaned_data = self.cleaned_data
upload = cleaned_data.get('upload_of_work')
if not upload:
... | Django form for submitting work as file. | WorkSubmissionFileForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkSubmissionFileForm:
"""Django form for submitting work as file."""
def addFileRequiredError(self):
"""Appends a form error message indicating that this field is required."""
<|body_0|>
def clean_upload_of_work(self):
"""Ensure that file field has data."""
... | stack_v2_sparse_classes_75kplus_train_003838 | 26,251 | permissive | [
{
"docstring": "Appends a form error message indicating that this field is required.",
"name": "addFileRequiredError",
"signature": "def addFileRequiredError(self)"
},
{
"docstring": "Ensure that file field has data.",
"name": "clean_upload_of_work",
"signature": "def clean_upload_of_wor... | 2 | stack_v2_sparse_classes_30k_train_020449 | Implement the Python class `WorkSubmissionFileForm` described below.
Class description:
Django form for submitting work as file.
Method signatures and docstrings:
- def addFileRequiredError(self): Appends a form error message indicating that this field is required.
- def clean_upload_of_work(self): Ensure that file f... | Implement the Python class `WorkSubmissionFileForm` described below.
Class description:
Django form for submitting work as file.
Method signatures and docstrings:
- def addFileRequiredError(self): Appends a form error message indicating that this field is required.
- def clean_upload_of_work(self): Ensure that file f... | f581989f168189fa3a58c028eff327a16c03e438 | <|skeleton|>
class WorkSubmissionFileForm:
"""Django form for submitting work as file."""
def addFileRequiredError(self):
"""Appends a form error message indicating that this field is required."""
<|body_0|>
def clean_upload_of_work(self):
"""Ensure that file field has data."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkSubmissionFileForm:
"""Django form for submitting work as file."""
def addFileRequiredError(self):
"""Appends a form error message indicating that this field is required."""
if not self._errors:
self._errors = ErrorDict()
self._errors['upload_of_work'] = self.error... | the_stack_v2_python_sparse | app/soc/modules/gci/views/task.py | sambitgaan/nupic.son | train | 0 |
d2e97e87533f5eeb2920586616b591d829dd7e46 | [
"self.params = params\nself.pdb = self.params.input.pdb\nself.mtz = self.params.input.mtz\nself.inputs = mmtbx.utils.process_command_line_args(args=[self.pdb, self.mtz], suppress_symmetry_related_errors=True)\nself.xrs = self._get_xrs()\nprint('After xrs')\nself._f_obs, self._r_free_flags = self._get_f_obs_r_free()... | <|body_start_0|>
self.params = params
self.pdb = self.params.input.pdb
self.mtz = self.params.input.mtz
self.inputs = mmtbx.utils.process_command_line_args(args=[self.pdb, self.mtz], suppress_symmetry_related_errors=True)
self.xrs = self._get_xrs()
print('After xrs')
... | Class holding crystal model and data Processing pdb and mtz file using mmtbx and cctbx to get required objects now encapsulated in this class for exhaustive search Attributes ---------- pdb: str pdb filepath mtz: str mtz filepath xrs: cctbx.xray.structure Xray structure object inputs: mmtbx.utils.process_command_line_a... | XtalModelData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XtalModelData:
"""Class holding crystal model and data Processing pdb and mtz file using mmtbx and cctbx to get required objects now encapsulated in this class for exhaustive search Attributes ---------- pdb: str pdb filepath mtz: str mtz filepath xrs: cctbx.xray.structure Xray structure object i... | stack_v2_sparse_classes_75kplus_train_003839 | 8,839 | no_license | [
{
"docstring": "Create XtalModelData class to hold data Parameters ---------- params: libtbx.phil.scope_extract python object from phil file, edited with any additional parameters",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Get f_obs and r_free_flags from p... | 6 | stack_v2_sparse_classes_30k_train_050735 | Implement the Python class `XtalModelData` described below.
Class description:
Class holding crystal model and data Processing pdb and mtz file using mmtbx and cctbx to get required objects now encapsulated in this class for exhaustive search Attributes ---------- pdb: str pdb filepath mtz: str mtz filepath xrs: cctbx... | Implement the Python class `XtalModelData` described below.
Class description:
Class holding crystal model and data Processing pdb and mtz file using mmtbx and cctbx to get required objects now encapsulated in this class for exhaustive search Attributes ---------- pdb: str pdb filepath mtz: str mtz filepath xrs: cctbx... | 8fcb13dcbe73877a063a9e4c31e08955245c2e62 | <|skeleton|>
class XtalModelData:
"""Class holding crystal model and data Processing pdb and mtz file using mmtbx and cctbx to get required objects now encapsulated in this class for exhaustive search Attributes ---------- pdb: str pdb filepath mtz: str mtz filepath xrs: cctbx.xray.structure Xray structure object i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XtalModelData:
"""Class holding crystal model and data Processing pdb and mtz file using mmtbx and cctbx to get required objects now encapsulated in this class for exhaustive search Attributes ---------- pdb: str pdb filepath mtz: str mtz filepath xrs: cctbx.xray.structure Xray structure object inputs: mmtbx.... | the_stack_v2_python_sparse | exhaustive/xtal_model_data.py | nelse003/exhaustive_search | train | 2 |
3de547f9284a4ac573cf6295b385d9c4719fc0ae | [
"callbacks = scope.setdefault('callbacks', collections.defaultdict(list))\nif self.arguments['reset']:\n pre_run_callbacks = [c for c in callbacks['pre_run'] if not isinstance(c, DEMInteraction)]\n callbacks['pre_run'] = pre_run_callbacks\ncallbacks['pre_run'].append(self)",
"interaction_type = self.argumen... | <|body_start_0|>
callbacks = scope.setdefault('callbacks', collections.defaultdict(list))
if self.arguments['reset']:
pre_run_callbacks = [c for c in callbacks['pre_run'] if not isinstance(c, DEMInteraction)]
callbacks['pre_run'] = pre_run_callbacks
callbacks['pre_run'].a... | Specify that DEM interactions should be included in future MD stages | DEMInteraction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DEMInteraction:
"""Specify that DEM interactions should be included in future MD stages"""
def run(self, scope, storage):
"""Registers this object to provide a DEM force compute in future MD stages"""
<|body_0|>
def __call__(self, scope, storage, context):
"""Cal... | stack_v2_sparse_classes_75kplus_train_003840 | 2,655 | permissive | [
{
"docstring": "Registers this object to provide a DEM force compute in future MD stages",
"name": "run",
"signature": "def run(self, scope, storage)"
},
{
"docstring": "Callback to be performed before each run command. Initializes a DEM pair potential interaction based on per-type shape informa... | 2 | stack_v2_sparse_classes_30k_train_002297 | Implement the Python class `DEMInteraction` described below.
Class description:
Specify that DEM interactions should be included in future MD stages
Method signatures and docstrings:
- def run(self, scope, storage): Registers this object to provide a DEM force compute in future MD stages
- def __call__(self, scope, s... | Implement the Python class `DEMInteraction` described below.
Class description:
Specify that DEM interactions should be included in future MD stages
Method signatures and docstrings:
- def run(self, scope, storage): Registers this object to provide a DEM force compute in future MD stages
- def __call__(self, scope, s... | 1edaf304e6cf82d308a4f964cf2602a213aae86b | <|skeleton|>
class DEMInteraction:
"""Specify that DEM interactions should be included in future MD stages"""
def run(self, scope, storage):
"""Registers this object to provide a DEM force compute in future MD stages"""
<|body_0|>
def __call__(self, scope, storage, context):
"""Cal... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DEMInteraction:
"""Specify that DEM interactions should be included in future MD stages"""
def run(self, scope, storage):
"""Registers this object to provide a DEM force compute in future MD stages"""
callbacks = scope.setdefault('callbacks', collections.defaultdict(list))
if self... | the_stack_v2_python_sparse | hoomd_flowws/DEMInteraction.py | klarh/hoomd_flowws | train | 1 |
4f3676a9a99246f9780071dbc3dbc96e994b1fe9 | [
"l = []\n\ndef _tostr(node):\n if node is None:\n l.append('null')\n else:\n l.append(str(node.val))\n _tostr(node.left)\n _tostr(node.right)\n_tostr(root)\nreturn ','.join(l)",
"l = data.split(',')\npos = [0]\n\ndef _totree():\n i = pos[0]\n pos[0] += 1\n if i >= len(l)... | <|body_start_0|>
l = []
def _tostr(node):
if node is None:
l.append('null')
else:
l.append(str(node.val))
_tostr(node.left)
_tostr(node.right)
_tostr(root)
return ','.join(l)
<|end_body_0|>
<|body_s... | 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_75kplus_train_003841 | 1,246 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_014660 | 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:... | 06dbf4f5b505a6a41e0d93367eedd231b611a84b | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
l = []
def _tostr(node):
if node is None:
l.append('null')
else:
l.append(str(node.val))
_tostr(node.left... | the_stack_v2_python_sparse | 499.Serialize and Deserialize BST.py | tlxxzj/leetcode | train | 2 | |
1cc55762659acd6d08d73f179fcb41ad4ae806f4 | [
"config = g.user.get_api().get_configuration(configuration)\nview = config.get_view(view)\ncname_record = view.get_alias_record(absolute_name)\nif cname_record is None:\n return ('No matching CName Record(s) found', 404)\nresult = cname_record.to_json()\nreturn jsonify(result)",
"config = g.user.get_api().get_... | <|body_start_0|>
config = g.user.get_api().get_configuration(configuration)
view = config.get_view(view)
cname_record = view.get_alias_record(absolute_name)
if cname_record is None:
return ('No matching CName Record(s) found', 404)
result = cname_record.to_json()
... | CNameRecord | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNameRecord:
def get(self, configuration, view, absolute_name):
"""Get specified cname record belonging to default or provided Configuration and View plus Zone hierarchy."""
<|body_0|>
def delete(self, configuration, view, absolute_name):
"""Delete specified cname re... | stack_v2_sparse_classes_75kplus_train_003842 | 33,507 | permissive | [
{
"docstring": "Get specified cname record belonging to default or provided Configuration and View plus Zone hierarchy.",
"name": "get",
"signature": "def get(self, configuration, view, absolute_name)"
},
{
"docstring": "Delete specified cname record belonging to default or provided Configuratio... | 3 | stack_v2_sparse_classes_30k_train_006675 | Implement the Python class `CNameRecord` described below.
Class description:
Implement the CNameRecord class.
Method signatures and docstrings:
- def get(self, configuration, view, absolute_name): Get specified cname record belonging to default or provided Configuration and View plus Zone hierarchy.
- def delete(self... | Implement the Python class `CNameRecord` described below.
Class description:
Implement the CNameRecord class.
Method signatures and docstrings:
- def get(self, configuration, view, absolute_name): Get specified cname record belonging to default or provided Configuration and View plus Zone hierarchy.
- def delete(self... | 60b36434e689c3ef852ab388ca2aae370e70c62d | <|skeleton|>
class CNameRecord:
def get(self, configuration, view, absolute_name):
"""Get specified cname record belonging to default or provided Configuration and View plus Zone hierarchy."""
<|body_0|>
def delete(self, configuration, view, absolute_name):
"""Delete specified cname re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNameRecord:
def get(self, configuration, view, absolute_name):
"""Get specified cname record belonging to default or provided Configuration and View plus Zone hierarchy."""
config = g.user.get_api().get_configuration(configuration)
view = config.get_view(view)
cname_record = v... | the_stack_v2_python_sparse | Community/rest_api/dns_page.py | bluecatlabs/gateway-workflows | train | 45 | |
39365c2c3046c14a833e4408ffa54e4112c3a9bf | [
"self.n_head = n_head\nself.d_k = self.d_v = d_k = d_v = d_model // n_head\nself.dropout = dropout\nvs_layer = tf.keras.layers.Dense(d_v, use_bias=False)\nself.qs_layers = [_dense_layer(d_k, use_bias=False) for _ in range(n_head)]\nself.ks_layers = [_dense_layer(d_k, use_bias=False) for _ in range(n_head)]\nself.vs... | <|body_start_0|>
self.n_head = n_head
self.d_k = self.d_v = d_k = d_v = d_model // n_head
self.dropout = dropout
vs_layer = tf.keras.layers.Dense(d_v, use_bias=False)
self.qs_layers = [_dense_layer(d_k, use_bias=False) for _ in range(n_head)]
self.ks_layers = [_dense_laye... | Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to apply qs_layers: The list of query layers across heads. ks_layers: The list of key layers across head... | InterpretableMultiHeadAttention | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to apply qs_layers: The list of query layers ... | stack_v2_sparse_classes_75kplus_train_003843 | 19,798 | permissive | [
{
"docstring": "Initialises layer. Args: n_head: The number of heads. d_model: The dimensionality of TFT state. dropout: The dropout rate to be applied to the output.",
"name": "__init__",
"signature": "def __init__(self, n_head, d_model, dropout)"
},
{
"docstring": "Applies interpretable multih... | 2 | stack_v2_sparse_classes_30k_train_048402 | Implement the Python class `InterpretableMultiHeadAttention` described below.
Class description:
Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to app... | Implement the Python class `InterpretableMultiHeadAttention` described below.
Class description:
Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to app... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to apply qs_layers: The list of query layers ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to apply qs_layers: The list of query layers across heads.... | the_stack_v2_python_sparse | saf/models/tft_layers.py | Jimmy-INL/google-research | train | 1 |
018c2d3ed7fa192e4ee5d874af4dcc7a3ebdd514 | [
"if not nums:\n return None\nfor i in range(len(nums)):\n if i != nums[i]:\n return i\nreturn len(nums)",
"if not nums:\n return None\ni, j = (0, len(nums))\nwhile i <= j:\n mid = i + int((j - i) / 2)\n if mid == nums[mid]:\n i = mid + 1\n else:\n j = mid - 1\nreturn i"
] | <|body_start_0|>
if not nums:
return None
for i in range(len(nums)):
if i != nums[i]:
return i
return len(nums)
<|end_body_0|>
<|body_start_1|>
if not nums:
return None
i, j = (0, len(nums))
while i <= j:
mi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def SearchInSortedArray(self, nums):
"""直接遍历法查找缺失值 :param nums: :return:"""
<|body_0|>
def SearchInSortedArrayBinarySearch(self, nums):
"""二分法查找缺失值 :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
... | stack_v2_sparse_classes_75kplus_train_003844 | 1,972 | no_license | [
{
"docstring": "直接遍历法查找缺失值 :param nums: :return:",
"name": "SearchInSortedArray",
"signature": "def SearchInSortedArray(self, nums)"
},
{
"docstring": "二分法查找缺失值 :param nums: :return:",
"name": "SearchInSortedArrayBinarySearch",
"signature": "def SearchInSortedArrayBinarySearch(self, nums... | 2 | stack_v2_sparse_classes_30k_test_000293 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def SearchInSortedArray(self, nums): 直接遍历法查找缺失值 :param nums: :return:
- def SearchInSortedArrayBinarySearch(self, nums): 二分法查找缺失值 :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def SearchInSortedArray(self, nums): 直接遍历法查找缺失值 :param nums: :return:
- def SearchInSortedArrayBinarySearch(self, nums): 二分法查找缺失值 :param nums: :return:
<|skeleton|>
class Soluti... | 32941ee052d0985a9569441d314378700ff4d225 | <|skeleton|>
class Solution:
def SearchInSortedArray(self, nums):
"""直接遍历法查找缺失值 :param nums: :return:"""
<|body_0|>
def SearchInSortedArrayBinarySearch(self, nums):
"""二分法查找缺失值 :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def SearchInSortedArray(self, nums):
"""直接遍历法查找缺失值 :param nums: :return:"""
if not nums:
return None
for i in range(len(nums)):
if i != nums[i]:
return i
return len(nums)
def SearchInSortedArrayBinarySearch(self, nums):
... | the_stack_v2_python_sparse | cecilia-python/剑指offer/chapter-3/SearchInSortedArray-2.py | Cecilia520/algorithmic-learning-leetcode | train | 7 | |
5026e48d76b1a728e01db9135d1be3e9bd20dfb6 | [
"pre = None\nwhile head:\n temp = head.next\n head.next = pre\n pre = head\n head = temp\nreturn pre",
"if not head:\n return None\nif not head.next:\n return head\nreversed_second = self.reverseList(head.next)\nnew_node = head.next\nnew_node.next = head\nhead.next = None\nreturn reversed_second... | <|body_start_0|>
pre = None
while head:
temp = head.next
head.next = pre
pre = head
head = temp
return pre
<|end_body_0|>
<|body_start_1|>
if not head:
return None
if not head.next:
return head
rever... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList1(self, head):
"""递归方法反转链表 :type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre = None
while he... | stack_v2_sparse_classes_75kplus_train_003845 | 968 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": "递归方法反转链表 :type head: ListNode :rtype: ListNode",
"name": "reverseList1",
"signature": "def reverseList1(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049928 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseList1(self, head): 递归方法反转链表 :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseList1(self, head): 递归方法反转链表 :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
... | 11ad9d3841de09c0b4dc3a667e7e63c3558656a5 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList1(self, head):
"""递归方法反转链表 :type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
pre = None
while head:
temp = head.next
head.next = pre
pre = head
head = temp
return pre
def reverseList1(self, head):
"""递归方法反转链表 :t... | the_stack_v2_python_sparse | reverse_linklist.py | ganlanshu/leetcode | train | 0 | |
b698ac2e1cdb958c5f3ad6fe55f31909450611e5 | [
"http_method = str(request_raw['method']).lower()\ntemp_url = str(request_raw['url']).strip()\ntemp_headers = header_to_lowercase(json.loads(request_raw['headers']))\nif http_method == HttpMethod.GET:\n parameters = self.get_parser_class(request_raw).get_parameter(url=temp_url, data=None, http_method=HttpMethod.... | <|body_start_0|>
http_method = str(request_raw['method']).lower()
temp_url = str(request_raw['url']).strip()
temp_headers = header_to_lowercase(json.loads(request_raw['headers']))
if http_method == HttpMethod.GET:
parameters = self.get_parser_class(request_raw).get_parameter(... | Checker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Checker:
def check_logic(self, request_raw):
"""检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:"""
<|body_0|>
def init_plugin_info(self):
"""初插件始化信息 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
http_method =... | stack_v2_sparse_classes_75kplus_train_003846 | 3,308 | permissive | [
{
"docstring": "检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:",
"name": "check_logic",
"signature": "def check_logic(self, request_raw)"
},
{
"docstring": "初插件始化信息 :return:",
"name": "init_plugin_info",
"signature": "def init_plugin_info(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051844 | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def check_logic(self, request_raw): 检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:
- def init_plugin_info(self): 初插件始化信息 :return: | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def check_logic(self, request_raw): 检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:
- def init_plugin_info(self): 初插件始化信息 :return:
<|skeleton|>
class... | 4ee5cca8dc5fc5d7e631e935517bd0f493c30a37 | <|skeleton|>
class Checker:
def check_logic(self, request_raw):
"""检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:"""
<|body_0|>
def init_plugin_info(self):
"""初插件始化信息 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Checker:
def check_logic(self, request_raw):
"""检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:"""
http_method = str(request_raw['method']).lower()
temp_url = str(request_raw['url']).strip()
temp_headers = header_to_lowercase(json.loads(request_raw... | the_stack_v2_python_sparse | HunterAdminApi/plugins/owasp/jsonp_hijacking.py | a1kaid/hunter | train | 0 | |
4ea8d5f89063d53d94eae68df1e35943c20ac8f4 | [
"if np.isscalar(times):\n t = np.asarray([times])\nelse:\n t = np.asarray(times)\nif np.isscalar(data):\n d = data * np.ones((t.size,))\nelse:\n d = np.asarray(data)\nreturn (d, t)",
"if len(data.shape) != 1:\n raise EquationException('{}: Invalid number of dimensions in prescribed scalar data. Exp... | <|body_start_0|>
if np.isscalar(times):
t = np.asarray([times])
else:
t = np.asarray(times)
if np.isscalar(data):
d = data * np.ones((t.size,))
else:
d = np.asarray(data)
return (d, t)
<|end_body_0|>
<|body_start_1|>
if len... | PrescribedScalarParameter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrescribedScalarParameter:
def _setScalarData(self, data, times=0):
"""Set prescribed scalar data appropriately."""
<|body_0|>
def _verifySettingsPrescribedScalarData(self, name, data, times):
"""Verify the structure of the prescribed data."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_003847 | 1,257 | permissive | [
{
"docstring": "Set prescribed scalar data appropriately.",
"name": "_setScalarData",
"signature": "def _setScalarData(self, data, times=0)"
},
{
"docstring": "Verify the structure of the prescribed data.",
"name": "_verifySettingsPrescribedScalarData",
"signature": "def _verifySettingsP... | 2 | stack_v2_sparse_classes_30k_train_020376 | Implement the Python class `PrescribedScalarParameter` described below.
Class description:
Implement the PrescribedScalarParameter class.
Method signatures and docstrings:
- def _setScalarData(self, data, times=0): Set prescribed scalar data appropriately.
- def _verifySettingsPrescribedScalarData(self, name, data, t... | Implement the Python class `PrescribedScalarParameter` described below.
Class description:
Implement the PrescribedScalarParameter class.
Method signatures and docstrings:
- def _setScalarData(self, data, times=0): Set prescribed scalar data appropriately.
- def _verifySettingsPrescribedScalarData(self, name, data, t... | eba9fabddfa4ef439737807ef30978a52ab55afb | <|skeleton|>
class PrescribedScalarParameter:
def _setScalarData(self, data, times=0):
"""Set prescribed scalar data appropriately."""
<|body_0|>
def _verifySettingsPrescribedScalarData(self, name, data, times):
"""Verify the structure of the prescribed data."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrescribedScalarParameter:
def _setScalarData(self, data, times=0):
"""Set prescribed scalar data appropriately."""
if np.isscalar(times):
t = np.asarray([times])
else:
t = np.asarray(times)
if np.isscalar(data):
d = data * np.ones((t.size,))... | the_stack_v2_python_sparse | py/DREAM/Settings/Equations/PrescribedScalarParameter.py | anymodel/DREAM-1 | train | 0 | |
4f9a310a401c03297f01ecb67660d9b5daf71e70 | [
"if n < 3:\n return n\narr = [1, 2]\nfor i in range(n - 2):\n arr.append(arr[-1] + arr[-2])\nreturn arr[-1]",
"if n < 3:\n return n\narr = [1, 2]\nfor i in range(n - 2):\n arr[0], arr[1] = (arr[1], arr[0] + arr[1])\nreturn arr[1]"
] | <|body_start_0|>
if n < 3:
return n
arr = [1, 2]
for i in range(n - 2):
arr.append(arr[-1] + arr[-2])
return arr[-1]
<|end_body_0|>
<|body_start_1|>
if n < 3:
return n
arr = [1, 2]
for i in range(n - 2):
arr[0], arr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 3:
return n
arr = [1, 2]
for i in... | stack_v2_sparse_classes_75kplus_train_003848 | 1,366 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs2",
"signature": "def climbStairs2(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs2(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs2(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def climbStairs(self, n):
""":... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
if n < 3:
return n
arr = [1, 2]
for i in range(n - 2):
arr.append(arr[-1] + arr[-2])
return arr[-1]
def climbStairs2(self, n):
""":type n: int :rtype: int"""
... | the_stack_v2_python_sparse | src/Climbing Stairs.py | jsdiuf/leetcode | train | 1 | |
57ef48beee4388ba99f5a1c93858843bc8e88cae | [
"edges.sort(key=lambda e: e.w)\nparent = [i for i in range(n)]\nrank = [0 for i in range(n)]\ntrees = n\nres = 0\nmst = []\nfor edge in edges:\n u, v = (edge.u, edge.v)\n if self.union(u, v, parent, rank):\n trees -= 1\n mst.append(edge)\n res += edge.w\nreturn res",
"uu = self.find_par... | <|body_start_0|>
edges.sort(key=lambda e: e.w)
parent = [i for i in range(n)]
rank = [0 for i in range(n)]
trees = n
res = 0
mst = []
for edge in edges:
u, v = (edge.u, edge.v)
if self.union(u, v, parent, rank):
trees -= 1
... | Kruskal's union-find implementation for minimum spanning tree. The core idea is to use union-find array to check if adding an edge could form a cycle. If no cycle is formed, the new edge is added; otherwise, discard the edge. 1. The union-find implementation with path compression will only require O(k*log(n)) time. 2. ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Kruskal's union-find implementation for minimum spanning tree. The core idea is to use union-find array to check if adding an edge could form a cycle. If no cycle is formed, the new edge is added; otherwise, discard the edge. 1. The union-find implementation with path compression wil... | stack_v2_sparse_classes_75kplus_train_003849 | 3,716 | no_license | [
{
"docstring": "Find MST in an undirected graph using Kruskal's algorithm 1. Sort all the edges in non-decreasing order of their weight. 2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. 3. Repeat step#2 until ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Kruskal's union-find implementation for minimum spanning tree. The core idea is to use union-find array to check if adding an edge could form a cycle. If no cycle is formed, the new edge is added; otherwise, discard the edge. 1. The union-find i... | Implement the Python class `Solution` described below.
Class description:
Kruskal's union-find implementation for minimum spanning tree. The core idea is to use union-find array to check if adding an edge could form a cycle. If no cycle is formed, the new edge is added; otherwise, discard the edge. 1. The union-find i... | cbe6a7e7f05eccb4f9c5fce8651c0d87e5168516 | <|skeleton|>
class Solution:
"""Kruskal's union-find implementation for minimum spanning tree. The core idea is to use union-find array to check if adding an edge could form a cycle. If no cycle is formed, the new edge is added; otherwise, discard the edge. 1. The union-find implementation with path compression wil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Kruskal's union-find implementation for minimum spanning tree. The core idea is to use union-find array to check if adding an edge could form a cycle. If no cycle is formed, the new edge is added; otherwise, discard the edge. 1. The union-find implementation with path compression will only requir... | the_stack_v2_python_sparse | src/graph/mst_kruskal_UnionFind.py | apepkuss/Cracking-Leetcode-in-Python | train | 2 |
d155ed8338c9b5c4608afec4838d8358ff8b93ed | [
"if isinstance(other, six.string_types):\n return self.name == other\nreturn super(Status, self).__eq__(other)",
"enum_value = cls.__members__.get(name, None)\nif enum_value is None:\n known_names = ', '.join(cls.__members__.keys())\n raise LookupError('%s (expected: %s)' % (name, known_names))\nreturn e... | <|body_start_0|>
if isinstance(other, six.string_types):
return self.name == other
return super(Status, self).__eq__(other)
<|end_body_0|>
<|body_start_1|>
enum_value = cls.__members__.get(name, None)
if enum_value is None:
known_names = ', '.join(cls.__members__... | Provides the (test-run) status of a model element. Features and Scenarios use: untested, skipped, passed, failed. Steps may use all enum-values. Enum values: * untested (initial state): Defines the initial state before a test-run. Sometimes used to indicate that the model element was not executed during a test run. * s... | Status | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Status:
"""Provides the (test-run) status of a model element. Features and Scenarios use: untested, skipped, passed, failed. Steps may use all enum-values. Enum values: * untested (initial state): Defines the initial state before a test-run. Sometimes used to indicate that the model element was n... | stack_v2_sparse_classes_75kplus_train_003850 | 14,223 | permissive | [
{
"docstring": "Comparison operator equals-to other value. Supports other enum-values and string (for backward compatibility). EXAMPLES:: status = Status.passed assert status == Status.passed assert status == \"passed\" assert status != \"failed\" :param other: Other value to compare (enum-value, string). :retu... | 2 | stack_v2_sparse_classes_30k_train_006195 | Implement the Python class `Status` described below.
Class description:
Provides the (test-run) status of a model element. Features and Scenarios use: untested, skipped, passed, failed. Steps may use all enum-values. Enum values: * untested (initial state): Defines the initial state before a test-run. Sometimes used t... | Implement the Python class `Status` described below.
Class description:
Provides the (test-run) status of a model element. Features and Scenarios use: untested, skipped, passed, failed. Steps may use all enum-values. Enum values: * untested (initial state): Defines the initial state before a test-run. Sometimes used t... | 1c6197b35c15e07b5bae62b3131a98f9caa88f4e | <|skeleton|>
class Status:
"""Provides the (test-run) status of a model element. Features and Scenarios use: untested, skipped, passed, failed. Steps may use all enum-values. Enum values: * untested (initial state): Defines the initial state before a test-run. Sometimes used to indicate that the model element was n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Status:
"""Provides the (test-run) status of a model element. Features and Scenarios use: untested, skipped, passed, failed. Steps may use all enum-values. Enum values: * untested (initial state): Defines the initial state before a test-run. Sometimes used to indicate that the model element was not executed d... | the_stack_v2_python_sparse | behave/model_core.py | behave/behave | train | 2,744 |
7003e587afb757d626b1d9a2a00c2c0af4c083ad | [
"_query_builder = Configuration.base_uri\n_query_builder += '/task/cancel'\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/json', 'content-type': 'application/json; charset=utf-8'}\n_request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_seriali... | <|body_start_0|>
_query_builder = Configuration.base_uri
_query_builder += '/task/cancel'
_query_url = APIHelper.clean_url(_query_builder)
_headers = {'accept': 'application/json', 'content-type': 'application/json; charset=utf-8'}
_request = self.http_client.post(_query_url, hea... | A Controller to access Endpoints in the ontraportlib API. | TasksController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TasksController:
"""A Controller to access Endpoints in the ontraportlib API."""
def create_task_cancel(self, criteria):
"""Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong>ids</strong> array in the <strong>criteria</strong> para... | stack_v2_sparse_classes_75kplus_train_003851 | 3,861 | permissive | [
{
"docstring": "Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong>ids</strong> array in the <strong>criteria</strong> parameter. Otherwise, you should use <strong>performAll</strong> and other criteria to select a Group of Tasks to cancel. Args: criteria (Cr... | 2 | stack_v2_sparse_classes_30k_train_025670 | Implement the Python class `TasksController` described below.
Class description:
A Controller to access Endpoints in the ontraportlib API.
Method signatures and docstrings:
- def create_task_cancel(self, criteria): Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong... | Implement the Python class `TasksController` described below.
Class description:
A Controller to access Endpoints in the ontraportlib API.
Method signatures and docstrings:
- def create_task_cancel(self, criteria): Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong... | fb4834e89b897dce3475c89c7e6c34bf8756880e | <|skeleton|>
class TasksController:
"""A Controller to access Endpoints in the ontraportlib API."""
def create_task_cancel(self, criteria):
"""Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong>ids</strong> array in the <strong>criteria</strong> para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TasksController:
"""A Controller to access Endpoints in the ontraportlib API."""
def create_task_cancel(self, criteria):
"""Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong>ids</strong> array in the <strong>criteria</strong> parameter. Otherw... | the_stack_v2_python_sparse | ontraportlib/controllers/tasks_controller.py | LifePosts/ontraportlib | train | 0 |
8833d88228d4cd13b8f1c1357938aaa7dc715d21 | [
"if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():\n qs = Well.objects.all()\nelse:\n qs = Well.objects.all().exclude(well_publication_status='Unpublished')\nreturn qs",
"qs = self.get_queryset()\nlocations = self.filter_queryset(qs)\ncount = locations.count()\nif count > 2000:\n raise P... | <|body_start_0|>
if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():
qs = Well.objects.all()
else:
qs = Well.objects.all().exclude(well_publication_status='Unpublished')
return qs
<|end_body_0|>
<|body_start_1|>
qs = self.get_queryset()
loc... | returns well locations for a given search get: returns a list of wells with locations only | WellLocationListAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WellLocationListAPIView:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
<|body_0|>
def get(self, request):
"""cancels req... | stack_v2_sparse_classes_75kplus_train_003852 | 24,123 | permissive | [
{
"docstring": "Excludes Unpublished wells for users without edit permissions",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "cancels request if too many wells are found",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022279 | Implement the Python class `WellLocationListAPIView` described below.
Class description:
returns well locations for a given search get: returns a list of wells with locations only
Method signatures and docstrings:
- def get_queryset(self): Excludes Unpublished wells for users without edit permissions
- def get(self, ... | Implement the Python class `WellLocationListAPIView` described below.
Class description:
returns well locations for a given search get: returns a list of wells with locations only
Method signatures and docstrings:
- def get_queryset(self): Excludes Unpublished wells for users without edit permissions
- def get(self, ... | 88e801bf58d281aa6b7bf7092a83c1f6e12d5b83 | <|skeleton|>
class WellLocationListAPIView:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
<|body_0|>
def get(self, request):
"""cancels req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WellLocationListAPIView:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():
... | the_stack_v2_python_sparse | app/backend/wells/views.py | anissa-agahchen/gwells | train | 1 |
97bb49acb9f092ae16a32a219e945e4959ef1180 | [
"super().__init__(name='SpecAugment')\nspec_augment_params = spectrum_augmenter.SpectrumAugmenter.Params()\nspec_augment_params.freq_mask_max_bins = freq_mask_max_bins\nspec_augment_params.freq_mask_count = freq_mask_count\nspec_augment_params.time_mask_max_frames = time_mask_max_frames\nspec_augment_params.time_ma... | <|body_start_0|>
super().__init__(name='SpecAugment')
spec_augment_params = spectrum_augmenter.SpectrumAugmenter.Params()
spec_augment_params.freq_mask_max_bins = freq_mask_max_bins
spec_augment_params.freq_mask_count = freq_mask_count
spec_augment_params.time_mask_max_frames = t... | A wrapper around lingo.core.spectrum_augmenter.SpectrumAugmenter . SpecAugment is a data augmentation that combines three transformations: - a time warping of up to max(time_warp_max_frames, time_warp_max_ratio*input_length) frames. - a masking of sampled frequencies with zeros along the entire time axis (freq_mask) - ... | SpecAugment | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecAugment:
"""A wrapper around lingo.core.spectrum_augmenter.SpectrumAugmenter . SpecAugment is a data augmentation that combines three transformations: - a time warping of up to max(time_warp_max_frames, time_warp_max_ratio*input_length) frames. - a masking of sampled frequencies with zeros al... | stack_v2_sparse_classes_75kplus_train_003853 | 4,036 | permissive | [
{
"docstring": "Builds SpecAugment. Args: freq_mask_max_bins: max number of consecutive mel bins to mask in a band. freq_mask_count: number of frequency bands to mask. time_mask_max_frames: max number of consecutive time frames to mask. time_mask_count: number of time bands to mask. time_mask_max_ratio: max tim... | 2 | null | Implement the Python class `SpecAugment` described below.
Class description:
A wrapper around lingo.core.spectrum_augmenter.SpectrumAugmenter . SpecAugment is a data augmentation that combines three transformations: - a time warping of up to max(time_warp_max_frames, time_warp_max_ratio*input_length) frames. - a maski... | Implement the Python class `SpecAugment` described below.
Class description:
A wrapper around lingo.core.spectrum_augmenter.SpectrumAugmenter . SpecAugment is a data augmentation that combines three transformations: - a time warping of up to max(time_warp_max_frames, time_warp_max_ratio*input_length) frames. - a maski... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SpecAugment:
"""A wrapper around lingo.core.spectrum_augmenter.SpectrumAugmenter . SpecAugment is a data augmentation that combines three transformations: - a time warping of up to max(time_warp_max_frames, time_warp_max_ratio*input_length) frames. - a masking of sampled frequencies with zeros al... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpecAugment:
"""A wrapper around lingo.core.spectrum_augmenter.SpectrumAugmenter . SpecAugment is a data augmentation that combines three transformations: - a time warping of up to max(time_warp_max_frames, time_warp_max_ratio*input_length) frames. - a masking of sampled frequencies with zeros along the entir... | the_stack_v2_python_sparse | non_semantic_speech_benchmark/data_prep/augmentation.py | Jimmy-INL/google-research | train | 1 |
830fdd57965002c33b9f60be7d82ded88b8b23f1 | [
"response: ResponseData = auth_service.list_users(session.get('token'))\nWebUtils.flash_response_messages(response)\nif response.get_content() is not None and isinstance(response.get_content(), list):\n return list(response.get_content())\nreturn []",
"response: ResponseData = auth_service.create_user(session.... | <|body_start_0|>
response: ResponseData = auth_service.list_users(session.get('token'))
WebUtils.flash_response_messages(response)
if response.get_content() is not None and isinstance(response.get_content(), list):
return list(response.get_content())
return []
<|end_body_0|>
... | Monostate class responsible of the user operation utilities. | WebUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebUser:
"""Monostate class responsible of the user operation utilities."""
def list_users(auth_service: AuthService) -> List:
"""Gets the list of users from the authentication service. Args: - auth_service (AuthService): The authentication service. Returns: - List: A list of user da... | stack_v2_sparse_classes_75kplus_train_003854 | 3,230 | no_license | [
{
"docstring": "Gets the list of users from the authentication service. Args: - auth_service (AuthService): The authentication service. Returns: - List: A list of user data dictionaries (the list may be empty)",
"name": "list_users",
"signature": "def list_users(auth_service: AuthService) -> List"
},
... | 4 | stack_v2_sparse_classes_30k_train_035176 | Implement the Python class `WebUser` described below.
Class description:
Monostate class responsible of the user operation utilities.
Method signatures and docstrings:
- def list_users(auth_service: AuthService) -> List: Gets the list of users from the authentication service. Args: - auth_service (AuthService): The a... | Implement the Python class `WebUser` described below.
Class description:
Monostate class responsible of the user operation utilities.
Method signatures and docstrings:
- def list_users(auth_service: AuthService) -> List: Gets the list of users from the authentication service. Args: - auth_service (AuthService): The a... | d7d50f84e93914d388ccd084b3bee7e02c9e717b | <|skeleton|>
class WebUser:
"""Monostate class responsible of the user operation utilities."""
def list_users(auth_service: AuthService) -> List:
"""Gets the list of users from the authentication service. Args: - auth_service (AuthService): The authentication service. Returns: - List: A list of user da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WebUser:
"""Monostate class responsible of the user operation utilities."""
def list_users(auth_service: AuthService) -> List:
"""Gets the list of users from the authentication service. Args: - auth_service (AuthService): The authentication service. Returns: - List: A list of user data dictionari... | the_stack_v2_python_sparse | components/dms2122frontend/dms2122frontend/presentation/web/webuser.py | Kencho/practica-dms-2021-2022 | train | 0 |
153fcdd0b802445ab55a0994ab8ed535ebc19fee | [
"self.variable_number = 0\ntry:\n with open(cnf_instance, 'r') as sat_file:\n self.variable_number = [clause.strip().split() for clause in sat_file.readlines() if clause.startswith('p')]\n self.variable_number = int(self.variable_number[0][2])\n sat_file.seek(0)\n self.clause_list = [... | <|body_start_0|>
self.variable_number = 0
try:
with open(cnf_instance, 'r') as sat_file:
self.variable_number = [clause.strip().split() for clause in sat_file.readlines() if clause.startswith('p')]
self.variable_number = int(self.variable_number[0][2])
... | CnfPreprocess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CnfPreprocess:
def __init__(self, cnf_instance):
""":param cnf_instance: Contains the cnf instance file"""
<|body_0|>
def filter_cnf_instance(self):
""":return: Clause List"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.variable_number = 0
... | stack_v2_sparse_classes_75kplus_train_003855 | 1,427 | no_license | [
{
"docstring": ":param cnf_instance: Contains the cnf instance file",
"name": "__init__",
"signature": "def __init__(self, cnf_instance)"
},
{
"docstring": ":return: Clause List",
"name": "filter_cnf_instance",
"signature": "def filter_cnf_instance(self)"
}
] | 2 | null | Implement the Python class `CnfPreprocess` described below.
Class description:
Implement the CnfPreprocess class.
Method signatures and docstrings:
- def __init__(self, cnf_instance): :param cnf_instance: Contains the cnf instance file
- def filter_cnf_instance(self): :return: Clause List | Implement the Python class `CnfPreprocess` described below.
Class description:
Implement the CnfPreprocess class.
Method signatures and docstrings:
- def __init__(self, cnf_instance): :param cnf_instance: Contains the cnf instance file
- def filter_cnf_instance(self): :return: Clause List
<|skeleton|>
class CnfPrepr... | 32fd8bd2f3d1a900f896ca7900c7057cfea2c69e | <|skeleton|>
class CnfPreprocess:
def __init__(self, cnf_instance):
""":param cnf_instance: Contains the cnf instance file"""
<|body_0|>
def filter_cnf_instance(self):
""":return: Clause List"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CnfPreprocess:
def __init__(self, cnf_instance):
""":param cnf_instance: Contains the cnf instance file"""
self.variable_number = 0
try:
with open(cnf_instance, 'r') as sat_file:
self.variable_number = [clause.strip().split() for clause in sat_file.readlines... | the_stack_v2_python_sparse | Assignment 2/preprocessing.py | dheerajalim/metaheuristic | train | 0 | |
87a56e2e23452b010778835f29a07f877c00ff4e | [
"try:\n devices = device_logic.get_all_devices()\nexcept HestiaException as error:\n return handle_hestia_exception(error)\nexcept Exception as error:\n return handle_standard_exception(error)\nreturn devices",
"try:\n json_required_info = namespace.apis[0].payload\n device_logic.create_new_device(... | <|body_start_0|>
try:
devices = device_logic.get_all_devices()
except HestiaException as error:
return handle_hestia_exception(error)
except Exception as error:
return handle_standard_exception(error)
return devices
<|end_body_0|>
<|body_start_1|>
... | Shows a list of all devices and adds a new device with POST | Devices | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Devices:
"""Shows a list of all devices and adds a new device with POST"""
def get(self):
"""List all devices"""
<|body_0|>
def post(self):
"""Post a new device"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
devices = device_lo... | stack_v2_sparse_classes_75kplus_train_003856 | 1,608 | no_license | [
{
"docstring": "List all devices",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Post a new device",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `Devices` described below.
Class description:
Shows a list of all devices and adds a new device with POST
Method signatures and docstrings:
- def get(self): List all devices
- def post(self): Post a new device | Implement the Python class `Devices` described below.
Class description:
Shows a list of all devices and adds a new device with POST
Method signatures and docstrings:
- def get(self): List all devices
- def post(self): Post a new device
<|skeleton|>
class Devices:
"""Shows a list of all devices and adds a new de... | 5b2de252065120ff7e16317d7793fd636b6c099d | <|skeleton|>
class Devices:
"""Shows a list of all devices and adds a new device with POST"""
def get(self):
"""List all devices"""
<|body_0|>
def post(self):
"""Post a new device"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Devices:
"""Shows a list of all devices and adds a new device with POST"""
def get(self):
"""List all devices"""
try:
devices = device_logic.get_all_devices()
except HestiaException as error:
return handle_hestia_exception(error)
except Exception as... | the_stack_v2_python_sparse | source/endpoints/devices/Devices.py | RUGSoftEng/2017-Hestia-Server | train | 2 |
95f93e26d599f39ee32c4eff286b4b4841b64b3f | [
"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... | data transfer service | DataTransferServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataTransferServiceServicer:
"""data transfer service"""
def push(self, request_iterator, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def pull(self, request, context):
"""Missing associated documentation comment in .proto f... | stack_v2_sparse_classes_75kplus_train_003857 | 9,317 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "push",
"signature": "def push(self, request_iterator, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "pull",
"signature": "def pull(self, request, context)... | 4 | stack_v2_sparse_classes_30k_train_040401 | Implement the Python class `DataTransferServiceServicer` described below.
Class description:
data transfer service
Method signatures and docstrings:
- def push(self, request_iterator, context): Missing associated documentation comment in .proto file.
- def pull(self, request, context): Missing associated documentatio... | Implement the Python class `DataTransferServiceServicer` described below.
Class description:
data transfer service
Method signatures and docstrings:
- def push(self, request_iterator, context): Missing associated documentation comment in .proto file.
- def pull(self, request, context): Missing associated documentatio... | 8767db5ec0cb93784f64b290bc39b7b545c530fb | <|skeleton|>
class DataTransferServiceServicer:
"""data transfer service"""
def push(self, request_iterator, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def pull(self, request, context):
"""Missing associated documentation comment in .proto f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataTransferServiceServicer:
"""data transfer service"""
def push(self, request_iterator, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplem... | the_stack_v2_python_sparse | python/fate_arch/protobuf/python/proxy_pb2_grpc.py | FederatedAI/FATE | train | 4,942 |
599e8bdf4f7c983c1f8bb4a6e39ff807495898dc | [
"end_offset = offset + max_messages\nresource = urljoin(mailing_list, offset, end_offset)\nr = self.fetch(self.GMANE_DOWNLOAD_RTYPE, resource)\nreturn r.content",
"r = self.fetch(self.GMANE_LISTID_RTYPE, mailing_list_address)\nif len(r.history) == 0:\n cause = '%s mailing list not found in Gmane'\n raise Re... | <|body_start_0|>
end_offset = offset + max_messages
resource = urljoin(mailing_list, offset, end_offset)
r = self.fetch(self.GMANE_DOWNLOAD_RTYPE, resource)
return r.content
<|end_body_0|>
<|body_start_1|>
r = self.fetch(self.GMANE_LISTID_RTYPE, mailing_list_address)
if ... | Gmane client. This class implements a simple client to access mailing lists stored in Gmane. | GmaneClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GmaneClient:
"""Gmane client. This class implements a simple client to access mailing lists stored in Gmane."""
def messages(self, mailing_list, offset, max_messages=MAX_MESSAGES):
"""Fetch a set of messages from the given mailing list. Given the mailing list identifier used by Gmane... | stack_v2_sparse_classes_75kplus_train_003858 | 13,089 | no_license | [
{
"docstring": "Fetch a set of messages from the given mailing list. Given the mailing list identifier used by Gmane and a offset, this method fetches a set of messages. :param mailing_list: mailing list identifier on Gmane :param offset: start to fetch from here :param max_messages: maximum number of messages ... | 3 | null | Implement the Python class `GmaneClient` described below.
Class description:
Gmane client. This class implements a simple client to access mailing lists stored in Gmane.
Method signatures and docstrings:
- def messages(self, mailing_list, offset, max_messages=MAX_MESSAGES): Fetch a set of messages from the given mail... | Implement the Python class `GmaneClient` described below.
Class description:
Gmane client. This class implements a simple client to access mailing lists stored in Gmane.
Method signatures and docstrings:
- def messages(self, mailing_list, offset, max_messages=MAX_MESSAGES): Fetch a set of messages from the given mail... | 666928c2f2466d07d59f7be8fd2ee1af6ef2222f | <|skeleton|>
class GmaneClient:
"""Gmane client. This class implements a simple client to access mailing lists stored in Gmane."""
def messages(self, mailing_list, offset, max_messages=MAX_MESSAGES):
"""Fetch a set of messages from the given mailing list. Given the mailing list identifier used by Gmane... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GmaneClient:
"""Gmane client. This class implements a simple client to access mailing lists stored in Gmane."""
def messages(self, mailing_list, offset, max_messages=MAX_MESSAGES):
"""Fetch a set of messages from the given mailing list. Given the mailing list identifier used by Gmane and a offset... | the_stack_v2_python_sparse | glusterDashboard-master/gitlab/lib/python3.5/site-packages/perceval/backends/gmane.py | fzachariah/Gluster-Dashboard | train | 1 |
4c571e829b3939609d5619b6522013c2cc7a083e | [
"self.userid = int(userid)\nself.handle = es.getplayerhandle(self.userid)\nself.regening = False\nself.repeat = None",
"if self.repeat is not None:\n self.repeat.stop()\n self.repeat.delete()",
"if not self.isRunning():\n if self.repeat is None:\n self.repeat = repeat.create('sourcerpg_regenammo... | <|body_start_0|>
self.userid = int(userid)
self.handle = es.getplayerhandle(self.userid)
self.regening = False
self.repeat = None
<|end_body_0|>
<|body_start_1|>
if self.repeat is not None:
self.repeat.stop()
self.repeat.delete()
<|end_body_1|>
<|body_st... | This object is player specific and acts as a wrapper between our main class instance and a repeat instance. Ensure that we can start and stop the repeat as / when needed | RegenAmmoObject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegenAmmoObject:
"""This object is player specific and acts as a wrapper between our main class instance and a repeat instance. Ensure that we can start and stop the repeat as / when needed"""
def __init__(self, userid):
"""Default constructor, initialize variables @PARAM userid - th... | stack_v2_sparse_classes_75kplus_train_003859 | 9,383 | no_license | [
{
"docstring": "Default constructor, initialize variables @PARAM userid - the user who this class represents",
"name": "__init__",
"signature": "def __init__(self, userid)"
},
{
"docstring": "Default deconstructor, executed when this object is removed. Ensure that the repeat is stopped and remov... | 6 | stack_v2_sparse_classes_30k_train_051029 | Implement the Python class `RegenAmmoObject` described below.
Class description:
This object is player specific and acts as a wrapper between our main class instance and a repeat instance. Ensure that we can start and stop the repeat as / when needed
Method signatures and docstrings:
- def __init__(self, userid): Def... | Implement the Python class `RegenAmmoObject` described below.
Class description:
This object is player specific and acts as a wrapper between our main class instance and a repeat instance. Ensure that we can start and stop the repeat as / when needed
Method signatures and docstrings:
- def __init__(self, userid): Def... | 25068200df0c410c585037e438d51a0450a111ac | <|skeleton|>
class RegenAmmoObject:
"""This object is player specific and acts as a wrapper between our main class instance and a repeat instance. Ensure that we can start and stop the repeat as / when needed"""
def __init__(self, userid):
"""Default constructor, initialize variables @PARAM userid - th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegenAmmoObject:
"""This object is player specific and acts as a wrapper between our main class instance and a repeat instance. Ensure that we can start and stop the repeat as / when needed"""
def __init__(self, userid):
"""Default constructor, initialize variables @PARAM userid - the user who th... | the_stack_v2_python_sparse | branches/release_2.1/addons/eventscripts/sourcerpg/skills/Regen Ammo/Regen Ammo.py | Grimston/sourcerpg-es | train | 0 |
ee64b80eb4f754529bbd8908a3fc6e62e69b05e9 | [
"table_parameters = self._get_table_parameters(database_name, table_name)\nlogger.info(f'Table parameters: {table_parameters}')\nvalidate_schema, validate_latest = self._parse_table_parameters(table_parameters)\nif validate_schema:\n table_schema = sorted(self._get_table_schema(database_name, table_name), key=la... | <|body_start_0|>
table_parameters = self._get_table_parameters(database_name, table_name)
logger.info(f'Table parameters: {table_parameters}')
validate_schema, validate_latest = self._parse_table_parameters(table_parameters)
if validate_schema:
table_schema = sorted(self._get... | ParquetSchemaValidator | [
"MIT-0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParquetSchemaValidator:
def validate(self, prefix, keys, database_name, table_name):
"""Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: list of S3 keys database_name: Glue database name table_name: Glue table name Returns: validation result: True ... | stack_v2_sparse_classes_75kplus_train_003860 | 5,404 | permissive | [
{
"docstring": "Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: list of S3 keys database_name: Glue database name table_name: Glue table name Returns: validation result: True or False",
"name": "validate",
"signature": "def validate(self, prefix, keys, database_n... | 3 | stack_v2_sparse_classes_30k_train_029453 | Implement the Python class `ParquetSchemaValidator` described below.
Class description:
Implement the ParquetSchemaValidator class.
Method signatures and docstrings:
- def validate(self, prefix, keys, database_name, table_name): Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: ... | Implement the Python class `ParquetSchemaValidator` described below.
Class description:
Implement the ParquetSchemaValidator class.
Method signatures and docstrings:
- def validate(self, prefix, keys, database_name, table_name): Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: ... | f75307daf35fd7914a839ec00ca002db1b6148f4 | <|skeleton|>
class ParquetSchemaValidator:
def validate(self, prefix, keys, database_name, table_name):
"""Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: list of S3 keys database_name: Glue database name table_name: Glue table name Returns: validation result: True ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParquetSchemaValidator:
def validate(self, prefix, keys, database_name, table_name):
"""Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: list of S3 keys database_name: Glue database name table_name: Glue table name Returns: validation result: True or False"""
... | the_stack_v2_python_sparse | sdlf-datalakeLibrary/python/datalake_library/data_quality/schema_validator.py | awslabs/aws-serverless-data-lake-framework | train | 357 | |
6b74dfb6a38219df55ff3ddb4ec8c9d150a883e1 | [
"if len(strs) == 0:\n return chr(258)\nreturn chr(257).join((i for i in strs))",
"if s == chr(258):\n return []\nreturn s.split(chr(257))"
] | <|body_start_0|>
if len(strs) == 0:
return chr(258)
return chr(257).join((i for i in strs))
<|end_body_0|>
<|body_start_1|>
if s == chr(258):
return []
return s.split(chr(257))
<|end_body_1|>
| Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(st... | stack_v2_sparse_classes_75kplus_train_003861 | 697 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | stack_v2_sparse_classes_30k_train_052067 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | 882724c8d50b2f21193c81e5072c31385c5e6b8e | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
if len(strs) == 0:
return chr(258)
return chr(257).join((i for i in strs))
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
... | the_stack_v2_python_sparse | 271. Encode and Decode Strings.py | QIAOZHIBAO0104/My-Leetcode-Records | train | 0 | |
c332ee4c72ed11a460fbdadece284858a927adfd | [
"nn.Module.__init__(self)\nself.interp_layer = nn.Upsample(size=(16, 16), mode='bilinear', align_corners=True)\nself.uplayer1 = nn.Sequential(UpResBlock(512, 512, upsample=False), UpResBlock(512, 256, upsample=True))\nself.uplayer2 = nn.Sequential(UpResBlock(256, 256, upsample=False), UpResBlock(256, 128, upsample=... | <|body_start_0|>
nn.Module.__init__(self)
self.interp_layer = nn.Upsample(size=(16, 16), mode='bilinear', align_corners=True)
self.uplayer1 = nn.Sequential(UpResBlock(512, 512, upsample=False), UpResBlock(512, 256, upsample=True))
self.uplayer2 = nn.Sequential(UpResBlock(256, 256, upsamp... | Combine multiple Up Residual Blocks to form a ResNet18 like decoder. | ResNet18_Decoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet18_Decoder:
"""Combine multiple Up Residual Blocks to form a ResNet18 like decoder."""
def __init__(self, output_channels=3):
"""Build the ResNet18-like decoder. The decoder is composed of a Linear layer. The linear layer is interpolated (bilinear) to 512x16x16 which is then pr... | stack_v2_sparse_classes_75kplus_train_003862 | 6,788 | permissive | [
{
"docstring": "Build the ResNet18-like decoder. The decoder is composed of a Linear layer. The linear layer is interpolated (bilinear) to 512x16x16 which is then processed by several Up-layer of Up Residual Blocks. Each Up-layer is composed of k Up residual blocks. The first ones are without up sampling. The l... | 2 | stack_v2_sparse_classes_30k_train_028807 | Implement the Python class `ResNet18_Decoder` described below.
Class description:
Combine multiple Up Residual Blocks to form a ResNet18 like decoder.
Method signatures and docstrings:
- def __init__(self, output_channels=3): Build the ResNet18-like decoder. The decoder is composed of a Linear layer. The linear layer... | Implement the Python class `ResNet18_Decoder` described below.
Class description:
Combine multiple Up Residual Blocks to form a ResNet18 like decoder.
Method signatures and docstrings:
- def __init__(self, output_channels=3): Build the ResNet18-like decoder. The decoder is composed of a Linear layer. The linear layer... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class ResNet18_Decoder:
"""Combine multiple Up Residual Blocks to form a ResNet18 like decoder."""
def __init__(self, output_channels=3):
"""Build the ResNet18-like decoder. The decoder is composed of a Linear layer. The linear layer is interpolated (bilinear) to 512x16x16 which is then pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResNet18_Decoder:
"""Combine multiple Up Residual Blocks to form a ResNet18 like decoder."""
def __init__(self, output_channels=3):
"""Build the ResNet18-like decoder. The decoder is composed of a Linear layer. The linear layer is interpolated (bilinear) to 512x16x16 which is then processed by se... | the_stack_v2_python_sparse | Code/src/models/networks/AE_network.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
f24c53b485789282e7d1e1df651e42b8dcae50de | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LearningProvider()",
"from .entity import Entity\nfrom .learning_content import LearningContent\nfrom .learning_course_activity import LearningCourseActivity\nfrom .entity import Entity\nfrom .learning_content import LearningContent\nf... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LearningProvider()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .learning_content import LearningContent
from .learning_course_activity import LearningCourseAc... | LearningProvider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningProvider:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningProvider:
"""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 R... | stack_v2_sparse_classes_75kplus_train_003863 | 5,806 | 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: LearningProvider",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_039320 | Implement the Python class `LearningProvider` described below.
Class description:
Implement the LearningProvider class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningProvider: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `LearningProvider` described below.
Class description:
Implement the LearningProvider class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningProvider: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LearningProvider:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningProvider:
"""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 R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LearningProvider:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningProvider:
"""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: Learni... | the_stack_v2_python_sparse | msgraph/generated/models/learning_provider.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b8a2e0b8e6fcc9ed26aea820e37dec857fabdd56 | [
"keyword = data.get('keyword')\ndescription = data.get('description')\n_keyword = Keyword(keyword)\nfunction_name = _keyword.get_function_name_from_source()\ndata = {'name': function_name, 'description': description, 'keyword': keyword}\nmodel = KeywordModel(**data)\ndb.session.add(model)\ndb.session.commit()\nretu... | <|body_start_0|>
keyword = data.get('keyword')
description = data.get('description')
_keyword = Keyword(keyword)
function_name = _keyword.get_function_name_from_source()
data = {'name': function_name, 'description': description, 'keyword': keyword}
model = KeywordModel(**... | KeywordService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordService:
def create(self, data):
"""# 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:"""
<|body_0|>
def delete(self, data):
""":param data: :return:"""
<|body_1|>
def update(self, data... | stack_v2_sparse_classes_75kplus_train_003864 | 3,159 | permissive | [
{
"docstring": "# 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:",
"name": "create",
"signature": "def create(self, data)"
},
{
"docstring": ":param data: :return:",
"name": "delete",
"signature": "def delete(self, data)"
... | 5 | stack_v2_sparse_classes_30k_train_032123 | Implement the Python class `KeywordService` described below.
Class description:
Implement the KeywordService class.
Method signatures and docstrings:
- def create(self, data): # 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:
- def delete(self, data): :pa... | Implement the Python class `KeywordService` described below.
Class description:
Implement the KeywordService class.
Method signatures and docstrings:
- def create(self, data): # 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:
- def delete(self, data): :pa... | 54dc4000263ab9e8873f0d429a7fe48b11fb727a | <|skeleton|>
class KeywordService:
def create(self, data):
"""# 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:"""
<|body_0|>
def delete(self, data):
""":param data: :return:"""
<|body_1|>
def update(self, data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeywordService:
def create(self, data):
"""# 暂时没有前端页面 -- SQL暂时不更换 # 这里需要先提取函数名,然后关键字用函数名进行索引,存到数据库。 # 如果数据库中函数名已经存在怎么办,是否需要先查询,重复则失败? :param data: :return:"""
keyword = data.get('keyword')
description = data.get('description')
_keyword = Keyword(keyword)
function_name =... | the_stack_v2_python_sparse | clover/keyword/service.py | taoyanli0808/clover | train | 18 | |
ccd2cce751ca970c128c9e6d92fb52047dfb350e | [
"count = defaultdict(int)\nstart = 0\nres = 0\nfor end, c in enumerate(s):\n count[c] += 1\n while count[c] > 1:\n count[s[start]] -= 1\n start += 1\n res = max(res, end - start + 1)\nreturn res",
"seen = []\nres = 0\nfor c in s:\n while c in seen:\n seen.pop(0)\n seen.append(c... | <|body_start_0|>
count = defaultdict(int)
start = 0
res = 0
for end, c in enumerate(s):
count[c] += 1
while count[c] > 1:
count[s[start]] -= 1
start += 1
res = max(res, end - start + 1)
return res
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = defaultdict(int)
start = 0... | stack_v2_sparse_classes_75kplus_train_003865 | 778 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring2",
"signature": "def lengthOfLongestSubstring2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031497 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthOf... | a32a1add8720de35e0ddc0c51efe781fb04c9d4a | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
count = defaultdict(int)
start = 0
res = 0
for end, c in enumerate(s):
count[c] += 1
while count[c] > 1:
count[s[start]] -= 1
start +=... | the_stack_v2_python_sparse | 双指针/leetcode_3_Longest_Substring_Without_Repeating_Characters.py | cleverer123/Algorithm | train | 0 | |
03cdcc52e2baa34b015d34c8357b1dadaa01b3d4 | [
"if sets:\n self.sets = sets\nelse:\n self.sets = {i: Node(value=i, parent=Node(-1)) for i in range(n)}",
"a_node = self.sets[a]\nb_node = self.sets[b]\nif a_node.value < b_node.value:\n b_node.parent = a_node\nelse:\n a_node.parent = b_node",
"a_node = self.sets[a]\nb_node = self.sets[b]\nif a_node... | <|body_start_0|>
if sets:
self.sets = sets
else:
self.sets = {i: Node(value=i, parent=Node(-1)) for i in range(n)}
<|end_body_0|>
<|body_start_1|>
a_node = self.sets[a]
b_node = self.sets[b]
if a_node.value < b_node.value:
b_node.parent = a_no... | data structure for union set (disjoint-set, union-find) | DisjointSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisjointSet:
"""data structure for union set (disjoint-set, union-find)"""
def __init__(self, n: int, sets: dict=None):
"""initialize elements for the value of -1 default"""
<|body_0|>
def union(self, a: int, b: int):
"""union a and b node"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_003866 | 2,154 | no_license | [
{
"docstring": "initialize elements for the value of -1 default",
"name": "__init__",
"signature": "def __init__(self, n: int, sets: dict=None)"
},
{
"docstring": "union a and b node",
"name": "union",
"signature": "def union(self, a: int, b: int)"
},
{
"docstring": "return true ... | 5 | null | Implement the Python class `DisjointSet` described below.
Class description:
data structure for union set (disjoint-set, union-find)
Method signatures and docstrings:
- def __init__(self, n: int, sets: dict=None): initialize elements for the value of -1 default
- def union(self, a: int, b: int): union a and b node
- ... | Implement the Python class `DisjointSet` described below.
Class description:
data structure for union set (disjoint-set, union-find)
Method signatures and docstrings:
- def __init__(self, n: int, sets: dict=None): initialize elements for the value of -1 default
- def union(self, a: int, b: int): union a and b node
- ... | 75857d293619a22db5b600bc5864fabeff093b11 | <|skeleton|>
class DisjointSet:
"""data structure for union set (disjoint-set, union-find)"""
def __init__(self, n: int, sets: dict=None):
"""initialize elements for the value of -1 default"""
<|body_0|>
def union(self, a: int, b: int):
"""union a and b node"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DisjointSet:
"""data structure for union set (disjoint-set, union-find)"""
def __init__(self, n: int, sets: dict=None):
"""initialize elements for the value of -1 default"""
if sets:
self.sets = sets
else:
self.sets = {i: Node(value=i, parent=Node(-1)) for ... | the_stack_v2_python_sparse | python/data_structures/union_set/union_set.py | bartkim0426/deliberate-practice | train | 0 |
6e2f8466664eddb8afcb5c87a0f6feb57fb95fc8 | [
"super(ChoicePhoneField, self).validate(value)\nif value and (not self.valid_value(value)):\n raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})",
"for k, v, j, f in self.choices:\n if isinstance(v, (list, tuple)):\n for k2, v2 in v:\n if value == smart_unicode... | <|body_start_0|>
super(ChoicePhoneField, self).validate(value)
if value and (not self.valid_value(value)):
raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
<|end_body_0|>
<|body_start_1|>
for k, v, j, f in self.choices:
if isinstance(v, (li... | ChoicePhoneField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChoicePhoneField:
def validate(self, value):
"""Validates that the input is in self.choices."""
<|body_0|>
def valid_value(self, value):
"""Check to see if the provided value is a valid choice"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Ch... | stack_v2_sparse_classes_75kplus_train_003867 | 9,752 | no_license | [
{
"docstring": "Validates that the input is in self.choices.",
"name": "validate",
"signature": "def validate(self, value)"
},
{
"docstring": "Check to see if the provided value is a valid choice",
"name": "valid_value",
"signature": "def valid_value(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040707 | Implement the Python class `ChoicePhoneField` described below.
Class description:
Implement the ChoicePhoneField class.
Method signatures and docstrings:
- def validate(self, value): Validates that the input is in self.choices.
- def valid_value(self, value): Check to see if the provided value is a valid choice | Implement the Python class `ChoicePhoneField` described below.
Class description:
Implement the ChoicePhoneField class.
Method signatures and docstrings:
- def validate(self, value): Validates that the input is in self.choices.
- def valid_value(self, value): Check to see if the provided value is a valid choice
<|sk... | 302324dccc135f55d92fb705c58314c55fed22aa | <|skeleton|>
class ChoicePhoneField:
def validate(self, value):
"""Validates that the input is in self.choices."""
<|body_0|>
def valid_value(self, value):
"""Check to see if the provided value is a valid choice"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChoicePhoneField:
def validate(self, value):
"""Validates that the input is in self.choices."""
super(ChoicePhoneField, self).validate(value)
if value and (not self.valid_value(value)):
raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
def... | the_stack_v2_python_sparse | django-shared/geobase/phone_code_widget.py | riyanhax/a-demo | train | 0 | |
f0337af9270b1b3b116473f9e2107ff38b28ea9b | [
"data = super(ZavodnikPridaniForm, self).clean()\nclovek, created = Clovek.objects.get_or_create(prijmeni=data['prijmeni'], jmeno=data['jmeno'], narozen=data['narozen'], defaults={'pohlavi': data['pohlavi']})\nself.instance.clovek = clovek\nreturn data",
"from django.forms.utils import ErrorDict\nself._errors = E... | <|body_start_0|>
data = super(ZavodnikPridaniForm, self).clean()
clovek, created = Clovek.objects.get_or_create(prijmeni=data['prijmeni'], jmeno=data['jmeno'], narozen=data['narozen'], defaults={'pohlavi': data['pohlavi']})
self.instance.clovek = clovek
return data
<|end_body_0|>
<|body... | ZavodnikPridaniForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZavodnikPridaniForm:
def clean(self):
"""z důvodu validace se `Clovek` vytvari uz v `clean` funkci"""
<|body_0|>
def full_clean(self):
"""prepsani defaultni funkce - pokud nejsou splneny podminky pro policka, pak preskoc dalsi kontrolu"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_003868 | 6,107 | no_license | [
{
"docstring": "z důvodu validace se `Clovek` vytvari uz v `clean` funkci",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "prepsani defaultni funkce - pokud nejsou splneny podminky pro policka, pak preskoc dalsi kontrolu",
"name": "full_clean",
"signature": "def full_... | 4 | stack_v2_sparse_classes_30k_train_003670 | Implement the Python class `ZavodnikPridaniForm` described below.
Class description:
Implement the ZavodnikPridaniForm class.
Method signatures and docstrings:
- def clean(self): z důvodu validace se `Clovek` vytvari uz v `clean` funkci
- def full_clean(self): prepsani defaultni funkce - pokud nejsou splneny podminky... | Implement the Python class `ZavodnikPridaniForm` described below.
Class description:
Implement the ZavodnikPridaniForm class.
Method signatures and docstrings:
- def clean(self): z důvodu validace se `Clovek` vytvari uz v `clean` funkci
- def full_clean(self): prepsani defaultni funkce - pokud nejsou splneny podminky... | b3d6bfa0090cbb2a546a632e735b98ae653efc7d | <|skeleton|>
class ZavodnikPridaniForm:
def clean(self):
"""z důvodu validace se `Clovek` vytvari uz v `clean` funkci"""
<|body_0|>
def full_clean(self):
"""prepsani defaultni funkce - pokud nejsou splneny podminky pro policka, pak preskoc dalsi kontrolu"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZavodnikPridaniForm:
def clean(self):
"""z důvodu validace se `Clovek` vytvari uz v `clean` funkci"""
data = super(ZavodnikPridaniForm, self).clean()
clovek, created = Clovek.objects.get_or_create(prijmeni=data['prijmeni'], jmeno=data['jmeno'], narozen=data['narozen'], defaults={'pohla... | the_stack_v2_python_sparse | zavodnici/forms.py | gumish/hanes | train | 0 | |
ef662fc56498e87c3e30d6bb125d87d13aea189f | [
"self.sensor = Sensor('127.0.0.1', 8000)\nself.pump = Pump('127.0.0.1', 8000)\nself.decider = Decider(10, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=11.3)\nself.pump.get_state = MagicMock(return_value='PUMP_IN')\nself.pump.set_state = ... | <|body_start_0|>
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(10, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=11.3)
... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Set up controller for test"""
<|body_0|>
def test_controller(self):
"""test controller tick method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sensor = Senso... | stack_v2_sparse_classes_75kplus_train_003869 | 3,554 | no_license | [
{
"docstring": "Set up controller for test",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test controller tick method",
"name": "test_controller",
"signature": "def test_controller(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041363 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Set up controller for test
- def test_controller(self): test controller tick method | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Set up controller for test
- def test_controller(self): test controller tick method
<|skeleton|>
class ControllerTests:
"""Unit tests for the C... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Set up controller for test"""
<|body_0|>
def test_controller(self):
"""test controller tick method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Set up controller for test"""
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(10, 0.05)
self.controller = Controller(self.sensor, self.... | the_stack_v2_python_sparse | students/smitco/lesson06/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
bfe6988bda715d01e6593a51584ba3e8118b056c | [
"if root is None:\n return ''\nans, level = ('', list())\nlevel.append(root)\nwhile level:\n new_level = []\n for node in level:\n ans += str(node.val) if ans == '' else f',{node.val}'\n if node.left:\n new_level.append(node.left)\n if node.right:\n new_level.appe... | <|body_start_0|>
if root is None:
return ''
ans, level = ('', list())
level.append(root)
while level:
new_level = []
for node in level:
ans += str(node.val) if ans == '' else f',{node.val}'
if node.left:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if r... | stack_v2_sparse_classes_75kplus_train_003870 | 9,453 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> Optional[TreeNode]"
}
] | 2 | stack_v2_sparse_classes_30k_train_050839 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree.
<|skeleton|... | 221f0cb3105e4ccaec40cd1d37b9d7d5e218c731 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if root is None:
return ''
ans, level = ('', list())
level.append(root)
while level:
new_level = []
for node in level:
ans += ... | the_stack_v2_python_sparse | problems/serialize_and_deserialize_bst.py | saubhik/leetcode | train | 3 | |
bf8e097feef512df7302f844369ac9cebc38e43f | [
"params = {'part': enf_parts(resource='comments', value=parts), 'maxResults': max_results, 'textFormat': text_format, 'pageToken': page_token, **kwargs}\nif comment_id is not None:\n params['id'] = enf_comma_separated(field='comment_id', value=comment_id)\nelif parent_id is not None:\n params['parentId'] = pa... | <|body_start_0|>
params = {'part': enf_parts(resource='comments', value=parts), 'maxResults': max_results, 'textFormat': text_format, 'pageToken': page_token, **kwargs}
if comment_id is not None:
params['id'] = enf_comma_separated(field='comment_id', value=comment_id)
elif parent_id ... | A comment resource contains information about a single YouTube comment. References: https://developers.google.com/youtube/v3/docs/comments | CommentsResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentsResource:
"""A comment resource contains information about a single YouTube comment. References: https://developers.google.com/youtube/v3/docs/comments"""
def list(self, parts: Optional[Union[str, list, tuple, set]]=None, comment_id: Optional[Union[str, list, tuple, set]]=None, paren... | stack_v2_sparse_classes_75kplus_train_003871 | 9,155 | permissive | [
{
"docstring": "Returns a list of comments that match the API request parameters. Args: parts: Comma-separated list of one or more comment resource properties. comment_id: Specifies a comma-separated list of comment IDs for the resources that are being retrieved. parent_id: Specifies the ID of the comment for w... | 6 | stack_v2_sparse_classes_30k_train_049623 | Implement the Python class `CommentsResource` described below.
Class description:
A comment resource contains information about a single YouTube comment. References: https://developers.google.com/youtube/v3/docs/comments
Method signatures and docstrings:
- def list(self, parts: Optional[Union[str, list, tuple, set]]=... | Implement the Python class `CommentsResource` described below.
Class description:
A comment resource contains information about a single YouTube comment. References: https://developers.google.com/youtube/v3/docs/comments
Method signatures and docstrings:
- def list(self, parts: Optional[Union[str, list, tuple, set]]=... | 1ed2f67a55b8df75c5fab9aacd7d9ff4d460812a | <|skeleton|>
class CommentsResource:
"""A comment resource contains information about a single YouTube comment. References: https://developers.google.com/youtube/v3/docs/comments"""
def list(self, parts: Optional[Union[str, list, tuple, set]]=None, comment_id: Optional[Union[str, list, tuple, set]]=None, paren... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentsResource:
"""A comment resource contains information about a single YouTube comment. References: https://developers.google.com/youtube/v3/docs/comments"""
def list(self, parts: Optional[Union[str, list, tuple, set]]=None, comment_id: Optional[Union[str, list, tuple, set]]=None, parent_id: Optiona... | the_stack_v2_python_sparse | pyyoutube/resources/comments.py | sns-sdks/python-youtube | train | 249 |
2d3507cc4df2f2a4fe84c1a9228cfc16a755875b | [
"if not 0 < p_dropout_inpt < 1 and (not 0 < p_dropout_hidden < 1):\n raise ValueError('dropout rates have to be in (0, 1)')\nself.p_dropout_inpt = p_dropout_inpt\nself.p_dropout_hidden = p_dropout_hidden\nself.max_length = max_length\nself.inpt_var = inpt_var\nsuper(FastDropoutNetwork, self).__init__(n_inpt, n_h... | <|body_start_0|>
if not 0 < p_dropout_inpt < 1 and (not 0 < p_dropout_hidden < 1):
raise ValueError('dropout rates have to be in (0, 1)')
self.p_dropout_inpt = p_dropout_inpt
self.p_dropout_hidden = p_dropout_hidden
self.max_length = max_length
self.inpt_var = inpt_va... | Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings of the 30th International Conference on Machine Learning (ICML-13). 2013. Attributes ... | FastDropoutNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastDropoutNetwork:
"""Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings of the 30th International Conference on... | stack_v2_sparse_classes_75kplus_train_003872 | 13,818 | no_license | [
{
"docstring": "Create a FastDropoutMlp object. Parameters ---------- Same parameters as an ``Mlp`` object. p_dropout_inpt : float Probability that an input unit is ommitted during a pass. p_dropout_hidden : float Probability that an input unit is ommitted during a pass. max_length : float or None Maximum squar... | 2 | stack_v2_sparse_classes_30k_test_002500 | Implement the Python class `FastDropoutNetwork` described below.
Class description:
Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings ... | Implement the Python class `FastDropoutNetwork` described below.
Class description:
Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings ... | 88db4a7fedba9e9ac6375c2051bd36825981c844 | <|skeleton|>
class FastDropoutNetwork:
"""Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings of the 30th International Conference on... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FastDropoutNetwork:
"""Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings of the 30th International Conference on Machine Lear... | the_stack_v2_python_sparse | breze/learn/mlp.py | rachelhornung/breze | train | 0 |
b84a28c9fdfd93806671569edce43bf3596106d0 | [
"global parts_list_page, admin_page\nparts_list_page = PartsListPage(self.driver)\nadmin_page = AdminPage(self.driver)\nadmin_page.into_subsystem('业务管理')\nadmin_page.select_menu('首页/渠道终端管理/设备管理')",
"admin_page.select_menu('T配件列表')\nparts_list_page.simple_query_parts(store='海南省')\nassert '海南省' in parts_list_page.r... | <|body_start_0|>
global parts_list_page, admin_page
parts_list_page = PartsListPage(self.driver)
admin_page = AdminPage(self.driver)
admin_page.into_subsystem('业务管理')
admin_page.select_menu('首页/渠道终端管理/设备管理')
<|end_body_0|>
<|body_start_1|>
admin_page.select_menu('T配件列表')... | TestPartsList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPartsList:
def set_up(self):
"""前置操作 :return:"""
<|body_0|>
def test_query_parts_list(self, set_up):
"""查询配件列表"""
<|body_1|>
def test_reset_query_parts_list(self):
"""重置查询配件列表"""
<|body_2|>
def test_click_more_query_parts_list(se... | stack_v2_sparse_classes_75kplus_train_003873 | 2,489 | no_license | [
{
"docstring": "前置操作 :return:",
"name": "set_up",
"signature": "def set_up(self)"
},
{
"docstring": "查询配件列表",
"name": "test_query_parts_list",
"signature": "def test_query_parts_list(self, set_up)"
},
{
"docstring": "重置查询配件列表",
"name": "test_reset_query_parts_list",
"sign... | 6 | stack_v2_sparse_classes_30k_train_016804 | Implement the Python class `TestPartsList` described below.
Class description:
Implement the TestPartsList class.
Method signatures and docstrings:
- def set_up(self): 前置操作 :return:
- def test_query_parts_list(self, set_up): 查询配件列表
- def test_reset_query_parts_list(self): 重置查询配件列表
- def test_click_more_query_parts_li... | Implement the Python class `TestPartsList` described below.
Class description:
Implement the TestPartsList class.
Method signatures and docstrings:
- def set_up(self): 前置操作 :return:
- def test_query_parts_list(self, set_up): 查询配件列表
- def test_reset_query_parts_list(self): 重置查询配件列表
- def test_click_more_query_parts_li... | 86d1b085af2d3808ac8472d541f4bf26d26591e0 | <|skeleton|>
class TestPartsList:
def set_up(self):
"""前置操作 :return:"""
<|body_0|>
def test_query_parts_list(self, set_up):
"""查询配件列表"""
<|body_1|>
def test_reset_query_parts_list(self):
"""重置查询配件列表"""
<|body_2|>
def test_click_more_query_parts_list(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestPartsList:
def set_up(self):
"""前置操作 :return:"""
global parts_list_page, admin_page
parts_list_page = PartsListPage(self.driver)
admin_page = AdminPage(self.driver)
admin_page.into_subsystem('业务管理')
admin_page.select_menu('首页/渠道终端管理/设备管理')
def test_quer... | the_stack_v2_python_sparse | src/cases/business_manage/channel_device_manage/device_manage/test_parts_list_page_310.py | 102244653/SeleniumByPython | train | 2 | |
c67c90ea579b7b8f36e6cd1f45af2939d6325125 | [
"if root is None:\n return '[]'\nqueue = [root]\nres = []\nwhile len(queue) != 0:\n current = queue[0]\n if isinstance(current, TreeNode):\n res.append(current.val)\n else:\n res.append(current)\n queue.pop(0)\n if current != None:\n queue.append(current.left)\n queue.a... | <|body_start_0|>
if root is None:
return '[]'
queue = [root]
res = []
while len(queue) != 0:
current = queue[0]
if isinstance(current, TreeNode):
res.append(current.val)
else:
res.append(current)
... | Codec | [
"MIT"
] | 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_75kplus_train_003874 | 4,160 | permissive | [
{
"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_000663 | 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:... | 9adbe5fc2bce71f4c09ccf83079c44699c27fce4 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return '[]'
queue = [root]
res = []
while len(queue) != 0:
current = queue[0]
if isinstance(current, TreeNode... | the_stack_v2_python_sparse | leetcode/binary_tree/297.py | 1lch2/PythonExercise | train | 1 | |
18b8bb37d713cf9dd6a3f7916e23fb55d5a119e2 | [
"super().__init__(app, pipeline, id=id, config=config)\nif isinstance(separator, str):\n separator = separator.encode('utf-8')\nself._separator = separator",
"latch = None\nfor line in f:\n if line.startswith(self._separator) and latch is not None:\n await self.process(latch)\n latch = line\n ... | <|body_start_0|>
super().__init__(app, pipeline, id=id, config=config)
if isinstance(separator, str):
separator = separator.encode('utf-8')
self._separator = separator
<|end_body_0|>
<|body_start_1|>
latch = None
for line in f:
if line.startswith(self._se... | Description: Read file line by line but try to join multi-line events by separator. Separator is a (fixed) pattern that should present at the begin of the line, if it is a new event. Example: <133>1 2018-03-24T02:37:01+00:00 machine program 22068 - Start of the multiline event 2nd line of the event 3rd line of the even... | FileMultiLineSource | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileMultiLineSource:
"""Description: Read file line by line but try to join multi-line events by separator. Separator is a (fixed) pattern that should present at the begin of the line, if it is a new event. Example: <133>1 2018-03-24T02:37:01+00:00 machine program 22068 - Start of the multiline e... | stack_v2_sparse_classes_75kplus_train_003875 | 2,375 | permissive | [
{
"docstring": "Description: **Parameters** app: Application Name of the `Application <https://asab.readthedocs.io/en/latest/asab/application.html>`_ pipeline : Pipeline Name of the Pipeline separator : id : ID, default = None config : JSON, default = None Configuration file with additional information",
"n... | 2 | stack_v2_sparse_classes_30k_train_036926 | Implement the Python class `FileMultiLineSource` described below.
Class description:
Description: Read file line by line but try to join multi-line events by separator. Separator is a (fixed) pattern that should present at the begin of the line, if it is a new event. Example: <133>1 2018-03-24T02:37:01+00:00 machine p... | Implement the Python class `FileMultiLineSource` described below.
Class description:
Description: Read file line by line but try to join multi-line events by separator. Separator is a (fixed) pattern that should present at the begin of the line, if it is a new event. Example: <133>1 2018-03-24T02:37:01+00:00 machine p... | 11ee3689d0ff6e9b662deeb3fc5e18bb0aabc8f2 | <|skeleton|>
class FileMultiLineSource:
"""Description: Read file line by line but try to join multi-line events by separator. Separator is a (fixed) pattern that should present at the begin of the line, if it is a new event. Example: <133>1 2018-03-24T02:37:01+00:00 machine program 22068 - Start of the multiline e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileMultiLineSource:
"""Description: Read file line by line but try to join multi-line events by separator. Separator is a (fixed) pattern that should present at the begin of the line, if it is a new event. Example: <133>1 2018-03-24T02:37:01+00:00 machine program 22068 - Start of the multiline event 2nd line... | the_stack_v2_python_sparse | bspump/file/filelinesource.py | LibertyAces/BitSwanPump | train | 24 |
adcdcacbe23177ce6da0b52e8d9bca3eba65918f | [
"self.opts = opts\nself.plain = plain\nself.align = align\nself.bg = bg\nself.bgUp = bgUp\nself.lineno = lineno + 1\nself.genericInit(self.lineno, nextlineno)\nlexer.lineno = nextlineno\nslideLexer.lineno = lineno + 1\nself.title = slideParser.parse(title, slideLexer)\nif bg:\n slideLexer.lineno += 1\nself.child... | <|body_start_0|>
self.opts = opts
self.plain = plain
self.align = align
self.bg = bg
self.bgUp = bgUp
self.lineno = lineno + 1
self.genericInit(self.lineno, nextlineno)
lexer.lineno = nextlineno
slideLexer.lineno = lineno + 1
self.title = s... | Slide | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slide:
def __init__(self, title, opts, plain, align, bg, bgUp, content, lexer, lineno, nextlineno):
"""Parse slide title and contents, remember other attributes, advance lexer line number :param title: Slide title :param opts: Break/shrink option :param plain: Decoration removal option :... | stack_v2_sparse_classes_75kplus_train_003876 | 29,071 | permissive | [
{
"docstring": "Parse slide title and contents, remember other attributes, advance lexer line number :param title: Slide title :param opts: Break/shrink option :param plain: Decoration removal option :param align: Vertical alignment option :param bg: Background image path :param bgUp: Background stretch opton :... | 2 | stack_v2_sparse_classes_30k_train_038667 | Implement the Python class `Slide` described below.
Class description:
Implement the Slide class.
Method signatures and docstrings:
- def __init__(self, title, opts, plain, align, bg, bgUp, content, lexer, lineno, nextlineno): Parse slide title and contents, remember other attributes, advance lexer line number :param... | Implement the Python class `Slide` described below.
Class description:
Implement the Slide class.
Method signatures and docstrings:
- def __init__(self, title, opts, plain, align, bg, bgUp, content, lexer, lineno, nextlineno): Parse slide title and contents, remember other attributes, advance lexer line number :param... | fbd2c7a72ed2b6347a131a5b54740e7b15bf1624 | <|skeleton|>
class Slide:
def __init__(self, title, opts, plain, align, bg, bgUp, content, lexer, lineno, nextlineno):
"""Parse slide title and contents, remember other attributes, advance lexer line number :param title: Slide title :param opts: Break/shrink option :param plain: Decoration removal option :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Slide:
def __init__(self, title, opts, plain, align, bg, bgUp, content, lexer, lineno, nextlineno):
"""Parse slide title and contents, remember other attributes, advance lexer line number :param title: Slide title :param opts: Break/shrink option :param plain: Decoration removal option :param align: V... | the_stack_v2_python_sparse | beamr/interpreters/hierarchical.py | teonistor/beamr | train | 5 | |
b3936db86a103b327db0b591f5fbecc5fbe4948c | [
"self.archive_log_enabled = archive_log_enabled\nself.bct_enabled = bct_enabled\nself.db_type = db_type\nself.hosts = hosts\nself.name = name\nself.owner_id = owner_id\nself.size = size\nself.mtype = mtype\nself.uuid = uuid\nself.version = version",
"if dictionary is None:\n return None\narchive_log_enabled = ... | <|body_start_0|>
self.archive_log_enabled = archive_log_enabled
self.bct_enabled = bct_enabled
self.db_type = db_type
self.hosts = hosts
self.name = name
self.owner_id = owner_id
self.size = size
self.mtype = mtype
self.uuid = uuid
self.ver... | Implementation of the 'Oracle Protection Source.' model. Specifies an Object representing one Oracle database. Attributes: archive_log_enabled (bool): Specifies whether the database is running in ARCHIVELOG mode. It enables the redo of log files into archived redo log files. bct_enabled (bool): Specifies whether the Bl... | OracleProtectionSource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OracleProtectionSource:
"""Implementation of the 'Oracle Protection Source.' model. Specifies an Object representing one Oracle database. Attributes: archive_log_enabled (bool): Specifies whether the database is running in ARCHIVELOG mode. It enables the redo of log files into archived redo log f... | stack_v2_sparse_classes_75kplus_train_003877 | 4,704 | permissive | [
{
"docstring": "Constructor for the OracleProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, archive_log_enabled=None, bct_enabled=None, db_type=None, hosts=None, name=None, owner_id=None, size=None, mtype=None, uuid=None, version=None)"
},
{
"docstring": "Creates an i... | 2 | stack_v2_sparse_classes_30k_train_031558 | Implement the Python class `OracleProtectionSource` described below.
Class description:
Implementation of the 'Oracle Protection Source.' model. Specifies an Object representing one Oracle database. Attributes: archive_log_enabled (bool): Specifies whether the database is running in ARCHIVELOG mode. It enables the red... | Implement the Python class `OracleProtectionSource` described below.
Class description:
Implementation of the 'Oracle Protection Source.' model. Specifies an Object representing one Oracle database. Attributes: archive_log_enabled (bool): Specifies whether the database is running in ARCHIVELOG mode. It enables the red... | 07c5adee58810979780679065250d82b4b2cdaab | <|skeleton|>
class OracleProtectionSource:
"""Implementation of the 'Oracle Protection Source.' model. Specifies an Object representing one Oracle database. Attributes: archive_log_enabled (bool): Specifies whether the database is running in ARCHIVELOG mode. It enables the redo of log files into archived redo log f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OracleProtectionSource:
"""Implementation of the 'Oracle Protection Source.' model. Specifies an Object representing one Oracle database. Attributes: archive_log_enabled (bool): Specifies whether the database is running in ARCHIVELOG mode. It enables the redo of log files into archived redo log files. bct_ena... | the_stack_v2_python_sparse | cohesity_management_sdk/models/oracle_protection_source.py | hemanshu-cohesity/management-sdk-python | train | 0 |
b5d10f44ebf814558b526e382590331b3171a39c | [
"camera = RaspberryPiCamera(self.mudpi, config)\nif camera:\n self.add_component(camera)\nreturn True",
"if not isinstance(config, list):\n config = [config]\nfor conf in config:\n if not conf.get('path'):\n raise ConfigError('Camera needs a `path` to save files to.')\nreturn config"
] | <|body_start_0|>
camera = RaspberryPiCamera(self.mudpi, config)
if camera:
self.add_component(camera)
return True
<|end_body_0|>
<|body_start_1|>
if not isinstance(config, list):
config = [config]
for conf in config:
if not conf.get('path'):
... | Interface | [
"BSD-4-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface:
def load(self, config):
"""Load pi camera component from configs"""
<|body_0|>
def validate(self, config):
"""Validate the camera config"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
camera = RaspberryPiCamera(self.mudpi, config)
... | stack_v2_sparse_classes_75kplus_train_003878 | 3,236 | permissive | [
{
"docstring": "Load pi camera component from configs",
"name": "load",
"signature": "def load(self, config)"
},
{
"docstring": "Validate the camera config",
"name": "validate",
"signature": "def validate(self, config)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002233 | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load pi camera component from configs
- def validate(self, config): Validate the camera config | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load pi camera component from configs
- def validate(self, config): Validate the camera config
<|skeleton|>
class Interface:
def load(self, config... | fb206b1136f529c7197f1e6b29629ed05630d377 | <|skeleton|>
class Interface:
def load(self, config):
"""Load pi camera component from configs"""
<|body_0|>
def validate(self, config):
"""Validate the camera config"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interface:
def load(self, config):
"""Load pi camera component from configs"""
camera = RaspberryPiCamera(self.mudpi, config)
if camera:
self.add_component(camera)
return True
def validate(self, config):
"""Validate the camera config"""
if not i... | the_stack_v2_python_sparse | mudpi/extensions/picamera/camera.py | mistasp0ck/mudpi-core | train | 0 | |
8ffc5eb7d3393d0d2b9dae72aea0e4360d18c3b6 | [
"try:\n noted = Notes.objects.get(pk=pk)\n if noted:\n notedata = NoteSerializers(noted)\n return Response(notedata.data, status=200)\n else:\n logger.warning('no such note present in db')\n raise ValueError\nexcept ValueError:\n return Response({'error': 'no such notes'}, st... | <|body_start_0|>
try:
noted = Notes.objects.get(pk=pk)
if noted:
notedata = NoteSerializers(noted)
return Response(notedata.data, status=200)
else:
logger.warning('no such note present in db')
raise ValueError
... | This methods are for updating, deleting and getting the notes created. | NotesApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotesApi:
"""This methods are for updating, deleting and getting the notes created."""
def get(self, request, pk):
""":param pk: the primary key of note :param request: request for data :return: returns the response"""
<|body_0|>
def delete(self, request, pk):
""... | stack_v2_sparse_classes_75kplus_train_003879 | 19,345 | no_license | [
{
"docstring": ":param pk: the primary key of note :param request: request for data :return: returns the response",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": ":param pk: the primary key of note :param request: request for data :return: returns the response",
... | 3 | null | Implement the Python class `NotesApi` described below.
Class description:
This methods are for updating, deleting and getting the notes created.
Method signatures and docstrings:
- def get(self, request, pk): :param pk: the primary key of note :param request: request for data :return: returns the response
- def delet... | Implement the Python class `NotesApi` described below.
Class description:
This methods are for updating, deleting and getting the notes created.
Method signatures and docstrings:
- def get(self, request, pk): :param pk: the primary key of note :param request: request for data :return: returns the response
- def delet... | 7675c635c33e51198a754697f07996cdb43980be | <|skeleton|>
class NotesApi:
"""This methods are for updating, deleting and getting the notes created."""
def get(self, request, pk):
""":param pk: the primary key of note :param request: request for data :return: returns the response"""
<|body_0|>
def delete(self, request, pk):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotesApi:
"""This methods are for updating, deleting and getting the notes created."""
def get(self, request, pk):
""":param pk: the primary key of note :param request: request for data :return: returns the response"""
try:
noted = Notes.objects.get(pk=pk)
if noted... | the_stack_v2_python_sparse | notes/views.py | someshj5/FundooApp | train | 0 |
3bec203c3074e167c5c1f3cc6590bb8e00166521 | [
"response = self.client.get(reverse('rooms:index'))\nself.assertEqual(response.status_code, 200)\nself.assertQuerysetEqual(response.context['room_list'], [])",
"Room.objects.create(name='room1')\nRoom.objects.create(name='room2')\nresponse = self.client.get(reverse('rooms:index'))\nself.assertEqual(response.statu... | <|body_start_0|>
response = self.client.get(reverse('rooms:index'))
self.assertEqual(response.status_code, 200)
self.assertQuerysetEqual(response.context['room_list'], [])
<|end_body_0|>
<|body_start_1|>
Room.objects.create(name='room1')
Room.objects.create(name='room2')
... | Set of tests related to viewing index page of rooms. | RoomsViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoomsViewTests:
"""Set of tests related to viewing index page of rooms."""
def test_index_view_with_no_rooms(self):
"""If no rooms exist, none of them should be displayed on the index page."""
<|body_0|>
def test_index_view_with_two_rooms(self):
"""The index page... | stack_v2_sparse_classes_75kplus_train_003880 | 3,370 | no_license | [
{
"docstring": "If no rooms exist, none of them should be displayed on the index page.",
"name": "test_index_view_with_no_rooms",
"signature": "def test_index_view_with_no_rooms(self)"
},
{
"docstring": "The index page may display multiple rooms.",
"name": "test_index_view_with_two_rooms",
... | 6 | null | Implement the Python class `RoomsViewTests` described below.
Class description:
Set of tests related to viewing index page of rooms.
Method signatures and docstrings:
- def test_index_view_with_no_rooms(self): If no rooms exist, none of them should be displayed on the index page.
- def test_index_view_with_two_rooms(... | Implement the Python class `RoomsViewTests` described below.
Class description:
Set of tests related to viewing index page of rooms.
Method signatures and docstrings:
- def test_index_view_with_no_rooms(self): If no rooms exist, none of them should be displayed on the index page.
- def test_index_view_with_two_rooms(... | 075d53cdee8bffef9c15167a481594318ada6340 | <|skeleton|>
class RoomsViewTests:
"""Set of tests related to viewing index page of rooms."""
def test_index_view_with_no_rooms(self):
"""If no rooms exist, none of them should be displayed on the index page."""
<|body_0|>
def test_index_view_with_two_rooms(self):
"""The index page... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoomsViewTests:
"""Set of tests related to viewing index page of rooms."""
def test_index_view_with_no_rooms(self):
"""If no rooms exist, none of them should be displayed on the index page."""
response = self.client.get(reverse('rooms:index'))
self.assertEqual(response.status_code... | the_stack_v2_python_sparse | rooms/tests.py | JaRutkowski/wesz | train | 0 |
397459f58944441cdcc984cda806f176cda75f90 | [
"self.n = n\nself.m = m\nself.input = np.ones(n + 1)\nself.output = np.ones(m)\nself.weights = np.zeros((1, self.m, self.n + 1))\nself.votes = np.zeros((1,))",
"self.input[1:] = input_sample\no = np.sign(np.dot(self.weights[-1, :, :], self.input))\nif o == output_sample:\n self.votes[-1] += 1\nelse:\n self.... | <|body_start_0|>
self.n = n
self.m = m
self.input = np.ones(n + 1)
self.output = np.ones(m)
self.weights = np.zeros((1, self.m, self.n + 1))
self.votes = np.zeros((1,))
<|end_body_0|>
<|body_start_1|>
self.input[1:] = input_sample
o = np.sign(np.dot(self.... | VotedPerceptron | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VotedPerceptron:
def __init__(self, n, m):
"""Initialization of the voted perceptron with given sizes."""
<|body_0|>
def learn(self, input_sample, output_sample):
"""The learning function : a single sample is expected"""
<|body_1|>
def __call__(self, inp... | stack_v2_sparse_classes_75kplus_train_003881 | 5,850 | permissive | [
{
"docstring": "Initialization of the voted perceptron with given sizes.",
"name": "__init__",
"signature": "def __init__(self, n, m)"
},
{
"docstring": "The learning function : a single sample is expected",
"name": "learn",
"signature": "def learn(self, input_sample, output_sample)"
}... | 3 | stack_v2_sparse_classes_30k_train_004421 | Implement the Python class `VotedPerceptron` described below.
Class description:
Implement the VotedPerceptron class.
Method signatures and docstrings:
- def __init__(self, n, m): Initialization of the voted perceptron with given sizes.
- def learn(self, input_sample, output_sample): The learning function : a single ... | Implement the Python class `VotedPerceptron` described below.
Class description:
Implement the VotedPerceptron class.
Method signatures and docstrings:
- def __init__(self, n, m): Initialization of the voted perceptron with given sizes.
- def learn(self, input_sample, output_sample): The learning function : a single ... | 8a4f77a16c407f8f3c2955ff930ee97d8a10bbb5 | <|skeleton|>
class VotedPerceptron:
def __init__(self, n, m):
"""Initialization of the voted perceptron with given sizes."""
<|body_0|>
def learn(self, input_sample, output_sample):
"""The learning function : a single sample is expected"""
<|body_1|>
def __call__(self, inp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VotedPerceptron:
def __init__(self, n, m):
"""Initialization of the voted perceptron with given sizes."""
self.n = n
self.m = m
self.input = np.ones(n + 1)
self.output = np.ones(m)
self.weights = np.zeros((1, self.m, self.n + 1))
self.votes = np.zeros((1... | the_stack_v2_python_sparse | recipes/ANN/voted-perceptron.py | praveen686/ML-Recipes | train | 0 | |
42b1333b62947bdd16eaa95fde881d23d6610d0d | [
"with DBMgr.__instance_lock:\n if DBMgr.__database is None or refresh:\n try:\n db_host = DBMgr.conf['host']\n db_port = DBMgr.conf['port']\n db_username = DBMgr.conf['username']\n db_password = DBMgr.conf['password']\n db_name = DBMgr.conf['database'... | <|body_start_0|>
with DBMgr.__instance_lock:
if DBMgr.__database is None or refresh:
try:
db_host = DBMgr.conf['host']
db_port = DBMgr.conf['port']
db_username = DBMgr.conf['username']
db_password = DBMgr... | DBMgr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBMgr:
def get_database(cls, refresh=False):
"""单例多线程模式获取db对象 :param refresh: :return:"""
<|body_0|>
def close_database(cls, func):
"""关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager import DBManager @DBManager.close_database def 使用了数据库的方法"""
... | stack_v2_sparse_classes_75kplus_train_003882 | 3,937 | permissive | [
{
"docstring": "单例多线程模式获取db对象 :param refresh: :return:",
"name": "get_database",
"signature": "def get_database(cls, refresh=False)"
},
{
"docstring": "关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager import DBManager @DBManager.close_database def 使用了数据库的方法",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_048207 | Implement the Python class `DBMgr` described below.
Class description:
Implement the DBMgr class.
Method signatures and docstrings:
- def get_database(cls, refresh=False): 单例多线程模式获取db对象 :param refresh: :return:
- def close_database(cls, func): 关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager imp... | Implement the Python class `DBMgr` described below.
Class description:
Implement the DBMgr class.
Method signatures and docstrings:
- def get_database(cls, refresh=False): 单例多线程模式获取db对象 :param refresh: :return:
- def close_database(cls, func): 关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager imp... | c679b15ca2f920fd4fa6bd3bb7d2a1a0ac297940 | <|skeleton|>
class DBMgr:
def get_database(cls, refresh=False):
"""单例多线程模式获取db对象 :param refresh: :return:"""
<|body_0|>
def close_database(cls, func):
"""关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager import DBManager @DBManager.close_database def 使用了数据库的方法"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DBMgr:
def get_database(cls, refresh=False):
"""单例多线程模式获取db对象 :param refresh: :return:"""
with DBMgr.__instance_lock:
if DBMgr.__database is None or refresh:
try:
db_host = DBMgr.conf['host']
db_port = DBMgr.conf['port']
... | the_stack_v2_python_sparse | dsPyLib/peewee/db_mgr.py | dragonsun7/dsPyLib | train | 0 | |
f9536df9852c4d11ef853d101cf5f1d93f2ec65f | [
"self.args = args\nself.train_args = load_args(args.checkpoint_paths[0])\nif (self.train_args.features_path is not None or self.train_args.features_generator is not None) and args.features_generator is None:\n raise ValueError('Features were used during training so they must be specified again during prediction ... | <|body_start_0|>
self.args = args
self.train_args = load_args(args.checkpoint_paths[0])
if (self.train_args.features_path is not None or self.train_args.features_generator is not None) and args.features_generator is None:
raise ValueError('Features were used during training so they m... | A :class:`ChempropModel` is a wrapper around a :class:`~chemprop.models.model.MoleculeModel` for interpretation. | ChempropModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChempropModel:
"""A :class:`ChempropModel` is a wrapper around a :class:`~chemprop.models.model.MoleculeModel` for interpretation."""
def __init__(self, args: InterpretArgs) -> None:
""":param args: A :class:`~chemprop.args.InterpretArgs` object containing arguments for interpretatio... | stack_v2_sparse_classes_75kplus_train_003883 | 13,921 | permissive | [
{
"docstring": ":param args: A :class:`~chemprop.args.InterpretArgs` object containing arguments for interpretation.",
"name": "__init__",
"signature": "def __init__(self, args: InterpretArgs) -> None"
},
{
"docstring": "Makes predictions on a list of SMILES. :param smiles: A list of SMILES to m... | 2 | stack_v2_sparse_classes_30k_train_046678 | Implement the Python class `ChempropModel` described below.
Class description:
A :class:`ChempropModel` is a wrapper around a :class:`~chemprop.models.model.MoleculeModel` for interpretation.
Method signatures and docstrings:
- def __init__(self, args: InterpretArgs) -> None: :param args: A :class:`~chemprop.args.Int... | Implement the Python class `ChempropModel` described below.
Class description:
A :class:`ChempropModel` is a wrapper around a :class:`~chemprop.models.model.MoleculeModel` for interpretation.
Method signatures and docstrings:
- def __init__(self, args: InterpretArgs) -> None: :param args: A :class:`~chemprop.args.Int... | f3d1bff19a6e1b03d28e9cfabdf4c80dd8c67382 | <|skeleton|>
class ChempropModel:
"""A :class:`ChempropModel` is a wrapper around a :class:`~chemprop.models.model.MoleculeModel` for interpretation."""
def __init__(self, args: InterpretArgs) -> None:
""":param args: A :class:`~chemprop.args.InterpretArgs` object containing arguments for interpretatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChempropModel:
"""A :class:`ChempropModel` is a wrapper around a :class:`~chemprop.models.model.MoleculeModel` for interpretation."""
def __init__(self, args: InterpretArgs) -> None:
""":param args: A :class:`~chemprop.args.InterpretArgs` object containing arguments for interpretation."""
... | the_stack_v2_python_sparse | chemprop/interpret.py | chemprop/chemprop | train | 1,139 |
3b21e2d89332a9f41311a972ea796464078cd055 | [
"self.sensor_refresh_rates = sensor_refresh_rates\nself.plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')\nself.plugins = sensors_list\nself.statistics = {}\nfor sensor in self.plugins:\n self.statistics[sensor.name] = sensor.currentValue\nself.stop_event = stop_event",
"for sensor in self.plugin... | <|body_start_0|>
self.sensor_refresh_rates = sensor_refresh_rates
self.plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')
self.plugins = sensors_list
self.statistics = {}
for sensor in self.plugins:
self.statistics[sensor.name] = sensor.currentValue
... | Statistics | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Statistics:
def __init__(self, sensors_list, stop_event, sensor_refresh_rates):
"""Record keeping for primitive system parameters"""
<|body_0|>
def generate(self):
"""Generate the stats using the plugins list periodically"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_003884 | 1,217 | permissive | [
{
"docstring": "Record keeping for primitive system parameters",
"name": "__init__",
"signature": "def __init__(self, sensors_list, stop_event, sensor_refresh_rates)"
},
{
"docstring": "Generate the stats using the plugins list periodically",
"name": "generate",
"signature": "def generat... | 2 | stack_v2_sparse_classes_30k_train_016773 | Implement the Python class `Statistics` described below.
Class description:
Implement the Statistics class.
Method signatures and docstrings:
- def __init__(self, sensors_list, stop_event, sensor_refresh_rates): Record keeping for primitive system parameters
- def generate(self): Generate the stats using the plugins ... | Implement the Python class `Statistics` described below.
Class description:
Implement the Statistics class.
Method signatures and docstrings:
- def __init__(self, sensors_list, stop_event, sensor_refresh_rates): Record keeping for primitive system parameters
- def generate(self): Generate the stats using the plugins ... | 2258dd996da03ac84d1ca3fb09ef51e83a409140 | <|skeleton|>
class Statistics:
def __init__(self, sensors_list, stop_event, sensor_refresh_rates):
"""Record keeping for primitive system parameters"""
<|body_0|>
def generate(self):
"""Generate the stats using the plugins list periodically"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Statistics:
def __init__(self, sensors_list, stop_event, sensor_refresh_rates):
"""Record keeping for primitive system parameters"""
self.sensor_refresh_rates = sensor_refresh_rates
self.plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')
self.plugins = sensors_list... | the_stack_v2_python_sparse | ptop/statistics/statistics.py | leovarmak/ptop | train | 1 | |
bbd0698a5d0d470066b2a3f67b6652dfef4366a6 | [
"self.true_labels = true_labels\nself.num_instances, self.num_labels = true_labels.shape\nself.remove_invalid = remove_invalid\nself.valid_idx = None\nif self.remove_invalid:\n samples = np.sum(self.true_labels, axis=1)\n self.valid_idx = np.arange(self.num_instances).reshape(-1, 1)[samples > 0]\n self.tru... | <|body_start_0|>
self.true_labels = true_labels
self.num_instances, self.num_labels = true_labels.shape
self.remove_invalid = remove_invalid
self.valid_idx = None
if self.remove_invalid:
samples = np.sum(self.true_labels, axis=1)
self.valid_idx = np.arange... | Metrics | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Metrics:
def __init__(self, true_labels, inv_psp=None, remove_invalid=False):
"""Class to compute vanilla and propensity scored precision and ndcg Arguments: --------- true_labels: csr_matrix or np.ndarray ground truth in sparse or dense format shape: (num_instances, num_labels) inv_psp:... | stack_v2_sparse_classes_75kplus_train_003885 | 15,487 | permissive | [
{
"docstring": "Class to compute vanilla and propensity scored precision and ndcg Arguments: --------- true_labels: csr_matrix or np.ndarray ground truth in sparse or dense format shape: (num_instances, num_labels) inv_psp: np.ndarray or None; default=None propensity scores for each label will compute propensit... | 2 | stack_v2_sparse_classes_30k_train_043012 | Implement the Python class `Metrics` described below.
Class description:
Implement the Metrics class.
Method signatures and docstrings:
- def __init__(self, true_labels, inv_psp=None, remove_invalid=False): Class to compute vanilla and propensity scored precision and ndcg Arguments: --------- true_labels: csr_matrix ... | Implement the Python class `Metrics` described below.
Class description:
Implement the Metrics class.
Method signatures and docstrings:
- def __init__(self, true_labels, inv_psp=None, remove_invalid=False): Class to compute vanilla and propensity scored precision and ndcg Arguments: --------- true_labels: csr_matrix ... | 6e23615742f0bb263313f2899f46bb027ea68007 | <|skeleton|>
class Metrics:
def __init__(self, true_labels, inv_psp=None, remove_invalid=False):
"""Class to compute vanilla and propensity scored precision and ndcg Arguments: --------- true_labels: csr_matrix or np.ndarray ground truth in sparse or dense format shape: (num_instances, num_labels) inv_psp:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Metrics:
def __init__(self, true_labels, inv_psp=None, remove_invalid=False):
"""Class to compute vanilla and propensity scored precision and ndcg Arguments: --------- true_labels: csr_matrix or np.ndarray ground truth in sparse or dense format shape: (num_instances, num_labels) inv_psp: np.ndarray or... | the_stack_v2_python_sparse | xclib/evaluation/xc_metrics.py | ryaninhust/pyxclib | train | 0 | |
58dad088a62149f810dfc1ccb95e6f92adf51455 | [
"self.config = config\nself.s3_util = CORTXS3Util(self.config, connectionType)\nif connection is None:\n super(CORTXS3KVApi, self).__init__(self.config, connectionType)\nelse:\n super(CORTXS3KVApi, self).__init__(self.config, connectionType, connection=connection)",
"if index_id is None:\n Log.error('Ind... | <|body_start_0|>
self.config = config
self.s3_util = CORTXS3Util(self.config, connectionType)
if connection is None:
super(CORTXS3KVApi, self).__init__(self.config, connectionType)
else:
super(CORTXS3KVApi, self).__init__(self.config, connectionType, connection=co... | CORTXS3KVApi provides key-value REST-API's Put, Get & Delete. | CORTXS3KVApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CORTXS3KVApi:
"""CORTXS3KVApi provides key-value REST-API's Put, Get & Delete."""
def __init__(self, config, connectionType, connection=None):
"""Initialise config."""
<|body_0|>
def put(self, index_id=None, object_key_name=None, value=''):
"""Perform PUT request... | stack_v2_sparse_classes_75kplus_train_003886 | 8,568 | permissive | [
{
"docstring": "Initialise config.",
"name": "__init__",
"signature": "def __init__(self, config, connectionType, connection=None)"
},
{
"docstring": "Perform PUT request and generate response.",
"name": "put",
"signature": "def put(self, index_id=None, object_key_name=None, value='')"
... | 4 | stack_v2_sparse_classes_30k_train_003134 | Implement the Python class `CORTXS3KVApi` described below.
Class description:
CORTXS3KVApi provides key-value REST-API's Put, Get & Delete.
Method signatures and docstrings:
- def __init__(self, config, connectionType, connection=None): Initialise config.
- def put(self, index_id=None, object_key_name=None, value='')... | Implement the Python class `CORTXS3KVApi` described below.
Class description:
CORTXS3KVApi provides key-value REST-API's Put, Get & Delete.
Method signatures and docstrings:
- def __init__(self, config, connectionType, connection=None): Initialise config.
- def put(self, index_id=None, object_key_name=None, value='')... | b1987967aec7e24530c9703db6f100d2c8289624 | <|skeleton|>
class CORTXS3KVApi:
"""CORTXS3KVApi provides key-value REST-API's Put, Get & Delete."""
def __init__(self, config, connectionType, connection=None):
"""Initialise config."""
<|body_0|>
def put(self, index_id=None, object_key_name=None, value=''):
"""Perform PUT request... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CORTXS3KVApi:
"""CORTXS3KVApi provides key-value REST-API's Put, Get & Delete."""
def __init__(self, config, connectionType, connection=None):
"""Initialise config."""
self.config = config
self.s3_util = CORTXS3Util(self.config, connectionType)
if connection is None:
... | the_stack_v2_python_sparse | s3backgrounddelete/s3backgrounddelete/cortx_s3_kv_api.py | Seagate/cortx-s3server | train | 38 |
0f4c485eb4324fd63468979bf018562474699973 | [
"if target == 'html':\n return f'<a href=\"{link}\">{description}</a>'\nelif target == 'md':\n return f'[{description}]({link})'\nelse:\n raise ValueError(f'Can only template links to `html` or `md`, got `{target}`')",
"link_format = request.query_params.get('link_format', 'md')\nif link_format not in ('... | <|body_start_0|>
if target == 'html':
return f'<a href="{link}">{description}</a>'
elif target == 'md':
return f'[{description}]({link})'
else:
raise ValueError(f'Can only template links to `html` or `md`, got `{target}`')
<|end_body_0|>
<|body_start_1|>
... | Return a list of the server's rules. ## Routes ### GET /rules Returns a JSON array containing the server's rules and keywords relating to each rule. Example response: >>> [ ... ["Eat candy.", ["candy", "sweets"]], ... ["Wake up at 4 AM.", ["wake_up", "early", "early_bird"]], ... ["Take your medicine.", ["medicine", "he... | RulesView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RulesView:
"""Return a list of the server's rules. ## Routes ### GET /rules Returns a JSON array containing the server's rules and keywords relating to each rule. Example response: >>> [ ... ["Eat candy.", ["candy", "sweets"]], ... ["Wake up at 4 AM.", ["wake_up", "early", "early_bird"]], ... ["T... | stack_v2_sparse_classes_75kplus_train_003887 | 7,527 | permissive | [
{
"docstring": "Build the markup for rendering the link. This will render `link` with `description` as its description in the given `target` language. Arguments: description (str): A textual description of the string. Represents the content between the `<a>` tags in HTML, or the content between the array bracke... | 2 | stack_v2_sparse_classes_30k_train_040475 | Implement the Python class `RulesView` described below.
Class description:
Return a list of the server's rules. ## Routes ### GET /rules Returns a JSON array containing the server's rules and keywords relating to each rule. Example response: >>> [ ... ["Eat candy.", ["candy", "sweets"]], ... ["Wake up at 4 AM.", ["wak... | Implement the Python class `RulesView` described below.
Class description:
Return a list of the server's rules. ## Routes ### GET /rules Returns a JSON array containing the server's rules and keywords relating to each rule. Example response: >>> [ ... ["Eat candy.", ["candy", "sweets"]], ... ["Wake up at 4 AM.", ["wak... | cb6326cabee6570a5725702cb2893ae39f752279 | <|skeleton|>
class RulesView:
"""Return a list of the server's rules. ## Routes ### GET /rules Returns a JSON array containing the server's rules and keywords relating to each rule. Example response: >>> [ ... ["Eat candy.", ["candy", "sweets"]], ... ["Wake up at 4 AM.", ["wake_up", "early", "early_bird"]], ... ["T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RulesView:
"""Return a list of the server's rules. ## Routes ### GET /rules Returns a JSON array containing the server's rules and keywords relating to each rule. Example response: >>> [ ... ["Eat candy.", ["candy", "sweets"]], ... ["Wake up at 4 AM.", ["wake_up", "early", "early_bird"]], ... ["Take your medi... | the_stack_v2_python_sparse | pydis_site/apps/api/views.py | python-discord/site | train | 746 |
072c6a8839086ff0901bd8228fe4c6714e7f50d0 | [
"input_dim = next(iter(loaders['train']))['features'].shape[1]\nparam['input_dim'] = input_dim\nm = self.model(**param)\nself.metric = m.config_dict['selection_metric']\n_ = m.train(loaders, phases=phases)\ndf = m.predict(loaders, phases=['val'])['performance']\nscore = df.loc[df['metric'] == self.metric]['performa... | <|body_start_0|>
input_dim = next(iter(loaders['train']))['features'].shape[1]
param['input_dim'] = input_dim
m = self.model(**param)
self.metric = m.config_dict['selection_metric']
_ = m.train(loaders, phases=phases)
df = m.predict(loaders, phases=['val'])['performance']... | Gridsearch built for torch models implemented in the nn module that inherits gridsearch class ----------- Parameters ----------- model: torch model from utils_prediction.nn.models param_grid: dictionary with keys being parameter type and values being parameters additional arguments: save_fpath: path to save model save_... | gridsearch_nn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class gridsearch_nn:
"""Gridsearch built for torch models implemented in the nn module that inherits gridsearch class ----------- Parameters ----------- model: torch model from utils_prediction.nn.models param_grid: dictionary with keys being parameter type and values being parameters additional argume... | stack_v2_sparse_classes_75kplus_train_003888 | 9,178 | no_license | [
{
"docstring": "helper function to fit a model using user-defined param & fit_param",
"name": "fit_helper",
"signature": "def fit_helper(self, param, loaders, phases)"
},
{
"docstring": "conduct parralel grid search, save and return the model with best hyperparameters",
"name": "fit",
"s... | 3 | null | Implement the Python class `gridsearch_nn` described below.
Class description:
Gridsearch built for torch models implemented in the nn module that inherits gridsearch class ----------- Parameters ----------- model: torch model from utils_prediction.nn.models param_grid: dictionary with keys being parameter type and va... | Implement the Python class `gridsearch_nn` described below.
Class description:
Gridsearch built for torch models implemented in the nn module that inherits gridsearch class ----------- Parameters ----------- model: torch model from utils_prediction.nn.models param_grid: dictionary with keys being parameter type and va... | 82dfcd130164e75bdc671fb6df89f5e1350ae972 | <|skeleton|>
class gridsearch_nn:
"""Gridsearch built for torch models implemented in the nn module that inherits gridsearch class ----------- Parameters ----------- model: torch model from utils_prediction.nn.models param_grid: dictionary with keys being parameter type and values being parameters additional argume... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class gridsearch_nn:
"""Gridsearch built for torch models implemented in the nn module that inherits gridsearch class ----------- Parameters ----------- model: torch model from utils_prediction.nn.models param_grid: dictionary with keys being parameter type and values being parameters additional arguments: save_fpa... | the_stack_v2_python_sparse | utils_prediction/utils_prediction/model_selection.py | sungresearch/mimic4ds_public | train | 8 |
3012f6c74bf29a76ec8c6dc6df44fe283e84d263 | [
"try:\n stripped_text = self._STRIPPER.transformString(raw_text)\n structure = self._MESSAGE.parseString(stripped_text)\nexcept pyparsing.ParseException as exception:\n raise errors.ParseError('Unable to parse raw text with error: {0!s}'.format(exception))\nnickname = self._GetValueFromStructure(structure,... | <|body_start_0|>
try:
stripped_text = self._STRIPPER.transformString(raw_text)
structure = self._MESSAGE.parseString(stripped_text)
except pyparsing.ParseException as exception:
raise errors.ParseError('Unable to parse raw text with error: {0!s}'.format(exception))
... | Text parser plugin for XChat scrollback log files. | XChatScrollbackLogTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XChatScrollbackLogTextPlugin:
"""Text parser plugin for XChat scrollback log files."""
def _ParseRawText(self, raw_text):
"""Parses the raw text. This method implements the XChat strip_color2 and fe_print_text functions, slightly modified to get pure text. From the parsing point of v... | stack_v2_sparse_classes_75kplus_train_003889 | 5,882 | permissive | [
{
"docstring": "Parses the raw text. This method implements the XChat strip_color2 and fe_print_text functions, slightly modified to get pure text. From the parsing point of view, after having stripped, the code takes everything as is, simply replacing tabs with spaces (as the original XChat code). Args: raw_te... | 3 | stack_v2_sparse_classes_30k_train_019963 | Implement the Python class `XChatScrollbackLogTextPlugin` described below.
Class description:
Text parser plugin for XChat scrollback log files.
Method signatures and docstrings:
- def _ParseRawText(self, raw_text): Parses the raw text. This method implements the XChat strip_color2 and fe_print_text functions, slight... | Implement the Python class `XChatScrollbackLogTextPlugin` described below.
Class description:
Text parser plugin for XChat scrollback log files.
Method signatures and docstrings:
- def _ParseRawText(self, raw_text): Parses the raw text. This method implements the XChat strip_color2 and fe_print_text functions, slight... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class XChatScrollbackLogTextPlugin:
"""Text parser plugin for XChat scrollback log files."""
def _ParseRawText(self, raw_text):
"""Parses the raw text. This method implements the XChat strip_color2 and fe_print_text functions, slightly modified to get pure text. From the parsing point of v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XChatScrollbackLogTextPlugin:
"""Text parser plugin for XChat scrollback log files."""
def _ParseRawText(self, raw_text):
"""Parses the raw text. This method implements the XChat strip_color2 and fe_print_text functions, slightly modified to get pure text. From the parsing point of view, after ha... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/xchatscrollback.py | log2timeline/plaso | train | 1,506 |
671e47df53905141bf952e62daa07d7d198d1f12 | [
"if basename is None:\n basename = self.get_default_basename(viewset)\nif router_class is not None:\n kwargs = {'trailing_slash': bool(self.trailing_slash)}\n single_object_router_classes = (AuthenticationRouter, SingleObjectRouter)\n if issubclass(router_class, single_object_router_classes):\n r... | <|body_start_0|>
if basename is None:
basename = self.get_default_basename(viewset)
if router_class is not None:
kwargs = {'trailing_slash': bool(self.trailing_slash)}
single_object_router_classes = (AuthenticationRouter, SingleObjectRouter)
if issubclass(... | Default router that provides shortcuts to register single object viewsets. | DefaultRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultRouter:
"""Default router that provides shortcuts to register single object viewsets."""
def register(self, prefix, viewset, basename=None, router_class=None):
"""Append the given viewset to the proper registry."""
<|body_0|>
def get_urls(self):
"""Generat... | stack_v2_sparse_classes_75kplus_train_003890 | 4,452 | no_license | [
{
"docstring": "Append the given viewset to the proper registry.",
"name": "register",
"signature": "def register(self, prefix, viewset, basename=None, router_class=None)"
},
{
"docstring": "Generate the list of URL patterns including the registered single object routers urls.",
"name": "get... | 2 | stack_v2_sparse_classes_30k_train_036785 | Implement the Python class `DefaultRouter` described below.
Class description:
Default router that provides shortcuts to register single object viewsets.
Method signatures and docstrings:
- def register(self, prefix, viewset, basename=None, router_class=None): Append the given viewset to the proper registry.
- def ge... | Implement the Python class `DefaultRouter` described below.
Class description:
Default router that provides shortcuts to register single object viewsets.
Method signatures and docstrings:
- def register(self, prefix, viewset, basename=None, router_class=None): Append the given viewset to the proper registry.
- def ge... | d7799719f067b11d33e3c918edb18352ee0b84af | <|skeleton|>
class DefaultRouter:
"""Default router that provides shortcuts to register single object viewsets."""
def register(self, prefix, viewset, basename=None, router_class=None):
"""Append the given viewset to the proper registry."""
<|body_0|>
def get_urls(self):
"""Generat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultRouter:
"""Default router that provides shortcuts to register single object viewsets."""
def register(self, prefix, viewset, basename=None, router_class=None):
"""Append the given viewset to the proper registry."""
if basename is None:
basename = self.get_default_basena... | the_stack_v2_python_sparse | backend/utils/routers.py | sanchezpili6/sistema-medico-integral | train | 1 |
7513b936056db28a6a62f662f805fbc43148b426 | [
"result = deepcopy(Nat.zero)\nfor _ in range(x):\n result = Nat.S(result)\nreturn result",
"if not isinstance(x, FuncTerm) or x.sort != Nat.sort:\n raise ValueError('to_int function expects a nat.')\nif x == Nat.zero:\n return 0\nif isinstance(x, FuncTerm) and x.function == Nat.S:\n return 1 + cls.to_... | <|body_start_0|>
result = deepcopy(Nat.zero)
for _ in range(x):
result = Nat.S(result)
return result
<|end_body_0|>
<|body_start_1|>
if not isinstance(x, FuncTerm) or x.sort != Nat.sort:
raise ValueError('to_int function expects a nat.')
if x == Nat.zero:... | Nat | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nat:
def from_int(cls, x: int) -> Term:
"""Converts an integer to a nat."""
<|body_0|>
def to_int(cls, x: Term) -> int:
"""Converts a nat to an int."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = deepcopy(Nat.zero)
for _ in range(x... | stack_v2_sparse_classes_75kplus_train_003891 | 6,439 | permissive | [
{
"docstring": "Converts an integer to a nat.",
"name": "from_int",
"signature": "def from_int(cls, x: int) -> Term"
},
{
"docstring": "Converts a nat to an int.",
"name": "to_int",
"signature": "def to_int(cls, x: Term) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_026745 | Implement the Python class `Nat` described below.
Class description:
Implement the Nat class.
Method signatures and docstrings:
- def from_int(cls, x: int) -> Term: Converts an integer to a nat.
- def to_int(cls, x: Term) -> int: Converts a nat to an int. | Implement the Python class `Nat` described below.
Class description:
Implement the Nat class.
Method signatures and docstrings:
- def from_int(cls, x: int) -> Term: Converts an integer to a nat.
- def to_int(cls, x: Term) -> int: Converts a nat to an int.
<|skeleton|>
class Nat:
def from_int(cls, x: int) -> Ter... | 9e8351bfe49b09da17eaa7862572e9b09c45e13c | <|skeleton|>
class Nat:
def from_int(cls, x: int) -> Term:
"""Converts an integer to a nat."""
<|body_0|>
def to_int(cls, x: Term) -> int:
"""Converts a nat to an int."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Nat:
def from_int(cls, x: int) -> Term:
"""Converts an integer to a nat."""
result = deepcopy(Nat.zero)
for _ in range(x):
result = Nat.S(result)
return result
def to_int(cls, x: Term) -> int:
"""Converts a nat to an int."""
if not isinstance(x,... | the_stack_v2_python_sparse | theories/symcollab/theories/old/_nat_old.py | symcollab/CryptoSolve | train | 1 | |
dd86f947201b6610d708f915d86ae274ab12dac1 | [
"self.fhDict = {}\nfor fname in glob.glob(join(path, '*.vcf.gz')):\n chrom = basename(fname).split('.')[1].replace('chr', '')\n self.fhDict[chrom] = pysam.Tabixfile(fname)",
"chrom = chrom.replace('chr', '')\ntbi = self.fhDict[chrom]\nit = tbi.fetch(chrom, start, end, parser=pysam.asVCF())\nfor row in it:\n... | <|body_start_0|>
self.fhDict = {}
for fname in glob.glob(join(path, '*.vcf.gz')):
chrom = basename(fname).split('.')[1].replace('chr', '')
self.fhDict[chrom] = pysam.Tabixfile(fname)
<|end_body_0|>
<|body_start_1|>
chrom = chrom.replace('chr', '')
tbi = self.fhDi... | VcfDir | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VcfDir:
def __init__(self, path):
"""open tabixes, one per chrom"""
<|body_0|>
def fetch(self, chrom, start, end):
"""yield tuples (vcf object + info dict key->val) for a range vcf row attributes are: contig pos chromosomal position, zero-based id ref reference alt a... | stack_v2_sparse_classes_75kplus_train_003892 | 1,813 | no_license | [
{
"docstring": "open tabixes, one per chrom",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "yield tuples (vcf object + info dict key->val) for a range vcf row attributes are: contig pos chromosomal position, zero-based id ref reference alt alt qual qual filter fi... | 2 | stack_v2_sparse_classes_30k_train_032392 | Implement the Python class `VcfDir` described below.
Class description:
Implement the VcfDir class.
Method signatures and docstrings:
- def __init__(self, path): open tabixes, one per chrom
- def fetch(self, chrom, start, end): yield tuples (vcf object + info dict key->val) for a range vcf row attributes are: contig ... | Implement the Python class `VcfDir` described below.
Class description:
Implement the VcfDir class.
Method signatures and docstrings:
- def __init__(self, path): open tabixes, one per chrom
- def fetch(self, chrom, start, end): yield tuples (vcf object + info dict key->val) for a range vcf row attributes are: contig ... | 99ad033be03779e9680ce8024cdd7a4bdc5a58bd | <|skeleton|>
class VcfDir:
def __init__(self, path):
"""open tabixes, one per chrom"""
<|body_0|>
def fetch(self, chrom, start, end):
"""yield tuples (vcf object + info dict key->val) for a range vcf row attributes are: contig pos chromosomal position, zero-based id ref reference alt a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VcfDir:
def __init__(self, path):
"""open tabixes, one per chrom"""
self.fhDict = {}
for fname in glob.glob(join(path, '*.vcf.gz')):
chrom = basename(fname).split('.')[1].replace('chr', '')
self.fhDict[chrom] = pysam.Tabixfile(fname)
def fetch(self, chrom, ... | the_stack_v2_python_sparse | lib/pubVcf.py | maximilianh/pubMunch | train | 43 | |
f388f316f71cb91c3897d4c28d74a7c8f156925c | [
"class Base(ServerEndpointBase):\n x = Metric(Int64)\n\nclass Foo(Base):\n pass\nfoo = Foo(GROUPID)\nself.assertEqual(foo.x, Int64().icpw_value)\nself.assertIn('x', foo.icpw_signature()['metrics'])\nself.assertIn('x', foo.icpw_all_metrics())",
"class Base(ServerEndpointBase):\n\n @icpw_timer(5)\n def ... | <|body_start_0|>
class Base(ServerEndpointBase):
x = Metric(Int64)
class Foo(Base):
pass
foo = Foo(GROUPID)
self.assertEqual(foo.x, Int64().icpw_value)
self.assertIn('x', foo.icpw_signature()['metrics'])
self.assertIn('x', foo.icpw_all_metrics())
... | InheritanceTester | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InheritanceTester:
def test_inherit_metric(self):
"""Test that an endpoint derived from another endpoint inherits its metrics."""
<|body_0|>
def test_inherit_timer(self):
"""Test that a derived endpoint inherits timers."""
<|body_1|>
def test_inherit_tri... | stack_v2_sparse_classes_75kplus_train_003893 | 18,502 | permissive | [
{
"docstring": "Test that an endpoint derived from another endpoint inherits its metrics.",
"name": "test_inherit_metric",
"signature": "def test_inherit_metric(self)"
},
{
"docstring": "Test that a derived endpoint inherits timers.",
"name": "test_inherit_timer",
"signature": "def test_... | 4 | stack_v2_sparse_classes_30k_train_005176 | Implement the Python class `InheritanceTester` described below.
Class description:
Implement the InheritanceTester class.
Method signatures and docstrings:
- def test_inherit_metric(self): Test that an endpoint derived from another endpoint inherits its metrics.
- def test_inherit_timer(self): Test that a derived end... | Implement the Python class `InheritanceTester` described below.
Class description:
Implement the InheritanceTester class.
Method signatures and docstrings:
- def test_inherit_metric(self): Test that an endpoint derived from another endpoint inherits its metrics.
- def test_inherit_timer(self): Test that a derived end... | a626f881d55c307bd857d0ff980cc526f2b18de2 | <|skeleton|>
class InheritanceTester:
def test_inherit_metric(self):
"""Test that an endpoint derived from another endpoint inherits its metrics."""
<|body_0|>
def test_inherit_timer(self):
"""Test that a derived endpoint inherits timers."""
<|body_1|>
def test_inherit_tri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InheritanceTester:
def test_inherit_metric(self):
"""Test that an endpoint derived from another endpoint inherits its metrics."""
class Base(ServerEndpointBase):
x = Metric(Int64)
class Foo(Base):
pass
foo = Foo(GROUPID)
self.assertEqual(foo.x, ... | the_stack_v2_python_sparse | icypaw/test_server_endpoint_base.py | sandialabs/IcyPaw | train | 0 | |
f7f15490002310f3a1b2f2955f42f961105ae762 | [
"self.id = NytramEngine.Entity_Add()\nself.scene = scene\nself.behaviors = Behaviors(self, parentAttr='entity')\nNytramEngine.Entity_SetStartCallback(self.id, self.behaviors.start.engineCallback)\nNytramEngine.Entity_SetUpdateCallback(self.id, self.behaviors.update.engineCallback)\nself.renderer = renderer\nself.tr... | <|body_start_0|>
self.id = NytramEngine.Entity_Add()
self.scene = scene
self.behaviors = Behaviors(self, parentAttr='entity')
NytramEngine.Entity_SetStartCallback(self.id, self.behaviors.start.engineCallback)
NytramEngine.Entity_SetUpdateCallback(self.id, self.behaviors.update.en... | Represents an entity in the game engine | Entity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Entity:
"""Represents an entity in the game engine"""
def __init__(self, scene, renderer=None, transform=None):
"""Initialize the Entity"""
<|body_0|>
def __getattr__(self, name):
"""Return the requested attr"""
<|body_1|>
def __setattr__(self, name,... | stack_v2_sparse_classes_75kplus_train_003894 | 1,274 | no_license | [
{
"docstring": "Initialize the Entity",
"name": "__init__",
"signature": "def __init__(self, scene, renderer=None, transform=None)"
},
{
"docstring": "Return the requested attr",
"name": "__getattr__",
"signature": "def __getattr__(self, name)"
},
{
"docstring": "Set the attr",
... | 3 | stack_v2_sparse_classes_30k_train_011559 | Implement the Python class `Entity` described below.
Class description:
Represents an entity in the game engine
Method signatures and docstrings:
- def __init__(self, scene, renderer=None, transform=None): Initialize the Entity
- def __getattr__(self, name): Return the requested attr
- def __setattr__(self, name, val... | Implement the Python class `Entity` described below.
Class description:
Represents an entity in the game engine
Method signatures and docstrings:
- def __init__(self, scene, renderer=None, transform=None): Initialize the Entity
- def __getattr__(self, name): Return the requested attr
- def __setattr__(self, name, val... | 98b2ec8e289e933f027736421f2c89357ab4473e | <|skeleton|>
class Entity:
"""Represents an entity in the game engine"""
def __init__(self, scene, renderer=None, transform=None):
"""Initialize the Entity"""
<|body_0|>
def __getattr__(self, name):
"""Return the requested attr"""
<|body_1|>
def __setattr__(self, name,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Entity:
"""Represents an entity in the game engine"""
def __init__(self, scene, renderer=None, transform=None):
"""Initialize the Entity"""
self.id = NytramEngine.Entity_Add()
self.scene = scene
self.behaviors = Behaviors(self, parentAttr='entity')
NytramEngine.Ent... | the_stack_v2_python_sparse | src/python/nytram/entity/entity.py | cloew/Nytram | train | 0 |
6bb9624ad6794e35bfa301abc06b194e4e4d66a2 | [
"profile = self.request.user.profile\nserializer_context = {'request': request}\ntry:\n article = Article.objects.get(slug=article_slug)\nexcept Article.DoesNotExist:\n raise NotFound('An article with this slug was not found.')\nprofile.unfavorite(article)\nserializer = self.serializer_class(article, context=... | <|body_start_0|>
profile = self.request.user.profile
serializer_context = {'request': request}
try:
article = Article.objects.get(slug=article_slug)
except Article.DoesNotExist:
raise NotFound('An article with this slug was not found.')
profile.unfavorite(... | This View allows users to Favorite and Unfavorite articles, an exception is thrown if the article doesn’t exist. | ArticlesFavoriteAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticlesFavoriteAPIView:
"""This View allows users to Favorite and Unfavorite articles, an exception is thrown if the article doesn’t exist."""
def delete(self, request, article_slug=None):
"""Unfavorites an existing article with the profile unfavorite method"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_003895 | 24,455 | permissive | [
{
"docstring": "Unfavorites an existing article with the profile unfavorite method",
"name": "delete",
"signature": "def delete(self, request, article_slug=None)"
},
{
"docstring": "unfavorites an existing article with the profile favorite method",
"name": "post",
"signature": "def post(... | 2 | stack_v2_sparse_classes_30k_train_002704 | Implement the Python class `ArticlesFavoriteAPIView` described below.
Class description:
This View allows users to Favorite and Unfavorite articles, an exception is thrown if the article doesn’t exist.
Method signatures and docstrings:
- def delete(self, request, article_slug=None): Unfavorites an existing article wi... | Implement the Python class `ArticlesFavoriteAPIView` described below.
Class description:
This View allows users to Favorite and Unfavorite articles, an exception is thrown if the article doesn’t exist.
Method signatures and docstrings:
- def delete(self, request, article_slug=None): Unfavorites an existing article wi... | ebe3a4621a5baf36a9345d4b126ba73dc37acd1f | <|skeleton|>
class ArticlesFavoriteAPIView:
"""This View allows users to Favorite and Unfavorite articles, an exception is thrown if the article doesn’t exist."""
def delete(self, request, article_slug=None):
"""Unfavorites an existing article with the profile unfavorite method"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArticlesFavoriteAPIView:
"""This View allows users to Favorite and Unfavorite articles, an exception is thrown if the article doesn’t exist."""
def delete(self, request, article_slug=None):
"""Unfavorites an existing article with the profile unfavorite method"""
profile = self.request.use... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/ah-leagueOfLegends | train | 0 |
c496dbd0244bc28e482f95e7d831f9c6b753f613 | [
"self.device_bus = device_bus\nself.device_index = device_index\nself.disk_size_bytes = disk_size_bytes",
"if dictionary is None:\n return None\ndevice_bus = dictionary.get('deviceBus')\ndevice_index = dictionary.get('deviceIndex')\ndisk_size_bytes = dictionary.get('diskSizeBytes')\nreturn cls(device_bus, devi... | <|body_start_0|>
self.device_bus = device_bus
self.device_index = device_index
self.disk_size_bytes = disk_size_bytes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
device_bus = dictionary.get('deviceBus')
device_index = dictionary.get('de... | Implementation of the 'VirtualDiskConfig' model. Acropolis Virtual Disk Attributes: device_bus (string): The device bus for the virtual disk device. device_index (int): Index of the device on the adapter type. disk_size_bytes (long|int): Disk size in Bytes. | VirtualDiskConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualDiskConfig:
"""Implementation of the 'VirtualDiskConfig' model. Acropolis Virtual Disk Attributes: device_bus (string): The device bus for the virtual disk device. device_index (int): Index of the device on the adapter type. disk_size_bytes (long|int): Disk size in Bytes."""
def __ini... | stack_v2_sparse_classes_75kplus_train_003896 | 1,862 | permissive | [
{
"docstring": "Constructor for the VirtualDiskConfig class",
"name": "__init__",
"signature": "def __init__(self, device_bus=None, device_index=None, disk_size_bytes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represe... | 2 | stack_v2_sparse_classes_30k_test_001363 | Implement the Python class `VirtualDiskConfig` described below.
Class description:
Implementation of the 'VirtualDiskConfig' model. Acropolis Virtual Disk Attributes: device_bus (string): The device bus for the virtual disk device. device_index (int): Index of the device on the adapter type. disk_size_bytes (long|int)... | Implement the Python class `VirtualDiskConfig` described below.
Class description:
Implementation of the 'VirtualDiskConfig' model. Acropolis Virtual Disk Attributes: device_bus (string): The device bus for the virtual disk device. device_index (int): Index of the device on the adapter type. disk_size_bytes (long|int)... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VirtualDiskConfig:
"""Implementation of the 'VirtualDiskConfig' model. Acropolis Virtual Disk Attributes: device_bus (string): The device bus for the virtual disk device. device_index (int): Index of the device on the adapter type. disk_size_bytes (long|int): Disk size in Bytes."""
def __ini... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VirtualDiskConfig:
"""Implementation of the 'VirtualDiskConfig' model. Acropolis Virtual Disk Attributes: device_bus (string): The device bus for the virtual disk device. device_index (int): Index of the device on the adapter type. disk_size_bytes (long|int): Disk size in Bytes."""
def __init__(self, dev... | the_stack_v2_python_sparse | cohesity_management_sdk/models/virtual_disk_config.py | cohesity/management-sdk-python | train | 24 |
d3293e64b58782f88ec07ae8be9eef4e1b1a044e | [
"super().__init__(**kwargs)\nfrom transformers import AutoModelForQuestionAnswering, AutoTokenizer\nself.model_name = model_name\nself.model = AutoModelForQuestionAnswering.from_pretrained(model_name)\nself.tokenizer = AutoTokenizer.from_pretrained(model_name)\nself.device = device\nself.model.eval()\nself.model.to... | <|body_start_0|>
super().__init__(**kwargs)
from transformers import AutoModelForQuestionAnswering, AutoTokenizer
self.model_name = model_name
self.model = AutoModelForQuestionAnswering.from_pretrained(model_name)
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
... | Span-based Reader. This is implemented as a simple Question Answering (QA) system. BERT-based QA is traditionally treated in an extractive setting, or span prediction. Instead of generating text, the BERT model will produce the start and end indices of the span in the document that comprise the answer. Check the offici... | SpanReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpanReader:
"""Span-based Reader. This is implemented as a simple Question Answering (QA) system. BERT-based QA is traditionally treated in an extractive setting, or span prediction. Instead of generating text, the BERT model will produce the start and end indices of the span in the document that... | stack_v2_sparse_classes_75kplus_train_003897 | 10,872 | permissive | [
{
"docstring": "Constructor of SpanReader class. Parameters ---------- model_name: str The name of the pretrained model to be used as a span extraction question answering. Should be BERT-based. device: str, defaults to \"cpu\" The name of the device to run this model on. max_length: int, defaults to 512 The max... | 2 | stack_v2_sparse_classes_30k_train_020023 | Implement the Python class `SpanReader` described below.
Class description:
Span-based Reader. This is implemented as a simple Question Answering (QA) system. BERT-based QA is traditionally treated in an extractive setting, or span prediction. Instead of generating text, the BERT model will produce the start and end i... | Implement the Python class `SpanReader` described below.
Class description:
Span-based Reader. This is implemented as a simple Question Answering (QA) system. BERT-based QA is traditionally treated in an extractive setting, or span prediction. Instead of generating text, the BERT model will produce the start and end i... | a80b36cf5287cbd97a084286ce14148b67ea5b8b | <|skeleton|>
class SpanReader:
"""Span-based Reader. This is implemented as a simple Question Answering (QA) system. BERT-based QA is traditionally treated in an extractive setting, or span prediction. Instead of generating text, the BERT model will produce the start and end indices of the span in the document that... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpanReader:
"""Span-based Reader. This is implemented as a simple Question Answering (QA) system. BERT-based QA is traditionally treated in an extractive setting, or span prediction. Instead of generating text, the BERT model will produce the start and end indices of the span in the document that comprise the... | the_stack_v2_python_sparse | hw3/code/reader.py | sameersingh/uci-statnlp | train | 25 |
fc7a956a6392adb7d3404c718d47926efac134c3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DirectoryAudit()",
"from .audit_activity_initiator import AuditActivityInitiator\nfrom .entity import Entity\nfrom .key_value import KeyValue\nfrom .operation_result import OperationResult\nfrom .target_resource import TargetResource\n... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DirectoryAudit()
<|end_body_0|>
<|body_start_1|>
from .audit_activity_initiator import AuditActivityInitiator
from .entity import Entity
from .key_value import KeyValue
f... | DirectoryAudit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectoryAudit:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryAudit:
"""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 Retur... | stack_v2_sparse_classes_75kplus_train_003898 | 6,639 | 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: DirectoryAudit",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | null | Implement the Python class `DirectoryAudit` described below.
Class description:
Implement the DirectoryAudit class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryAudit: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `DirectoryAudit` described below.
Class description:
Implement the DirectoryAudit class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryAudit: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DirectoryAudit:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryAudit:
"""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 Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DirectoryAudit:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryAudit:
"""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: DirectoryA... | the_stack_v2_python_sparse | msgraph/generated/models/directory_audit.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
9124c4aad50d04b9f2c93ede29828cd02f3fe9e9 | [
"bboxes = []\nfor i in range(len(ocr_results['text'])):\n detected_text = ocr_results['text'][i]\n if detected_text:\n bbox = {'left': ocr_results['left'][i], 'top': ocr_results['top'][i], 'width': ocr_results['width'][i], 'height': ocr_results['height'][i], 'conf': float(ocr_results['conf'][i]), 'labe... | <|body_start_0|>
bboxes = []
for i in range(len(ocr_results['text'])):
detected_text = ocr_results['text'][i]
if detected_text:
bbox = {'left': ocr_results['left'][i], 'top': ocr_results['top'][i], 'width': ocr_results['width'][i], 'height': ocr_results['height'][... | Common module for general bounding box operators. | BboxProcessor | [
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"BSD-3-Clause",
"Unlicense",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-warranty-disclaimer",
"CNRI-Python",
"MIT",
"LicenseRef-scancode-secret-labs-2011",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BboxProcessor:
"""Common module for general bounding box operators."""
def get_bboxes_from_ocr_results(self, ocr_results: Dict[str, List[Union[int, str]]]) -> List[Dict[str, Union[int, float, str]]]:
"""Get bounding boxes on padded image for all detected words from ocr_results. :para... | stack_v2_sparse_classes_75kplus_train_003899 | 4,970 | permissive | [
{
"docstring": "Get bounding boxes on padded image for all detected words from ocr_results. :param ocr_results: Raw results from OCR. :return: Bounding box information per word.",
"name": "get_bboxes_from_ocr_results",
"signature": "def get_bboxes_from_ocr_results(self, ocr_results: Dict[str, List[Union... | 4 | stack_v2_sparse_classes_30k_train_037201 | Implement the Python class `BboxProcessor` described below.
Class description:
Common module for general bounding box operators.
Method signatures and docstrings:
- def get_bboxes_from_ocr_results(self, ocr_results: Dict[str, List[Union[int, str]]]) -> List[Dict[str, Union[int, float, str]]]: Get bounding boxes on pa... | Implement the Python class `BboxProcessor` described below.
Class description:
Common module for general bounding box operators.
Method signatures and docstrings:
- def get_bboxes_from_ocr_results(self, ocr_results: Dict[str, List[Union[int, str]]]) -> List[Dict[str, Union[int, float, str]]]: Get bounding boxes on pa... | 3effc1467b8714714d5112ef7b627889507ea83d | <|skeleton|>
class BboxProcessor:
"""Common module for general bounding box operators."""
def get_bboxes_from_ocr_results(self, ocr_results: Dict[str, List[Union[int, str]]]) -> List[Dict[str, Union[int, float, str]]]:
"""Get bounding boxes on padded image for all detected words from ocr_results. :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BboxProcessor:
"""Common module for general bounding box operators."""
def get_bboxes_from_ocr_results(self, ocr_results: Dict[str, List[Union[int, str]]]) -> List[Dict[str, Union[int, float, str]]]:
"""Get bounding boxes on padded image for all detected words from ocr_results. :param ocr_results... | the_stack_v2_python_sparse | presidio-image-redactor/presidio_image_redactor/bbox.py | microsoft/presidio | train | 2,092 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.