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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
333f1e77562f3295fa1cced6c3a2d28320fbf1ea | [
"N = len(nums)\ndp = [[float('inf') for _ in range(m + 1)] for _ in range(N + 1)]\nacc = [0 for _ in range(N + 1)]\nfor i in range(N + 1):\n acc[i + 1] = acc[i] + nums[i]\ndp[0][0] = 0\nfor i in range(1, N + 1):\n for j in range(1, m + 1):\n for k in range(i):\n dp[i][j] = min(dp[i][j], max(... | <|body_start_0|>
N = len(nums)
dp = [[float('inf') for _ in range(m + 1)] for _ in range(N + 1)]
acc = [0 for _ in range(N + 1)]
for i in range(N + 1):
acc[i + 1] = acc[i] + nums[i]
dp[0][0] = 0
for i in range(1, N + 1):
for j in range(1, m + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_0|>
def min_human(self, tasks, days):
"""type days: int type task: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
N = len(nums)
d... | stack_v2_sparse_classes_75kplus_train_009400 | 1,911 | no_license | [
{
"docstring": ":type nums: List[int] :type m: int :rtype: int",
"name": "splitArray",
"signature": "def splitArray(self, nums, m)"
},
{
"docstring": "type days: int type task: List[int]",
"name": "min_human",
"signature": "def min_human(self, tasks, days)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int
- def min_human(self, tasks, days): type days: int type task: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int
- def min_human(self, tasks, days): type days: int type task: List[int]
<|skeleton|>
class Solution... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_0|>
def min_human(self, tasks, days):
"""type days: int type task: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
N = len(nums)
dp = [[float('inf') for _ in range(m + 1)] for _ in range(N + 1)]
acc = [0 for _ in range(N + 1)]
for i in range(N + 1):
acc[i + 1] = acc[i] + nums[i]... | the_stack_v2_python_sparse | Algorithm/410_Split_Array_Largest_Sum.py | Gi1ia/TechNoteBook | train | 7 | |
1c9c233b175fe713ecfa3d98ad640f9291151b73 | [
"self.generator = random_number_generator\nself.length = length\nself.num_generated_numbers = None",
"if self.num_generated_numbers is not None:\n raise RuntimeError\nself.num_generated_numbers = 0\nreturn self",
"if self.num_generated_numbers is None:\n raise RuntimeError('Cannot call \"next\" before Ran... | <|body_start_0|>
self.generator = random_number_generator
self.length = length
self.num_generated_numbers = None
<|end_body_0|>
<|body_start_1|>
if self.num_generated_numbers is not None:
raise RuntimeError
self.num_generated_numbers = 0
return self
<|end_bod... | RandIter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandIter:
def __init__(self, random_number_generator, length):
"""Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate"""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_009401 | 3,027 | no_license | [
{
"docstring": "Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate",
"name": "__init__",
"signature": "def __init__(self, random_number_generator, length... | 3 | stack_v2_sparse_classes_30k_train_020359 | Implement the Python class `RandIter` described below.
Class description:
Implement the RandIter class.
Method signatures and docstrings:
- def __init__(self, random_number_generator, length): Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and re... | Implement the Python class `RandIter` described below.
Class description:
Implement the RandIter class.
Method signatures and docstrings:
- def __init__(self, random_number_generator, length): Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and re... | 527f908422b559e6afc1ec025c04336d7a13828d | <|skeleton|>
class RandIter:
def __init__(self, random_number_generator, length):
"""Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate"""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandIter:
def __init__(self, random_number_generator, length):
"""Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate"""
self.generator = random... | the_stack_v2_python_sparse | src/nicolai_munsterhjelm_ex/ex05/myrand.py | Nicomunster/INF200-2019-Exercises | train | 0 | |
363a45c6bf1ab508861ef94dedc9776eb690ebd1 | [
"self._scenario = []\nself._approaches = []\nself._approaches.append(PatApproach())\nself._approaches.append(MatApproach())\nself._approaches.append(MaxApproach())\nself._approaches.append(PacApproach())",
"scenario_file = open(scenario_file_name)\nfor current_line in scenario_file:\n new_customer = Customer(c... | <|body_start_0|>
self._scenario = []
self._approaches = []
self._approaches.append(PatApproach())
self._approaches.append(MatApproach())
self._approaches.append(MaxApproach())
self._approaches.append(PacApproach())
<|end_body_0|>
<|body_start_1|>
scenario_file = ... | A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and methods you want. But because you should not change the interface, you may n... | Simulator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulator:
"""A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and methods you want. But because you shoul... | stack_v2_sparse_classes_75kplus_train_009402 | 4,220 | no_license | [
{
"docstring": "Initialize a Simulation.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Load a scenario from the scenario_file_name and store it in _scenario :param scenario_file_name: Name of the scenario file :type scenario_file_name: str :rtype: None",
"name": ... | 3 | stack_v2_sparse_classes_30k_test_000397 | Implement the Python class `Simulator` described below.
Class description:
A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and ... | Implement the Python class `Simulator` described below.
Class description:
A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and ... | 2b9312b30171686f1bb08f4052edd8c748cf848f | <|skeleton|>
class Simulator:
"""A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and methods you want. But because you shoul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Simulator:
"""A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and methods you want. But because you should not change ... | the_stack_v2_python_sparse | Assignments/a1/simulator.py | Lost-Accountant/csc148_2016_s | train | 0 |
2d57ae37f7de4d2ff20b69506a16cb64c84ce72b | [
"if self._instance is None:\n self._instance = object.__new__(self, *args, **kargs)\n self._tables = {}\n self._labels = []\nreturn self._instance",
"if label == None:\n raise RelaxError('The table label must be supplied.')\nif label in self._labels:\n raise RelaxError(\"The table with label '%s' h... | <|body_start_0|>
if self._instance is None:
self._instance = object.__new__(self, *args, **kargs)
self._tables = {}
self._labels = []
return self._instance
<|end_body_0|>
<|body_start_1|>
if label == None:
raise RelaxError('The table label must be... | The data singleton holding all of the description tables. | Uf_tables | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Uf_tables:
"""The data singleton holding all of the description tables."""
def __new__(self, *args, **kargs):
"""Replacement method for implementing the singleton design pattern."""
<|body_0|>
def add_table(self, label=None, caption=None, caption_short=None, spacing=True... | stack_v2_sparse_classes_75kplus_train_009403 | 9,776 | no_license | [
{
"docstring": "Replacement method for implementing the singleton design pattern.",
"name": "__new__",
"signature": "def __new__(self, *args, **kargs)"
},
{
"docstring": "Add a new table to the object. @keyword label: The unique label of the table. This is used to identify tables, and is also us... | 3 | stack_v2_sparse_classes_30k_train_047944 | Implement the Python class `Uf_tables` described below.
Class description:
The data singleton holding all of the description tables.
Method signatures and docstrings:
- def __new__(self, *args, **kargs): Replacement method for implementing the singleton design pattern.
- def add_table(self, label=None, caption=None, ... | Implement the Python class `Uf_tables` described below.
Class description:
The data singleton holding all of the description tables.
Method signatures and docstrings:
- def __new__(self, *args, **kargs): Replacement method for implementing the singleton design pattern.
- def add_table(self, label=None, caption=None, ... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Uf_tables:
"""The data singleton holding all of the description tables."""
def __new__(self, *args, **kargs):
"""Replacement method for implementing the singleton design pattern."""
<|body_0|>
def add_table(self, label=None, caption=None, caption_short=None, spacing=True... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Uf_tables:
"""The data singleton holding all of the description tables."""
def __new__(self, *args, **kargs):
"""Replacement method for implementing the singleton design pattern."""
if self._instance is None:
self._instance = object.__new__(self, *args, **kargs)
se... | the_stack_v2_python_sparse | user_functions/data.py | jlec/relax | train | 4 |
5a583ca1d3a3038c033ae1f39a38904479b7cfcc | [
"obj = Sensor.objects(name=name).first()\nif obj is None:\n return jsonify(responses.invalid_uuid)\ntags_owned = [{'name': tag.name, 'value': tag.value} for tag in obj.tags]\ntags = get_building_tags(obj.building)\nresponse = dict(responses.success_true)\nresponse.update({'tags': tags, 'tags_owned': tags_owned})... | <|body_start_0|>
obj = Sensor.objects(name=name).first()
if obj is None:
return jsonify(responses.invalid_uuid)
tags_owned = [{'name': tag.name, 'value': tag.value} for tag in obj.tags]
tags = get_building_tags(obj.building)
response = dict(responses.success_true)
... | SensorTagsService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensorTagsService:
def get(self, name):
"""Args as data: "name" : <sensor-uuid> Returns (JSON): { "tags": { "Tag Name": [ List of eligible values], . . . }, (These are the list of eligibile tags for this sensor) "tags_owned": [ { "name": <Tag-Name>, "value": <Tag-Value> }, . . . ] (These... | stack_v2_sparse_classes_75kplus_train_009404 | 2,802 | permissive | [
{
"docstring": "Args as data: \"name\" : <sensor-uuid> Returns (JSON): { \"tags\": { \"Tag Name\": [ List of eligible values], . . . }, (These are the list of eligibile tags for this sensor) \"tags_owned\": [ { \"name\": <Tag-Name>, \"value\": <Tag-Value> }, . . . ] (These are the list of tags owned by this sen... | 2 | null | Implement the Python class `SensorTagsService` described below.
Class description:
Implement the SensorTagsService class.
Method signatures and docstrings:
- def get(self, name): Args as data: "name" : <sensor-uuid> Returns (JSON): { "tags": { "Tag Name": [ List of eligible values], . . . }, (These are the list of el... | Implement the Python class `SensorTagsService` described below.
Class description:
Implement the SensorTagsService class.
Method signatures and docstrings:
- def get(self, name): Args as data: "name" : <sensor-uuid> Returns (JSON): { "tags": { "Tag Name": [ List of eligible values], . . . }, (These are the list of el... | 53ba7519c56d46af1e32a77aab5cf1c5cd8143fc | <|skeleton|>
class SensorTagsService:
def get(self, name):
"""Args as data: "name" : <sensor-uuid> Returns (JSON): { "tags": { "Tag Name": [ List of eligible values], . . . }, (These are the list of eligibile tags for this sensor) "tags_owned": [ { "name": <Tag-Name>, "value": <Tag-Value> }, . . . ] (These... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SensorTagsService:
def get(self, name):
"""Args as data: "name" : <sensor-uuid> Returns (JSON): { "tags": { "Tag Name": [ List of eligible values], . . . }, (These are the list of eligibile tags for this sensor) "tags_owned": [ { "name": <Tag-Name>, "value": <Tag-Value> }, . . . ] (These are the list ... | the_stack_v2_python_sparse | BuildingDepot-v3.2.8/buildingdepot/CentralService/app/rest_api/sensors/sensor_tags.py | Entromorgan/GIoTTo | train | 0 | |
dc17fb0f49a4c61be892bc5341567d564ca82806 | [
"if session is None and slot is None:\n raise LunaException('A slot ID or a session handle must be specified!')\nself.password = password\nself.user = user\nself.session = session\nself.slot = slot\nself._session = None",
"if self.session is None:\n self._session = Session(self.slot)\n self.session = sel... | <|body_start_0|>
if session is None and slot is None:
raise LunaException('A slot ID or a session handle must be specified!')
self.password = password
self.user = user
self.session = session
self.slot = slot
self._session = None
<|end_body_0|>
<|body_start_1|... | Session which has a user authenticated; C_Login is run | AuthenticatedSession | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticatedSession:
"""Session which has a user authenticated; C_Login is run"""
def __init__(self, password, user, session=None, slot=None):
"""A session can optionally already be open. Otherwise open one on entry. It is an error to omit both session and slot. :param password: use... | stack_v2_sparse_classes_75kplus_train_009405 | 3,686 | permissive | [
{
"docstring": "A session can optionally already be open. Otherwise open one on entry. It is an error to omit both session and slot. :param password: user password :param user: user :param session: session handle of an already open session :param slot: slot number",
"name": "__init__",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_040776 | Implement the Python class `AuthenticatedSession` described below.
Class description:
Session which has a user authenticated; C_Login is run
Method signatures and docstrings:
- def __init__(self, password, user, session=None, slot=None): A session can optionally already be open. Otherwise open one on entry. It is an ... | Implement the Python class `AuthenticatedSession` described below.
Class description:
Session which has a user authenticated; C_Login is run
Method signatures and docstrings:
- def __init__(self, password, user, session=None, slot=None): A session can optionally already be open. Otherwise open one on entry. It is an ... | 1d0b94307b9c92c4f19c3d3fe3bda1be37f4c853 | <|skeleton|>
class AuthenticatedSession:
"""Session which has a user authenticated; C_Login is run"""
def __init__(self, password, user, session=None, slot=None):
"""A session can optionally already be open. Otherwise open one on entry. It is an error to omit both session and slot. :param password: use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthenticatedSession:
"""Session which has a user authenticated; C_Login is run"""
def __init__(self, password, user, session=None, slot=None):
"""A session can optionally already be open. Otherwise open one on entry. It is an error to omit both session and slot. :param password: user password :p... | the_stack_v2_python_sparse | pycryptoki/utilities.py | ThalesGroup/pycryptoki | train | 29 |
0bc101cb949a2fdb2bf83006b13d2dd98a690a04 | [
"self.bills = {}\nself.cost_entries = {}\nself.line_items = []\nself.products = {}\nself.reservations = {}\nself.pricing = {}\nself.requested_partitions = set()",
"self.bills = {}\nself.cost_entries = {}\nself.line_items = []\nself.products = {}\nself.reservations = {}\nself.pricing = {}"
] | <|body_start_0|>
self.bills = {}
self.cost_entries = {}
self.line_items = []
self.products = {}
self.reservations = {}
self.pricing = {}
self.requested_partitions = set()
<|end_body_0|>
<|body_start_1|>
self.bills = {}
self.cost_entries = {}
... | Cost usage report transcribed to our database models. Effectively a struct for associated database tables. | ProcessedReport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessedReport:
"""Cost usage report transcribed to our database models. Effectively a struct for associated database tables."""
def __init__(self):
"""Initialize new cost entry containers."""
<|body_0|>
def remove_processed_rows(self):
"""Clear a batch of rows ... | stack_v2_sparse_classes_75kplus_train_009406 | 19,503 | permissive | [
{
"docstring": "Initialize new cost entry containers.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Clear a batch of rows from their containers.",
"name": "remove_processed_rows",
"signature": "def remove_processed_rows(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001374 | Implement the Python class `ProcessedReport` described below.
Class description:
Cost usage report transcribed to our database models. Effectively a struct for associated database tables.
Method signatures and docstrings:
- def __init__(self): Initialize new cost entry containers.
- def remove_processed_rows(self): C... | Implement the Python class `ProcessedReport` described below.
Class description:
Cost usage report transcribed to our database models. Effectively a struct for associated database tables.
Method signatures and docstrings:
- def __init__(self): Initialize new cost entry containers.
- def remove_processed_rows(self): C... | 2979f03fbdd1c20c3abc365a963a1282b426f321 | <|skeleton|>
class ProcessedReport:
"""Cost usage report transcribed to our database models. Effectively a struct for associated database tables."""
def __init__(self):
"""Initialize new cost entry containers."""
<|body_0|>
def remove_processed_rows(self):
"""Clear a batch of rows ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProcessedReport:
"""Cost usage report transcribed to our database models. Effectively a struct for associated database tables."""
def __init__(self):
"""Initialize new cost entry containers."""
self.bills = {}
self.cost_entries = {}
self.line_items = []
self.produc... | the_stack_v2_python_sparse | koku/masu/processor/aws/aws_report_processor.py | luisfdez/koku | train | 0 |
ea97491740fdb756629ae14602b1db028a3c93fa | [
"leoTkinterDialog.__init__(self, title, resizeable)\nself.createTopFrame()\nself.top.bind('<Key>', self.onKey)\nif message:\n self.createMessageFrame(message)\nbuttons = ({'text': 'Yes', 'command': self.yesButton, 'default': True}, {'text': 'No', 'command': self.noButton})\nself.createButtons(buttons)",
"ch = ... | <|body_start_0|>
leoTkinterDialog.__init__(self, title, resizeable)
self.createTopFrame()
self.top.bind('<Key>', self.onKey)
if message:
self.createMessageFrame(message)
buttons = ({'text': 'Yes', 'command': self.yesButton, 'default': True}, {'text': 'No', 'command': ... | A class that creates a Tkinter dialog with two buttons: Yes and No. | tkinterAskYesNo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tkinterAskYesNo:
"""A class that creates a Tkinter dialog with two buttons: Yes and No."""
def __init__(self, title, message=None, resizeable=False):
"""Create a dialog having yes and no buttons."""
<|body_0|>
def onKey(self, event):
"""Handle keystroke events in... | stack_v2_sparse_classes_75kplus_train_009407 | 25,997 | no_license | [
{
"docstring": "Create a dialog having yes and no buttons.",
"name": "__init__",
"signature": "def __init__(self, title, message=None, resizeable=False)"
},
{
"docstring": "Handle keystroke events in dialogs having yes and no buttons.",
"name": "onKey",
"signature": "def onKey(self, even... | 2 | stack_v2_sparse_classes_30k_train_040082 | Implement the Python class `tkinterAskYesNo` described below.
Class description:
A class that creates a Tkinter dialog with two buttons: Yes and No.
Method signatures and docstrings:
- def __init__(self, title, message=None, resizeable=False): Create a dialog having yes and no buttons.
- def onKey(self, event): Handl... | Implement the Python class `tkinterAskYesNo` described below.
Class description:
A class that creates a Tkinter dialog with two buttons: Yes and No.
Method signatures and docstrings:
- def __init__(self, title, message=None, resizeable=False): Create a dialog having yes and no buttons.
- def onKey(self, event): Handl... | 28c22721e1bc313c120a8a6c288893bc566a5c67 | <|skeleton|>
class tkinterAskYesNo:
"""A class that creates a Tkinter dialog with two buttons: Yes and No."""
def __init__(self, title, message=None, resizeable=False):
"""Create a dialog having yes and no buttons."""
<|body_0|>
def onKey(self, event):
"""Handle keystroke events in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class tkinterAskYesNo:
"""A class that creates a Tkinter dialog with two buttons: Yes and No."""
def __init__(self, title, message=None, resizeable=False):
"""Create a dialog having yes and no buttons."""
leoTkinterDialog.__init__(self, title, resizeable)
self.createTopFrame()
s... | the_stack_v2_python_sparse | Projects/jyleo/src/leoTkinterDialog.py | leo-editor/leo-editor-contrib | train | 6 |
7206e842d94c92cdf7ea889171d61692c53c469d | [
"from models import Proyecto, User, users\nproyecto = Proyecto.query.filter(Proyecto.nombre == proyectoNombre).first_or_404()\nusuario = User.query.filter(User.name == userName).first_or_404()\nproyecto.users.append(usuario)\ndb.session.commit()",
"from models import Proyecto, User, users\nproyecto = Proyecto.que... | <|body_start_0|>
from models import Proyecto, User, users
proyecto = Proyecto.query.filter(Proyecto.nombre == proyectoNombre).first_or_404()
usuario = User.query.filter(User.name == userName).first_or_404()
proyecto.users.append(usuario)
db.session.commit()
<|end_body_0|>
<|body... | MgrProyectoXUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MgrProyectoXUser:
def guardar(self, proyectoNombre, userName):
"""asigna a un proyecto un usuario"""
<|body_0|>
def borrar(self, proyectoNombre, userName):
"""deasigna a un proyecto un usuario"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from mod... | stack_v2_sparse_classes_75kplus_train_009408 | 837 | no_license | [
{
"docstring": "asigna a un proyecto un usuario",
"name": "guardar",
"signature": "def guardar(self, proyectoNombre, userName)"
},
{
"docstring": "deasigna a un proyecto un usuario",
"name": "borrar",
"signature": "def borrar(self, proyectoNombre, userName)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045983 | Implement the Python class `MgrProyectoXUser` described below.
Class description:
Implement the MgrProyectoXUser class.
Method signatures and docstrings:
- def guardar(self, proyectoNombre, userName): asigna a un proyecto un usuario
- def borrar(self, proyectoNombre, userName): deasigna a un proyecto un usuario | Implement the Python class `MgrProyectoXUser` described below.
Class description:
Implement the MgrProyectoXUser class.
Method signatures and docstrings:
- def guardar(self, proyectoNombre, userName): asigna a un proyecto un usuario
- def borrar(self, proyectoNombre, userName): deasigna a un proyecto un usuario
<|sk... | da5330f318698f86af12c3c91cb3f1524540f4ca | <|skeleton|>
class MgrProyectoXUser:
def guardar(self, proyectoNombre, userName):
"""asigna a un proyecto un usuario"""
<|body_0|>
def borrar(self, proyectoNombre, userName):
"""deasigna a un proyecto un usuario"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MgrProyectoXUser:
def guardar(self, proyectoNombre, userName):
"""asigna a un proyecto un usuario"""
from models import Proyecto, User, users
proyecto = Proyecto.query.filter(Proyecto.nombre == proyectoNombre).first_or_404()
usuario = User.query.filter(User.name == userName).fi... | the_stack_v2_python_sparse | src/mgrProyectoXUser.py | frvc123/proyecto-sicp | train | 0 | |
0f5b66ea01ab3465d24c9e5dad991f469ce9f6e6 | [
"dict.__init__(self)\nself.setdefault('Name', None)\nself.setdefault('Size', None)\nself.setdefault('NumEvents', None)\nself.setdefault('NumFiles', None)\nself.update(args)",
"block = Block()\nblock['Name'] = blockInfo[0]['name']\nblock['NumFiles'] = blockInfo[0]['num_files']\nblock['NumEvents'] = blockInfo[0]['n... | <|body_start_0|>
dict.__init__(self)
self.setdefault('Name', None)
self.setdefault('Size', None)
self.setdefault('NumEvents', None)
self.setdefault('NumFiles', None)
self.update(args)
<|end_body_0|>
<|body_start_1|>
block = Block()
block['Name'] = blockIn... | _Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles | Block | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Block:
"""_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles"""
def __init__(self, **args):
"""___init___ Initialize all attributes."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_009409 | 1,071 | permissive | [
{
"docstring": "___init___ Initialize all attributes.",
"name": "__init__",
"signature": "def __init__(self, **args)"
},
{
"docstring": "convert to the Block structure from db column format",
"name": "getBlock",
"signature": "def getBlock(blockInfo)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050042 | Implement the Python class `Block` described below.
Class description:
_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles
Method signatures and docstrings:
- def __init__(self, **args): ___ini... | Implement the Python class `Block` described below.
Class description:
_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles
Method signatures and docstrings:
- def __init__(self, **args): ___ini... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class Block:
"""_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles"""
def __init__(self, **args):
"""___init___ Initialize all attributes."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Block:
"""_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles"""
def __init__(self, **args):
"""___init___ Initialize all attributes."""
dict.__init__(self)
... | the_stack_v2_python_sparse | src/python/WMCore/WorkQueue/DataStructs/Block.py | vkuznet/WMCore | train | 0 |
43a9c9d8e3d3b9636750a9b1dcda7b57e388c428 | [
"ar = np.array(ar)\nar0 = ar.reshape(1, -1)\nnf, p1 = ar0.shape\nif p == None:\n p = p1 - 1\nff = np.fft.rfft(ar0, n=2 * p + 2).T ** (-1)\nreturn ff",
"N = len(x)\ne = np.zeros((N, p + 1))\nb = np.zeros((N, p + 1))\nalphal = np.zeros((p, p))\ne[:, 0] = x\nb[:, 0] = x\nk = np.zeros(p)\nk[0] = np.sum(e[p:p + L, ... | <|body_start_0|>
ar = np.array(ar)
ar0 = ar.reshape(1, -1)
nf, p1 = ar0.shape
if p == None:
p = p1 - 1
ff = np.fft.rfft(ar0, n=2 * p + 2).T ** (-1)
return ff
<|end_body_0|>
<|body_start_1|>
N = len(x)
e = np.zeros((N, p + 1))
b = np.ze... | LPC | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LPC:
def lpcar2ff(ar, p=None):
"""Convert AR coefs to complex spectrum FF=(AR,P) :param ar: :param p: :return ff:"""
<|body_0|>
def latticem(x, L, p):
"""用几何平均格型法求出线性预测的系数 :param x: 一帧语音数据 (长度大于等于L+p) :param L: 该帧数据中做格型法处理的长度 :param p: 线性预测的系数 :return E: 最小均方误差 :retu... | stack_v2_sparse_classes_75kplus_train_009410 | 2,100 | permissive | [
{
"docstring": "Convert AR coefs to complex spectrum FF=(AR,P) :param ar: :param p: :return ff:",
"name": "lpcar2ff",
"signature": "def lpcar2ff(ar, p=None)"
},
{
"docstring": "用几何平均格型法求出线性预测的系数 :param x: 一帧语音数据 (长度大于等于L+p) :param L: 该帧数据中做格型法处理的长度 :param p: 线性预测的系数 :return E: 最小均方误差 :return G: ... | 3 | stack_v2_sparse_classes_30k_train_038373 | Implement the Python class `LPC` described below.
Class description:
Implement the LPC class.
Method signatures and docstrings:
- def lpcar2ff(ar, p=None): Convert AR coefs to complex spectrum FF=(AR,P) :param ar: :param p: :return ff:
- def latticem(x, L, p): 用几何平均格型法求出线性预测的系数 :param x: 一帧语音数据 (长度大于等于L+p) :param L: ... | Implement the Python class `LPC` described below.
Class description:
Implement the LPC class.
Method signatures and docstrings:
- def lpcar2ff(ar, p=None): Convert AR coefs to complex spectrum FF=(AR,P) :param ar: :param p: :return ff:
- def latticem(x, L, p): 用几何平均格型法求出线性预测的系数 :param x: 一帧语音数据 (长度大于等于L+p) :param L: ... | 0074ad1d519387a75d5eca42c77f4d6966eb0a0e | <|skeleton|>
class LPC:
def lpcar2ff(ar, p=None):
"""Convert AR coefs to complex spectrum FF=(AR,P) :param ar: :param p: :return ff:"""
<|body_0|>
def latticem(x, L, p):
"""用几何平均格型法求出线性预测的系数 :param x: 一帧语音数据 (长度大于等于L+p) :param L: 该帧数据中做格型法处理的长度 :param p: 线性预测的系数 :return E: 最小均方误差 :retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LPC:
def lpcar2ff(ar, p=None):
"""Convert AR coefs to complex spectrum FF=(AR,P) :param ar: :param p: :return ff:"""
ar = np.array(ar)
ar0 = ar.reshape(1, -1)
nf, p1 = ar0.shape
if p == None:
p = p1 - 1
ff = np.fft.rfft(ar0, n=2 * p + 2).T ** (-1)
... | the_stack_v2_python_sparse | Chapter4_LinearPrediction/LPC.py | BarryZM/Python_Speech_SZY | train | 0 | |
d3cc8310d97dc56435af170cca8267ac83559e93 | [
"fy_obj = self.env['account.fiscalyear']\nperiod_obj = self.env['account.period']\nmove = super(AccountMove, self).create(vals)\nif move.date and move.company_id:\n fy = fy_obj.finds(dt=move.date, company_id=move.company_id.id)\n if not fy:\n raise UserError(_('Fiscal Year is not defined for journal en... | <|body_start_0|>
fy_obj = self.env['account.fiscalyear']
period_obj = self.env['account.period']
move = super(AccountMove, self).create(vals)
if move.date and move.company_id:
fy = fy_obj.finds(dt=move.date, company_id=move.company_id.id)
if not fy:
... | AccountMove | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountMove:
def create(self, vals):
"""This method overwrite to link fiscal year and period in account move based on date :param vals: dictionary of fields and it's values :return: new created recordset of account move"""
<|body_0|>
def write(self, vals):
"""This me... | stack_v2_sparse_classes_75kplus_train_009411 | 3,702 | no_license | [
{
"docstring": "This method overwrite to link fiscal year and period in account move based on date :param vals: dictionary of fields and it's values :return: new created recordset of account move",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "This method overwrite t... | 3 | null | Implement the Python class `AccountMove` described below.
Class description:
Implement the AccountMove class.
Method signatures and docstrings:
- def create(self, vals): This method overwrite to link fiscal year and period in account move based on date :param vals: dictionary of fields and it's values :return: new cr... | Implement the Python class `AccountMove` described below.
Class description:
Implement the AccountMove class.
Method signatures and docstrings:
- def create(self, vals): This method overwrite to link fiscal year and period in account move based on date :param vals: dictionary of fields and it's values :return: new cr... | c2706bd2904f5f5f60012c928ba9016ed7e9f547 | <|skeleton|>
class AccountMove:
def create(self, vals):
"""This method overwrite to link fiscal year and period in account move based on date :param vals: dictionary of fields and it's values :return: new created recordset of account move"""
<|body_0|>
def write(self, vals):
"""This me... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountMove:
def create(self, vals):
"""This method overwrite to link fiscal year and period in account move based on date :param vals: dictionary of fields and it's values :return: new created recordset of account move"""
fy_obj = self.env['account.fiscalyear']
period_obj = self.env['... | the_stack_v2_python_sparse | gts_account_fiscal_year/models/account_move.py | kumar7668/Odoo14_dev | train | 1 | |
c03e1e265230658d35fa998d78af0a144110c05c | [
"self.size = size\nself.sum = 0\nself.window = [0] * size\nself.index = 0\nself.currSize = 0",
"self.window[self.index % self.size] = val\nself.index += 1\nself.sum += val\nself.sum -= self.window[self.index % self.size]\nself.currSize += 1 if self.currSize < self.size else self.currSize\nreturn float(self.sum) /... | <|body_start_0|>
self.size = size
self.sum = 0
self.window = [0] * size
self.index = 0
self.currSize = 0
<|end_body_0|>
<|body_start_1|>
self.window[self.index % self.size] = val
self.index += 1
self.sum += val
self.sum -= self.window[self.index %... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.sum = 0... | stack_v2_sparse_classes_75kplus_train_009412 | 1,065 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026328 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 608157956f13fccb663b3a3d888a585dbde78cde | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.sum = 0
self.window = [0] * size
self.index = 0
self.currSize = 0
def next(self, val):
""":type val: int :rtype: float"""
... | the_stack_v2_python_sparse | interview/bloomberg/moving average from data stream.py | totemw/algorithm | train | 0 | |
cebf97271ebba0dff0b53dfeb9dcd95ffb82d77f | [
"if '_method' in request.form and request.form['_method'] == 'put':\n if build_campaign(request, create=False):\n return (None, status.HTTP_200_OK)\nelif build_campaign(request, create=True):\n return (None, status.HTTP_200_OK)\nreturn (None, status.HTTP_500_INTERNAL_SERVER_ERROR)",
"if build_campaig... | <|body_start_0|>
if '_method' in request.form and request.form['_method'] == 'put':
if build_campaign(request, create=False):
return (None, status.HTTP_200_OK)
elif build_campaign(request, create=True):
return (None, status.HTTP_200_OK)
return (None, statu... | Flask-RESTful resource endpoints for CampaignModel by ID. | ManageCampaigns | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageCampaigns:
"""Flask-RESTful resource endpoints for CampaignModel by ID."""
def post(self):
"""Endpoint to post a campaign."""
<|body_0|>
def put(self):
"""Endpoint to update a campaign."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if '_... | stack_v2_sparse_classes_75kplus_train_009413 | 3,941 | no_license | [
{
"docstring": "Endpoint to post a campaign.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Endpoint to update a campaign.",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054752 | Implement the Python class `ManageCampaigns` described below.
Class description:
Flask-RESTful resource endpoints for CampaignModel by ID.
Method signatures and docstrings:
- def post(self): Endpoint to post a campaign.
- def put(self): Endpoint to update a campaign. | Implement the Python class `ManageCampaigns` described below.
Class description:
Flask-RESTful resource endpoints for CampaignModel by ID.
Method signatures and docstrings:
- def post(self): Endpoint to post a campaign.
- def put(self): Endpoint to update a campaign.
<|skeleton|>
class ManageCampaigns:
"""Flask-... | d5ffcc5d276692d1578cea704125b1b3952beb1c | <|skeleton|>
class ManageCampaigns:
"""Flask-RESTful resource endpoints for CampaignModel by ID."""
def post(self):
"""Endpoint to post a campaign."""
<|body_0|>
def put(self):
"""Endpoint to update a campaign."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ManageCampaigns:
"""Flask-RESTful resource endpoints for CampaignModel by ID."""
def post(self):
"""Endpoint to post a campaign."""
if '_method' in request.form and request.form['_method'] == 'put':
if build_campaign(request, create=False):
return (None, status... | the_stack_v2_python_sparse | application/resources/campaign.py | transreductionist/API-Project-1 | train | 0 |
45a7a36584c056c15650a48c18cc037e73ebb62f | [
"driver.find_element_by_css_selector('.start-webinar').click()\nwindows = driver.window_handles\ndriver.switch_to.window(windows[1])\nsleep(2)\ndriver.find_element_by_link_text('发起直播').click()\ndriver.switch_to.window(windows[1])\nelement = WebDriverWait(driver, 20, 1).until(EC.presence_of_element_located((By.CSS_S... | <|body_start_0|>
driver.find_element_by_css_selector('.start-webinar').click()
windows = driver.window_handles
driver.switch_to.window(windows[1])
sleep(2)
driver.find_element_by_link_text('发起直播').click()
driver.switch_to.window(windows[1])
element = WebDriverWait... | Test_case_03_toolsAB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_case_03_toolsAB:
def test_03_startVideo(self):
"""开始直播"""
<|body_0|>
def test_04_questionnaire(self):
"""发起问卷"""
<|body_1|>
def test_05_signIn(self):
"""发起签到"""
<|body_2|>
def test_06_QandA(self):
"""开启问答"""
<|bo... | stack_v2_sparse_classes_75kplus_train_009414 | 3,477 | no_license | [
{
"docstring": "开始直播",
"name": "test_03_startVideo",
"signature": "def test_03_startVideo(self)"
},
{
"docstring": "发起问卷",
"name": "test_04_questionnaire",
"signature": "def test_04_questionnaire(self)"
},
{
"docstring": "发起签到",
"name": "test_05_signIn",
"signature": "def... | 6 | stack_v2_sparse_classes_30k_train_027924 | Implement the Python class `Test_case_03_toolsAB` described below.
Class description:
Implement the Test_case_03_toolsAB class.
Method signatures and docstrings:
- def test_03_startVideo(self): 开始直播
- def test_04_questionnaire(self): 发起问卷
- def test_05_signIn(self): 发起签到
- def test_06_QandA(self): 开启问答
- def test_07_... | Implement the Python class `Test_case_03_toolsAB` described below.
Class description:
Implement the Test_case_03_toolsAB class.
Method signatures and docstrings:
- def test_03_startVideo(self): 开始直播
- def test_04_questionnaire(self): 发起问卷
- def test_05_signIn(self): 发起签到
- def test_06_QandA(self): 开启问答
- def test_07_... | a47c6afe7734037695e397052cf189510e816f9e | <|skeleton|>
class Test_case_03_toolsAB:
def test_03_startVideo(self):
"""开始直播"""
<|body_0|>
def test_04_questionnaire(self):
"""发起问卷"""
<|body_1|>
def test_05_signIn(self):
"""发起签到"""
<|body_2|>
def test_06_QandA(self):
"""开启问答"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_case_03_toolsAB:
def test_03_startVideo(self):
"""开始直播"""
driver.find_element_by_css_selector('.start-webinar').click()
windows = driver.window_handles
driver.switch_to.window(windows[1])
sleep(2)
driver.find_element_by_link_text('发起直播').click()
dri... | the_stack_v2_python_sparse | Test_vhall/vhall_unittest/test_case/test_case_03_toolsAB.py | 1065865483/python_script | train | 0 | |
92dd2eb502fe98fcf18c6a12fa85b0f2603ac61f | [
"assert nextxy.shape[0] == 2 and nextxy.ndim == 3, 'check nextxy dimensions'\nif not zero_based:\n nextxy = np.where(nextxy > 0, nextxy - 1, nextxy)\npit_value = np.array([-9, -9])[:, None, None]\nsuper(NextXY, self).__init__('nextxy', dd=None, raster=nextxy, transform=transform, pit_value=pit_value, fill_value=... | <|body_start_0|>
assert nextxy.shape[0] == 2 and nextxy.ndim == 3, 'check nextxy dimensions'
if not zero_based:
nextxy = np.where(nextxy > 0, nextxy - 1, nextxy)
pit_value = np.array([-9, -9])[:, None, None]
super(NextXY, self).__init__('nextxy', dd=None, raster=nextxy, trans... | NextXY | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NextXY:
def __init__(self, nextxy, transform, search_radius=1, fill_value=-9999, zero_based=False, **kwargs):
"""initialize drainage direction object based on nextxy definition"""
<|body_0|>
def _nb_downstream_idx(self, row, col):
"""neighborhood downstream index"""
... | stack_v2_sparse_classes_75kplus_train_009415 | 16,667 | permissive | [
{
"docstring": "initialize drainage direction object based on nextxy definition",
"name": "__init__",
"signature": "def __init__(self, nextxy, transform, search_radius=1, fill_value=-9999, zero_based=False, **kwargs)"
},
{
"docstring": "neighborhood downstream index",
"name": "_nb_downstream... | 4 | stack_v2_sparse_classes_30k_train_036863 | Implement the Python class `NextXY` described below.
Class description:
Implement the NextXY class.
Method signatures and docstrings:
- def __init__(self, nextxy, transform, search_radius=1, fill_value=-9999, zero_based=False, **kwargs): initialize drainage direction object based on nextxy definition
- def _nb_downst... | Implement the Python class `NextXY` described below.
Class description:
Implement the NextXY class.
Method signatures and docstrings:
- def __init__(self, nextxy, transform, search_radius=1, fill_value=-9999, zero_based=False, **kwargs): initialize drainage direction object based on nextxy definition
- def _nb_downst... | f9d7960633be80e8e24d2f2563df367cc3f060c6 | <|skeleton|>
class NextXY:
def __init__(self, nextxy, transform, search_radius=1, fill_value=-9999, zero_based=False, **kwargs):
"""initialize drainage direction object based on nextxy definition"""
<|body_0|>
def _nb_downstream_idx(self, row, col):
"""neighborhood downstream index"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NextXY:
def __init__(self, nextxy, transform, search_radius=1, fill_value=-9999, zero_based=False, **kwargs):
"""initialize drainage direction object based on nextxy definition"""
assert nextxy.shape[0] == 2 and nextxy.ndim == 3, 'check nextxy dimensions'
if not zero_based:
... | the_stack_v2_python_sparse | src/1-prepare/cmftools/nb/dd_ops.py | Jiangchao3/compound_hotspots | train | 0 | |
b98ab0a1c89c4b644a3692a6edf449cf65cabe48 | [
"self.logger = create_logger('methods.inprocessing.NeuralNetwork')\nself.optimizer_class = optimizer\nself.loss_class = loss\nkwargs['activation_type'] = import_object(activation)\nself.learning_rate = learning_rate\nself.weight_decay = weight_decay\nself.epochs = epochs\nself.batch_size = batch_size\nself.logger.d... | <|body_start_0|>
self.logger = create_logger('methods.inprocessing.NeuralNetwork')
self.optimizer_class = optimizer
self.loss_class = loss
kwargs['activation_type'] = import_object(activation)
self.learning_rate = learning_rate
self.weight_decay = weight_decay
sel... | NeuralNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralNetwork:
def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs):
"""Creates a neural network model. Parameters ---------- optimizer : str The optimizer to use. Must be a class from the torch.... | stack_v2_sparse_classes_75kplus_train_009416 | 7,243 | permissive | [
{
"docstring": "Creates a neural network model. Parameters ---------- optimizer : str The optimizer to use. Must be a class from the torch.optim package. loss_class : str The loss function to use. Must be a class from the torch.nn package. activation_class : str The activation function to use. Must be a class f... | 3 | stack_v2_sparse_classes_30k_train_016167 | Implement the Python class `NeuralNetwork` described below.
Class description:
Implement the NeuralNetwork class.
Method signatures and docstrings:
- def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs): Creates a neural netw... | Implement the Python class `NeuralNetwork` described below.
Class description:
Implement the NeuralNetwork class.
Method signatures and docstrings:
- def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs): Creates a neural netw... | a0012dfcaef0b5d33452451dca955a99f7e7cccf | <|skeleton|>
class NeuralNetwork:
def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs):
"""Creates a neural network model. Parameters ---------- optimizer : str The optimizer to use. Must be a class from the torch.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralNetwork:
def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs):
"""Creates a neural network model. Parameters ---------- optimizer : str The optimizer to use. Must be a class from the torch.optim package.... | the_stack_v2_python_sparse | src/aequitas/fairflow/methods/inprocessing/neural_network.py | dssg/aequitas | train | 575 | |
86367a1d88a19de1f9555d5703d705fba9ca793d | [
"try:\n with transaction.atomic():\n self.create(user=user, group=group, project=group.project, is_active=True, reason=reason)\nexcept IntegrityError:\n pass",
"from sentry.models import User, UserOption, UserOptionValue\nusers = User.objects.filter(sentry_orgmember_set__teams=group.project.team, is_... | <|body_start_0|>
try:
with transaction.atomic():
self.create(user=user, group=group, project=group.project, is_active=True, reason=reason)
except IntegrityError:
pass
<|end_body_0|>
<|body_start_1|>
from sentry.models import User, UserOption, UserOptionVa... | GroupSubscriptionManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupSubscriptionManager:
def subscribe(self, group, user, reason=GroupSubscriptionReason.unknown):
"""Subscribe a user to an issue, but only if the user has not explicitly unsubscribed."""
<|body_0|>
def get_participants(self, group):
"""Identify all users who are p... | stack_v2_sparse_classes_75kplus_train_009417 | 5,262 | permissive | [
{
"docstring": "Subscribe a user to an issue, but only if the user has not explicitly unsubscribed.",
"name": "subscribe",
"signature": "def subscribe(self, group, user, reason=GroupSubscriptionReason.unknown)"
},
{
"docstring": "Identify all users who are participating with a given issue.",
... | 2 | stack_v2_sparse_classes_30k_train_037583 | Implement the Python class `GroupSubscriptionManager` described below.
Class description:
Implement the GroupSubscriptionManager class.
Method signatures and docstrings:
- def subscribe(self, group, user, reason=GroupSubscriptionReason.unknown): Subscribe a user to an issue, but only if the user has not explicitly un... | Implement the Python class `GroupSubscriptionManager` described below.
Class description:
Implement the GroupSubscriptionManager class.
Method signatures and docstrings:
- def subscribe(self, group, user, reason=GroupSubscriptionReason.unknown): Subscribe a user to an issue, but only if the user has not explicitly un... | b937615079d7b24dc225a83b99b1b65da932fc66 | <|skeleton|>
class GroupSubscriptionManager:
def subscribe(self, group, user, reason=GroupSubscriptionReason.unknown):
"""Subscribe a user to an issue, but only if the user has not explicitly unsubscribed."""
<|body_0|>
def get_participants(self, group):
"""Identify all users who are p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupSubscriptionManager:
def subscribe(self, group, user, reason=GroupSubscriptionReason.unknown):
"""Subscribe a user to an issue, but only if the user has not explicitly unsubscribed."""
try:
with transaction.atomic():
self.create(user=user, group=group, project=... | the_stack_v2_python_sparse | src/sentry/models/groupsubscription.py | atlassian/sentry | train | 1 | |
18800cfb1d3bad8b20423badddf20f23d0a63b25 | [
"user_ids = self.search(cr, uid, [('login', '=', login)], context=context)\nif not user_ids:\n user_ids = self.search(cr, uid, [('email', '=', login)], context=context)\nif len(user_ids) != 1:\n raise Exception('Reset password: invalid username or email')\nreturn self.action_reset_password(cr, uid, user_ids, ... | <|body_start_0|>
user_ids = self.search(cr, uid, [('login', '=', login)], context=context)
if not user_ids:
user_ids = self.search(cr, uid, [('email', '=', login)], context=context)
if len(user_ids) != 1:
raise Exception('Reset password: invalid username or email')
... | res_users | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class res_users:
def reset_password(self, cr, uid, login, context=None):
"""retrieve the user corresponding to login (login or email), and reset their password"""
<|body_0|>
def action_reset_password(self, cr, uid, ids, context=None):
"""create signup token for each user, ... | stack_v2_sparse_classes_75kplus_train_009418 | 2,688 | no_license | [
{
"docstring": "retrieve the user corresponding to login (login or email), and reset their password",
"name": "reset_password",
"signature": "def reset_password(self, cr, uid, login, context=None)"
},
{
"docstring": "create signup token for each user, and send their signup url by email",
"na... | 2 | stack_v2_sparse_classes_30k_train_037570 | Implement the Python class `res_users` described below.
Class description:
Implement the res_users class.
Method signatures and docstrings:
- def reset_password(self, cr, uid, login, context=None): retrieve the user corresponding to login (login or email), and reset their password
- def action_reset_password(self, cr... | Implement the Python class `res_users` described below.
Class description:
Implement the res_users class.
Method signatures and docstrings:
- def reset_password(self, cr, uid, login, context=None): retrieve the user corresponding to login (login or email), and reset their password
- def action_reset_password(self, cr... | 911cc2b7cb845f3fb6c891e03b99a4020069d380 | <|skeleton|>
class res_users:
def reset_password(self, cr, uid, login, context=None):
"""retrieve the user corresponding to login (login or email), and reset their password"""
<|body_0|>
def action_reset_password(self, cr, uid, ids, context=None):
"""create signup token for each user, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class res_users:
def reset_password(self, cr, uid, login, context=None):
"""retrieve the user corresponding to login (login or email), and reset their password"""
user_ids = self.search(cr, uid, [('login', '=', login)], context=context)
if not user_ids:
user_ids = self.search(cr,... | the_stack_v2_python_sparse | auth_reset_password/res_users.py | ShantiSR/openerp-addons | train | 0 | |
957af9a64f24200768e1c28b5340ce3a1a8eaee9 | [
"server = get_object_or_404(models.FederatedServer, id=server)\nusers = server.user_set\ndata = {'server': server, 'users': users, 'reports': models.Report.objects.filter(user__in=users.all()), 'followed_by_us': users.filter(followers__local=True), 'followed_by_them': users.filter(following__local=True), 'blocked_b... | <|body_start_0|>
server = get_object_or_404(models.FederatedServer, id=server)
users = server.user_set
data = {'server': server, 'users': users, 'reports': models.Report.objects.filter(user__in=users.all()), 'followed_by_us': users.filter(followers__local=True), 'followed_by_them': users.filter(... | views for handling a specific federated server | FederatedServer | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FederatedServer:
"""views for handling a specific federated server"""
def get(self, request, server):
"""load a server"""
<|body_0|>
def post(self, request, server):
"""update note"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
server = get_obj... | stack_v2_sparse_classes_75kplus_train_009419 | 6,777 | no_license | [
{
"docstring": "load a server",
"name": "get",
"signature": "def get(self, request, server)"
},
{
"docstring": "update note",
"name": "post",
"signature": "def post(self, request, server)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053947 | Implement the Python class `FederatedServer` described below.
Class description:
views for handling a specific federated server
Method signatures and docstrings:
- def get(self, request, server): load a server
- def post(self, request, server): update note | Implement the Python class `FederatedServer` described below.
Class description:
views for handling a specific federated server
Method signatures and docstrings:
- def get(self, request, server): load a server
- def post(self, request, server): update note
<|skeleton|>
class FederatedServer:
"""views for handlin... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class FederatedServer:
"""views for handling a specific federated server"""
def get(self, request, server):
"""load a server"""
<|body_0|>
def post(self, request, server):
"""update note"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FederatedServer:
"""views for handling a specific federated server"""
def get(self, request, server):
"""load a server"""
server = get_object_or_404(models.FederatedServer, id=server)
users = server.user_set
data = {'server': server, 'users': users, 'reports': models.Repor... | the_stack_v2_python_sparse | bookwyrm/views/admin/federation.py | bookwyrm-social/bookwyrm | train | 1,398 |
fd3c13af74c6049fadb2d306176cd60729b1f076 | [
"_session = db.create_scoped_session()\ntry:\n _protein_ac_per_protein_id = {}\n for protein in _session.query(Protein).filter(Protein.id.in_(_protein_ids)).all():\n _protein_ac_per_protein_id[protein.id] = protein.uniprot_ac\n return _protein_ac_per_protein_id\nexcept (AlchemyResourceClosedError, A... | <|body_start_0|>
_session = db.create_scoped_session()
try:
_protein_ac_per_protein_id = {}
for protein in _session.query(Protein).filter(Protein.id.in_(_protein_ids)).all():
_protein_ac_per_protein_id[protein.id] = protein.uniprot_ac
return _protein_a... | ProteinRepository | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProteinRepository:
def retrieve_protein_ac_for_multiple_protein_ids(_protein_ids):
"""Retrieves all uniprot accession codes for multiple Protein objects as {protein_id: uniprot_ac}"""
<|body_0|>
def retrieve_protein_id_for_multiple_protein_acs(_protein_acs):
"""Retri... | stack_v2_sparse_classes_75kplus_train_009420 | 17,106 | permissive | [
{
"docstring": "Retrieves all uniprot accession codes for multiple Protein objects as {protein_id: uniprot_ac}",
"name": "retrieve_protein_ac_for_multiple_protein_ids",
"signature": "def retrieve_protein_ac_for_multiple_protein_ids(_protein_ids)"
},
{
"docstring": "Retrieves all protein ids for ... | 3 | null | Implement the Python class `ProteinRepository` described below.
Class description:
Implement the ProteinRepository class.
Method signatures and docstrings:
- def retrieve_protein_ac_for_multiple_protein_ids(_protein_ids): Retrieves all uniprot accession codes for multiple Protein objects as {protein_id: uniprot_ac}
-... | Implement the Python class `ProteinRepository` described below.
Class description:
Implement the ProteinRepository class.
Method signatures and docstrings:
- def retrieve_protein_ac_for_multiple_protein_ids(_protein_ids): Retrieves all uniprot accession codes for multiple Protein objects as {protein_id: uniprot_ac}
-... | 2b4448b33cbc5512b56f5aaa7453d0a255ee1628 | <|skeleton|>
class ProteinRepository:
def retrieve_protein_ac_for_multiple_protein_ids(_protein_ids):
"""Retrieves all uniprot accession codes for multiple Protein objects as {protein_id: uniprot_ac}"""
<|body_0|>
def retrieve_protein_id_for_multiple_protein_acs(_protein_acs):
"""Retri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProteinRepository:
def retrieve_protein_ac_for_multiple_protein_ids(_protein_ids):
"""Retrieves all uniprot accession codes for multiple Protein objects as {protein_id: uniprot_ac}"""
_session = db.create_scoped_session()
try:
_protein_ac_per_protein_id = {}
for... | the_stack_v2_python_sparse | metadome/domain/repositories.py | kchennen/metadome | train | 0 | |
46f324c5e26717807963c5ebe1bd34e28eacbc0e | [
"language = Language.objects.all()\nserializer = LanguageSerializer(language, many=True)\nreturn Response(serializer.data)",
"queryset = Language.objects.all()\nlanguage = get_object_or_404(queryset, pk=pk)\nserializer = LanguageSerializer(language)\nreturn Response(serializer.data)"
] | <|body_start_0|>
language = Language.objects.all()
serializer = LanguageSerializer(language, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = Language.objects.all()
language = get_object_or_404(queryset, pk=pk)
serializer = LanguageS... | LanguageView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageView:
def list(self, request):
"""Получение списка языков"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение языка по идентификатору pk - идентификатор языка"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
language = Language.o... | stack_v2_sparse_classes_75kplus_train_009421 | 12,404 | no_license | [
{
"docstring": "Получение списка языков",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Получение языка по идентификатору pk - идентификатор языка",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004233 | Implement the Python class `LanguageView` described below.
Class description:
Implement the LanguageView class.
Method signatures and docstrings:
- def list(self, request): Получение списка языков
- def retrieve(self, request, pk=None): Получение языка по идентификатору pk - идентификатор языка | Implement the Python class `LanguageView` described below.
Class description:
Implement the LanguageView class.
Method signatures and docstrings:
- def list(self, request): Получение списка языков
- def retrieve(self, request, pk=None): Получение языка по идентификатору pk - идентификатор языка
<|skeleton|>
class La... | be47a0a6f50bf8680b22e0b9cae3e3b34a198a3d | <|skeleton|>
class LanguageView:
def list(self, request):
"""Получение списка языков"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение языка по идентификатору pk - идентификатор языка"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LanguageView:
def list(self, request):
"""Получение списка языков"""
language = Language.objects.all()
serializer = LanguageSerializer(language, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
"""Получение языка по идентификатору p... | the_stack_v2_python_sparse | StarfinderBack/starfinder/views.py | Skirgus/StarfinderMasterAssistant | train | 0 | |
b720374348ac19f61edd1ad1c01900c3d1595e30 | [
"preO = [0]\npreE = [0]\nfor i, v in enumerate(nums):\n if i % 2 == 0:\n preO.append(preO[-1] + v)\n preE.append(preE[-1])\n else:\n preE.append(preE[-1] + v)\n preO.append(preO[-1])\nans = 0\nfor i in range(1, len(nums) + 1):\n sumO = preO[i - 1] - preO[0] + preE[-1] - preE[i]\... | <|body_start_0|>
preO = [0]
preE = [0]
for i, v in enumerate(nums):
if i % 2 == 0:
preO.append(preO[-1] + v)
preE.append(preE[-1])
else:
preE.append(preE[-1] + v)
preO.append(preO[-1])
ans = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def waysToMakeFair(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def waysToMakeFairO1Space(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
preO = [0]
preE = [0]
... | stack_v2_sparse_classes_75kplus_train_009422 | 3,000 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "waysToMakeFair",
"signature": "def waysToMakeFair(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "waysToMakeFairO1Space",
"signature": "def waysToMakeFairO1Space(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024067 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def waysToMakeFair(self, nums): :type nums: List[int] :rtype: int
- def waysToMakeFairO1Space(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def waysToMakeFair(self, nums): :type nums: List[int] :rtype: int
- def waysToMakeFairO1Space(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
de... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def waysToMakeFair(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def waysToMakeFairO1Space(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def waysToMakeFair(self, nums):
""":type nums: List[int] :rtype: int"""
preO = [0]
preE = [0]
for i, v in enumerate(nums):
if i % 2 == 0:
preO.append(preO[-1] + v)
preE.append(preE[-1])
else:
preE... | the_stack_v2_python_sparse | W/WaystoMakeaFairArray.py | bssrdf/pyleet | train | 2 | |
07574c495be2a9acf06160ee7bd0cc81992cd2ae | [
"if len(nums) == 0:\n return 0\nmax_length = 0\ncur = 1\nfor i in range(len(nums) - 1):\n if nums[i] < nums[i + 1]:\n cur += 1\n else:\n max_length = cur if cur > max_length else max_length\n cur = 1\nreturn max_length if cur < max_length else cur",
"if len(nums) == 0:\n return 0\... | <|body_start_0|>
if len(nums) == 0:
return 0
max_length = 0
cur = 1
for i in range(len(nums) - 1):
if nums[i] < nums[i + 1]:
cur += 1
else:
max_length = cur if cur > max_length else max_length
cur = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
ret... | stack_v2_sparse_classes_75kplus_train_009423 | 1,034 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findLengthOfLCIS1",
"signature": "def findLengthOfLCIS1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findLengthOfLCIS",
"signature": "def findLengthOfLCIS(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002568 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLengthOfLCIS1(self, nums): :type nums: List[int] :rtype: int
- def findLengthOfLCIS(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLengthOfLCIS1(self, nums): :type nums: List[int] :rtype: int
- def findLengthOfLCIS(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
max_length = 0
cur = 1
for i in range(len(nums) - 1):
if nums[i] < nums[i + 1]:
cur += 1
else:
... | the_stack_v2_python_sparse | python/leetcode_bak/674_Longest_Continuous_Increasing_Subsequence.py | bobcaoge/my-code | train | 0 | |
d34e6ecb064dc94b1360a5b72692cd45c23a993d | [
"self.ad_object_meta_data = ad_object_meta_data\nself.document_type = document_type\nself.email_meta_data = email_meta_data\nself.file_versions = file_versions\nself.filename = filename\nself.is_folder = is_folder\nself.job_id = job_id\nself.job_uid = job_uid\nself.one_drive_document_metadata = one_drive_document_m... | <|body_start_0|>
self.ad_object_meta_data = ad_object_meta_data
self.document_type = document_type
self.email_meta_data = email_meta_data
self.file_versions = file_versions
self.filename = filename
self.is_folder = is_folder
self.job_id = job_id
self.job_u... | Implementation of the 'FileSearchResult' model. Specifies details about the found file or folder. Attributes: ad_object_meta_data (AdObjectMetaData): Specifies the metadata about the AD objects. document_type (string): Specifies the inferred document type. email_meta_data (EmailMetaData): Specifies the metadata about t... | FileSearchResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSearchResult:
"""Implementation of the 'FileSearchResult' model. Specifies details about the found file or folder. Attributes: ad_object_meta_data (AdObjectMetaData): Specifies the metadata about the AD objects. document_type (string): Specifies the inferred document type. email_meta_data (Em... | stack_v2_sparse_classes_75kplus_train_009424 | 8,984 | permissive | [
{
"docstring": "Constructor for the FileSearchResult class",
"name": "__init__",
"signature": "def __init__(self, ad_object_meta_data=None, document_type=None, email_meta_data=None, file_versions=None, filename=None, is_folder=None, job_id=None, job_uid=None, one_drive_document_metadata=None, protection... | 2 | stack_v2_sparse_classes_30k_train_051074 | Implement the Python class `FileSearchResult` described below.
Class description:
Implementation of the 'FileSearchResult' model. Specifies details about the found file or folder. Attributes: ad_object_meta_data (AdObjectMetaData): Specifies the metadata about the AD objects. document_type (string): Specifies the infe... | Implement the Python class `FileSearchResult` described below.
Class description:
Implementation of the 'FileSearchResult' model. Specifies details about the found file or folder. Attributes: ad_object_meta_data (AdObjectMetaData): Specifies the metadata about the AD objects. document_type (string): Specifies the infe... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FileSearchResult:
"""Implementation of the 'FileSearchResult' model. Specifies details about the found file or folder. Attributes: ad_object_meta_data (AdObjectMetaData): Specifies the metadata about the AD objects. document_type (string): Specifies the inferred document type. email_meta_data (Em... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileSearchResult:
"""Implementation of the 'FileSearchResult' model. Specifies details about the found file or folder. Attributes: ad_object_meta_data (AdObjectMetaData): Specifies the metadata about the AD objects. document_type (string): Specifies the inferred document type. email_meta_data (EmailMetaData):... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_search_result.py | cohesity/management-sdk-python | train | 24 |
3e884902d02680956d1a3827861b928fda0a4081 | [
"self.game_active = False\nself.settings = settings\nself.high_score = 0\nself.reset_stats()",
"self.shiplift = self.settings.ship_limit\nself.score = 0\nself.level = 1"
] | <|body_start_0|>
self.game_active = False
self.settings = settings
self.high_score = 0
self.reset_stats()
<|end_body_0|>
<|body_start_1|>
self.shiplift = self.settings.ship_limit
self.score = 0
self.level = 1
<|end_body_1|>
| 跟踪游戏的统计信息 | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, settings):
"""初始化统计信息"""
<|body_0|>
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.game_active = False
self.settings = settings
sel... | stack_v2_sparse_classes_75kplus_train_009425 | 700 | no_license | [
{
"docstring": "初始化统计信息",
"name": "__init__",
"signature": "def __init__(self, settings)"
},
{
"docstring": "初始化在游戏运行期间可能变化的统计信息",
"name": "reset_stats",
"signature": "def reset_stats(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053453 | Implement the Python class `GameStats` described below.
Class description:
跟踪游戏的统计信息
Method signatures and docstrings:
- def __init__(self, settings): 初始化统计信息
- def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息 | Implement the Python class `GameStats` described below.
Class description:
跟踪游戏的统计信息
Method signatures and docstrings:
- def __init__(self, settings): 初始化统计信息
- def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息
<|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, settings):
"""初始化统计信息"""
... | 88dde4802823d68978ce633e443dd632a6ffd29d | <|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, settings):
"""初始化统计信息"""
<|body_0|>
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, settings):
"""初始化统计信息"""
self.game_active = False
self.settings = settings
self.high_score = 0
self.reset_stats()
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
self.shiplift = self.settings.ship_... | the_stack_v2_python_sparse | alien_invasion/geme_stats.py | zhangbin0git/demo | train | 0 |
a336ef000ab596e522c1b2ebb922b1fc3207b773 | [
"super().__init__(source_image_path, source_image_size, output_image_path, output_image_size)\nself.__levels = len(neighbourhood_padding)\nself.__neighbourhood_padding = neighbourhood_padding\nself.__tsvq_branching_factor = tsvq_branching_factor\nassert self.__levels > 0, 'At least one neighbourhood padding size mu... | <|body_start_0|>
super().__init__(source_image_path, source_image_size, output_image_path, output_image_size)
self.__levels = len(neighbourhood_padding)
self.__neighbourhood_padding = neighbourhood_padding
self.__tsvq_branching_factor = tsvq_branching_factor
assert self.__levels ... | A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise from the source Image and then resolve the pixels one-by-one in scanline order by finding the best ne... | RasterPixelNeighbourhoodSynthesizer | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RasterPixelNeighbourhoodSynthesizer:
"""A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise from the source Image and then resolve... | stack_v2_sparse_classes_75kplus_train_009426 | 6,847 | permissive | [
{
"docstring": "Constructs a new RasterPixelNeighbourhoodSynthesizer object with the given TextureSynthesizer parameters and neighbourhood padding. Args: source_image_path: See TextureSynthesizer.__init__(). source_image_size: See TextureSynthesizer.__init__(). output_image_path: See TextureSynthesizer.__init__... | 5 | stack_v2_sparse_classes_30k_train_028970 | Implement the Python class `RasterPixelNeighbourhoodSynthesizer` described below.
Class description:
A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise... | Implement the Python class `RasterPixelNeighbourhoodSynthesizer` described below.
Class description:
A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise... | 7e7282698befd53383cbd6566039340babb0a289 | <|skeleton|>
class RasterPixelNeighbourhoodSynthesizer:
"""A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise from the source Image and then resolve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RasterPixelNeighbourhoodSynthesizer:
"""A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise from the source Image and then resolve the pixels o... | the_stack_v2_python_sparse | sandbox/synthesizers/raster_pixel_neighbourhood_synthesizer.py | Mandrenkov/SVBRDF-Texture-Synthesis | train | 3 |
ad87955238cb00805102d6d8592dc064e1bfbd6c | [
"media_sources = [NewsMediaOrg(news_org=ALJAZEERA, media_types=MEDIA_TYPE_VIDEOS)]\nfor videos_ingestor in media_sources:\n for video in videos_ingestor.parse_videos():\n yield video",
"while True:\n try:\n logging.info('Getting Videos')\n for video in self.get_news_videos():\n ... | <|body_start_0|>
media_sources = [NewsMediaOrg(news_org=ALJAZEERA, media_types=MEDIA_TYPE_VIDEOS)]
for videos_ingestor in media_sources:
for video in videos_ingestor.parse_videos():
yield video
<|end_body_0|>
<|body_start_1|>
while True:
try:
... | Video class | VideosCrawler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideosCrawler:
"""Video class"""
def get_news_videos(self):
"""get news videos :return:"""
<|body_0|>
def run(self):
"""run the thread :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
media_sources = [NewsMediaOrg(news_org=ALJAZEERA, med... | stack_v2_sparse_classes_75kplus_train_009427 | 1,219 | permissive | [
{
"docstring": "get news videos :return:",
"name": "get_news_videos",
"signature": "def get_news_videos(self)"
},
{
"docstring": "run the thread :return:",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `VideosCrawler` described below.
Class description:
Video class
Method signatures and docstrings:
- def get_news_videos(self): get news videos :return:
- def run(self): run the thread :return: | Implement the Python class `VideosCrawler` described below.
Class description:
Video class
Method signatures and docstrings:
- def get_news_videos(self): get news videos :return:
- def run(self): run the thread :return:
<|skeleton|>
class VideosCrawler:
"""Video class"""
def get_news_videos(self):
"... | 2b1d8050e701f574890d3484d49954ee6e22df52 | <|skeleton|>
class VideosCrawler:
"""Video class"""
def get_news_videos(self):
"""get news videos :return:"""
<|body_0|>
def run(self):
"""run the thread :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideosCrawler:
"""Video class"""
def get_news_videos(self):
"""get news videos :return:"""
media_sources = [NewsMediaOrg(news_org=ALJAZEERA, media_types=MEDIA_TYPE_VIDEOS)]
for videos_ingestor in media_sources:
for video in videos_ingestor.parse_videos():
... | the_stack_v2_python_sparse | wren/data_ingestion/videos_crawler.py | vishnugithub1989/wren | train | 0 |
813ea1128b348cceea4fa60edd62d0a745888fe5 | [
"self.username = username\nself.password = password\nself.spamList = spamList\nself.serverAddress = self.getServerAddress(domainName.lower())\nself.totalMsg = None",
"domainAddresses = {'gmail': 'imap.gmail.com', 'hotmail': 'imap-mail.outlook.com'}\nif domainAddresses.get(domainName) is None:\n raise ValueErro... | <|body_start_0|>
self.username = username
self.password = password
self.spamList = spamList
self.serverAddress = self.getServerAddress(domainName.lower())
self.totalMsg = None
<|end_body_0|>
<|body_start_1|>
domainAddresses = {'gmail': 'imap.gmail.com', 'hotmail': 'imap-... | EmailAccount | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailAccount:
def __init__(self, username, password, domainName, spamList=None):
"""username = email address password = email password domainName = email type, e.g.: gmail, hotmail"""
<|body_0|>
def getServerAddress(domainName):
"""Return server address."""
<... | stack_v2_sparse_classes_75kplus_train_009428 | 5,003 | no_license | [
{
"docstring": "username = email address password = email password domainName = email type, e.g.: gmail, hotmail",
"name": "__init__",
"signature": "def __init__(self, username, password, domainName, spamList=None)"
},
{
"docstring": "Return server address.",
"name": "getServerAddress",
... | 2 | stack_v2_sparse_classes_30k_train_049426 | Implement the Python class `EmailAccount` described below.
Class description:
Implement the EmailAccount class.
Method signatures and docstrings:
- def __init__(self, username, password, domainName, spamList=None): username = email address password = email password domainName = email type, e.g.: gmail, hotmail
- def ... | Implement the Python class `EmailAccount` described below.
Class description:
Implement the EmailAccount class.
Method signatures and docstrings:
- def __init__(self, username, password, domainName, spamList=None): username = email address password = email password domainName = email type, e.g.: gmail, hotmail
- def ... | 6d99062529abac3801d8a9a55c4e68d30ccec163 | <|skeleton|>
class EmailAccount:
def __init__(self, username, password, domainName, spamList=None):
"""username = email address password = email password domainName = email type, e.g.: gmail, hotmail"""
<|body_0|>
def getServerAddress(domainName):
"""Return server address."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailAccount:
def __init__(self, username, password, domainName, spamList=None):
"""username = email address password = email password domainName = email type, e.g.: gmail, hotmail"""
self.username = username
self.password = password
self.spamList = spamList
self.server... | the_stack_v2_python_sparse | emailLib.py | reshinto/useless_apps | train | 0 | |
371a21d7261f195731ee4bf31584640c8cb7cb40 | [
"super(Decoder, self).__init__()\nself.embedding = nn.Embedding(num_p, emb_dim)\nself.lstm = nn.LSTMCell(emb_dim, hidden_dim)\nself.attn = Attention(hidden_dim)\nself.linear = nn.Linear(hidden_dim, num_p)",
"out = []\ne_seq = self.embedding(p_seq)\nfor emb in e_seq.chunk(e_seq.shape[1], 1):\n emb = emb.squeeze... | <|body_start_0|>
super(Decoder, self).__init__()
self.embedding = nn.Embedding(num_p, emb_dim)
self.lstm = nn.LSTMCell(emb_dim, hidden_dim)
self.attn = Attention(hidden_dim)
self.linear = nn.Linear(hidden_dim, num_p)
<|end_body_0|>
<|body_start_1|>
out = []
e_seq... | PyTorch decoder LSTM module with attention | Decoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""PyTorch decoder LSTM module with attention"""
def __init__(self, num_p: int, emb_dim: int, hidden_dim: int):
"""Input arguments: * num_p (int): The size of the phoneme vocabulary * emb_dim (int): The dimensionality of the character embeddings used * hidden_dim (int): The ... | stack_v2_sparse_classes_75kplus_train_009429 | 11,886 | permissive | [
{
"docstring": "Input arguments: * num_p (int): The size of the phoneme vocabulary * emb_dim (int): The dimensionality of the character embeddings used * hidden_dim (int): The hidden dimensionality of the decoder RNN",
"name": "__init__",
"signature": "def __init__(self, num_p: int, emb_dim: int, hidden... | 2 | stack_v2_sparse_classes_30k_train_013919 | Implement the Python class `Decoder` described below.
Class description:
PyTorch decoder LSTM module with attention
Method signatures and docstrings:
- def __init__(self, num_p: int, emb_dim: int, hidden_dim: int): Input arguments: * num_p (int): The size of the phoneme vocabulary * emb_dim (int): The dimensionality ... | Implement the Python class `Decoder` described below.
Class description:
PyTorch decoder LSTM module with attention
Method signatures and docstrings:
- def __init__(self, num_p: int, emb_dim: int, hidden_dim: int): Input arguments: * num_p (int): The size of the phoneme vocabulary * emb_dim (int): The dimensionality ... | 61ab2683fdc31e10d31ebdfb856efb92a145b37a | <|skeleton|>
class Decoder:
"""PyTorch decoder LSTM module with attention"""
def __init__(self, num_p: int, emb_dim: int, hidden_dim: int):
"""Input arguments: * num_p (int): The size of the phoneme vocabulary * emb_dim (int): The dimensionality of the character embeddings used * hidden_dim (int): The ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
"""PyTorch decoder LSTM module with attention"""
def __init__(self, num_p: int, emb_dim: int, hidden_dim: int):
"""Input arguments: * num_p (int): The size of the phoneme vocabulary * emb_dim (int): The dimensionality of the character embeddings used * hidden_dim (int): The hidden dimens... | the_stack_v2_python_sparse | torchG2P/g2p.py | StefanGunnlaugur/tts_data | train | 0 |
34c3b2e251a594a8081fc61e90360aff9c14c6dd | [
"if value:\n if GoogleDriveSource.parse_address(value):\n return value\n else:\n raise exceptions.ValidationError('Invalid Google Drive URL.')",
"if value:\n if re.match('^([a-z\\\\d])([a-z\\\\d_\\\\-]{10,})$', value, re.I):\n return value\n else:\n raise exceptions.Validat... | <|body_start_0|>
if value:
if GoogleDriveSource.parse_address(value):
return value
else:
raise exceptions.ValidationError('Invalid Google Drive URL.')
<|end_body_0|>
<|body_start_1|>
if value:
if re.match('^([a-z\\d])([a-z\\d_\\-]{10,}... | Serializer for Google Drive sources. | GoogleDriveSourceSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleDriveSourceSerializer:
"""Serializer for Google Drive sources."""
def validate_url(self, value):
"""Validate the Google Drive URL."""
<|body_0|>
def validate_google_id(self, value):
"""Validate the Google Drive id."""
<|body_1|>
def validate(se... | stack_v2_sparse_classes_75kplus_train_009430 | 40,006 | permissive | [
{
"docstring": "Validate the Google Drive URL.",
"name": "validate_url",
"signature": "def validate_url(self, value)"
},
{
"docstring": "Validate the Google Drive id.",
"name": "validate_google_id",
"signature": "def validate_google_id(self, value)"
},
{
"docstring": "Ensure that... | 3 | stack_v2_sparse_classes_30k_train_038486 | Implement the Python class `GoogleDriveSourceSerializer` described below.
Class description:
Serializer for Google Drive sources.
Method signatures and docstrings:
- def validate_url(self, value): Validate the Google Drive URL.
- def validate_google_id(self, value): Validate the Google Drive id.
- def validate(self, ... | Implement the Python class `GoogleDriveSourceSerializer` described below.
Class description:
Serializer for Google Drive sources.
Method signatures and docstrings:
- def validate_url(self, value): Validate the Google Drive URL.
- def validate_google_id(self, value): Validate the Google Drive id.
- def validate(self, ... | b0edf060f4cc5494eef81fce62a563bd5b4e8e31 | <|skeleton|>
class GoogleDriveSourceSerializer:
"""Serializer for Google Drive sources."""
def validate_url(self, value):
"""Validate the Google Drive URL."""
<|body_0|>
def validate_google_id(self, value):
"""Validate the Google Drive id."""
<|body_1|>
def validate(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoogleDriveSourceSerializer:
"""Serializer for Google Drive sources."""
def validate_url(self, value):
"""Validate the Google Drive URL."""
if value:
if GoogleDriveSource.parse_address(value):
return value
else:
raise exceptions.Vali... | the_stack_v2_python_sparse | manager/projects/api/serializers.py | stencila/hub | train | 31 |
67f3c55d95928ad0b76e110373baaacfaab2a022 | [
"token = request.GET.get('token', None)\nself.error = None\nself.user = None\npayload = None\nif token:\n try:\n payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])\n except jwt.ExpiredSignatureError:\n self.error = 'Verification link has expired.'\n except jwt.PyJWTError:\... | <|body_start_0|>
token = request.GET.get('token', None)
self.error = None
self.user = None
payload = None
if token:
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
... | Change password. | ChangePasswordView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangePasswordView:
"""Change password."""
def dispatch(self, request, *args, **kwargs):
"""Validate token."""
<|body_0|>
def get_form_kwargs(self):
"""Set user in form context."""
<|body_1|>
def get_context_data(self, **kwargs):
"""Pass poss... | stack_v2_sparse_classes_75kplus_train_009431 | 5,474 | permissive | [
{
"docstring": "Validate token.",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Set user in form context.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Pass possible error to template.... | 4 | stack_v2_sparse_classes_30k_val_002600 | Implement the Python class `ChangePasswordView` described below.
Class description:
Change password.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Validate token.
- def get_form_kwargs(self): Set user in form context.
- def get_context_data(self, **kwargs): Pass possible error to t... | Implement the Python class `ChangePasswordView` described below.
Class description:
Change password.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Validate token.
- def get_form_kwargs(self): Set user in form context.
- def get_context_data(self, **kwargs): Pass possible error to t... | 2c39ba45aa6aef37820b385c3060c83a73f8f910 | <|skeleton|>
class ChangePasswordView:
"""Change password."""
def dispatch(self, request, *args, **kwargs):
"""Validate token."""
<|body_0|>
def get_form_kwargs(self):
"""Set user in form context."""
<|body_1|>
def get_context_data(self, **kwargs):
"""Pass poss... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangePasswordView:
"""Change password."""
def dispatch(self, request, *args, **kwargs):
"""Validate token."""
token = request.GET.get('token', None)
self.error = None
self.user = None
payload = None
if token:
try:
payload = jwt.... | the_stack_v2_python_sparse | weight/users/views/users.py | SeptumDevs/lose_weightapp | train | 1 |
dbc816bc5a0c19aaef690677a17ed457c8698675 | [
"super(InstructionsDensification, self).__init__(config)\nself._max_reward_per_cone = config['max_reward_per_cone']\nself._cone_radius_meters = config['cone_radius_meters']\nself._min_distance_reached = float('inf')\nself._distance_to_next_waypoint = float('inf')\nassert config['proportion_of_panos_with_coins'] == ... | <|body_start_0|>
super(InstructionsDensification, self).__init__(config)
self._max_reward_per_cone = config['max_reward_per_cone']
self._cone_radius_meters = config['cone_radius_meters']
self._min_distance_reached = float('inf')
self._distance_to_next_waypoint = float('inf')
... | StreetLang game with a cone around each waypoint reward. | InstructionsDensification | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstructionsDensification:
"""StreetLang game with a cone around each waypoint reward."""
def __init__(self, config):
"""Creates an instance of the StreetLang level. Args: config: config dict of various settings."""
<|body_0|>
def on_reset(self, streetlearn):
"""... | stack_v2_sparse_classes_75kplus_train_009432 | 3,598 | permissive | [
{
"docstring": "Creates an instance of the StreetLang level. Args: config: config dict of various settings.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Gets called after StreetLearn:reset(). Args: streetlearn: a streetlearn instance. Returns: A newly popula... | 3 | stack_v2_sparse_classes_30k_train_000414 | Implement the Python class `InstructionsDensification` described below.
Class description:
StreetLang game with a cone around each waypoint reward.
Method signatures and docstrings:
- def __init__(self, config): Creates an instance of the StreetLang level. Args: config: config dict of various settings.
- def on_reset... | Implement the Python class `InstructionsDensification` described below.
Class description:
StreetLang game with a cone around each waypoint reward.
Method signatures and docstrings:
- def __init__(self, config): Creates an instance of the StreetLang level. Args: config: config dict of various settings.
- def on_reset... | dd348cb811064582a77abe855b9ac15799e4a1ef | <|skeleton|>
class InstructionsDensification:
"""StreetLang game with a cone around each waypoint reward."""
def __init__(self, config):
"""Creates an instance of the StreetLang level. Args: config: config dict of various settings."""
<|body_0|>
def on_reset(self, streetlearn):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstructionsDensification:
"""StreetLang game with a cone around each waypoint reward."""
def __init__(self, config):
"""Creates an instance of the StreetLang level. Args: config: config dict of various settings."""
super(InstructionsDensification, self).__init__(config)
self._max... | the_stack_v2_python_sparse | streetlearn/python/environment/instructions_densification.py | turningpoint1988/streetlearn | train | 0 |
a73de47b65448323d0a45d8b512bcd1f869e8882 | [
"user = request.user\ntry:\n video_client = user.video_client\n if timezone.now() > video_client.expires_at:\n video_client.delete()\n raise ValueError()\nexcept (AttributeError, ValueError):\n try:\n video_client = create_video_client(user)\n except (ValidationError, IntegrityError... | <|body_start_0|>
user = request.user
try:
video_client = user.video_client
if timezone.now() > video_client.expires_at:
video_client.delete()
raise ValueError()
except (AttributeError, ValueError):
try:
video_cli... | Shoutit Twilio API Resources. | ShoutitTwilioViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identit... | stack_v2_sparse_classes_75kplus_train_009433 | 7,701 | no_license | [
{
"docstring": "Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { \"token\": \"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE\", \"identity\": \"7c6ca4737db3447f936037374473e61f\" } </code></pre> ---",
"name": "video_auth",
"sign... | 4 | stack_v2_sparse_classes_30k_train_035704 | Implement the Python class `ShoutitTwilioViewSet` described below.
Class description:
Shoutit Twilio API Resources.
Method signatures and docstrings:
- def video_auth(self, request): Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAi... | Implement the Python class `ShoutitTwilioViewSet` described below.
Class description:
Shoutit Twilio API Resources.
Method signatures and docstrings:
- def video_auth(self, request): Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAi... | f3c95585ac639b45c28521712ed33a178ab36ea4 | <|skeleton|>
class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identity": "7c6ca473... | the_stack_v2_python_sparse | src/shoutit_twilio/views.py | shoutit/shoutit-api | train | 0 |
a0077cf72e6d5a749cc96501d89d5b388bf594cf | [
"assert batch_size == env.nenvs, 'batch_size should equal number of envs in vec_env'\nself.scheme = scheme\nself.env = env\nself.mac = mac\nself.logger = logger\nself.batch_size = batch_size\nself.max_episode_len = max_episode_len\nself.device = device\nself.t_env = t_env\nself.is_training = is_training\nself.share... | <|body_start_0|>
assert batch_size == env.nenvs, 'batch_size should equal number of envs in vec_env'
self.scheme = scheme
self.env = env
self.mac = mac
self.logger = logger
self.batch_size = batch_size
self.max_episode_len = max_episode_len
self.device = d... | wrap upon vectorized env to collect episdoes (vec env collect steps) | CTDEStepRunner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CTDEStepRunner:
"""wrap upon vectorized env to collect episdoes (vec env collect steps)"""
def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[], ma_step_keys=[], **kwargs):
"""Arguments: - scheme: sampl... | stack_v2_sparse_classes_75kplus_train_009434 | 17,139 | permissive | [
{
"docstring": "Arguments: - scheme: sample batch specs - env: vectorized (parallelized) env - mac: multiagent controller (e.g. maddpgs) - t_env: total env step so far using runner, used when restoring training",
"name": "__init__",
"signature": "def __init__(self, scheme, env, mac, logger, batch_size, ... | 5 | stack_v2_sparse_classes_30k_train_052846 | Implement the Python class `CTDEStepRunner` described below.
Class description:
wrap upon vectorized env to collect episdoes (vec env collect steps)
Method signatures and docstrings:
- def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[... | Implement the Python class `CTDEStepRunner` described below.
Class description:
wrap upon vectorized env to collect episdoes (vec env collect steps)
Method signatures and docstrings:
- def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[... | eb013bb3bab269bda8a8075e64fe3bcd2964d8ae | <|skeleton|>
class CTDEStepRunner:
"""wrap upon vectorized env to collect episdoes (vec env collect steps)"""
def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[], ma_step_keys=[], **kwargs):
"""Arguments: - scheme: sampl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CTDEStepRunner:
"""wrap upon vectorized env to collect episdoes (vec env collect steps)"""
def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[], ma_step_keys=[], **kwargs):
"""Arguments: - scheme: sample batch specs... | the_stack_v2_python_sparse | marl/runners/ctde_runner.py | zhangtjtongxue/learn-to-interact | train | 0 |
fde2f43111cc6e471931a244a3ba6f4e1447dcdb | [
"op_maker = OpMaker()\nread_op = op_maker.create('general_reader')\ninfer_op = op_maker.create('general_infer')\nresponse_op = op_maker.create('general_response')\nread_op_dict = yaml.safe_load(read_op)\nassert read_op_dict['name'] == 'general_reader_0'\nassert read_op_dict['type'] == 'GeneralReaderOp'\ninfer_op_di... | <|body_start_0|>
op_maker = OpMaker()
read_op = op_maker.create('general_reader')
infer_op = op_maker.create('general_infer')
response_op = op_maker.create('general_response')
read_op_dict = yaml.safe_load(read_op)
assert read_op_dict['name'] == 'general_reader_0'
... | test OpMaker class | TestOpMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOpMaker:
"""test OpMaker class"""
def test_create_with_existed_node(self):
"""test create normally"""
<|body_0|>
def test_create_with_undefined_node(self):
"""test create with undefined node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
op... | stack_v2_sparse_classes_75kplus_train_009435 | 3,472 | no_license | [
{
"docstring": "test create normally",
"name": "test_create_with_existed_node",
"signature": "def test_create_with_existed_node(self)"
},
{
"docstring": "test create with undefined node",
"name": "test_create_with_undefined_node",
"signature": "def test_create_with_undefined_node(self)"
... | 2 | stack_v2_sparse_classes_30k_train_039649 | Implement the Python class `TestOpMaker` described below.
Class description:
test OpMaker class
Method signatures and docstrings:
- def test_create_with_existed_node(self): test create normally
- def test_create_with_undefined_node(self): test create with undefined node | Implement the Python class `TestOpMaker` described below.
Class description:
test OpMaker class
Method signatures and docstrings:
- def test_create_with_existed_node(self): test create normally
- def test_create_with_undefined_node(self): test create with undefined node
<|skeleton|>
class TestOpMaker:
"""test Op... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class TestOpMaker:
"""test OpMaker class"""
def test_create_with_existed_node(self):
"""test create normally"""
<|body_0|>
def test_create_with_undefined_node(self):
"""test create with undefined node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestOpMaker:
"""test OpMaker class"""
def test_create_with_existed_node(self):
"""test create normally"""
op_maker = OpMaker()
read_op = op_maker.create('general_reader')
infer_op = op_maker.create('general_infer')
response_op = op_maker.create('general_response')
... | the_stack_v2_python_sparse | inference/serving_api_test/paddle_serving_server/test_dag.py | PaddlePaddle/PaddleTest | train | 42 |
8ede07b3bc1bb34c52a0211b293b9d18f584ce2f | [
"try:\n field = self.order_with_respect_to\n return {field: getattr(self, field)}\nexcept AttributeError:\n return {}",
"if self._order is None:\n lookup = self.with_respect_to()\n concrete_model = base_concrete_model(Orderable, self)\n self._order = concrete_model.objects.filter(**lookup).count... | <|body_start_0|>
try:
field = self.order_with_respect_to
return {field: getattr(self, field)}
except AttributeError:
return {}
<|end_body_0|>
<|body_start_1|>
if self._order is None:
lookup = self.with_respect_to()
concrete_model = bas... | Abstract model that provides a custom ordering integer field similar to using Meta's ``order_with_respect_to``, since to date (Django 1.2) this doesn't work with ``ForeignKey("self")``. We may also want this feature for models that aren't ordered with respect to a particular field. | Orderable | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Orderable:
"""Abstract model that provides a custom ordering integer field similar to using Meta's ``order_with_respect_to``, since to date (Django 1.2) this doesn't work with ``ForeignKey("self")``. We may also want this feature for models that aren't ordered with respect to a particular field."... | stack_v2_sparse_classes_75kplus_train_009436 | 8,916 | permissive | [
{
"docstring": "Returns a dict to use as a filter for ordering operations containing the original ``Meta.order_with_respect_to`` value if provided.",
"name": "with_respect_to",
"signature": "def with_respect_to(self)"
},
{
"docstring": "Set the initial ordering value.",
"name": "save",
"... | 3 | stack_v2_sparse_classes_30k_train_011642 | Implement the Python class `Orderable` described below.
Class description:
Abstract model that provides a custom ordering integer field similar to using Meta's ``order_with_respect_to``, since to date (Django 1.2) this doesn't work with ``ForeignKey("self")``. We may also want this feature for models that aren't order... | Implement the Python class `Orderable` described below.
Class description:
Abstract model that provides a custom ordering integer field similar to using Meta's ``order_with_respect_to``, since to date (Django 1.2) this doesn't work with ``ForeignKey("self")``. We may also want this feature for models that aren't order... | 216dac182bf57c3028124445f5f3dc00a3be47bc | <|skeleton|>
class Orderable:
"""Abstract model that provides a custom ordering integer field similar to using Meta's ``order_with_respect_to``, since to date (Django 1.2) this doesn't work with ``ForeignKey("self")``. We may also want this feature for models that aren't ordered with respect to a particular field."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Orderable:
"""Abstract model that provides a custom ordering integer field similar to using Meta's ``order_with_respect_to``, since to date (Django 1.2) this doesn't work with ``ForeignKey("self")``. We may also want this feature for models that aren't ordered with respect to a particular field."""
def w... | the_stack_v2_python_sparse | mezzanine/core/models.py | iciclespider/mezzanine | train | 1 |
4170601f8607d03a5be45f1bebd88a3c12db554f | [
"if not self.cache:\n if self.concrete:\n return 'dbPointer'\n return 'objectId'\nreturn 'object'",
"kinds = list(self.kinds)\nif isinstance(value, oid):\n return value\nreturn kinds[0].from_mongo(value, value.keys())",
"cache = None\nif isinstance(value, Document):\n cache = value\n ident... | <|body_start_0|>
if not self.cache:
if self.concrete:
return 'dbPointer'
return 'objectId'
return 'object'
<|end_body_0|>
<|body_start_1|>
kinds = list(self.kinds)
if isinstance(value, oid):
return value
return kinds[0].from_mo... | Reference | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reference:
def __foreign__(self):
"""Advertise that we store a simple reference, or deep reference, or object, depending on configuration."""
<|body_0|>
def to_native(self, obj, name, value):
"""Transform the MongoDB value into a Marrow Mongo value."""
<|body... | stack_v2_sparse_classes_75kplus_train_009437 | 6,177 | permissive | [
{
"docstring": "Advertise that we store a simple reference, or deep reference, or object, depending on configuration.",
"name": "__foreign__",
"signature": "def __foreign__(self)"
},
{
"docstring": "Transform the MongoDB value into a Marrow Mongo value.",
"name": "to_native",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_000614 | Implement the Python class `Reference` described below.
Class description:
Implement the Reference class.
Method signatures and docstrings:
- def __foreign__(self): Advertise that we store a simple reference, or deep reference, or object, depending on configuration.
- def to_native(self, obj, name, value): Transform ... | Implement the Python class `Reference` described below.
Class description:
Implement the Reference class.
Method signatures and docstrings:
- def __foreign__(self): Advertise that we store a simple reference, or deep reference, or object, depending on configuration.
- def to_native(self, obj, name, value): Transform ... | 5f357b3951600a9aecbe6c50727891b1485df210 | <|skeleton|>
class Reference:
def __foreign__(self):
"""Advertise that we store a simple reference, or deep reference, or object, depending on configuration."""
<|body_0|>
def to_native(self, obj, name, value):
"""Transform the MongoDB value into a Marrow Mongo value."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Reference:
def __foreign__(self):
"""Advertise that we store a simple reference, or deep reference, or object, depending on configuration."""
if not self.cache:
if self.concrete:
return 'dbPointer'
return 'objectId'
return 'object'
def to_na... | the_stack_v2_python_sparse | dependencies/mongo/marrow/mongo/core/field/complex.py | bmillham/djrq2 | train | 1 | |
5392a7ba173dfd19e5172f858875a6a2ad3d20e4 | [
"defined_in_cli = set()\nfor option in kwargs:\n if ctx.get_parameter_source(option) == ParameterSource.COMMANDLINE:\n defined_in_cli.add(option)\nreturn cls(**kwargs, defined_in_cli=defined_in_cli)",
"options_map = map_class_fields_with_their_types(self)\nparsed_config = {'defined_in_config': {'defined... | <|body_start_0|>
defined_in_cli = set()
for option in kwargs:
if ctx.get_parameter_source(option) == ParameterSource.COMMANDLINE:
defined_in_cli.add(option)
return cls(**kwargs, defined_in_cli=defined_in_cli)
<|end_body_0|>
<|body_start_1|>
options_map = map_... | Configuration read directly from cli or configuration file. | RawConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawConfig:
"""Configuration read directly from cli or configuration file."""
def from_cli(cls, ctx: click.Context, **kwargs):
"""Creates RawConfig instance while saving which options were supplied from CLI."""
<|body_0|>
def from_config_file(self, config: Dict, config_pa... | stack_v2_sparse_classes_75kplus_train_009438 | 15,395 | permissive | [
{
"docstring": "Creates RawConfig instance while saving which options were supplied from CLI.",
"name": "from_cli",
"signature": "def from_cli(cls, ctx: click.Context, **kwargs)"
},
{
"docstring": "Creates new RawConfig instance from dictionary. Dictionary key:values needs to be normalized and p... | 3 | null | Implement the Python class `RawConfig` described below.
Class description:
Configuration read directly from cli or configuration file.
Method signatures and docstrings:
- def from_cli(cls, ctx: click.Context, **kwargs): Creates RawConfig instance while saving which options were supplied from CLI.
- def from_config_fi... | Implement the Python class `RawConfig` described below.
Class description:
Configuration read directly from cli or configuration file.
Method signatures and docstrings:
- def from_cli(cls, ctx: click.Context, **kwargs): Creates RawConfig instance while saving which options were supplied from CLI.
- def from_config_fi... | d72e5310ed4a8165d7ee516d79e0accccaf7748c | <|skeleton|>
class RawConfig:
"""Configuration read directly from cli or configuration file."""
def from_cli(cls, ctx: click.Context, **kwargs):
"""Creates RawConfig instance while saving which options were supplied from CLI."""
<|body_0|>
def from_config_file(self, config: Dict, config_pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RawConfig:
"""Configuration read directly from cli or configuration file."""
def from_cli(cls, ctx: click.Context, **kwargs):
"""Creates RawConfig instance while saving which options were supplied from CLI."""
defined_in_cli = set()
for option in kwargs:
if ctx.get_par... | the_stack_v2_python_sparse | robocorp-python-ls-core/src/robocorp_ls_core/libs/robotidy_lib/robotidy/config.py | robocorp/robotframework-lsp | train | 167 |
1131904bef4d3ce228ab65c5932251e061df7d29 | [
"self.logger = logger\nself.queues = queues\nself.config = Config()\nself.redis_host = redisHost\nself.redis_port = redisPort\nself.encrypted_aes_key_path = encryptedAESKeyPath",
"self.logger.info('Decrypting AES Key')\nwrapper = AESKeyWrapper(vault=self.config.azure_keyvault_url, client_id=self.config.service_pr... | <|body_start_0|>
self.logger = logger
self.queues = queues
self.config = Config()
self.redis_host = redisHost
self.redis_port = redisPort
self.encrypted_aes_key_path = encryptedAESKeyPath
<|end_body_0|>
<|body_start_1|>
self.logger.info('Decrypting AES Key')
... | Processes Redis Q jobs | Processor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Processor:
"""Processes Redis Q jobs"""
def __init__(self, logger, redisHost, redisPort, queues, encryptedAESKeyPath):
""":param logger logger: the logger :param str redis_host: Redis host where the Redis Q is running :param int redis_port: Redis port where the Redis Q is running :pa... | stack_v2_sparse_classes_75kplus_train_009439 | 5,001 | permissive | [
{
"docstring": ":param logger logger: the logger :param str redis_host: Redis host where the Redis Q is running :param int redis_port: Redis port where the Redis Q is running :param array queues: the queues the worker will listen on :param str encryptedAesKeyPath: path to the encrypted AES key file",
"name"... | 3 | stack_v2_sparse_classes_30k_train_029202 | Implement the Python class `Processor` described below.
Class description:
Processes Redis Q jobs
Method signatures and docstrings:
- def __init__(self, logger, redisHost, redisPort, queues, encryptedAESKeyPath): :param logger logger: the logger :param str redis_host: Redis host where the Redis Q is running :param in... | Implement the Python class `Processor` described below.
Class description:
Processes Redis Q jobs
Method signatures and docstrings:
- def __init__(self, logger, redisHost, redisPort, queues, encryptedAESKeyPath): :param logger logger: the logger :param str redis_host: Redis host where the Redis Q is running :param in... | c079e8fd73c9c6108702174a6a1a5a3b9a9f7395 | <|skeleton|>
class Processor:
"""Processes Redis Q jobs"""
def __init__(self, logger, redisHost, redisPort, queues, encryptedAESKeyPath):
""":param logger logger: the logger :param str redis_host: Redis host where the Redis Q is running :param int redis_port: Redis port where the Redis Q is running :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Processor:
"""Processes Redis Q jobs"""
def __init__(self, logger, redisHost, redisPort, queues, encryptedAESKeyPath):
""":param logger logger: the logger :param str redis_host: Redis host where the Redis Q is running :param int redis_port: Redis port where the Redis Q is running :param array que... | the_stack_v2_python_sparse | app/processor.py | Claudiusgonzo/azure-python-redis-queue-processor | train | 0 |
9fc8942e0d3f78140cd1a770eb10df060c343b62 | [
"self.task = 'ner'\nself._set_metadata(md)\nself.load_dictionary()\nself.load_tag_dict()\nself.sentences = []\nsent = []\nfor line in sys.stdin:\n line = line.decode('utf-8').strip()\n if line:\n form, pos, tag = line.split(None, 2)\n sent.append([form, pos])\n else:\n self.sentences.a... | <|body_start_0|>
self.task = 'ner'
self._set_metadata(md)
self.load_dictionary()
self.load_tag_dict()
self.sentences = []
sent = []
for line in sys.stdin:
line = line.decode('utf-8').strip()
if line:
form, pos, tag = line.sp... | This class reads data from a CoNLL03 corpus and turns it into a format readable by the neural network for the NER tagging task. | NerTagReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NerTagReader:
"""This class reads data from a CoNLL03 corpus and turns it into a format readable by the neural network for the NER tagging task."""
def __init__(self, md=None):
"""Read sentences from stdin."""
<|body_0|>
def toIOB(self, tags):
"""Convert from IOB... | stack_v2_sparse_classes_75kplus_train_009440 | 4,737 | permissive | [
{
"docstring": "Read sentences from stdin.",
"name": "__init__",
"signature": "def __init__(self, md=None)"
},
{
"docstring": "Convert from IOBES to IOB notation.",
"name": "toIOB",
"signature": "def toIOB(self, tags)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014527 | Implement the Python class `NerTagReader` described below.
Class description:
This class reads data from a CoNLL03 corpus and turns it into a format readable by the neural network for the NER tagging task.
Method signatures and docstrings:
- def __init__(self, md=None): Read sentences from stdin.
- def toIOB(self, ta... | Implement the Python class `NerTagReader` described below.
Class description:
This class reads data from a CoNLL03 corpus and turns it into a format readable by the neural network for the NER tagging task.
Method signatures and docstrings:
- def __init__(self, md=None): Read sentences from stdin.
- def toIOB(self, ta... | 45c76e3b0f6e94703ed02846fb0ea44937946881 | <|skeleton|>
class NerTagReader:
"""This class reads data from a CoNLL03 corpus and turns it into a format readable by the neural network for the NER tagging task."""
def __init__(self, md=None):
"""Read sentences from stdin."""
<|body_0|>
def toIOB(self, tags):
"""Convert from IOB... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NerTagReader:
"""This class reads data from a CoNLL03 corpus and turns it into a format readable by the neural network for the NER tagging task."""
def __init__(self, md=None):
"""Read sentences from stdin."""
self.task = 'ner'
self._set_metadata(md)
self.load_dictionary()... | the_stack_v2_python_sparse | nlpnet/ner/ner_reader.py | attardi/nlpnet | train | 6 |
4d771bfd3174f71bb01fe59ef63b3848b0b749a9 | [
"cache_node = set()\nwhile headA:\n cache_node.add(headA)\n headA = headA.next\nwhile headB:\n if headB in cache_node:\n return headB\n headB = headB.next\nreturn",
"pA = headA\npB = headB\nwhile pA != pB:\n pA = pA.next if pA else headB\n pB = pB.next if pB else headA\nreturn pA"
] | <|body_start_0|>
cache_node = set()
while headA:
cache_node.add(headA)
headA = headA.next
while headB:
if headB in cache_node:
return headB
headB = headB.next
return
<|end_body_0|>
<|body_start_1|>
pA = headA
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode:
"""哈希表 时间复杂度: O(n) 空间复杂度: O(n)"""
<|body_0|>
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""双指针 时间复杂度:O(n) 空间福再度:O(1) 设: headA节点长度为m,需要a个节点达到公共节点 ... | stack_v2_sparse_classes_75kplus_train_009441 | 1,810 | no_license | [
{
"docstring": "哈希表 时间复杂度: O(n) 空间复杂度: O(n)",
"name": "getIntersectionNode2",
"signature": "def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode"
},
{
"docstring": "双指针 时间复杂度:O(n) 空间福再度:O(1) 设: headA节点长度为m,需要a个节点达到公共节点 headB节点长度n,需要b个节点达到公共节点 公共节点长度为c 创建两个指针pA和pB分别指向headA... | 2 | stack_v2_sparse_classes_30k_train_020761 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode: 哈希表 时间复杂度: O(n) 空间复杂度: O(n)
- def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode: 哈希表 时间复杂度: O(n) 空间复杂度: O(n)
- def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Lis... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode:
"""哈希表 时间复杂度: O(n) 空间复杂度: O(n)"""
<|body_0|>
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""双指针 时间复杂度:O(n) 空间福再度:O(1) 设: headA节点长度为m,需要a个节点达到公共节点 ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode:
"""哈希表 时间复杂度: O(n) 空间复杂度: O(n)"""
cache_node = set()
while headA:
cache_node.add(headA)
headA = headA.next
while headB:
if headB in cache_node:
... | the_stack_v2_python_sparse | leetcode/剑指offer/剑指 Offer 52. 两个链表的第一个公共节点.py | tenqaz/crazy_arithmetic | train | 0 | |
bdb011cb977feed885ad8df37b13285e2ce49f25 | [
"self.refer = refer\nself.top_N = top_N\nself.threshold = threshold",
"num_hit = 0\nnum_proposal = 0\nnum_ref = 0\nfor ref_id in self.refer.getRefIds(split=split):\n ref = self.refer.Refs[ref_id]\n image_id = ref['image_id']\n ann_id = ref['ann_id']\n ann = self.refer.Anns[ann_id]\n gt_box = xywh_t... | <|body_start_0|>
self.refer = refer
self.top_N = top_N
self.threshold = threshold
<|end_body_0|>
<|body_start_1|>
num_hit = 0
num_proposal = 0
num_ref = 0
for ref_id in self.refer.getRefIds(split=split):
ref = self.refer.Refs[ref_id]
image... | NewHitRateEvaluator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewHitRateEvaluator:
def __init__(self, refer, top_N=None, threshold=0.5):
"""Evaluate refexp-based hit rate. Args: refdb: `refdb` dict. split: Dataset split to evaluate on. top_N: Select top-N scoring proposals to evaluate. `None` means no selection. Default `None`."""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_009442 | 3,999 | permissive | [
{
"docstring": "Evaluate refexp-based hit rate. Args: refdb: `refdb` dict. split: Dataset split to evaluate on. top_N: Select top-N scoring proposals to evaluate. `None` means no selection. Default `None`.",
"name": "__init__",
"signature": "def __init__(self, refer, top_N=None, threshold=0.5)"
},
{... | 2 | null | Implement the Python class `NewHitRateEvaluator` described below.
Class description:
Implement the NewHitRateEvaluator class.
Method signatures and docstrings:
- def __init__(self, refer, top_N=None, threshold=0.5): Evaluate refexp-based hit rate. Args: refdb: `refdb` dict. split: Dataset split to evaluate on. top_N:... | Implement the Python class `NewHitRateEvaluator` described below.
Class description:
Implement the NewHitRateEvaluator class.
Method signatures and docstrings:
- def __init__(self, refer, top_N=None, threshold=0.5): Evaluate refexp-based hit rate. Args: refdb: `refdb` dict. split: Dataset split to evaluate on. top_N:... | 8f83f350c497d0ef875c778a8ce76725552abb3c | <|skeleton|>
class NewHitRateEvaluator:
def __init__(self, refer, top_N=None, threshold=0.5):
"""Evaluate refexp-based hit rate. Args: refdb: `refdb` dict. split: Dataset split to evaluate on. top_N: Select top-N scoring proposals to evaluate. `None` means no selection. Default `None`."""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewHitRateEvaluator:
def __init__(self, refer, top_N=None, threshold=0.5):
"""Evaluate refexp-based hit rate. Args: refdb: `refdb` dict. split: Dataset split to evaluate on. top_N: Select top-N scoring proposals to evaluate. `None` means no selection. Default `None`."""
self.refer = refer
... | the_stack_v2_python_sparse | utils/hit_rate_utils.py | eustcPL/ref-nms | train | 0 | |
a2fde0ec714941c39427de31477d1dadc2e106f3 | [
"query = 'SELECT user_id,\\n course_id,\\n course_title,\\n course_description,\\n course_category,\\n center,\\n created_on\\n FROM leads\\n ORDER BY created_on DESC\\n '\ndf = self.create_df_from_query(query)\nreturn df",
"qu... | <|body_start_0|>
query = 'SELECT user_id,\n course_id,\n course_title,\n course_description,\n course_category,\n center,\n created_on\n FROM leads\n ORDER BY created_on DESC\n '
df = self.create_df_from_query(query)
... | Extract | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Extract:
def extract_leads(self) -> pd.DataFrame:
"""Create a leads dataframe from query :return: a dataframe with leads"""
<|body_0|>
def extract_reviews(self) -> pd.DataFrame:
"""Create a reviews dataframe from query :return: a dataframe with reviews"""
<|b... | stack_v2_sparse_classes_75kplus_train_009443 | 1,038 | no_license | [
{
"docstring": "Create a leads dataframe from query :return: a dataframe with leads",
"name": "extract_leads",
"signature": "def extract_leads(self) -> pd.DataFrame"
},
{
"docstring": "Create a reviews dataframe from query :return: a dataframe with reviews",
"name": "extract_reviews",
"s... | 2 | null | Implement the Python class `Extract` described below.
Class description:
Implement the Extract class.
Method signatures and docstrings:
- def extract_leads(self) -> pd.DataFrame: Create a leads dataframe from query :return: a dataframe with leads
- def extract_reviews(self) -> pd.DataFrame: Create a reviews dataframe... | Implement the Python class `Extract` described below.
Class description:
Implement the Extract class.
Method signatures and docstrings:
- def extract_leads(self) -> pd.DataFrame: Create a leads dataframe from query :return: a dataframe with leads
- def extract_reviews(self) -> pd.DataFrame: Create a reviews dataframe... | 0326c80efa4677a1ce5ff6a855eb9ad0dab92977 | <|skeleton|>
class Extract:
def extract_leads(self) -> pd.DataFrame:
"""Create a leads dataframe from query :return: a dataframe with leads"""
<|body_0|>
def extract_reviews(self) -> pd.DataFrame:
"""Create a reviews dataframe from query :return: a dataframe with reviews"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Extract:
def extract_leads(self) -> pd.DataFrame:
"""Create a leads dataframe from query :return: a dataframe with leads"""
query = 'SELECT user_id,\n course_id,\n course_title,\n course_description,\n course_category,\n center,\n ... | the_stack_v2_python_sparse | automate/classes/extract.py | fdelgados/courses_recommender | train | 0 | |
7764868f603b1ee6fd7041a72d53aefdd5ca0721 | [
"if reactant_conformers is None:\n reactant_conformers = [-1 for i in range(len(reactants))]\nif product_conformers is None:\n product_conformers = [-1 for i in range(len(products))]\nself.energy_calculator = energy_calculator\nself.reactants = reactants\nself.products = products\nself.reactant_conformers = r... | <|body_start_0|>
if reactant_conformers is None:
reactant_conformers = [-1 for i in range(len(reactants))]
if product_conformers is None:
product_conformers = [-1 for i in range(len(products))]
self.energy_calculator = energy_calculator
self.reactants = reactants
... | Calculates the formation energy of a molecule. Attributes ---------- energy_calculator : :class:`EnergyCalculator` The :class:`EnergyCalculator` used to calculate the energy of all reactant and product molecules. reactants : :class:`list` of :class:`.Molecule` The reactants. If there are multiples of the same reactant ... | FormationEnergy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormationEnergy:
"""Calculates the formation energy of a molecule. Attributes ---------- energy_calculator : :class:`EnergyCalculator` The :class:`EnergyCalculator` used to calculate the energy of all reactant and product molecules. reactants : :class:`list` of :class:`.Molecule` The reactants. I... | stack_v2_sparse_classes_75kplus_train_009444 | 12,373 | permissive | [
{
"docstring": "Initializes a :class:`FormationEnergy` instance. Parameters ---------- energy_calculator : :class:`EnergyCalculator` The :class:`EnergyCalculator` used to calculate the energy of all reactant and product molecules. reactants : :class:`list` of :class:`.Molecule` The reactants. If there are multi... | 2 | stack_v2_sparse_classes_30k_train_006182 | Implement the Python class `FormationEnergy` described below.
Class description:
Calculates the formation energy of a molecule. Attributes ---------- energy_calculator : :class:`EnergyCalculator` The :class:`EnergyCalculator` used to calculate the energy of all reactant and product molecules. reactants : :class:`list`... | Implement the Python class `FormationEnergy` described below.
Class description:
Calculates the formation energy of a molecule. Attributes ---------- energy_calculator : :class:`EnergyCalculator` The :class:`EnergyCalculator` used to calculate the energy of all reactant and product molecules. reactants : :class:`list`... | c85ce1f1874cf4bacf00bec7f77ceb7793600911 | <|skeleton|>
class FormationEnergy:
"""Calculates the formation energy of a molecule. Attributes ---------- energy_calculator : :class:`EnergyCalculator` The :class:`EnergyCalculator` used to calculate the energy of all reactant and product molecules. reactants : :class:`list` of :class:`.Molecule` The reactants. I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FormationEnergy:
"""Calculates the formation energy of a molecule. Attributes ---------- energy_calculator : :class:`EnergyCalculator` The :class:`EnergyCalculator` used to calculate the energy of all reactant and product molecules. reactants : :class:`list` of :class:`.Molecule` The reactants. If there are m... | the_stack_v2_python_sparse | stk/calculators/energy/energy_calculators.py | lucaspedroni/stk | train | 0 |
98d9df822fd3b722acdb5e2e0c3f3ee0915146f9 | [
"super().__init__()\nself.stfts = torch.nn.ModuleList([TorchSTFT(sample_rate=sample_rate, fft_size=x * 4, hop_size=x, win_size=x * 4, normalized=True, domain=domain, mel_scale=mel_scale) for x in hop_lengths])\nself.domain = domain\nif domain == 'double':\n self.discriminators = torch.nn.ModuleList([BaseFrequenc... | <|body_start_0|>
super().__init__()
self.stfts = torch.nn.ModuleList([TorchSTFT(sample_rate=sample_rate, fft_size=x * 4, hop_size=x, win_size=x * 4, normalized=True, domain=domain, mel_scale=mel_scale) for x in hop_lengths])
self.domain = domain
if domain == 'double':
self.di... | Multi-Frequency Discriminator module in UnivNet. | MultiFrequencyDiscriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiFrequencyDiscriminator:
"""Multi-Frequency Discriminator module in UnivNet."""
def __init__(self, sample_rate: int=22050, hop_lengths=[128, 256, 512], hidden_channels=[256, 512, 512], domain='double', mel_scale=True, divisors=[32, 16, 8, 4, 2, 1, 1], strides=[1, 2, 1, 2, 1, 2, 1]):
... | stack_v2_sparse_classes_75kplus_train_009445 | 35,285 | permissive | [
{
"docstring": "Initialize Multi-Frequency Discriminator module. Args: hop_lengths (list): List of hop lengths. hidden_channels (list): List of number of channels in hidden layers. domain (str): Domain of input signal. Default is \"double\". mel_scale (bool): Whether to use mel-scale frequency. Default is True.... | 2 | null | Implement the Python class `MultiFrequencyDiscriminator` described below.
Class description:
Multi-Frequency Discriminator module in UnivNet.
Method signatures and docstrings:
- def __init__(self, sample_rate: int=22050, hop_lengths=[128, 256, 512], hidden_channels=[256, 512, 512], domain='double', mel_scale=True, di... | Implement the Python class `MultiFrequencyDiscriminator` described below.
Class description:
Multi-Frequency Discriminator module in UnivNet.
Method signatures and docstrings:
- def __init__(self, sample_rate: int=22050, hop_lengths=[128, 256, 512], hidden_channels=[256, 512, 512], domain='double', mel_scale=True, di... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class MultiFrequencyDiscriminator:
"""Multi-Frequency Discriminator module in UnivNet."""
def __init__(self, sample_rate: int=22050, hop_lengths=[128, 256, 512], hidden_channels=[256, 512, 512], domain='double', mel_scale=True, divisors=[32, 16, 8, 4, 2, 1, 1], strides=[1, 2, 1, 2, 1, 2, 1]):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiFrequencyDiscriminator:
"""Multi-Frequency Discriminator module in UnivNet."""
def __init__(self, sample_rate: int=22050, hop_lengths=[128, 256, 512], hidden_channels=[256, 512, 512], domain='double', mel_scale=True, divisors=[32, 16, 8, 4, 2, 1, 1], strides=[1, 2, 1, 2, 1, 2, 1]):
"""Initia... | the_stack_v2_python_sparse | espnet2/gan_svs/visinger2/visinger2_vocoder.py | espnet/espnet | train | 7,242 |
84d50e581e672f418cdaaf6c758b57ff5c88b914 | [
"param = req.media\nif 'cartridgeModelName' in param:\n data = db.Db()\n newId = data.addCartdrigeModel(param['cartridgeModelName'])\n resp.text = json.dumps({'id': newId, 'model': param['cartridgeModelName'], 'depString': ''})",
"queryString = falcon.uri.parse_query_string(req.query_string)\ndata = db.D... | <|body_start_0|>
param = req.media
if 'cartridgeModelName' in param:
data = db.Db()
newId = data.addCartdrigeModel(param['cartridgeModelName'])
resp.text = json.dumps({'id': newId, 'model': param['cartridgeModelName'], 'depString': ''})
<|end_body_0|>
<|body_start_1|... | CartridgeModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartridgeModel:
def on_post(self, req, resp):
"""handle post"""
<|body_0|>
def on_get(self, req, resp):
"""handle get request"""
<|body_1|>
def on_put(self, req, resp):
"""handle put request"""
<|body_2|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_009446 | 1,406 | no_license | [
{
"docstring": "handle post",
"name": "on_post",
"signature": "def on_post(self, req, resp)"
},
{
"docstring": "handle get request",
"name": "on_get",
"signature": "def on_get(self, req, resp)"
},
{
"docstring": "handle put request",
"name": "on_put",
"signature": "def on... | 3 | stack_v2_sparse_classes_30k_train_003937 | Implement the Python class `CartridgeModel` described below.
Class description:
Implement the CartridgeModel class.
Method signatures and docstrings:
- def on_post(self, req, resp): handle post
- def on_get(self, req, resp): handle get request
- def on_put(self, req, resp): handle put request | Implement the Python class `CartridgeModel` described below.
Class description:
Implement the CartridgeModel class.
Method signatures and docstrings:
- def on_post(self, req, resp): handle post
- def on_get(self, req, resp): handle get request
- def on_put(self, req, resp): handle put request
<|skeleton|>
class Cart... | 529e9a0c66a6c7021224a2daf60f378f01164ca5 | <|skeleton|>
class CartridgeModel:
def on_post(self, req, resp):
"""handle post"""
<|body_0|>
def on_get(self, req, resp):
"""handle get request"""
<|body_1|>
def on_put(self, req, resp):
"""handle put request"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CartridgeModel:
def on_post(self, req, resp):
"""handle post"""
param = req.media
if 'cartridgeModelName' in param:
data = db.Db()
newId = data.addCartdrigeModel(param['cartridgeModelName'])
resp.text = json.dumps({'id': newId, 'model': param['cartri... | the_stack_v2_python_sparse | answers/cartridge_model.py | Logsod/noti_rest_server | train | 0 | |
5d28e4c93036f7d520948a3c6e642e89b0e2dc2d | [
"pull_request_template = PullRequestTemplate.objects.get(owner=owner, repo=repo)\nserializer = PullRequestTemplateSerializer(pull_request_template)\nreturn Response(serializer.data)",
"pr_template = PullRequestTemplate.objects.filter(owner=owner, repo=repo)\nif pr_template:\n serializer = PullRequestTemplateSe... | <|body_start_0|>
pull_request_template = PullRequestTemplate.objects.get(owner=owner, repo=repo)
serializer = PullRequestTemplateSerializer(pull_request_template)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
pr_template = PullRequestTemplate.objects.filter(owner=owne... | PullRequestTemplateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PullRequestTemplateView:
def get(self, request, owner, repo, token_auth):
"""Return if a repository have a pull request template or not"""
<|body_0|>
def post(self, request, owner, repo, token_auth):
"""Post pull request template object"""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus_train_009447 | 4,065 | permissive | [
{
"docstring": "Return if a repository have a pull request template or not",
"name": "get",
"signature": "def get(self, request, owner, repo, token_auth)"
},
{
"docstring": "Post pull request template object",
"name": "post",
"signature": "def post(self, request, owner, repo, token_auth)... | 3 | stack_v2_sparse_classes_30k_train_037674 | Implement the Python class `PullRequestTemplateView` described below.
Class description:
Implement the PullRequestTemplateView class.
Method signatures and docstrings:
- def get(self, request, owner, repo, token_auth): Return if a repository have a pull request template or not
- def post(self, request, owner, repo, t... | Implement the Python class `PullRequestTemplateView` described below.
Class description:
Implement the PullRequestTemplateView class.
Method signatures and docstrings:
- def get(self, request, owner, repo, token_auth): Return if a repository have a pull request template or not
- def post(self, request, owner, repo, t... | 3f031eac9559a10fdcf70a88ee4c548cf93e4ac2 | <|skeleton|>
class PullRequestTemplateView:
def get(self, request, owner, repo, token_auth):
"""Return if a repository have a pull request template or not"""
<|body_0|>
def post(self, request, owner, repo, token_auth):
"""Post pull request template object"""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PullRequestTemplateView:
def get(self, request, owner, repo, token_auth):
"""Return if a repository have a pull request template or not"""
pull_request_template = PullRequestTemplate.objects.get(owner=owner, repo=repo)
serializer = PullRequestTemplateSerializer(pull_request_template)
... | the_stack_v2_python_sparse | hubcare/metrics/community_metrics/pull_request_template/views.py | fga-eps-mds/2019.1-hubcare-api | train | 7 | |
150465317aa985a95567b7a23c1030e2b14fca8c | [
"data = json.loads(self._event['data'])\nvalue = data.get('value', {})\nif not value:\n return\nself.attributeName = self._event['action'].split('.')[-1]\nself.oldValue = value['old']\nself.newValue = value['new']\nself.setText(u'Attribute <span style=\"color: #E6E6E6;\">{0}</span> changed from <span style=\"col... | <|body_start_0|>
data = json.loads(self._event['data'])
value = data.get('value', {})
if not value:
return
self.attributeName = self._event['action'].split('.')[-1]
self.oldValue = value['old']
self.newValue = value['new']
self.setText(u'Attribute <spa... | Represent property notification. | PropertyNotification | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertyNotification:
"""Represent property notification."""
def _load(self):
"""Internal load of data from event."""
<|body_0|>
def value(self):
"""Override and add extra information."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = json.... | stack_v2_sparse_classes_75kplus_train_009448 | 6,407 | permissive | [
{
"docstring": "Internal load of data from event.",
"name": "_load",
"signature": "def _load(self)"
},
{
"docstring": "Override and add extra information.",
"name": "value",
"signature": "def value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032608 | Implement the Python class `PropertyNotification` described below.
Class description:
Represent property notification.
Method signatures and docstrings:
- def _load(self): Internal load of data from event.
- def value(self): Override and add extra information. | Implement the Python class `PropertyNotification` described below.
Class description:
Represent property notification.
Method signatures and docstrings:
- def _load(self): Internal load of data from event.
- def value(self): Override and add extra information.
<|skeleton|>
class PropertyNotification:
"""Represen... | f55f52787484fcf931c4653e7e241791f052c04f | <|skeleton|>
class PropertyNotification:
"""Represent property notification."""
def _load(self):
"""Internal load of data from event."""
<|body_0|>
def value(self):
"""Override and add extra information."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PropertyNotification:
"""Represent property notification."""
def _load(self):
"""Internal load of data from event."""
data = json.loads(self._event['data'])
value = data.get('value', {})
if not value:
return
self.attributeName = self._event['action'].sp... | the_stack_v2_python_sparse | source/ftrack_connect/ui/widget/notification_directive.py | IngenuityEngine/ftrack-connect | train | 0 |
6fa1ba51c2c7320aed81bb6cdfa134cf4be5a6a8 | [
"self.sib_host = settings['sib_host']\nself.sib_port = settings['sib_port']\nself.block_size = settings['block_size']",
"res = None\ng = Graph()\ntry:\n res = g.parse(filename, format='n3')\nexcept Exception as e:\n raise N3KBLoaderException(str(e))\ntriple_list = []\nfor triple in res:\n s = []\n for... | <|body_start_0|>
self.sib_host = settings['sib_host']
self.sib_port = settings['sib_port']
self.block_size = settings['block_size']
<|end_body_0|>
<|body_start_1|>
res = None
g = Graph()
try:
res = g.parse(filename, format='n3')
except Exception as e:... | This class is used to load N3 files into the SIB. NOTE: this class will be modified to support different types of files. | N3KBLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class N3KBLoader:
"""This class is used to load N3 files into the SIB. NOTE: this class will be modified to support different types of files."""
def __init__(self, settings):
"""Constructor for the N3KBLoader class"""
<|body_0|>
def load_n3file(self, filename):
"""This... | stack_v2_sparse_classes_75kplus_train_009449 | 2,412 | no_license | [
{
"docstring": "Constructor for the N3KBLoader class",
"name": "__init__",
"signature": "def __init__(self, settings)"
},
{
"docstring": "This method load the content of the N3 file into the SIB",
"name": "load_n3file",
"signature": "def load_n3file(self, filename)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048052 | Implement the Python class `N3KBLoader` described below.
Class description:
This class is used to load N3 files into the SIB. NOTE: this class will be modified to support different types of files.
Method signatures and docstrings:
- def __init__(self, settings): Constructor for the N3KBLoader class
- def load_n3file(... | Implement the Python class `N3KBLoader` described below.
Class description:
This class is used to load N3 files into the SIB. NOTE: this class will be modified to support different types of files.
Method signatures and docstrings:
- def __init__(self, settings): Constructor for the N3KBLoader class
- def load_n3file(... | f3655856fd38eae2abf0fc73c1fa4817491cfc18 | <|skeleton|>
class N3KBLoader:
"""This class is used to load N3 files into the SIB. NOTE: this class will be modified to support different types of files."""
def __init__(self, settings):
"""Constructor for the N3KBLoader class"""
<|body_0|>
def load_n3file(self, filename):
"""This... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class N3KBLoader:
"""This class is used to load N3 files into the SIB. NOTE: this class will be modified to support different types of files."""
def __init__(self, settings):
"""Constructor for the N3KBLoader class"""
self.sib_host = settings['sib_host']
self.sib_port = settings['sib_po... | the_stack_v2_python_sparse | libs/n3loader.py | desmovalvo/otmbs | train | 0 |
1015f6a6b2f05eaf6ea7f32f43c17edd9c3a841c | [
"msg = Message(**attributes)\nself.message_store.append(msg)\nreturn",
"to_be_listed = self.message_store\nif filter_by:\n events = [msg.generate_events() for msg in to_be_listed if msg.to in filter_by]\nelse:\n events = [msg.generate_events() for msg in to_be_listed]\nreturn {'items': events, 'paging': {'n... | <|body_start_0|>
msg = Message(**attributes)
self.message_store.append(msg)
return
<|end_body_0|>
<|body_start_1|>
to_be_listed = self.message_store
if filter_by:
events = [msg.generate_events() for msg in to_be_listed if msg.to in filter_by]
else:
... | A collection of message objects. | MessageStore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageStore:
"""A collection of message objects."""
def add_to_message_store(self, **attributes):
"""Create a new Message object and add it to the :obj: `message_store`"""
<|body_0|>
def list_messages(self, filter_by=None):
"""List all the messages. :param str f... | stack_v2_sparse_classes_75kplus_train_009450 | 3,639 | permissive | [
{
"docstring": "Create a new Message object and add it to the :obj: `message_store`",
"name": "add_to_message_store",
"signature": "def add_to_message_store(self, **attributes)"
},
{
"docstring": "List all the messages. :param str filter_by: supports filtering the List by `to` addresses only cur... | 3 | stack_v2_sparse_classes_30k_train_016785 | Implement the Python class `MessageStore` described below.
Class description:
A collection of message objects.
Method signatures and docstrings:
- def add_to_message_store(self, **attributes): Create a new Message object and add it to the :obj: `message_store`
- def list_messages(self, filter_by=None): List all the m... | Implement the Python class `MessageStore` described below.
Class description:
A collection of message objects.
Method signatures and docstrings:
- def add_to_message_store(self, **attributes): Create a new Message object and add it to the :obj: `message_store`
- def list_messages(self, filter_by=None): List all the m... | 8e7eeed84ec5ae97863f9330023298845623c639 | <|skeleton|>
class MessageStore:
"""A collection of message objects."""
def add_to_message_store(self, **attributes):
"""Create a new Message object and add it to the :obj: `message_store`"""
<|body_0|>
def list_messages(self, filter_by=None):
"""List all the messages. :param str f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageStore:
"""A collection of message objects."""
def add_to_message_store(self, **attributes):
"""Create a new Message object and add it to the :obj: `message_store`"""
msg = Message(**attributes)
self.message_store.append(msg)
return
def list_messages(self, filte... | the_stack_v2_python_sparse | mimic/model/mailgun_objects.py | ranjithpeddi/mimic | train | 1 |
1a443b76c13e15eed4842416b38f2faae4813523 | [
"while True:\n logger.info('extracting movies from postgres')\n df = (yield)\n if not df.empty:\n genres_ids = id_list(df['id'])\n query = f'\\n SELECT movie_id, array_agg(name) as genre\\n FROM genre\\n JOIN (SELECT * FROM ... | <|body_start_0|>
while True:
logger.info('extracting movies from postgres')
df = (yield)
if not df.empty:
genres_ids = id_list(df['id'])
query = f'\n SELECT movie_id, array_agg(name) as genre\n FROM... | Class for etl process, which moves data from postgres DB to elasticsearch | GenreETL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenreETL:
"""Class for etl process, which moves data from postgres DB to elasticsearch"""
def extract_first_level_connections(self, data):
"""Coroutine that queries postgres to get genres based on the movies ids gotten in the previous step :param data: :return: dataframe with genres ... | stack_v2_sparse_classes_75kplus_train_009451 | 2,866 | no_license | [
{
"docstring": "Coroutine that queries postgres to get genres based on the movies ids gotten in the previous step :param data: :return: dataframe with genres data + movies",
"name": "extract_first_level_connections",
"signature": "def extract_first_level_connections(self, data)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_000634 | Implement the Python class `GenreETL` described below.
Class description:
Class for etl process, which moves data from postgres DB to elasticsearch
Method signatures and docstrings:
- def extract_first_level_connections(self, data): Coroutine that queries postgres to get genres based on the movies ids gotten in the p... | Implement the Python class `GenreETL` described below.
Class description:
Class for etl process, which moves data from postgres DB to elasticsearch
Method signatures and docstrings:
- def extract_first_level_connections(self, data): Coroutine that queries postgres to get genres based on the movies ids gotten in the p... | 4ddc8a77e5a9e9bc2a900c7bb6ffbcf5999e8c89 | <|skeleton|>
class GenreETL:
"""Class for etl process, which moves data from postgres DB to elasticsearch"""
def extract_first_level_connections(self, data):
"""Coroutine that queries postgres to get genres based on the movies ids gotten in the previous step :param data: :return: dataframe with genres ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenreETL:
"""Class for etl process, which moves data from postgres DB to elasticsearch"""
def extract_first_level_connections(self, data):
"""Coroutine that queries postgres to get genres based on the movies ids gotten in the previous step :param data: :return: dataframe with genres data + movies... | the_stack_v2_python_sparse | postgres_to_es/etl_genre.py | maffka123/Admin_panel_sprint_2 | train | 0 |
b55236a26d47009d650a3b50b721c9af6b677c13 | [
"installed = dpkg.installed()\nrgx = '^postgresql-client-(?P<version>(?P<major>[0-9]+)(\\\\.(?P<minor>[0-9]+))?)$'\nscanner = re.compile(rgx)\nfor key in installed.keys():\n match = scanner.match(key)\n if match:\n packages = (match.group(), 'libpq-dev')\n missing = [pkg for pkg in packages if p... | <|body_start_0|>
installed = dpkg.installed()
rgx = '^postgresql-client-(?P<version>(?P<major>[0-9]+)(\\.(?P<minor>[0-9]+))?)$'
scanner = re.compile(rgx)
for key in installed.keys():
match = scanner.match(key)
if match:
packages = (match.group(), '... | The package manager for postgres client development | Postgres | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Postgres:
"""The package manager for postgres client development"""
def dpkgAlternatives(cls, dpkg):
"""Go through the installed packages and identify those that are relevant for providing support for my installations"""
<|body_0|>
def dpkgPackages(cls, packager):
... | stack_v2_sparse_classes_75kplus_train_009452 | 7,944 | permissive | [
{
"docstring": "Go through the installed packages and identify those that are relevant for providing support for my installations",
"name": "dpkgAlternatives",
"signature": "def dpkgAlternatives(cls, dpkg)"
},
{
"docstring": "Provide alternative compatible implementations of python on dpkg machi... | 3 | stack_v2_sparse_classes_30k_train_034887 | Implement the Python class `Postgres` described below.
Class description:
The package manager for postgres client development
Method signatures and docstrings:
- def dpkgAlternatives(cls, dpkg): Go through the installed packages and identify those that are relevant for providing support for my installations
- def dpk... | Implement the Python class `Postgres` described below.
Class description:
The package manager for postgres client development
Method signatures and docstrings:
- def dpkgAlternatives(cls, dpkg): Go through the installed packages and identify those that are relevant for providing support for my installations
- def dpk... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Postgres:
"""The package manager for postgres client development"""
def dpkgAlternatives(cls, dpkg):
"""Go through the installed packages and identify those that are relevant for providing support for my installations"""
<|body_0|>
def dpkgPackages(cls, packager):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Postgres:
"""The package manager for postgres client development"""
def dpkgAlternatives(cls, dpkg):
"""Go through the installed packages and identify those that are relevant for providing support for my installations"""
installed = dpkg.installed()
rgx = '^postgresql-client-(?P<v... | the_stack_v2_python_sparse | packages/pyre/externals/Postgres.py | pyre/pyre | train | 27 |
01937e90e33bc2dd7dc01a0f4599458b8d7e76d2 | [
"if self.settings.get('debug') is True:\n self.set_header('Access-Control-Allow-Origin', '*')\n self.set_header('Access-Control-Allow-Headers', 'duck-token')\n self.set_header('Access-Control-Allow-Methods', 'DELETE, PUT, POST, GET, OPTIONS')",
"if self.settings.get('debug') is True:\n self.set_status... | <|body_start_0|>
if self.settings.get('debug') is True:
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', 'duck-token')
self.set_header('Access-Control-Allow-Methods', 'DELETE, PUT, POST, GET, OPTIONS')
<|end_body_0|>
<|body_... | allow for development | BaseHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseHandler:
"""allow for development"""
def set_default_headers(self):
"""allow access for development"""
<|body_0|>
def options(self, *args, **kwargs):
"""allow dev request"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.settings.get('... | stack_v2_sparse_classes_75kplus_train_009453 | 813 | permissive | [
{
"docstring": "allow access for development",
"name": "set_default_headers",
"signature": "def set_default_headers(self)"
},
{
"docstring": "allow dev request",
"name": "options",
"signature": "def options(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002101 | Implement the Python class `BaseHandler` described below.
Class description:
allow for development
Method signatures and docstrings:
- def set_default_headers(self): allow access for development
- def options(self, *args, **kwargs): allow dev request | Implement the Python class `BaseHandler` described below.
Class description:
allow for development
Method signatures and docstrings:
- def set_default_headers(self): allow access for development
- def options(self, *args, **kwargs): allow dev request
<|skeleton|>
class BaseHandler:
"""allow for development"""
... | e6d0e62d378bd2d9ed0cd5ce4bc7ab3476b86020 | <|skeleton|>
class BaseHandler:
"""allow for development"""
def set_default_headers(self):
"""allow access for development"""
<|body_0|>
def options(self, *args, **kwargs):
"""allow dev request"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseHandler:
"""allow for development"""
def set_default_headers(self):
"""allow access for development"""
if self.settings.get('debug') is True:
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', 'duck-token')
... | the_stack_v2_python_sparse | duckdown/handlers/base_handler.py | blueshed/duckdown | train | 0 |
b4d78528fb80f06763b588157ee35e7f3a4ca7df | [
"external_temp_dir = tempfile.mkdtemp()\ntry:\n external_temp_file = os.path.join(external_temp_dir, 'test.txt')\n with open(external_temp_file, 'w', encoding='utf-8') as fd:\n fd.write('HI')\n link_dir = os.path.join(self.tmp_dir, 'foo', 'link_dir')\n MakeSymLink(external_temp_file, link_dir)\n ... | <|body_start_0|>
external_temp_dir = tempfile.mkdtemp()
try:
external_temp_file = os.path.join(external_temp_dir, 'test.txt')
with open(external_temp_file, 'w', encoding='utf-8') as fd:
fd.write('HI')
link_dir = os.path.join(self.tmp_dir, 'foo', 'link_... | WinSymlinkTest | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WinSymlinkTest:
def testRmtreeOsWalkDoesNotFollowSymlinks(self):
"""_RmtreeOsWalk(...) will delete the symlink and not the target."""
<|body_0|>
def testRmtreeCmdShellDoesNotFollowSymlinks(self):
"""_RmtreeShellCmd(...) will delete the symlink and not the target."""
... | stack_v2_sparse_classes_75kplus_train_009454 | 3,426 | permissive | [
{
"docstring": "_RmtreeOsWalk(...) will delete the symlink and not the target.",
"name": "testRmtreeOsWalkDoesNotFollowSymlinks",
"signature": "def testRmtreeOsWalkDoesNotFollowSymlinks(self)"
},
{
"docstring": "_RmtreeShellCmd(...) will delete the symlink and not the target.",
"name": "test... | 2 | stack_v2_sparse_classes_30k_train_009224 | Implement the Python class `WinSymlinkTest` described below.
Class description:
Implement the WinSymlinkTest class.
Method signatures and docstrings:
- def testRmtreeOsWalkDoesNotFollowSymlinks(self): _RmtreeOsWalk(...) will delete the symlink and not the target.
- def testRmtreeCmdShellDoesNotFollowSymlinks(self): _... | Implement the Python class `WinSymlinkTest` described below.
Class description:
Implement the WinSymlinkTest class.
Method signatures and docstrings:
- def testRmtreeOsWalkDoesNotFollowSymlinks(self): _RmtreeOsWalk(...) will delete the symlink and not the target.
- def testRmtreeCmdShellDoesNotFollowSymlinks(self): _... | acefdaaadd3ef46f10f63d1acae2259e4024d383 | <|skeleton|>
class WinSymlinkTest:
def testRmtreeOsWalkDoesNotFollowSymlinks(self):
"""_RmtreeOsWalk(...) will delete the symlink and not the target."""
<|body_0|>
def testRmtreeCmdShellDoesNotFollowSymlinks(self):
"""_RmtreeShellCmd(...) will delete the symlink and not the target."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WinSymlinkTest:
def testRmtreeOsWalkDoesNotFollowSymlinks(self):
"""_RmtreeOsWalk(...) will delete the symlink and not the target."""
external_temp_dir = tempfile.mkdtemp()
try:
external_temp_file = os.path.join(external_temp_dir, 'test.txt')
with open(external_... | the_stack_v2_python_sparse | starboard/tools/win_symlink_test.py | youtube/cobalt | train | 169 | |
99e80c48e4db9a4b98e852b4f699c35ff1a95d28 | [
"if val < 0:\n raise ValueError\nelif val == 0:\n raise OSError\nelif val == 1:\n raise FileNotFoundError\nelif val == 2:\n raise MyVeryOwnError\nelse:\n return val",
"try:\n Exceptions.throwSomething(val)\n return str(val)\nexcept ValueError:\n return 'Negative values are not allowed'\nex... | <|body_start_0|>
if val < 0:
raise ValueError
elif val == 0:
raise OSError
elif val == 1:
raise FileNotFoundError
elif val == 2:
raise MyVeryOwnError
else:
return val
<|end_body_0|>
<|body_start_1|>
try:
... | Exceptions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exceptions:
def throwSomething(val):
"""See https://docs.python.org/3/library/exceptions.html Return the val, UNLESS: val<0, then raise a ValueError, val==0, then raise a OSError val==1, then raise a FileNotFoundError val==2, then raise a MyNewError HINT: It will be helpful to you to loo... | stack_v2_sparse_classes_75kplus_train_009455 | 2,503 | no_license | [
{
"docstring": "See https://docs.python.org/3/library/exceptions.html Return the val, UNLESS: val<0, then raise a ValueError, val==0, then raise a OSError val==1, then raise a FileNotFoundError val==2, then raise a MyNewError HINT: It will be helpful to you to look at the required messages in catchSomething :pa... | 2 | stack_v2_sparse_classes_30k_train_018507 | Implement the Python class `Exceptions` described below.
Class description:
Implement the Exceptions class.
Method signatures and docstrings:
- def throwSomething(val): See https://docs.python.org/3/library/exceptions.html Return the val, UNLESS: val<0, then raise a ValueError, val==0, then raise a OSError val==1, th... | Implement the Python class `Exceptions` described below.
Class description:
Implement the Exceptions class.
Method signatures and docstrings:
- def throwSomething(val): See https://docs.python.org/3/library/exceptions.html Return the val, UNLESS: val<0, then raise a ValueError, val==0, then raise a OSError val==1, th... | 91836d91445e778b17257129c0b73c68b9190a2c | <|skeleton|>
class Exceptions:
def throwSomething(val):
"""See https://docs.python.org/3/library/exceptions.html Return the val, UNLESS: val<0, then raise a ValueError, val==0, then raise a OSError val==1, then raise a FileNotFoundError val==2, then raise a MyNewError HINT: It will be helpful to you to loo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Exceptions:
def throwSomething(val):
"""See https://docs.python.org/3/library/exceptions.html Return the val, UNLESS: val<0, then raise a ValueError, val==0, then raise a OSError val==1, then raise a FileNotFoundError val==2, then raise a MyNewError HINT: It will be helpful to you to look at the requi... | the_stack_v2_python_sparse | cpsc250-p4-exceptions-s19-master/src/exceptions.py | ElijahWeske/CPSC250----Python | train | 0 | |
52fe65d722c479f57c493d449f39cae664d2b8d7 | [
"user = request.user\nif user.is_anonymous():\n user = User.objects.get(display_name='AnonymousUser')\ndata = request.data\nproject = Project.objects.as_contributor(request.user, project_id)\nif not data.get('meta').get('status') == 'draft' and project.can_moderate(user):\n data['meta']['status'] = 'active'\n... | <|body_start_0|>
user = request.user
if user.is_anonymous():
user = User.objects.get(display_name='AnonymousUser')
data = request.data
project = Project.objects.as_contributor(request.user, project_id)
if not data.get('meta').get('status') == 'draft' and project.can_m... | Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions | ProjectObservations | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectObservations:
"""Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions"""
def post(self, request, project_id):
"""Adds a new contribution to a project Parameters ---------- request : rest_framework.request.Request Represents the requ... | stack_v2_sparse_classes_75kplus_train_009456 | 10,813 | permissive | [
{
"docstring": "Adds a new contribution to a project Parameters ---------- request : rest_framework.request.Request Represents the request project_id : int identifies the project in the data base Returns ------- rest_framework.response.Respone Contains the serialised contribution",
"name": "post",
"sign... | 2 | stack_v2_sparse_classes_30k_train_050183 | Implement the Python class `ProjectObservations` described below.
Class description:
Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions
Method signatures and docstrings:
- def post(self, request, project_id): Adds a new contribution to a project Parameters ---------- req... | Implement the Python class `ProjectObservations` described below.
Class description:
Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions
Method signatures and docstrings:
- def post(self, request, project_id): Adds a new contribution to a project Parameters ---------- req... | 16d31b5207de9f699fc01054baad1fe65ad1c3ca | <|skeleton|>
class ProjectObservations:
"""Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions"""
def post(self, request, project_id):
"""Adds a new contribution to a project Parameters ---------- request : rest_framework.request.Request Represents the requ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectObservations:
"""Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions"""
def post(self, request, project_id):
"""Adds a new contribution to a project Parameters ---------- request : rest_framework.request.Request Represents the request project_i... | the_stack_v2_python_sparse | geokey/contributions/views/observations.py | NeolithEra/geokey | train | 0 |
d26d6be4f9ed44b79b13f1d73cecc94d8c9410e4 | [
"if n == 1 or n == 2:\n return n\nif n >= 3:\n return self.climb_stairs_recursive(n - 1) + self.climb_stairs_recursive(n - 2)\nreturn n",
"if n == 1:\n return 1\ndp = [1, 2]\nfor i in range(2, n):\n dp.append(dp[i - 1] + dp[i - 2])\nreturn dp[n - 1]"
] | <|body_start_0|>
if n == 1 or n == 2:
return n
if n >= 3:
return self.climb_stairs_recursive(n - 1) + self.climb_stairs_recursive(n - 2)
return n
<|end_body_0|>
<|body_start_1|>
if n == 1:
return 1
dp = [1, 2]
for i in range(2, n):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climb_stairs_recursive(self, n: int) -> int:
"""递归法"""
<|body_0|>
def climb_stairs_dp(self, n: int) -> int:
"""动态规划"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 1 or n == 2:
return n
if n >= 3:
... | stack_v2_sparse_classes_75kplus_train_009457 | 1,278 | no_license | [
{
"docstring": "递归法",
"name": "climb_stairs_recursive",
"signature": "def climb_stairs_recursive(self, n: int) -> int"
},
{
"docstring": "动态规划",
"name": "climb_stairs_dp",
"signature": "def climb_stairs_dp(self, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_018711 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climb_stairs_recursive(self, n: int) -> int: 递归法
- def climb_stairs_dp(self, n: int) -> int: 动态规划 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climb_stairs_recursive(self, n: int) -> int: 递归法
- def climb_stairs_dp(self, n: int) -> int: 动态规划
<|skeleton|>
class Solution:
def climb_stairs_recursive(self, n: int) ... | 91d0a4145b066c885272cf1896b5564439f855fa | <|skeleton|>
class Solution:
def climb_stairs_recursive(self, n: int) -> int:
"""递归法"""
<|body_0|>
def climb_stairs_dp(self, n: int) -> int:
"""动态规划"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def climb_stairs_recursive(self, n: int) -> int:
"""递归法"""
if n == 1 or n == 2:
return n
if n >= 3:
return self.climb_stairs_recursive(n - 1) + self.climb_stairs_recursive(n - 2)
return n
def climb_stairs_dp(self, n: int) -> int:
"... | the_stack_v2_python_sparse | DP问题/leetcode70 爬楼梯.py | Deaseyy/algorithm | train | 0 | |
f003181799610663c462e1ff16481c92cfef9c4c | [
"super(MinCutPoolModel, self).__init__()\nself.act = nn.ReLU(inplace=True)\nself.conv1 = GraphConvolution(input_dim, hidden_dim, use_bias)\nself.conv2 = DenseGraphConvolution(hidden_dim, hidden_dim, aggregate, use_bias)\nself.conv3 = DenseGraphConvolution(hidden_dim, hidden_dim, aggregate, use_bias)\nself.cluster1 ... | <|body_start_0|>
super(MinCutPoolModel, self).__init__()
self.act = nn.ReLU(inplace=True)
self.conv1 = GraphConvolution(input_dim, hidden_dim, use_bias)
self.conv2 = DenseGraphConvolution(hidden_dim, hidden_dim, aggregate, use_bias)
self.conv3 = DenseGraphConvolution(hidden_dim, ... | MinCutPool模型结构 | MinCutPoolModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinCutPoolModel:
"""MinCutPool模型结构"""
def __init__(self, input_dim, hidden_dim, output_dim, avg_nodes, aggregate='sum', dropout=0.0, use_bias=True):
"""MinCutPool模型结构 Inputs: ------- input_dim: int, 节点特征数量 hidden_dim: int, 各隐层计算输出的特征数 output_dim: int, 输出类别数量 avg_nodes: int, 所有图平均节点数,... | stack_v2_sparse_classes_75kplus_train_009458 | 3,547 | permissive | [
{
"docstring": "MinCutPool模型结构 Inputs: ------- input_dim: int, 节点特征数量 hidden_dim: int, 各隐层计算输出的特征数 output_dim: int, 输出类别数量 avg_nodes: int, 所有图平均节点数, 用于确定各聚类层的聚类个数 aggregate: string, DenseGraphConvolution层中节点聚合方式 dropout: float, 输出层使用的dopout比例 use_bias: boolean, 图卷积层是否使用偏置",
"name": "__init__",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_036030 | Implement the Python class `MinCutPoolModel` described below.
Class description:
MinCutPool模型结构
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, output_dim, avg_nodes, aggregate='sum', dropout=0.0, use_bias=True): MinCutPool模型结构 Inputs: ------- input_dim: int, 节点特征数量 hidden_dim: int, 各隐层计... | Implement the Python class `MinCutPoolModel` described below.
Class description:
MinCutPool模型结构
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, output_dim, avg_nodes, aggregate='sum', dropout=0.0, use_bias=True): MinCutPool模型结构 Inputs: ------- input_dim: int, 节点特征数量 hidden_dim: int, 各隐层计... | ee16c37fd065ba4c732138096f715f04c0ad6fcf | <|skeleton|>
class MinCutPoolModel:
"""MinCutPool模型结构"""
def __init__(self, input_dim, hidden_dim, output_dim, avg_nodes, aggregate='sum', dropout=0.0, use_bias=True):
"""MinCutPool模型结构 Inputs: ------- input_dim: int, 节点特征数量 hidden_dim: int, 各隐层计算输出的特征数 output_dim: int, 输出类别数量 avg_nodes: int, 所有图平均节点数,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinCutPoolModel:
"""MinCutPool模型结构"""
def __init__(self, input_dim, hidden_dim, output_dim, avg_nodes, aggregate='sum', dropout=0.0, use_bias=True):
"""MinCutPool模型结构 Inputs: ------- input_dim: int, 节点特征数量 hidden_dim: int, 各隐层计算输出的特征数 output_dim: int, 输出类别数量 avg_nodes: int, 所有图平均节点数, 用于确定各聚类层的聚类个... | the_stack_v2_python_sparse | Graph/MinCutPool/script/model.py | robbinc91/GNN-Pytorch | train | 0 |
ef7c0d09dff5cdea6955a082b4e271b14071be5a | [
"KratosMultiphysics.Process.__init__(self)\ndefault_settings = KratosMultiphysics.Parameters('\\n {\\n \"help\" : \"This sets the initial conditions in terms of imposed strain, stress or deformation gradient\",\\n \"mesh_id\" : 0,\\n \"model_part_name\" : \... | <|body_start_0|>
KratosMultiphysics.Process.__init__(self)
default_settings = KratosMultiphysics.Parameters('\n {\n "help" : "This sets the initial conditions in terms of imposed strain, stress or deformation gradient",\n "mesh_id" : 0,\n "model... | This process sets a given value for a certain flag in all the nodes of a submodelpart Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings. | SetInitialStateProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetInitialStateProcess:
"""This process sets a given value for a certain flag in all the nodes of a submodelpart Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containi... | stack_v2_sparse_classes_75kplus_train_009459 | 6,326 | permissive | [
{
"docstring": "The default constructor of the class Keyword arguments: self -- It signifies an instance of a class. Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings.",
"name": "__init__",
"signature": "def __init__(self, Model, settings)"
}... | 3 | stack_v2_sparse_classes_30k_train_022087 | Implement the Python class `SetInitialStateProcess` described below.
Class description:
This process sets a given value for a certain flag in all the nodes of a submodelpart Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts.... | Implement the Python class `SetInitialStateProcess` described below.
Class description:
This process sets a given value for a certain flag in all the nodes of a submodelpart Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts.... | 366949ec4e3651702edc6ac3061d2988f10dd271 | <|skeleton|>
class SetInitialStateProcess:
"""This process sets a given value for a certain flag in all the nodes of a submodelpart Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SetInitialStateProcess:
"""This process sets a given value for a certain flag in all the nodes of a submodelpart Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver set... | the_stack_v2_python_sparse | kratos/python_scripts/set_initial_state_process.py | KratosMultiphysics/Kratos | train | 994 |
df6a7b653ef080e4791c7f38390c12275e91e678 | [
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_dat... | <|body_start_0|>
try:
return_data = ''
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(return_data))
<|end_body_0|>
<|body_start_1|>
try:
retu... | WorkFlowNetConf | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkFlowNetConf:
def post(self, request, nnid, ver, node):
"""- desc : insert data"""
<|body_0|>
def get(self, request, nnid, ver, node):
"""- desc : get data"""
<|body_1|>
def put(self, request, nnid, ver, node):
"""- request ; update data"""
... | stack_v2_sparse_classes_75kplus_train_009460 | 2,259 | permissive | [
{
"docstring": "- desc : insert data",
"name": "post",
"signature": "def post(self, request, nnid, ver, node)"
},
{
"docstring": "- desc : get data",
"name": "get",
"signature": "def get(self, request, nnid, ver, node)"
},
{
"docstring": "- request ; update data",
"name": "pu... | 4 | null | Implement the Python class `WorkFlowNetConf` described below.
Class description:
Implement the WorkFlowNetConf class.
Method signatures and docstrings:
- def post(self, request, nnid, ver, node): - desc : insert data
- def get(self, request, nnid, ver, node): - desc : get data
- def put(self, request, nnid, ver, node... | Implement the Python class `WorkFlowNetConf` described below.
Class description:
Implement the WorkFlowNetConf class.
Method signatures and docstrings:
- def post(self, request, nnid, ver, node): - desc : insert data
- def get(self, request, nnid, ver, node): - desc : get data
- def put(self, request, nnid, ver, node... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class WorkFlowNetConf:
def post(self, request, nnid, ver, node):
"""- desc : insert data"""
<|body_0|>
def get(self, request, nnid, ver, node):
"""- desc : get data"""
<|body_1|>
def put(self, request, nnid, ver, node):
"""- request ; update data"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkFlowNetConf:
def post(self, request, nnid, ver, node):
"""- desc : insert data"""
try:
return_data = ''
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(... | the_stack_v2_python_sparse | api/views/workflow_netconf.py | yurimkoo/tensormsa | train | 1 | |
ac04aec14e4f971031f843d5c216e6bfd42577fc | [
"is_page = request.args.to_dict()['is_page'] if 'is_page' in request.args.to_dict() else False\nif IdParse().get_result().id:\n model = self._find_by_id(IdParse().get_result().id)\n return make_result(model)\nelif not is_page:\n query, by = self._parse_query_field()\n page, size = self._parse_page_size(... | <|body_start_0|>
is_page = request.args.to_dict()['is_page'] if 'is_page' in request.args.to_dict() else False
if IdParse().get_result().id:
model = self._find_by_id(IdParse().get_result().id)
return make_result(model)
elif not is_page:
query, by = self._parse... | serverBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class serverBase:
def get(self):
"""获取该表单项或者全部记录"""
<|body_0|>
def post(self):
"""向该表新增某项或多项纪录"""
<|body_1|>
def delete(self):
"""删除该表的某项或多项纪录"""
<|body_2|>
def put(self):
"""修改该表的某项或多项纪录"""
<|body_3|>
def _chose_to_do... | stack_v2_sparse_classes_75kplus_train_009461 | 4,787 | no_license | [
{
"docstring": "获取该表单项或者全部记录",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "向该表新增某项或多项纪录",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "删除该表的某项或多项纪录",
"name": "delete",
"signature": "def delete(self)"
},
{
"docstring": "修改该表的某... | 5 | null | Implement the Python class `serverBase` described below.
Class description:
Implement the serverBase class.
Method signatures and docstrings:
- def get(self): 获取该表单项或者全部记录
- def post(self): 向该表新增某项或多项纪录
- def delete(self): 删除该表的某项或多项纪录
- def put(self): 修改该表的某项或多项纪录
- def _chose_to_do(self, do, models, total_count, fa... | Implement the Python class `serverBase` described below.
Class description:
Implement the serverBase class.
Method signatures and docstrings:
- def get(self): 获取该表单项或者全部记录
- def post(self): 向该表新增某项或多项纪录
- def delete(self): 删除该表的某项或多项纪录
- def put(self): 修改该表的某项或多项纪录
- def _chose_to_do(self, do, models, total_count, fa... | 1df34a65758072d28d147b246acb82633faf9e53 | <|skeleton|>
class serverBase:
def get(self):
"""获取该表单项或者全部记录"""
<|body_0|>
def post(self):
"""向该表新增某项或多项纪录"""
<|body_1|>
def delete(self):
"""删除该表的某项或多项纪录"""
<|body_2|>
def put(self):
"""修改该表的某项或多项纪录"""
<|body_3|>
def _chose_to_do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class serverBase:
def get(self):
"""获取该表单项或者全部记录"""
is_page = request.args.to_dict()['is_page'] if 'is_page' in request.args.to_dict() else False
if IdParse().get_result().id:
model = self._find_by_id(IdParse().get_result().id)
return make_result(model)
elif n... | the_stack_v2_python_sparse | app/server/Server.py | row-yanbing/Job-back-end | train | 0 | |
6c32522055f7db96b9b58b60e98888a296833fd3 | [
"self._run_resource_id = run_resource_id\nself._api = api\nself._tag_to_time_series_proto: Dict[str, tensorboard_time_series.TensorboardTimeSeries] = {}",
"if tag_name in self._tag_to_time_series_proto:\n return self._tag_to_time_series_proto[tag_name]\ntime_series = time_series_resource_creator()\ntime_series... | <|body_start_0|>
self._run_resource_id = run_resource_id
self._api = api
self._tag_to_time_series_proto: Dict[str, tensorboard_time_series.TensorboardTimeSeries] = {}
<|end_body_0|>
<|body_start_1|>
if tag_name in self._tag_to_time_series_proto:
return self._tag_to_time_seri... | Helper class managing Time Series resources. | TimeSeriesResourceManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeSeriesResourceManager:
"""Helper class managing Time Series resources."""
def __init__(self, run_resource_id: str, api: TensorboardServiceClient):
"""Constructor for TimeSeriesResourceManager. Args: run_resource_id (str): Required. The resource id for the run with the following f... | stack_v2_sparse_classes_75kplus_train_009462 | 19,502 | permissive | [
{
"docstring": "Constructor for TimeSeriesResourceManager. Args: run_resource_id (str): Required. The resource id for the run with the following format. projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run} api (TensorboardServiceClient): Required. A TensorboardS... | 2 | null | Implement the Python class `TimeSeriesResourceManager` described below.
Class description:
Helper class managing Time Series resources.
Method signatures and docstrings:
- def __init__(self, run_resource_id: str, api: TensorboardServiceClient): Constructor for TimeSeriesResourceManager. Args: run_resource_id (str): R... | Implement the Python class `TimeSeriesResourceManager` described below.
Class description:
Helper class managing Time Series resources.
Method signatures and docstrings:
- def __init__(self, run_resource_id: str, api: TensorboardServiceClient): Constructor for TimeSeriesResourceManager. Args: run_resource_id (str): R... | 76b95b92c1d3b87c72d754d8c02b1bca652b9a27 | <|skeleton|>
class TimeSeriesResourceManager:
"""Helper class managing Time Series resources."""
def __init__(self, run_resource_id: str, api: TensorboardServiceClient):
"""Constructor for TimeSeriesResourceManager. Args: run_resource_id (str): Required. The resource id for the run with the following f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeSeriesResourceManager:
"""Helper class managing Time Series resources."""
def __init__(self, run_resource_id: str, api: TensorboardServiceClient):
"""Constructor for TimeSeriesResourceManager. Args: run_resource_id (str): Required. The resource id for the run with the following format. projec... | the_stack_v2_python_sparse | google/cloud/aiplatform/tensorboard/uploader_utils.py | googleapis/python-aiplatform | train | 418 |
8bbf99349863bc26c0a81f7d18978a15d112189f | [
"input_stream_ids = {f'input_{idx}': ik for idx, ik in enumerate(input_stream_keys)}\nassert 'dim' in config, \"SqueezeModule relies on 'dim' value.\\n Not found in config.\"\nsuper(SqueezeModule, self).__init__(id=id, type='SqueezeModule', config=config, input_stream_ids=input_stream_ids)\nself.sque... | <|body_start_0|>
input_stream_ids = {f'input_{idx}': ik for idx, ik in enumerate(input_stream_keys)}
assert 'dim' in config, "SqueezeModule relies on 'dim' value.\n Not found in config."
super(SqueezeModule, self).__init__(id=id, type='SqueezeModule', config=config, input_stream_i... | SqueezeModule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqueezeModule:
def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]):
"""Squeeze input streams data (beware the batch dimension if it is equal to 1...). :param config: Dict of parameters. Expectes: - "dim": List of None/Tuple/List/torch.Size representing th... | stack_v2_sparse_classes_75kplus_train_009463 | 2,766 | permissive | [
{
"docstring": "Squeeze input streams data (beware the batch dimension if it is equal to 1...). :param config: Dict of parameters. Expectes: - \"dim\": List of None/Tuple/List/torch.Size representing the index of the dimension to squeeze for each input stream. If multiple input streams are proposed but only one... | 2 | stack_v2_sparse_classes_30k_train_040203 | Implement the Python class `SqueezeModule` described below.
Class description:
Implement the SqueezeModule class.
Method signatures and docstrings:
- def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): Squeeze input streams data (beware the batch dimension if it is equal to 1...). :p... | Implement the Python class `SqueezeModule` described below.
Class description:
Implement the SqueezeModule class.
Method signatures and docstrings:
- def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): Squeeze input streams data (beware the batch dimension if it is equal to 1...). :p... | afe22da2ac20c0d24e93b4dbd1f1ad61374d1a6c | <|skeleton|>
class SqueezeModule:
def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]):
"""Squeeze input streams data (beware the batch dimension if it is equal to 1...). :param config: Dict of parameters. Expectes: - "dim": List of None/Tuple/List/torch.Size representing th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SqueezeModule:
def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]):
"""Squeeze input streams data (beware the batch dimension if it is equal to 1...). :param config: Dict of parameters. Expectes: - "dim": List of None/Tuple/List/torch.Size representing the index of the... | the_stack_v2_python_sparse | ReferentialGym/modules/squeeze_module.py | mk788/ReferentialGym | train | 0 | |
74ea819c52b17e12eba1017fb439ebe2476e0b52 | [
"self.base = util.get_base_color()\nself.view = view\nself.on_cancel = on_cancel\nself.setup_gamut_style()\nself.setup_image_border()\nself.setup_sizes()",
"if self.on_cancel is not None:\n call = self.on_cancel.get('command', 'color_helper')\n args = self.on_cancel.get('args', {})\n self.view.run_comman... | <|body_start_0|>
self.base = util.get_base_color()
self.view = view
self.on_cancel = on_cancel
self.setup_gamut_style()
self.setup_image_border()
self.setup_sizes()
<|end_body_0|>
<|body_start_1|>
if self.on_cancel is not None:
call = self.on_cancel.g... | Color input handler base class. | _ColorInputHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ColorInputHandler:
"""Color input handler base class."""
def __init__(self, view, on_cancel=None, **kwargs):
"""Initialize."""
<|body_0|>
def cancel(self):
"""On cancel."""
<|body_1|>
def get_html_style(self):
"""Get HTML style."""
<... | stack_v2_sparse_classes_75kplus_train_009464 | 2,168 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, view, on_cancel=None, **kwargs)"
},
{
"docstring": "On cancel.",
"name": "cancel",
"signature": "def cancel(self)"
},
{
"docstring": "Get HTML style.",
"name": "get_html_style",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_033462 | Implement the Python class `_ColorInputHandler` described below.
Class description:
Color input handler base class.
Method signatures and docstrings:
- def __init__(self, view, on_cancel=None, **kwargs): Initialize.
- def cancel(self): On cancel.
- def get_html_style(self): Get HTML style. | Implement the Python class `_ColorInputHandler` described below.
Class description:
Color input handler base class.
Method signatures and docstrings:
- def __init__(self, view, on_cancel=None, **kwargs): Initialize.
- def cancel(self): On cancel.
- def get_html_style(self): Get HTML style.
<|skeleton|>
class _ColorI... | ad4d779bff57a65b7c77cda0b79c10cf904eb817 | <|skeleton|>
class _ColorInputHandler:
"""Color input handler base class."""
def __init__(self, view, on_cancel=None, **kwargs):
"""Initialize."""
<|body_0|>
def cancel(self):
"""On cancel."""
<|body_1|>
def get_html_style(self):
"""Get HTML style."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _ColorInputHandler:
"""Color input handler base class."""
def __init__(self, view, on_cancel=None, **kwargs):
"""Initialize."""
self.base = util.get_base_color()
self.view = view
self.on_cancel = on_cancel
self.setup_gamut_style()
self.setup_image_border()
... | the_stack_v2_python_sparse | ch_tools.py | facelessuser/ColorHelper | train | 279 |
81c19b6db7780f52925ea637f1642df4fa161191 | [
"if self.context is None:\n raise ValueError('Attribute not bound to a context.')\nreturn super().fromUnicode(str(ustr))",
"if interfaces.IDeprecated.providedBy(self) and self.deprecatedName in self.context.element.attrib:\n name = self.deprecatedName\n logger.warning('Deprecated attribute \"{}\": {} {}'... | <|body_start_0|>
if self.context is None:
raise ValueError('Attribute not bound to a context.')
return super().fromUnicode(str(ustr))
<|end_body_0|>
<|body_start_1|>
if interfaces.IDeprecated.providedBy(self) and self.deprecatedName in self.context.element.attrib:
name =... | An attribute of the RML directive. | RMLAttribute | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMLAttribute:
"""An attribute of the RML directive."""
def fromUnicode(self, ustr):
"""See zope.schema.interfaces.IField"""
<|body_0|>
def get(self):
"""See zope.schema.interfaces.IField"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.co... | stack_v2_sparse_classes_75kplus_train_009465 | 24,284 | permissive | [
{
"docstring": "See zope.schema.interfaces.IField",
"name": "fromUnicode",
"signature": "def fromUnicode(self, ustr)"
},
{
"docstring": "See zope.schema.interfaces.IField",
"name": "get",
"signature": "def get(self)"
}
] | 2 | null | Implement the Python class `RMLAttribute` described below.
Class description:
An attribute of the RML directive.
Method signatures and docstrings:
- def fromUnicode(self, ustr): See zope.schema.interfaces.IField
- def get(self): See zope.schema.interfaces.IField | Implement the Python class `RMLAttribute` described below.
Class description:
An attribute of the RML directive.
Method signatures and docstrings:
- def fromUnicode(self, ustr): See zope.schema.interfaces.IField
- def get(self): See zope.schema.interfaces.IField
<|skeleton|>
class RMLAttribute:
"""An attribute o... | 42581266311f7e24dfc7fe28de4080dfd4522aa6 | <|skeleton|>
class RMLAttribute:
"""An attribute of the RML directive."""
def fromUnicode(self, ustr):
"""See zope.schema.interfaces.IField"""
<|body_0|>
def get(self):
"""See zope.schema.interfaces.IField"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RMLAttribute:
"""An attribute of the RML directive."""
def fromUnicode(self, ustr):
"""See zope.schema.interfaces.IField"""
if self.context is None:
raise ValueError('Attribute not bound to a context.')
return super().fromUnicode(str(ustr))
def get(self):
... | the_stack_v2_python_sparse | src/z3c/rml/attr.py | zopefoundation/z3c.rml | train | 90 |
73337c65d2b541fa0fcbce2e01067c23a3fade91 | [
"gtk.Alignment.__init__(self)\nself.color_infos = color_infos\nself.set(0.0, 0.0, 1.0, 0.0)\nself.set_padding(padding_y, padding_y, padding_x, padding_x)\nself.separator = gtk.VBox()\nself.separator.set_size_request(-1, 1)\nself.separator.connect('expose-event', self.expose_hseparator)\nself.add(self.separator)\nse... | <|body_start_0|>
gtk.Alignment.__init__(self)
self.color_infos = color_infos
self.set(0.0, 0.0, 1.0, 0.0)
self.set_padding(padding_y, padding_y, padding_x, padding_x)
self.separator = gtk.VBox()
self.separator.set_size_request(-1, 1)
self.separator.connect('expose... | Horizontal separator. | HSeparator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HSeparator:
"""Horizontal separator."""
def __init__(self, color_infos, padding_x=0, padding_y=0):
"""Init horizontal separator."""
<|body_0|>
def expose_hseparator(self, widget, event):
"""Expose separator item."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_009466 | 1,970 | no_license | [
{
"docstring": "Init horizontal separator.",
"name": "__init__",
"signature": "def __init__(self, color_infos, padding_x=0, padding_y=0)"
},
{
"docstring": "Expose separator item.",
"name": "expose_hseparator",
"signature": "def expose_hseparator(self, widget, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035294 | Implement the Python class `HSeparator` described below.
Class description:
Horizontal separator.
Method signatures and docstrings:
- def __init__(self, color_infos, padding_x=0, padding_y=0): Init horizontal separator.
- def expose_hseparator(self, widget, event): Expose separator item. | Implement the Python class `HSeparator` described below.
Class description:
Horizontal separator.
Method signatures and docstrings:
- def __init__(self, color_infos, padding_x=0, padding_y=0): Init horizontal separator.
- def expose_hseparator(self, widget, event): Expose separator item.
<|skeleton|>
class HSeparato... | d8c8665b327f7156bf8d9d7ec04f47214faf3cc3 | <|skeleton|>
class HSeparator:
"""Horizontal separator."""
def __init__(self, color_infos, padding_x=0, padding_y=0):
"""Init horizontal separator."""
<|body_0|>
def expose_hseparator(self, widget, event):
"""Expose separator item."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HSeparator:
"""Horizontal separator."""
def __init__(self, color_infos, padding_x=0, padding_y=0):
"""Init horizontal separator."""
gtk.Alignment.__init__(self)
self.color_infos = color_infos
self.set(0.0, 0.0, 1.0, 0.0)
self.set_padding(padding_y, padding_y, paddi... | the_stack_v2_python_sparse | linux/gui/line.py | iiiyu/old-oh-my-password | train | 0 |
58e3d249b9c2a72a6dc261ee7f5617ccec5da1a1 | [
"super(MuninnRouter, self).__init__(*args, **kwargs)\nroute_kwargs = {'url': u'^{prefix}/(?P<product_type>[^/.]+)/(?P<product_name>[^/.]+){trailing_slash}$', 'mapping': {u'put': u'update', u'delete': u'destroy', u'patch': u'partial_update', u'get': u'retrieve'}, 'name': u'{basename}-detail', 'detail': True, 'initkw... | <|body_start_0|>
super(MuninnRouter, self).__init__(*args, **kwargs)
route_kwargs = {'url': u'^{prefix}/(?P<product_type>[^/.]+)/(?P<product_name>[^/.]+){trailing_slash}$', 'mapping': {u'put': u'update', u'delete': u'destroy', u'patch': u'partial_update', u'get': u'retrieve'}, 'name': u'{basename}-detai... | MuninnRouter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MuninnRouter:
def __init__(self, muninn_archive=None, *args, **kwargs):
"""`muninn_archive` specifies an archive (defined in the settings) that will be registered automatically. Use as a shorthand for use cases whre there is only one archive to be served under a URL path."""
<|bo... | stack_v2_sparse_classes_75kplus_train_009467 | 2,088 | permissive | [
{
"docstring": "`muninn_archive` specifies an archive (defined in the settings) that will be registered automatically. Use as a shorthand for use cases whre there is only one archive to be served under a URL path.",
"name": "__init__",
"signature": "def __init__(self, muninn_archive=None, *args, **kwarg... | 2 | stack_v2_sparse_classes_30k_train_044644 | Implement the Python class `MuninnRouter` described below.
Class description:
Implement the MuninnRouter class.
Method signatures and docstrings:
- def __init__(self, muninn_archive=None, *args, **kwargs): `muninn_archive` specifies an archive (defined in the settings) that will be registered automatically. Use as a ... | Implement the Python class `MuninnRouter` described below.
Class description:
Implement the MuninnRouter class.
Method signatures and docstrings:
- def __init__(self, muninn_archive=None, *args, **kwargs): `muninn_archive` specifies an archive (defined in the settings) that will be registered automatically. Use as a ... | 6a148ece961d4906b85f5864feff6151db370537 | <|skeleton|>
class MuninnRouter:
def __init__(self, muninn_archive=None, *args, **kwargs):
"""`muninn_archive` specifies an archive (defined in the settings) that will be registered automatically. Use as a shorthand for use cases whre there is only one archive to be served under a URL path."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MuninnRouter:
def __init__(self, muninn_archive=None, *args, **kwargs):
"""`muninn_archive` specifies an archive (defined in the settings) that will be registered automatically. Use as a shorthand for use cases whre there is only one archive to be served under a URL path."""
super(MuninnRouter... | the_stack_v2_python_sparse | muninn_django/routers.py | stcorp/muninn-django | train | 1 | |
4e39c062fb33e2f8a77f52961eef1c3eb7c4fd7a | [
"from atom import Atom\nself._center = Atom('atomic')\nself._center.position = center\nself._radius = radius",
"distance_from_surface = abs(self._radius - distance(atom, self._center))\nif distance_from_surface <= cutoff_distance:\n return True\nelse:\n return False",
"distance_from_center = distance(atom... | <|body_start_0|>
from atom import Atom
self._center = Atom('atomic')
self._center.position = center
self._radius = radius
<|end_body_0|>
<|body_start_1|>
distance_from_surface = abs(self._radius - distance(atom, self._center))
if distance_from_surface <= cutoff_distance:... | Write Later | Sphere | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sphere:
"""Write Later"""
def __init__(self, center, radius):
"""Write Later"""
<|body_0|>
def nearest_neighbor(self, atom, cutoff_distance):
"""Write Later"""
<|body_1|>
def in_shape(self, atom):
"""Write Later"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus_train_009468 | 8,615 | no_license | [
{
"docstring": "Write Later",
"name": "__init__",
"signature": "def __init__(self, center, radius)"
},
{
"docstring": "Write Later",
"name": "nearest_neighbor",
"signature": "def nearest_neighbor(self, atom, cutoff_distance)"
},
{
"docstring": "Write Later",
"name": "in_shape... | 4 | stack_v2_sparse_classes_30k_train_003882 | Implement the Python class `Sphere` described below.
Class description:
Write Later
Method signatures and docstrings:
- def __init__(self, center, radius): Write Later
- def nearest_neighbor(self, atom, cutoff_distance): Write Later
- def in_shape(self, atom): Write Later
- def random_position_on_surface(self, cutoff... | Implement the Python class `Sphere` described below.
Class description:
Write Later
Method signatures and docstrings:
- def __init__(self, center, radius): Write Later
- def nearest_neighbor(self, atom, cutoff_distance): Write Later
- def in_shape(self, atom): Write Later
- def random_position_on_surface(self, cutoff... | 602c292f30398fd7f80accce6b436af3799b00c9 | <|skeleton|>
class Sphere:
"""Write Later"""
def __init__(self, center, radius):
"""Write Later"""
<|body_0|>
def nearest_neighbor(self, atom, cutoff_distance):
"""Write Later"""
<|body_1|>
def in_shape(self, atom):
"""Write Later"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sphere:
"""Write Later"""
def __init__(self, center, radius):
"""Write Later"""
from atom import Atom
self._center = Atom('atomic')
self._center.position = center
self._radius = radius
def nearest_neighbor(self, atom, cutoff_distance):
"""Write Later""... | the_stack_v2_python_sparse | space.py | drzeus99/lmpsdata2 | train | 0 |
9c9bb8db59455eae6ea4872ef9057a3ad6147e70 | [
"res = []\nfor i in range(len(nums)):\n target = -1 * nums[i]\n for j in nums[i + 1:]:\n dic[nums[j]] = j\n if two:\n sol = [nums[i], nums[two[0] + i + 1], nums[two[1] + i + 1]]\n sol.sort()\n if sol not in res:\n res.append(sol)\nreturn res",
"dic = dict()\nfor i i... | <|body_start_0|>
res = []
for i in range(len(nums)):
target = -1 * nums[i]
for j in nums[i + 1:]:
dic[nums[j]] = j
if two:
sol = [nums[i], nums[two[0] + i + 1], nums[two[1] + i + 1]]
sol.sort()
if sol not... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
... | stack_v2_sparse_classes_75kplus_train_009469 | 936 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033818 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
<|skeleton|>
... | 16e8a7935811fa71ce71998da8549e29ba68f847 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
res = []
for i in range(len(nums)):
target = -1 * nums[i]
for j in nums[i + 1:]:
dic[nums[j]] = j
if two:
sol = [nums[i], nums[two... | the_stack_v2_python_sparse | leetcode/threeSum.py | lizyang95/leetcode | train | 0 | |
a71866d5049b9b675fa61fd7d9bad96c63f8fea6 | [
"try:\n payload = {'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=10), 'iat': datetime.datetime.utcnow(), 'iss': 'ken', 'data': {'id': user_id, 'login_time': login_time}}\n return jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256')\nexcept Exception as e:\n retu... | <|body_start_0|>
try:
payload = {'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=10), 'iat': datetime.datetime.utcnow(), 'iss': 'ken', 'data': {'id': user_id, 'login_time': login_time}}
return jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256')... | Auth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auth:
def encode_auth_token(user_id, login_time):
"""生成认证Token :param user_id: int :param login_time: int(timestamp) :return: string"""
<|body_0|>
def decode_auth_token(auth_token):
"""验证Token :param auth_token: :return: integer|string"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_009470 | 3,044 | no_license | [
{
"docstring": "生成认证Token :param user_id: int :param login_time: int(timestamp) :return: string",
"name": "encode_auth_token",
"signature": "def encode_auth_token(user_id, login_time)"
},
{
"docstring": "验证Token :param auth_token: :return: integer|string",
"name": "decode_auth_token",
"s... | 3 | stack_v2_sparse_classes_30k_train_033429 | Implement the Python class `Auth` described below.
Class description:
Implement the Auth class.
Method signatures and docstrings:
- def encode_auth_token(user_id, login_time): 生成认证Token :param user_id: int :param login_time: int(timestamp) :return: string
- def decode_auth_token(auth_token): 验证Token :param auth_token... | Implement the Python class `Auth` described below.
Class description:
Implement the Auth class.
Method signatures and docstrings:
- def encode_auth_token(user_id, login_time): 生成认证Token :param user_id: int :param login_time: int(timestamp) :return: string
- def decode_auth_token(auth_token): 验证Token :param auth_token... | 121fb26d816da0f76df8083d2fd37ca92c904338 | <|skeleton|>
class Auth:
def encode_auth_token(user_id, login_time):
"""生成认证Token :param user_id: int :param login_time: int(timestamp) :return: string"""
<|body_0|>
def decode_auth_token(auth_token):
"""验证Token :param auth_token: :return: integer|string"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Auth:
def encode_auth_token(user_id, login_time):
"""生成认证Token :param user_id: int :param login_time: int(timestamp) :return: string"""
try:
payload = {'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=10), 'iat': datetime.datetime.utcnow(), 'iss': 'ken', 'data... | the_stack_v2_python_sparse | train_module/src/Data_Processing/DataSet/token/auths.py | limingzhang513/lmzrepository | train | 0 | |
2985d549b7984a80d3b46b5ac78dd31e6fad6e8a | [
"try:\n return getattr(cls, endpoint).request_cls\nexcept AttributeError:\n raise MessageException('Unknown endpoint.')",
"try:\n return getattr(cls, endpoint).response_cls\nexcept AttributeError:\n raise MessageException('Unknown endpoint.')"
] | <|body_start_0|>
try:
return getattr(cls, endpoint).request_cls
except AttributeError:
raise MessageException('Unknown endpoint.')
<|end_body_0|>
<|body_start_1|>
try:
return getattr(cls, endpoint).response_cls
except AttributeError:
raise... | Factory for holding message types. | MessageFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageFactory:
"""Factory for holding message types."""
def get_request_type(cls, endpoint: str):
"""Return class representing the request_cls for given endpoint."""
<|body_0|>
def get_response_type(cls, endpoint: str):
"""Return class representing the response_... | stack_v2_sparse_classes_75kplus_train_009471 | 38,983 | permissive | [
{
"docstring": "Return class representing the request_cls for given endpoint.",
"name": "get_request_type",
"signature": "def get_request_type(cls, endpoint: str)"
},
{
"docstring": "Return class representing the response_cls for given endpoint.",
"name": "get_response_type",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_015869 | Implement the Python class `MessageFactory` described below.
Class description:
Factory for holding message types.
Method signatures and docstrings:
- def get_request_type(cls, endpoint: str): Return class representing the request_cls for given endpoint.
- def get_response_type(cls, endpoint: str): Return class repre... | Implement the Python class `MessageFactory` described below.
Class description:
Factory for holding message types.
Method signatures and docstrings:
- def get_request_type(cls, endpoint: str): Return class representing the request_cls for given endpoint.
- def get_response_type(cls, endpoint: str): Return class repre... | 2e751ed84039259a2b138148eae204c877518950 | <|skeleton|>
class MessageFactory:
"""Factory for holding message types."""
def get_request_type(cls, endpoint: str):
"""Return class representing the request_cls for given endpoint."""
<|body_0|>
def get_response_type(cls, endpoint: str):
"""Return class representing the response_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageFactory:
"""Factory for holding message types."""
def get_request_type(cls, endpoint: str):
"""Return class representing the request_cls for given endpoint."""
try:
return getattr(cls, endpoint).request_cls
except AttributeError:
raise MessageExcepti... | the_stack_v2_python_sparse | src/oic/oauth2/message.py | peppelinux/pyoidc | train | 1 |
f4443349b2b6f642bed4bb0e00428038f65076f6 | [
"self.game_config = game_config\nself.games = None\nself.batch_size = 0",
"if not games:\n self.games = [i + 1 for i in range(self.game_config.game.max_game_id, self.game_config.game.max_eval_game_id)]\n self.batch_size = len(self.games)\nelse:\n self.games = games\n self.batch_size = len(games)",
"... | <|body_start_0|>
self.game_config = game_config
self.games = None
self.batch_size = 0
<|end_body_0|>
<|body_start_1|>
if not games:
self.games = [i + 1 for i in range(self.game_config.game.max_game_id, self.game_config.game.max_eval_game_id)]
self.batch_size = le... | This class is responsible evaluating the population across a set of games. | EvaluationEnv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluationEnv:
"""This class is responsible evaluating the population across a set of games."""
def __init__(self, game_config: Config):
"""The evaluator is given a set of genomes which it then evaluates using the MultiEnvironment."""
<|body_0|>
def set_games(self, games... | stack_v2_sparse_classes_75kplus_train_009472 | 5,850 | permissive | [
{
"docstring": "The evaluator is given a set of genomes which it then evaluates using the MultiEnvironment.",
"name": "__init__",
"signature": "def __init__(self, game_config: Config)"
},
{
"docstring": "Set the game-IDs that will be used to evaluate the population. The full game-set as defined ... | 4 | null | Implement the Python class `EvaluationEnv` described below.
Class description:
This class is responsible evaluating the population across a set of games.
Method signatures and docstrings:
- def __init__(self, game_config: Config): The evaluator is given a set of genomes which it then evaluates using the MultiEnvironm... | Implement the Python class `EvaluationEnv` described below.
Class description:
This class is responsible evaluating the population across a set of games.
Method signatures and docstrings:
- def __init__(self, game_config: Config): The evaluator is given a set of genomes which it then evaluates using the MultiEnvironm... | 334d7b9cab0edb22d4670cfaf39fbed76c351758 | <|skeleton|>
class EvaluationEnv:
"""This class is responsible evaluating the population across a set of games."""
def __init__(self, game_config: Config):
"""The evaluator is given a set of genomes which it then evaluates using the MultiEnvironment."""
<|body_0|>
def set_games(self, games... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EvaluationEnv:
"""This class is responsible evaluating the population across a set of games."""
def __init__(self, game_config: Config):
"""The evaluator is given a set of genomes which it then evaluates using the MultiEnvironment."""
self.game_config = game_config
self.games = No... | the_stack_v2_python_sparse | environment/env_evaluation.py | RubenPants/RobotSimulator2D | train | 0 |
d63e24a12e3ce0c526f90de101e66f3dbfba1a80 | [
"res = []\n\ndef dfs(node):\n if not node:\n return\n res.append(str(node.val))\n res.append(str(len(node.children or [])))\n if node.children:\n for child in node.children:\n dfs(child)\ndfs(root)\nreturn '#'.join(res)",
"if not data:\n return None\ndata = iter(data.split(... | <|body_start_0|>
res = []
def dfs(node):
if not node:
return
res.append(str(node.val))
res.append(str(len(node.children or [])))
if node.children:
for child in node.children:
dfs(child)
dfs(root)... | Codec1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec1:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_009473 | 4,054 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_041496 | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to t... | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to t... | 44765a7d89423b7ec2c159f70b1a6f6e446523c2 | <|skeleton|>
class Codec1:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec1:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
def dfs(node):
if not node:
return
res.append(str(node.val))
res.append(str(len(node.children or [])))
... | the_stack_v2_python_sparse | python/_0001_0500/0428_serialize-and-deserialize-n-ary-tree.py | Wang-Yann/LeetCodeMe | train | 0 | |
0d6e5ee3cc02ede6de613b9c96492372e087416d | [
"self.pr = pr\nself.retEvent = False if events is None else True\nself.events = events",
"res = random.random() < self.pr\nif self.retEvent:\n res = self.events[0] if res else self.events[1]\nreturn res"
] | <|body_start_0|>
self.pr = pr
self.retEvent = False if events is None else True
self.events = events
<|end_body_0|>
<|body_start_1|>
res = random.random() < self.pr
if self.retEvent:
res = self.events[0] if res else self.events[1]
return res
<|end_body_1|>
| bernoulli trial sampler return True or False | BernoulliTrialSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BernoulliTrialSampler:
"""bernoulli trial sampler return True or False"""
def __init__(self, pr, events=None):
"""initializer Parameters pr : probability events : event values"""
<|body_0|>
def sample(self):
"""samples value"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_009474 | 32,264 | permissive | [
{
"docstring": "initializer Parameters pr : probability events : event values",
"name": "__init__",
"signature": "def __init__(self, pr, events=None)"
},
{
"docstring": "samples value",
"name": "sample",
"signature": "def sample(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007033 | Implement the Python class `BernoulliTrialSampler` described below.
Class description:
bernoulli trial sampler return True or False
Method signatures and docstrings:
- def __init__(self, pr, events=None): initializer Parameters pr : probability events : event values
- def sample(self): samples value | Implement the Python class `BernoulliTrialSampler` described below.
Class description:
bernoulli trial sampler return True or False
Method signatures and docstrings:
- def __init__(self, pr, events=None): initializer Parameters pr : probability events : event values
- def sample(self): samples value
<|skeleton|>
cla... | 861fd06b6b7abaffe5e8ca795136ab0fbb2234b5 | <|skeleton|>
class BernoulliTrialSampler:
"""bernoulli trial sampler return True or False"""
def __init__(self, pr, events=None):
"""initializer Parameters pr : probability events : event values"""
<|body_0|>
def sample(self):
"""samples value"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BernoulliTrialSampler:
"""bernoulli trial sampler return True or False"""
def __init__(self, pr, events=None):
"""initializer Parameters pr : probability events : event values"""
self.pr = pr
self.retEvent = False if events is None else True
self.events = events
def s... | the_stack_v2_python_sparse | matumizi/matumizi/sampler.py | pranab/whakapai | train | 18 |
4420faa3fef2e2c25e658043004a198c1468c048 | [
"self.lang = 'polish'\nself.region = 'pl'\nself.offline = offline\nabs_path = os.path.dirname(os.path.abspath(__file__))\nwith open(os.path.join(abs_path, self.path_key), 'r') as f:\n self.api_key = f.read()\nself.client = googlemaps.Client(key=self.api_key)",
"print('Requesting geolocation of: ', addr)\nif se... | <|body_start_0|>
self.lang = 'polish'
self.region = 'pl'
self.offline = offline
abs_path = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(abs_path, self.path_key), 'r') as f:
self.api_key = f.read()
self.client = googlemaps.Client(key=self.a... | GMaps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GMaps:
def __init__(self, offline=False):
"""Initialize GMaps object. Read API key. `offline` arg can be set to True if you want to test code using this object."""
<|body_0|>
def get_location(self, addr):
"""Do the request to GMaps and extract latitude and longitude ... | stack_v2_sparse_classes_75kplus_train_009475 | 5,343 | no_license | [
{
"docstring": "Initialize GMaps object. Read API key. `offline` arg can be set to True if you want to test code using this object.",
"name": "__init__",
"signature": "def __init__(self, offline=False)"
},
{
"docstring": "Do the request to GMaps and extract latitude and longitude of given place.... | 4 | stack_v2_sparse_classes_30k_train_046758 | Implement the Python class `GMaps` described below.
Class description:
Implement the GMaps class.
Method signatures and docstrings:
- def __init__(self, offline=False): Initialize GMaps object. Read API key. `offline` arg can be set to True if you want to test code using this object.
- def get_location(self, addr): D... | Implement the Python class `GMaps` described below.
Class description:
Implement the GMaps class.
Method signatures and docstrings:
- def __init__(self, offline=False): Initialize GMaps object. Read API key. `offline` arg can be set to True if you want to test code using this object.
- def get_location(self, addr): D... | d9209f20073d075ae7150250cb1a369f8cb215b7 | <|skeleton|>
class GMaps:
def __init__(self, offline=False):
"""Initialize GMaps object. Read API key. `offline` arg can be set to True if you want to test code using this object."""
<|body_0|>
def get_location(self, addr):
"""Do the request to GMaps and extract latitude and longitude ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GMaps:
def __init__(self, offline=False):
"""Initialize GMaps object. Read API key. `offline` arg can be set to True if you want to test code using this object."""
self.lang = 'polish'
self.region = 'pl'
self.offline = offline
abs_path = os.path.dirname(os.path.abspath(... | the_stack_v2_python_sparse | Experiments/CVRP_DWave/2018_10_19_benchmark_small_csvrp/src/vrp_solver_subtree/src/gmaps.py | BOHRTECHNOLOGY/public_research | train | 17 | |
c57f1160fb160f8e68a0ec2500ffeb2c7f442ab7 | [
"n = len(nums1)\nm = len(nums2)\ni = -1\nj = 0\nans = []\nwhile k:\n ch = []\n if 0 <= i + 1 < n and 0 <= j < m:\n ch.append((nums1[i + 1] + nums2[j], i + 1, 0, nums1[i + 1], nums2[j]))\n if 0 <= j + 1 < m and 0 <= i < n:\n ch.append((nums1[i] + nums2[j + 1], 0, j + 1, nums1[i], nums2[j + 1])... | <|body_start_0|>
n = len(nums1)
m = len(nums2)
i = -1
j = 0
ans = []
while k:
ch = []
if 0 <= i + 1 < n and 0 <= j < m:
ch.append((nums1[i + 1] + nums2[j], i + 1, 0, nums1[i + 1], nums2[j]))
if 0 <= j + 1 < m and 0 <= i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kSmallestPairsWA(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype:... | stack_v2_sparse_classes_75kplus_train_009476 | 2,425 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"name": "kSmallestPairsWA",
"signature": "def kSmallestPairsWA(self, nums1, nums2, k)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_train_027718 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairsWA(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs(self, nums1, nums2, k): :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairsWA(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs(self, nums1, nums2, k): :type... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def kSmallestPairsWA(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kSmallestPairsWA(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
n = len(nums1)
m = len(nums2)
i = -1
j = 0
ans = []
while k:
ch = []
if 0 <= i + 1 < n... | the_stack_v2_python_sparse | python/leetcode.373.py | CalvinNeo/LeetCode | train | 3 | |
ed4a8d4e4bac5645ff2541d4a57d40adafd1545b | [
"self.graph_creator = create_molecular_torch_geometric_graph\nsuper().__init__(data_path, properties=properties, sanitize=sanitize, file_geometries=file_geometries, optimize_molecule=optimize_molecule)\nself.dataset = TorchGeometricGraphDataset(self.molecular_graphs)\nself.data_loader_fun = tg.data.DataLoader",
"... | <|body_start_0|>
self.graph_creator = create_molecular_torch_geometric_graph
super().__init__(data_path, properties=properties, sanitize=sanitize, file_geometries=file_geometries, optimize_molecule=optimize_molecule)
self.dataset = TorchGeometricGraphDataset(self.molecular_graphs)
self.d... | Data loader for graph data. | TorchGeometricGraphData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TorchGeometricGraphData:
"""Data loader for graph data."""
def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, optimize_molecule: bool=False) -> None:
"""Generate a dataset using grap... | stack_v2_sparse_classes_75kplus_train_009477 | 3,077 | permissive | [
{
"docstring": "Generate a dataset using graphs Parameters ---------- data_path path of the csv file properties Labels names sanitize Check that molecules have a valid conformer file_geometries Path to a file with the geometries in PDB format optimize_molecule Optimize the geometry if the ``file_geometries`` is... | 2 | stack_v2_sparse_classes_30k_train_039991 | Implement the Python class `TorchGeometricGraphData` described below.
Class description:
Data loader for graph data.
Method signatures and docstrings:
- def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, optimize_mol... | Implement the Python class `TorchGeometricGraphData` described below.
Class description:
Data loader for graph data.
Method signatures and docstrings:
- def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, optimize_mol... | 4edc9dc363ce901b1fcc19444bec42fc5930c4b9 | <|skeleton|>
class TorchGeometricGraphData:
"""Data loader for graph data."""
def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, optimize_molecule: bool=False) -> None:
"""Generate a dataset using grap... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TorchGeometricGraphData:
"""Data loader for graph data."""
def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, optimize_molecule: bool=False) -> None:
"""Generate a dataset using graphs Parameters... | the_stack_v2_python_sparse | swan/dataset/torch_geometric_graph_data.py | nlesc-nano/swan | train | 15 |
1ea85f28bec44c722a4c462ac6f3ff6194964709 | [
"if isinstance(interval, int):\n self._i = interval\nelif isinstance(int(interval), int):\n self._i = int(interval)\nif self._i < 0:\n raise ValueError('interval should be positive')",
"if self._check_compute_input(values, pressure_values) == False:\n return np.array(values)\nl = len(values)\nvalues =... | <|body_start_0|>
if isinstance(interval, int):
self._i = interval
elif isinstance(int(interval), int):
self._i = int(interval)
if self._i < 0:
raise ValueError('interval should be positive')
<|end_body_0|>
<|body_start_1|>
if self._check_compute_input... | Simple in-place moving average. This class implements the classic moving average algorithm. Each sample will be summed with all the samples in the interval and the sum will be divided by the length of the interval, then the result will replace the value of the sample and the algorithm will evaluate the next interval. | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
"""Simple in-place moving average. This class implements the classic moving average algorithm. Each sample will be summed with all the samples in the interval and the sum will be divided by the length of the interval, then the result will replace the value of the sample and the alg... | stack_v2_sparse_classes_75kplus_train_009478 | 6,931 | no_license | [
{
"docstring": "MovingAverage class constructor. Args: - *interval*: the interval of samples to consider. Raises: - ValueError if interval is negative.",
"name": "__init__",
"signature": "def __init__(self, interval)"
},
{
"docstring": "Returns the moving average on values. Args: - *values*: the... | 2 | stack_v2_sparse_classes_30k_train_011631 | Implement the Python class `MovingAverage` described below.
Class description:
Simple in-place moving average. This class implements the classic moving average algorithm. Each sample will be summed with all the samples in the interval and the sum will be divided by the length of the interval, then the result will repl... | Implement the Python class `MovingAverage` described below.
Class description:
Simple in-place moving average. This class implements the classic moving average algorithm. Each sample will be summed with all the samples in the interval and the sum will be divided by the length of the interval, then the result will repl... | 985f34c2214ea55cd4d324704847d5a0d2a9de1e | <|skeleton|>
class MovingAverage:
"""Simple in-place moving average. This class implements the classic moving average algorithm. Each sample will be summed with all the samples in the interval and the sum will be divided by the length of the interval, then the result will replace the value of the sample and the alg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovingAverage:
"""Simple in-place moving average. This class implements the classic moving average algorithm. Each sample will be summed with all the samples in the interval and the sum will be divided by the length of the interval, then the result will replace the value of the sample and the algorithm will e... | the_stack_v2_python_sparse | mhelpers/mean.py | inogs/bit.sea | train | 4 |
58139f73f8f81555ffe1858f5d94ca1603dbca3b | [
"participant_models = []\nParticipantModel = model_init_service.ModelService.get_participant_model_class()\nfor participant in participants:\n user_name = participant.get('name', '')\n session_dates = SessionDateModelHelper.create_session_date_models(participant.get('leaveSessions'))\n session_conut_dict =... | <|body_start_0|>
participant_models = []
ParticipantModel = model_init_service.ModelService.get_participant_model_class()
for participant in participants:
user_name = participant.get('name', '')
session_dates = SessionDateModelHelper.create_session_date_models(participant... | Class encapsulating methods which handles the operations on participants models | ParticipantModelHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipantModelHelper:
"""Class encapsulating methods which handles the operations on participants models"""
def create_participant_models(self, participants: List[Dict[str, List[Dict[datetime.date, List[str]]]]], sessions_list: List[str]):
"""Method to create List of participant mo... | stack_v2_sparse_classes_75kplus_train_009479 | 1,682 | permissive | [
{
"docstring": "Method to create List of participant models",
"name": "create_participant_models",
"signature": "def create_participant_models(self, participants: List[Dict[str, List[Dict[datetime.date, List[str]]]]], sessions_list: List[str])"
},
{
"docstring": "This method creates a dict which... | 2 | null | Implement the Python class `ParticipantModelHelper` described below.
Class description:
Class encapsulating methods which handles the operations on participants models
Method signatures and docstrings:
- def create_participant_models(self, participants: List[Dict[str, List[Dict[datetime.date, List[str]]]]], sessions_... | Implement the Python class `ParticipantModelHelper` described below.
Class description:
Class encapsulating methods which handles the operations on participants models
Method signatures and docstrings:
- def create_participant_models(self, participants: List[Dict[str, List[Dict[datetime.date, List[str]]]]], sessions_... | 23131aff6e0c20497bde632ed32aadcad0947e56 | <|skeleton|>
class ParticipantModelHelper:
"""Class encapsulating methods which handles the operations on participants models"""
def create_participant_models(self, participants: List[Dict[str, List[Dict[datetime.date, List[str]]]]], sessions_list: List[str]):
"""Method to create List of participant mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParticipantModelHelper:
"""Class encapsulating methods which handles the operations on participants models"""
def create_participant_models(self, participants: List[Dict[str, List[Dict[datetime.date, List[str]]]]], sessions_list: List[str]):
"""Method to create List of participant models"""
... | the_stack_v2_python_sparse | roster-backend/roster_project/roster_api/utils/helpers/business_helpers/model_helpers/participant_model_helper.py | akhilanil/roster | train | 0 |
2b95c81167a9c8ad2b419ba7df2b789271935d7a | [
"if value <= 0:\n raise ValueError(f'Log file size should be > 0 MB, passed value {value}')\nsuper().put(value)",
"log_file_size = super().get()\nassert log_file_size > 0, '`LogFileSize` should be > 0'\nreturn log_file_size"
] | <|body_start_0|>
if value <= 0:
raise ValueError(f'Log file size should be > 0 MB, passed value {value}')
super().put(value)
<|end_body_0|>
<|body_start_1|>
log_file_size = super().get()
assert log_file_size > 0, '`LogFileSize` should be > 0'
return log_file_size
<|e... | Max size of logs (in MBs) to store per Modin job. | LogFileSize | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogFileSize:
"""Max size of logs (in MBs) to store per Modin job."""
def put(cls, value: int) -> None:
"""Set ``LogFileSize`` with extra checks. Parameters ---------- value : int Config value to set."""
<|body_0|>
def get(cls) -> int:
"""Get ``LogFileSize`` with ... | stack_v2_sparse_classes_75kplus_train_009480 | 21,244 | permissive | [
{
"docstring": "Set ``LogFileSize`` with extra checks. Parameters ---------- value : int Config value to set.",
"name": "put",
"signature": "def put(cls, value: int) -> None"
},
{
"docstring": "Get ``LogFileSize`` with extra checks. Returns ------- int",
"name": "get",
"signature": "def ... | 2 | null | Implement the Python class `LogFileSize` described below.
Class description:
Max size of logs (in MBs) to store per Modin job.
Method signatures and docstrings:
- def put(cls, value: int) -> None: Set ``LogFileSize`` with extra checks. Parameters ---------- value : int Config value to set.
- def get(cls) -> int: Get ... | Implement the Python class `LogFileSize` described below.
Class description:
Max size of logs (in MBs) to store per Modin job.
Method signatures and docstrings:
- def put(cls, value: int) -> None: Set ``LogFileSize`` with extra checks. Parameters ---------- value : int Config value to set.
- def get(cls) -> int: Get ... | 8f6e00378e095817deccd25f4140406c5ee6c992 | <|skeleton|>
class LogFileSize:
"""Max size of logs (in MBs) to store per Modin job."""
def put(cls, value: int) -> None:
"""Set ``LogFileSize`` with extra checks. Parameters ---------- value : int Config value to set."""
<|body_0|>
def get(cls) -> int:
"""Get ``LogFileSize`` with ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogFileSize:
"""Max size of logs (in MBs) to store per Modin job."""
def put(cls, value: int) -> None:
"""Set ``LogFileSize`` with extra checks. Parameters ---------- value : int Config value to set."""
if value <= 0:
raise ValueError(f'Log file size should be > 0 MB, passed v... | the_stack_v2_python_sparse | modin/config/envvars.py | modin-project/modin | train | 9,241 |
6e37b1348c1be40e545799b6bc4e433b804de5af | [
"self.__author__ = 'GodSaveTheDoge'\nself.selector = '#mw-content-text li , p'\nself.url = 'https://{}.wikipedia.org/wiki/{}'\nself.apiurl = 'https://en.wikipedia.org/w/api.php?action=query&titles={}&format=json'",
"if '-1' in requests.get(self.apiurl.format(page)).json()['query']['pages']:\n return False\nret... | <|body_start_0|>
self.__author__ = 'GodSaveTheDoge'
self.selector = '#mw-content-text li , p'
self.url = 'https://{}.wikipedia.org/wiki/{}'
self.apiurl = 'https://en.wikipedia.org/w/api.php?action=query&titles={}&format=json'
<|end_body_0|>
<|body_start_1|>
if '-1' in requests.g... | Wikipedia | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wikipedia:
def __init__(self) -> None:
"""You can use this class to look up a page on wikipedia"""
<|body_0|>
def exists(self, page: str) -> bool:
"""Check if a page exists :param page: url of the page :return:"""
<|body_1|>
def getpage(self, page: str, ... | stack_v2_sparse_classes_75kplus_train_009481 | 1,240 | no_license | [
{
"docstring": "You can use this class to look up a page on wikipedia",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Check if a page exists :param page: url of the page :return:",
"name": "exists",
"signature": "def exists(self, page: str) -> bool"
}... | 3 | stack_v2_sparse_classes_30k_train_029686 | Implement the Python class `Wikipedia` described below.
Class description:
Implement the Wikipedia class.
Method signatures and docstrings:
- def __init__(self) -> None: You can use this class to look up a page on wikipedia
- def exists(self, page: str) -> bool: Check if a page exists :param page: url of the page :re... | Implement the Python class `Wikipedia` described below.
Class description:
Implement the Wikipedia class.
Method signatures and docstrings:
- def __init__(self) -> None: You can use this class to look up a page on wikipedia
- def exists(self, page: str) -> bool: Check if a page exists :param page: url of the page :re... | cc0db796c5516b36e82ef6f70c5649902366df62 | <|skeleton|>
class Wikipedia:
def __init__(self) -> None:
"""You can use this class to look up a page on wikipedia"""
<|body_0|>
def exists(self, page: str) -> bool:
"""Check if a page exists :param page: url of the page :return:"""
<|body_1|>
def getpage(self, page: str, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Wikipedia:
def __init__(self) -> None:
"""You can use this class to look up a page on wikipedia"""
self.__author__ = 'GodSaveTheDoge'
self.selector = '#mw-content-text li , p'
self.url = 'https://{}.wikipedia.org/wiki/{}'
self.apiurl = 'https://en.wikipedia.org/w/api.ph... | the_stack_v2_python_sparse | methods/Wiki.py | ankit-sinha-18/MultiUserbot | train | 0 | |
d1cf2693d6534155191cf92b85d6544d2c307cd2 | [
"data = np.array([[1, 2, 3], [2, 4, 6], [5, 10, 15]])\nself.cube = set_up_variable_cube(data, 'wind_speed', 'm s-1', 'equalarea', realizations=np.array([1, 2]))\nself.plugin = DifferenceBetweenAdjacentGridSquares()",
"expected_x = np.array([[1, 1], [2, 2], [5, 5]])\nexpected_y = np.array([[1, 2, 3], [3, 6, 9]])\n... | <|body_start_0|>
data = np.array([[1, 2, 3], [2, 4, 6], [5, 10, 15]])
self.cube = set_up_variable_cube(data, 'wind_speed', 'm s-1', 'equalarea', realizations=np.array([1, 2]))
self.plugin = DifferenceBetweenAdjacentGridSquares()
<|end_body_0|>
<|body_start_1|>
expected_x = np.array([[1,... | Test the process method. | Test_process | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_process:
"""Test the process method."""
def setUp(self):
"""Set up cube."""
<|body_0|>
def test_basic(self):
"""Test that differences are calculated along both the x and y dimensions and returned as separate cubes."""
<|body_1|>
def test_metadat... | stack_v2_sparse_classes_75kplus_train_009482 | 8,701 | permissive | [
{
"docstring": "Set up cube.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that differences are calculated along both the x and y dimensions and returned as separate cubes.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "... | 4 | stack_v2_sparse_classes_30k_val_001709 | Implement the Python class `Test_process` described below.
Class description:
Test the process method.
Method signatures and docstrings:
- def setUp(self): Set up cube.
- def test_basic(self): Test that differences are calculated along both the x and y dimensions and returned as separate cubes.
- def test_metadata(se... | Implement the Python class `Test_process` described below.
Class description:
Test the process method.
Method signatures and docstrings:
- def setUp(self): Set up cube.
- def test_basic(self): Test that differences are calculated along both the x and y dimensions and returned as separate cubes.
- def test_metadata(se... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_process:
"""Test the process method."""
def setUp(self):
"""Set up cube."""
<|body_0|>
def test_basic(self):
"""Test that differences are calculated along both the x and y dimensions and returned as separate cubes."""
<|body_1|>
def test_metadat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_process:
"""Test the process method."""
def setUp(self):
"""Set up cube."""
data = np.array([[1, 2, 3], [2, 4, 6], [5, 10, 15]])
self.cube = set_up_variable_cube(data, 'wind_speed', 'm s-1', 'equalarea', realizations=np.array([1, 2]))
self.plugin = DifferenceBetweenAd... | the_stack_v2_python_sparse | improver_tests/utilities/test_DifferenceBetweenAdjacentGridSquares.py | metoppv/improver | train | 101 |
b41e041d7e7aca67a81e717c028ebbb18df491ab | [
"if not head:\n return None\nstack = deque()\nbegin = start = ListNode()\nstart.next = head\ncnt = 0\nleft_ptr = None\nright_ptr = None\nwhile start:\n cnt = cnt + 1\n if cnt < left:\n start = start.next\n continue\n if cnt == left:\n left_ptr = start\n if cnt == right:\n ... | <|body_start_0|>
if not head:
return None
stack = deque()
begin = start = ListNode()
start.next = head
cnt = 0
left_ptr = None
right_ptr = None
while start:
cnt = cnt + 1
if cnt < left:
start = start.next... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
"""reverse with the help of a stack :param head: :param left: :param right: :return:"""
<|body_0|>
def reverseBetween_v2(self, head: Optional[ListNode], left: int, righ... | stack_v2_sparse_classes_75kplus_train_009483 | 3,084 | no_license | [
{
"docstring": "reverse with the help of a stack :param head: :param left: :param right: :return:",
"name": "reverseBetween",
"signature": "def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]"
},
{
"docstring": "reverse using subroutine :param head: :p... | 3 | stack_v2_sparse_classes_30k_train_042075 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: reverse with the help of a stack :param head: :param left: :param right: :return:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: reverse with the help of a stack :param head: :param left: :param right: :return:... | 46bd8d1b44cb19aa773cc072cc9be97e9a0e348d | <|skeleton|>
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
"""reverse with the help of a stack :param head: :param left: :param right: :return:"""
<|body_0|>
def reverseBetween_v2(self, head: Optional[ListNode], left: int, righ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
"""reverse with the help of a stack :param head: :param left: :param right: :return:"""
if not head:
return None
stack = deque()
begin = start = ListNode()
... | the_stack_v2_python_sparse | src/python/data_structure/linked_list/92_reverse_linkedlist2.py | alannesta/algo4 | train | 0 | |
ffb1dac782305e50e060985045b4dce987b9048c | [
"Sprite.__init__(self, pygame.image.load('Resources/sprites/deer.png'), image_rect, 'deer')\nself.speed = 24\nself.radius = 100\nself.runningAway = False\nGlobal.deer_group.add_internal(self)",
"Sprite.button_ops(self)\nif self.health_monitor():\n return\nif not self.flee():\n self.runningAway = False\n ... | <|body_start_0|>
Sprite.__init__(self, pygame.image.load('Resources/sprites/deer.png'), image_rect, 'deer')
self.speed = 24
self.radius = 100
self.runningAway = False
Global.deer_group.add_internal(self)
<|end_body_0|>
<|body_start_1|>
Sprite.button_ops(self)
if ... | Deer sprite class | DeerSprite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeerSprite:
"""Deer sprite class"""
def __init__(self, image_rect):
"""Calls Spite.init as super Sets speed, radius and runningAway (a boolean) Adds to global deer_group"""
<|body_0|>
def update(self):
"""Updates the deer sprite Either dies, runs away from a wolf... | stack_v2_sparse_classes_75kplus_train_009484 | 6,365 | no_license | [
{
"docstring": "Calls Spite.init as super Sets speed, radius and runningAway (a boolean) Adds to global deer_group",
"name": "__init__",
"signature": "def __init__(self, image_rect)"
},
{
"docstring": "Updates the deer sprite Either dies, runs away from a wolf, calls Sprite.hunt for plants or ca... | 4 | null | Implement the Python class `DeerSprite` described below.
Class description:
Deer sprite class
Method signatures and docstrings:
- def __init__(self, image_rect): Calls Spite.init as super Sets speed, radius and runningAway (a boolean) Adds to global deer_group
- def update(self): Updates the deer sprite Either dies, ... | Implement the Python class `DeerSprite` described below.
Class description:
Deer sprite class
Method signatures and docstrings:
- def __init__(self, image_rect): Calls Spite.init as super Sets speed, radius and runningAway (a boolean) Adds to global deer_group
- def update(self): Updates the deer sprite Either dies, ... | d973d8344c23158c6c76d2a7b26a83d429106b85 | <|skeleton|>
class DeerSprite:
"""Deer sprite class"""
def __init__(self, image_rect):
"""Calls Spite.init as super Sets speed, radius and runningAway (a boolean) Adds to global deer_group"""
<|body_0|>
def update(self):
"""Updates the deer sprite Either dies, runs away from a wolf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeerSprite:
"""Deer sprite class"""
def __init__(self, image_rect):
"""Calls Spite.init as super Sets speed, radius and runningAway (a boolean) Adds to global deer_group"""
Sprite.__init__(self, pygame.image.load('Resources/sprites/deer.png'), image_rect, 'deer')
self.speed = 24
... | the_stack_v2_python_sparse | Sprites/DeerSprite.py | EcoSimulator/EcoSim | train | 0 |
7053b84b914ea3600bb61ec71fe3e3d752c928a5 | [
"self.sharedVarName = sharedVarName\ntry:\n self.bbVarType = bbVarType\n self.rosMsgType = bridge_utils.BB2ROS_TYPE_MAP[self.bbVarType][1]\n self.rosPublisher = rospy.Publisher(self.sharedVarName, self.rosMsgType, queue_size=1000)\n rospy.logdebug('ROS publisher \"' + str(self.rosMsgType) + '\" for \"' ... | <|body_start_0|>
self.sharedVarName = sharedVarName
try:
self.bbVarType = bbVarType
self.rosMsgType = bridge_utils.BB2ROS_TYPE_MAP[self.bbVarType][1]
self.rosPublisher = rospy.Publisher(self.sharedVarName, self.rosMsgType, queue_size=1000)
rospy.logdebug('... | Class to bridge the BB Shared Vars to ROS Topics | BB2RosPublisher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BB2RosPublisher:
"""Class to bridge the BB Shared Vars to ROS Topics"""
def __init__(self, sharedVarName, bbVarType):
"""Constructor Creates a new BB2ROSPublisher Object. Receives: shredVarName: Name of the shared var to bridge. bbVarType: The type of the var."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_009485 | 4,802 | no_license | [
{
"docstring": "Constructor Creates a new BB2ROSPublisher Object. Receives: shredVarName: Name of the shared var to bridge. bbVarType: The type of the var.",
"name": "__init__",
"signature": "def __init__(self, sharedVarName, bbVarType)"
},
{
"docstring": "bridge_SV_data Callback for the BB shar... | 3 | stack_v2_sparse_classes_30k_test_000396 | Implement the Python class `BB2RosPublisher` described below.
Class description:
Class to bridge the BB Shared Vars to ROS Topics
Method signatures and docstrings:
- def __init__(self, sharedVarName, bbVarType): Constructor Creates a new BB2ROSPublisher Object. Receives: shredVarName: Name of the shared var to bridge... | Implement the Python class `BB2RosPublisher` described below.
Class description:
Class to bridge the BB Shared Vars to ROS Topics
Method signatures and docstrings:
- def __init__(self, sharedVarName, bbVarType): Constructor Creates a new BB2ROSPublisher Object. Receives: shredVarName: Name of the shared var to bridge... | c2b4de807d5f3a18b317b9b01fdeb0cec3f7327e | <|skeleton|>
class BB2RosPublisher:
"""Class to bridge the BB Shared Vars to ROS Topics"""
def __init__(self, sharedVarName, bbVarType):
"""Constructor Creates a new BB2ROSPublisher Object. Receives: shredVarName: Name of the shared var to bridge. bbVarType: The type of the var."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BB2RosPublisher:
"""Class to bridge the BB Shared Vars to ROS Topics"""
def __init__(self, sharedVarName, bbVarType):
"""Constructor Creates a new BB2ROSPublisher Object. Receives: shredVarName: Name of the shared var to bridge. bbVarType: The type of the var."""
self.sharedVarName = shar... | the_stack_v2_python_sparse | catkin_ws/src/interoperation/bbros_bridge/src/bbros_bridge/sv_bridge.py | RobotJustina/JUSTINA | train | 7 |
8c1a3f07977b699cdb70ac5fa35d6a3d0805990f | [
"d = {}\nl = len(nums)\nfor i in range(l):\n d[nums[i]] = d.get(nums[i], 0) + 1\nfor k, v in d.items():\n if v > 1:\n return k",
"if len(nums) > 1:\n slow = nums[0]\n fast = nums[nums[0]]\n while slow != fast:\n slow = nums[slow]\n fast = nums[nums[fast]]\n fast = 0\n whi... | <|body_start_0|>
d = {}
l = len(nums)
for i in range(l):
d[nums[i]] = d.get(nums[i], 0) + 1
for k, v in d.items():
if v > 1:
return k
<|end_body_0|>
<|body_start_1|>
if len(nums) > 1:
slow = nums[0]
fast = nums[nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int 通常能想到的方案"""
<|body_0|>
def findDuplicate1(self, nums):
""":type nums: List[int] :rtype: int 想象成链表,判断是否有环,利用快慢指针 空间复杂度为1,时间复杂度为n [3,1,3,4,2] 首先第一个数字3指向下标3的数字4, 数字4指向下标4的数字2 数字2指向下标2的数字3 数字1指... | stack_v2_sparse_classes_75kplus_train_009486 | 3,381 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 通常能想到的方案",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 想象成链表,判断是否有环,利用快慢指针 空间复杂度为1,时间复杂度为n [3,1,3,4,2] 首先第一个数字3指向下标3的数字4, 数字4指向下标4的数字2 数字2指向下标2的数字3 数字1指向下标1的数字1 举例来说,假... | 2 | stack_v2_sparse_classes_30k_train_006418 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int 通常能想到的方案
- def findDuplicate1(self, nums): :type nums: List[int] :rtype: int 想象成链表,判断是否有环,利用快慢指针 空间复杂度为1,时间复杂度为n ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int 通常能想到的方案
- def findDuplicate1(self, nums): :type nums: List[int] :rtype: int 想象成链表,判断是否有环,利用快慢指针 空间复杂度为1,时间复杂度为n ... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int 通常能想到的方案"""
<|body_0|>
def findDuplicate1(self, nums):
""":type nums: List[int] :rtype: int 想象成链表,判断是否有环,利用快慢指针 空间复杂度为1,时间复杂度为n [3,1,3,4,2] 首先第一个数字3指向下标3的数字4, 数字4指向下标4的数字2 数字2指向下标2的数字3 数字1指... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int 通常能想到的方案"""
d = {}
l = len(nums)
for i in range(l):
d[nums[i]] = d.get(nums[i], 0) + 1
for k, v in d.items():
if v > 1:
return k
def findDuplicate1... | the_stack_v2_python_sparse | 算法/数组/寻找重复数.py | RichieSong/algorithm | train | 0 | |
e1d1d51b1c9cf3f4788f30e17aeeeaebf2b55977 | [
"from dw.api import make, put\nfrom dw.entity.data import image_directory\nput.db_rows(make.data(image_directory)(root, 'clean_fmd_comics'))",
"from dw.api import make, put\nfrom dw.db import orm\nfrom dw.entity.data import manga109\nfrom dw.ui import log\norm.init(conn)\nput.db_rows(make.data(manga109)(root))\nl... | <|body_start_0|>
from dw.api import make, put
from dw.entity.data import image_directory
put.db_rows(make.data(image_directory)(root, 'clean_fmd_comics'))
<|end_body_0|>
<|body_start_1|>
from dw.api import make, put
from dw.db import orm
from dw.entity.data import manga1... | Add data to DB (not dataset) | data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class data:
"""Add data to DB (not dataset)"""
def image_directory(conn, root, note=None):
"""Add all images of directory into DB. `root` is path of image directory. It must contains images only. If not, it raise assertion error. args: conn: connection str. 'id:pw@host:port/dbname' format.... | stack_v2_sparse_classes_75kplus_train_009487 | 6,458 | no_license | [
{
"docstring": "Add all images of directory into DB. `root` is path of image directory. It must contains images only. If not, it raise assertion error. args: conn: connection str. 'id:pw@host:port/dbname' format. root: root directory path string of data. note: note for running command. If not None, it is logged... | 4 | null | Implement the Python class `data` described below.
Class description:
Add data to DB (not dataset)
Method signatures and docstrings:
- def image_directory(conn, root, note=None): Add all images of directory into DB. `root` is path of image directory. It must contains images only. If not, it raise assertion error. arg... | Implement the Python class `data` described below.
Class description:
Add data to DB (not dataset)
Method signatures and docstrings:
- def image_directory(conn, root, note=None): Add all images of directory into DB. `root` is path of image directory. It must contains images only. If not, it raise assertion error. arg... | a93febf6df4b7cbaf49e90409bbb7fd64bde0fe5 | <|skeleton|>
class data:
"""Add data to DB (not dataset)"""
def image_directory(conn, root, note=None):
"""Add all images of directory into DB. `root` is path of image directory. It must contains images only. If not, it raise assertion error. args: conn: connection str. 'id:pw@host:port/dbname' format.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class data:
"""Add data to DB (not dataset)"""
def image_directory(conn, root, note=None):
"""Add all images of directory into DB. `root` is path of image directory. It must contains images only. If not, it raise assertion error. args: conn: connection str. 'id:pw@host:port/dbname' format. root: root d... | the_stack_v2_python_sparse | dw/ui/cli.py | KUR-creative/old-2-data-warehouse | train | 0 |
bcad9a059d3f5d5d63688c9fe42f9867532b904d | [
"self.any_permission = any_permission\nself.add_permission = add_permission\nself.change_permission = change_permission\nself.delete_permission = delete_permission",
"add_name = self.get_full_permission_string('add')\nchange_name = self.get_full_permission_string('change')\ndelete_name = self.get_full_permission_... | <|body_start_0|>
self.any_permission = any_permission
self.add_permission = add_permission
self.change_permission = change_permission
self.delete_permission = delete_permission
<|end_body_0|>
<|body_start_1|>
add_name = self.get_full_permission_string('add')
change_name ... | Permission logic class for role based permission system It is checked by user_obj.role | BaseRolePermissionLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseRolePermissionLogic:
"""Permission logic class for role based permission system It is checked by user_obj.role"""
def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=False):
"""Constructor Parameters ---------- any_permission ... | stack_v2_sparse_classes_75kplus_train_009488 | 6,884 | no_license | [
{
"docstring": "Constructor Parameters ---------- any_permission : boolean True for give any permission of the specified object or model to the role. Default value will be `False` add_permission : boolean True for give add permission of the specified model to the role. Default value will be 'False' change_permi... | 2 | stack_v2_sparse_classes_30k_train_012292 | Implement the Python class `BaseRolePermissionLogic` described below.
Class description:
Permission logic class for role based permission system It is checked by user_obj.role
Method signatures and docstrings:
- def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=... | Implement the Python class `BaseRolePermissionLogic` described below.
Class description:
Permission logic class for role based permission system It is checked by user_obj.role
Method signatures and docstrings:
- def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=... | 8f9a850c4df41b0fc1da5b73189772552d5cd531 | <|skeleton|>
class BaseRolePermissionLogic:
"""Permission logic class for role based permission system It is checked by user_obj.role"""
def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=False):
"""Constructor Parameters ---------- any_permission ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseRolePermissionLogic:
"""Permission logic class for role based permission system It is checked by user_obj.role"""
def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=False):
"""Constructor Parameters ---------- any_permission : boolean Tru... | the_stack_v2_python_sparse | src/kawaz/core/personas/perms.py | kawazrepos/Kawaz3rd | train | 7 |
9b5064a672d0fe14038bbd1040b23d0c2811e769 | [
"self.size = 10\nself.times = [0 for _ in range(self.size)]\nself.d = collections.defaultdict(set)",
"t = timestamp % self.size\nif timestamp != self.times[t]:\n self.d[t] = set()\n self.times[t] = timestamp\nfor i in range(self.size):\n if self.times[i] + 10 > timestamp and message in self.d[i]:\n ... | <|body_start_0|>
self.size = 10
self.times = [0 for _ in range(self.size)]
self.d = collections.defaultdict(set)
<|end_body_0|>
<|body_start_1|>
t = timestamp % self.size
if timestamp != self.times[t]:
self.d[t] = set()
self.times[t] = timestamp
f... | Logger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method retu... | stack_v2_sparse_classes_75kplus_train_009489 | 2,846 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timest... | 2 | stack_v2_sparse_classes_30k_train_044129 | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def shouldPrintMessage(self, timestamp: int, message: str) -> bool: Returns true if the message should be printed in the gi... | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def shouldPrintMessage(self, timestamp: int, message: str) -> bool: Returns true if the message should be printed in the gi... | 4c1288c99f78823c7c3bac0ceedd532e64af1258 | <|skeleton|>
class Logger:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logger:
def __init__(self):
"""Initialize your data structure here."""
self.size = 10
self.times = [0 for _ in range(self.size)]
self.d = collections.defaultdict(set)
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message... | the_stack_v2_python_sparse | Algorithms/0359 Logger Rate Limiter.py | cravo123/LeetCode | train | 6 | |
7a55a952afff52b63f99c94e5d131fa3cd31151b | [
"profile = request.user.get_profile()\ntry:\n friendgroup = FriendGroup.objects.get(id=id, owner=profile)\nexcept FriendGroup.DoesNotExist:\n return response.send(errors='Group with ID %s does not exist' % id, status=404)\nmembers = [profile.dict() for profile in friendgroup.members.all()]\nresponse.set(name=... | <|body_start_0|>
profile = request.user.get_profile()
try:
friendgroup = FriendGroup.objects.get(id=id, owner=profile)
except FriendGroup.DoesNotExist:
return response.send(errors='Group with ID %s does not exist' % id, status=404)
members = [profile.dict() for pr... | GroupHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupHandler:
def read(self, request, id, response):
"""Get a group's details by ID API Handler: GET /friends/group/{id}"""
<|body_0|>
def create(self, request, response):
"""Create a new Group API Handler: POST /friends/group Params: @name [string] name of the new g... | stack_v2_sparse_classes_75kplus_train_009490 | 10,549 | no_license | [
{
"docstring": "Get a group's details by ID API Handler: GET /friends/group/{id}",
"name": "read",
"signature": "def read(self, request, id, response)"
},
{
"docstring": "Create a new Group API Handler: POST /friends/group Params: @name [string] name of the new group",
"name": "create",
... | 4 | stack_v2_sparse_classes_30k_train_040886 | Implement the Python class `GroupHandler` described below.
Class description:
Implement the GroupHandler class.
Method signatures and docstrings:
- def read(self, request, id, response): Get a group's details by ID API Handler: GET /friends/group/{id}
- def create(self, request, response): Create a new Group API Hand... | Implement the Python class `GroupHandler` described below.
Class description:
Implement the GroupHandler class.
Method signatures and docstrings:
- def read(self, request, id, response): Get a group's details by ID API Handler: GET /friends/group/{id}
- def create(self, request, response): Create a new Group API Hand... | 460da9ac57cbac158b9cde816eeddd3f06878d6a | <|skeleton|>
class GroupHandler:
def read(self, request, id, response):
"""Get a group's details by ID API Handler: GET /friends/group/{id}"""
<|body_0|>
def create(self, request, response):
"""Create a new Group API Handler: POST /friends/group Params: @name [string] name of the new g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupHandler:
def read(self, request, id, response):
"""Get a group's details by ID API Handler: GET /friends/group/{id}"""
profile = request.user.get_profile()
try:
friendgroup = FriendGroup.objects.get(id=id, owner=profile)
except FriendGroup.DoesNotExist:
... | the_stack_v2_python_sparse | webservice_tools/apps/friends/handlers.py | DexterW/django-webservice-tools | train | 0 | |
b55236a26d47009d650a3b50b721c9af6b677c13 | [
"bin, dev = packager.identify(installation=self)\nself.version, _ = packager.info(package=dev)\nself.psql = 'psql'\nlauncher = 'bin/{.psql}'.format(self)\nbindir = packager.findfirst(target=launcher, contents=packager.contents(package=bin))\nself.bindir = [bindir / 'bin'] if bindir else []\nheader = 'libpq-fe\\\\.h... | <|body_start_0|>
bin, dev = packager.identify(installation=self)
self.version, _ = packager.info(package=dev)
self.psql = 'psql'
launcher = 'bin/{.psql}'.format(self)
bindir = packager.findfirst(target=launcher, contents=packager.contents(package=bin))
self.bindir = [bind... | A generic postgres installation | Default | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Default:
"""A generic postgres installation"""
def dpkg(self, packager):
"""Attempt to repair my configuration"""
<|body_0|>
def macports(self, packager, **kwds):
"""Attempt to repair my configuration"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_009491 | 7,944 | permissive | [
{
"docstring": "Attempt to repair my configuration",
"name": "dpkg",
"signature": "def dpkg(self, packager)"
},
{
"docstring": "Attempt to repair my configuration",
"name": "macports",
"signature": "def macports(self, packager, **kwds)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015709 | Implement the Python class `Default` described below.
Class description:
A generic postgres installation
Method signatures and docstrings:
- def dpkg(self, packager): Attempt to repair my configuration
- def macports(self, packager, **kwds): Attempt to repair my configuration | Implement the Python class `Default` described below.
Class description:
A generic postgres installation
Method signatures and docstrings:
- def dpkg(self, packager): Attempt to repair my configuration
- def macports(self, packager, **kwds): Attempt to repair my configuration
<|skeleton|>
class Default:
"""A gen... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Default:
"""A generic postgres installation"""
def dpkg(self, packager):
"""Attempt to repair my configuration"""
<|body_0|>
def macports(self, packager, **kwds):
"""Attempt to repair my configuration"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Default:
"""A generic postgres installation"""
def dpkg(self, packager):
"""Attempt to repair my configuration"""
bin, dev = packager.identify(installation=self)
self.version, _ = packager.info(package=dev)
self.psql = 'psql'
launcher = 'bin/{.psql}'.format(self)
... | the_stack_v2_python_sparse | packages/pyre/externals/Postgres.py | pyre/pyre | train | 27 |
9147e6e42b554b1e4b69e6061abeef698caa2663 | [
"article = Article.objects.get(slug=slug)\nbookmark = {}\nbookmark['user'] = self.request.user.id\nbookmark['article'] = article.pk\nserializer = self.serializer_class(data=bookmark)\nserializer.is_valid(raise_exception=True)\nserializer.save()\narticle_serializer = ArticleSerializer(instance=article, context={'req... | <|body_start_0|>
article = Article.objects.get(slug=slug)
bookmark = {}
bookmark['user'] = self.request.user.id
bookmark['article'] = article.pk
serializer = self.serializer_class(data=bookmark)
serializer.is_valid(raise_exception=True)
serializer.save()
a... | Views for the bookmark functionality | BookmarkAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookmarkAPIView:
"""Views for the bookmark functionality"""
def post(self, request, slug=None, pk=None):
"""Create a bookmark method"""
<|body_0|>
def check_article(self, slug):
"""Check if article with the pass in slug exists if not :return 404"""
<|body... | stack_v2_sparse_classes_75kplus_train_009492 | 3,951 | permissive | [
{
"docstring": "Create a bookmark method",
"name": "post",
"signature": "def post(self, request, slug=None, pk=None)"
},
{
"docstring": "Check if article with the pass in slug exists if not :return 404",
"name": "check_article",
"signature": "def check_article(self, slug)"
},
{
"... | 4 | stack_v2_sparse_classes_30k_val_001921 | Implement the Python class `BookmarkAPIView` described below.
Class description:
Views for the bookmark functionality
Method signatures and docstrings:
- def post(self, request, slug=None, pk=None): Create a bookmark method
- def check_article(self, slug): Check if article with the pass in slug exists if not :return ... | Implement the Python class `BookmarkAPIView` described below.
Class description:
Views for the bookmark functionality
Method signatures and docstrings:
- def post(self, request, slug=None, pk=None): Create a bookmark method
- def check_article(self, slug): Check if article with the pass in slug exists if not :return ... | e8438b78b88c52d108520429d0b67cd3d13e0824 | <|skeleton|>
class BookmarkAPIView:
"""Views for the bookmark functionality"""
def post(self, request, slug=None, pk=None):
"""Create a bookmark method"""
<|body_0|>
def check_article(self, slug):
"""Check if article with the pass in slug exists if not :return 404"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookmarkAPIView:
"""Views for the bookmark functionality"""
def post(self, request, slug=None, pk=None):
"""Create a bookmark method"""
article = Article.objects.get(slug=slug)
bookmark = {}
bookmark['user'] = self.request.user.id
bookmark['article'] = article.pk
... | the_stack_v2_python_sparse | authors/apps/bookmarks/views.py | andela/ah-sealteam | train | 1 |
64535387923dab6c9b6dd9b235680647e52ff975 | [
"Thread.__init__(self)\nself.command = command\nself.process = None",
"self.process = subprocess.Popen(self.command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\ntry:\n _stream_output(self.process)\nexcept RuntimeError as e:\n msg = 'Failed to run: %s, %s' % (self.command, str(e))\n raise RuntimeErro... | <|body_start_0|>
Thread.__init__(self)
self.command = command
self.process = None
<|end_body_0|>
<|body_start_1|>
self.process = subprocess.Popen(self.command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
_stream_output(self.process)
except RuntimeErr... | Placeholder docstring. | _HostingContainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _HostingContainer:
"""Placeholder docstring."""
def __init__(self, command):
"""Creates a new threaded hosting container. Args: command:"""
<|body_0|>
def run(self):
"""Placeholder docstring"""
<|body_1|>
def down(self):
"""Placeholder docstr... | stack_v2_sparse_classes_75kplus_train_009493 | 43,196 | permissive | [
{
"docstring": "Creates a new threaded hosting container. Args: command:",
"name": "__init__",
"signature": "def __init__(self, command)"
},
{
"docstring": "Placeholder docstring",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Placeholder docstring",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_038996 | Implement the Python class `_HostingContainer` described below.
Class description:
Placeholder docstring.
Method signatures and docstrings:
- def __init__(self, command): Creates a new threaded hosting container. Args: command:
- def run(self): Placeholder docstring
- def down(self): Placeholder docstring | Implement the Python class `_HostingContainer` described below.
Class description:
Placeholder docstring.
Method signatures and docstrings:
- def __init__(self, command): Creates a new threaded hosting container. Args: command:
- def run(self): Placeholder docstring
- def down(self): Placeholder docstring
<|skeleton... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class _HostingContainer:
"""Placeholder docstring."""
def __init__(self, command):
"""Creates a new threaded hosting container. Args: command:"""
<|body_0|>
def run(self):
"""Placeholder docstring"""
<|body_1|>
def down(self):
"""Placeholder docstr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _HostingContainer:
"""Placeholder docstring."""
def __init__(self, command):
"""Creates a new threaded hosting container. Args: command:"""
Thread.__init__(self)
self.command = command
self.process = None
def run(self):
"""Placeholder docstring"""
self... | the_stack_v2_python_sparse | src/sagemaker/local/image.py | aws/sagemaker-python-sdk | train | 2,050 |
e990cdfd99b2716dec01321ee81cb322c0f0c4ef | [
"from jnius import autoclass, cast\nPythonActivity = autoclass('org.kivy.android.PythonActivity')\nactivity = PythonActivity.mActivity\nif activity is None:\n PythonService = autoclass('org.kivy.android.PythonService')\n activity = PythonService.mService\ncontext = cast('android.content.Context', activity)\nf... | <|body_start_0|>
from jnius import autoclass, cast
PythonActivity = autoclass('org.kivy.android.PythonActivity')
activity = PythonActivity.mActivity
if activity is None:
PythonService = autoclass('org.kivy.android.PythonService')
activity = PythonService.mService
... | EtherollApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EtherollApp:
def get_files_dir():
"""Alternative App._get_user_data_dir() implementation for Android that also works when within a service activity."""
<|body_0|>
def _get_user_data_dir(self):
"""Overrides the default `App._get_user_data_dir()` behavior on Android to... | stack_v2_sparse_classes_75kplus_train_009494 | 7,618 | permissive | [
{
"docstring": "Alternative App._get_user_data_dir() implementation for Android that also works when within a service activity.",
"name": "get_files_dir",
"signature": "def get_files_dir()"
},
{
"docstring": "Overrides the default `App._get_user_data_dir()` behavior on Android to also work with ... | 2 | stack_v2_sparse_classes_30k_train_052631 | Implement the Python class `EtherollApp` described below.
Class description:
Implement the EtherollApp class.
Method signatures and docstrings:
- def get_files_dir(): Alternative App._get_user_data_dir() implementation for Android that also works when within a service activity.
- def _get_user_data_dir(self): Overrid... | Implement the Python class `EtherollApp` described below.
Class description:
Implement the EtherollApp class.
Method signatures and docstrings:
- def get_files_dir(): Alternative App._get_user_data_dir() implementation for Android that also works when within a service activity.
- def _get_user_data_dir(self): Overrid... | 2ccc30fad736a6fee0cba8b99c521bee6ad13087 | <|skeleton|>
class EtherollApp:
def get_files_dir():
"""Alternative App._get_user_data_dir() implementation for Android that also works when within a service activity."""
<|body_0|>
def _get_user_data_dir(self):
"""Overrides the default `App._get_user_data_dir()` behavior on Android to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EtherollApp:
def get_files_dir():
"""Alternative App._get_user_data_dir() implementation for Android that also works when within a service activity."""
from jnius import autoclass, cast
PythonActivity = autoclass('org.kivy.android.PythonActivity')
activity = PythonActivity.mAct... | the_stack_v2_python_sparse | src/etherollapp/service/main.py | AndreMiras/EtherollApp | train | 59 | |
b0ea628baa6110af9330b6544603806266c37bf7 | [
"for obj in obj_list['hits']['hits']:\n obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)\nreturn obj_list['hits']",
"aggs = obj_list.get('aggregations')\nif not aggs:\n return missing\nreturn aggs"
] | <|body_start_0|>
for obj in obj_list['hits']['hits']:
obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)
return obj_list['hits']
<|end_body_0|>
<|body_start_1|>
aggs = obj_list.get('aggregations')
if not aggs:
return missing
r... | Schema for dumping extra information in the UI. | UIListSchema | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
<|body_0|>
def get_aggs(self, obj_list):
"""Apply aggregations transformation."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_009495 | 7,049 | permissive | [
{
"docstring": "Apply hits transformation.",
"name": "get_hits",
"signature": "def get_hits(self, obj_list)"
},
{
"docstring": "Apply aggregations transformation.",
"name": "get_aggs",
"signature": "def get_aggs(self, obj_list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028384 | Implement the Python class `UIListSchema` described below.
Class description:
Schema for dumping extra information in the UI.
Method signatures and docstrings:
- def get_hits(self, obj_list): Apply hits transformation.
- def get_aggs(self, obj_list): Apply aggregations transformation. | Implement the Python class `UIListSchema` described below.
Class description:
Schema for dumping extra information in the UI.
Method signatures and docstrings:
- def get_hits(self, obj_list): Apply hits transformation.
- def get_aggs(self, obj_list): Apply aggregations transformation.
<|skeleton|>
class UIListSchema... | b4bcc2e16df6048149177a6e1ebd514bdb6b0626 | <|skeleton|>
class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
<|body_0|>
def get_aggs(self, obj_list):
"""Apply aggregations transformation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
for obj in obj_list['hits']['hits']:
obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)
return obj_list['hits... | the_stack_v2_python_sparse | invenio_rdm_records/resources/serializers/ui/schema.py | ppanero/invenio-rdm-records | train | 0 |
011bc5956b1e9ec88ee3aa2f277415a06ff1e2ad | [
"user = User.objects.get(email=email)\nsalt = sha1(str(random.random())).hexdigest()[:5]\nkey = sha1(salt + user.username).hexdigest()\nResetPassword.objects.create(user=user, activation_key=key)\nurl = '{}{}'.format('tandlr://', key)\nurl_web = '{}{}/{}'.format(settings.FRONTEND_RECOVERY_PASSWORD_URL, key, user.em... | <|body_start_0|>
user = User.objects.get(email=email)
salt = sha1(str(random.random())).hexdigest()[:5]
key = sha1(salt + user.username).hexdigest()
ResetPassword.objects.create(user=user, activation_key=key)
url = '{}{}'.format('tandlr://', key)
url_web = '{}{}/{}'.forma... | ActivationKeysManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivationKeysManager:
def reset_user_password(self, email, request=None):
"""Custom reset password"""
<|body_0|>
def activation_user(self, user, request=None):
"""Custom activation user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = User.ob... | stack_v2_sparse_classes_75kplus_train_009496 | 5,482 | permissive | [
{
"docstring": "Custom reset password",
"name": "reset_user_password",
"signature": "def reset_user_password(self, email, request=None)"
},
{
"docstring": "Custom activation user",
"name": "activation_user",
"signature": "def activation_user(self, user, request=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024082 | Implement the Python class `ActivationKeysManager` described below.
Class description:
Implement the ActivationKeysManager class.
Method signatures and docstrings:
- def reset_user_password(self, email, request=None): Custom reset password
- def activation_user(self, user, request=None): Custom activation user | Implement the Python class `ActivationKeysManager` described below.
Class description:
Implement the ActivationKeysManager class.
Method signatures and docstrings:
- def reset_user_password(self, email, request=None): Custom reset password
- def activation_user(self, user, request=None): Custom activation user
<|ske... | 7349ce18f56658d67daedf5e1abb352b5c15a029 | <|skeleton|>
class ActivationKeysManager:
def reset_user_password(self, email, request=None):
"""Custom reset password"""
<|body_0|>
def activation_user(self, user, request=None):
"""Custom activation user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivationKeysManager:
def reset_user_password(self, email, request=None):
"""Custom reset password"""
user = User.objects.get(email=email)
salt = sha1(str(random.random())).hexdigest()[:5]
key = sha1(salt + user.username).hexdigest()
ResetPassword.objects.create(user=u... | the_stack_v2_python_sparse | src/tandlr/registration/models.py | shrmoud/schoolapp | train | 0 | |
8d75a14158e3e2e806ef137ad2f824a5bc638cb4 | [
"for transaction in orm.Transaction.objects.all():\n payment = orm['payment.MPowerPayment'].objects.create(mpower_opr_token=transaction.mpower_opr_token, mpower_confirm_token=transaction.mpower_confirm_token, mpower_invoice_token=transaction.mpower_invoice_token, mpower_response_code=transaction.mpower_response_... | <|body_start_0|>
for transaction in orm.Transaction.objects.all():
payment = orm['payment.MPowerPayment'].objects.create(mpower_opr_token=transaction.mpower_opr_token, mpower_confirm_token=transaction.mpower_confirm_token, mpower_invoice_token=transaction.mpower_invoice_token, mpower_response_code=t... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Manually written forwards method."""
<|body_0|>
def backwards(self, orm):
"""Manually written forwards method."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for transaction in orm.Transaction.objects.all():
... | stack_v2_sparse_classes_75kplus_train_009497 | 6,221 | no_license | [
{
"docstring": "Manually written forwards method.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Manually written forwards method.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | null | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Manually written forwards method.
- def backwards(self, orm): Manually written forwards method. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Manually written forwards method.
- def backwards(self, orm): Manually written forwards method.
<|skeleton|>
class Migration:
def forwards(self, ... | 3b31c5899d063c2615e43641d1d6d7f4f675de0f | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Manually written forwards method."""
<|body_0|>
def backwards(self, orm):
"""Manually written forwards method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Migration:
def forwards(self, orm):
"""Manually written forwards method."""
for transaction in orm.Transaction.objects.all():
payment = orm['payment.MPowerPayment'].objects.create(mpower_opr_token=transaction.mpower_opr_token, mpower_confirm_token=transaction.mpower_confirm_token, ... | the_stack_v2_python_sparse | transaction/migrations/0019_decouple_payments.py | kahihia/Kitiwa | train | 0 | |
10d18b45bfdaf8b5661b1d3456545b9f97974da4 | [
"super(ShowAttendTell, self).__init__()\nself.encoder_dim = encoder_dim\nself.attention_dim = attention_dim\nself.embed_dim = embed_dim\nself.decoder_dim = decoder_dim\nself.vocab_size = vocab_size\nself.dropout = dropout\nself.attention = Attention(encoder_dim, decoder_dim, attention_dim)\nself.embedding = nn.Embe... | <|body_start_0|>
super(ShowAttendTell, self).__init__()
self.encoder_dim = encoder_dim
self.attention_dim = attention_dim
self.embed_dim = embed_dim
self.decoder_dim = decoder_dim
self.vocab_size = vocab_size
self.dropout = dropout
self.attention = Attenti... | Decoder. | ShowAttendTell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowAttendTell:
"""Decoder."""
def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5):
""":param attention_dim: size of attention network :param embed_dim: embedding size :param decoder_dim: size of decoder's RNN :param vocab_size: size o... | stack_v2_sparse_classes_75kplus_train_009498 | 6,934 | no_license | [
{
"docstring": ":param attention_dim: size of attention network :param embed_dim: embedding size :param decoder_dim: size of decoder's RNN :param vocab_size: size of vocabulary :param encoder_dim: feature size of encoded images :param dropout: dropout",
"name": "__init__",
"signature": "def __init__(sel... | 4 | stack_v2_sparse_classes_30k_train_051751 | Implement the Python class `ShowAttendTell` described below.
Class description:
Decoder.
Method signatures and docstrings:
- def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5): :param attention_dim: size of attention network :param embed_dim: embedding size :param dec... | Implement the Python class `ShowAttendTell` described below.
Class description:
Decoder.
Method signatures and docstrings:
- def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5): :param attention_dim: size of attention network :param embed_dim: embedding size :param dec... | 542765c409b381def35362972068ae9b73bd9d8a | <|skeleton|>
class ShowAttendTell:
"""Decoder."""
def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5):
""":param attention_dim: size of attention network :param embed_dim: embedding size :param decoder_dim: size of decoder's RNN :param vocab_size: size o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShowAttendTell:
"""Decoder."""
def __init__(self, attention_dim, embed_dim, decoder_dim, vocab_size, encoder_dim=2048, dropout=0.5):
""":param attention_dim: size of attention network :param embed_dim: embedding size :param decoder_dim: size of decoder's RNN :param vocab_size: size of vocabulary ... | the_stack_v2_python_sparse | models/show_attend_tell.py | maartje/NeuralImageCaptionGeneration | train | 0 |
d7784f46060d2636ff485544f671b0617ddf3fa3 | [
"output = ''\nsummary = ''\nlogic = True\nfor bucket in list(result.keys()):\n summary += '\\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'\n output += '\\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'\n output += '\\n Analyzing for Bucket {0}'.format(bucket)\n summary += '... | <|body_start_0|>
output = ''
summary = ''
logic = True
for bucket in list(result.keys()):
summary += '\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
output += '\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
output += '\n... | Class containing methods to help analyze results for data analysis | DataAnalysisResultAnalyzer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataAnalysisResultAnalyzer:
"""Class containing methods to help analyze results for data analysis"""
def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False):
"""Method to Generate & analyze result AND output the logical and analysis result This ... | stack_v2_sparse_classes_75kplus_train_009499 | 48,606 | permissive | [
{
"docstring": "Method to Generate & analyze result AND output the logical and analysis result This works on a bucket level only since we have already taken a union for all nodes",
"name": "analyze_all_result",
"signature": "def analyze_all_result(self, result, deletedItems=False, addedItems=False, upda... | 3 | stack_v2_sparse_classes_30k_train_007654 | Implement the Python class `DataAnalysisResultAnalyzer` described below.
Class description:
Class containing methods to help analyze results for data analysis
Method signatures and docstrings:
- def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): Method to Generate & analyz... | Implement the Python class `DataAnalysisResultAnalyzer` described below.
Class description:
Class containing methods to help analyze results for data analysis
Method signatures and docstrings:
- def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): Method to Generate & analyz... | 9d8220a0925327bddf0e10887e22b57c5d6adb37 | <|skeleton|>
class DataAnalysisResultAnalyzer:
"""Class containing methods to help analyze results for data analysis"""
def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False):
"""Method to Generate & analyze result AND output the logical and analysis result This ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataAnalysisResultAnalyzer:
"""Class containing methods to help analyze results for data analysis"""
def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False):
"""Method to Generate & analyze result AND output the logical and analysis result This works on a bu... | the_stack_v2_python_sparse | lib/couchbase_helper/data_analysis_helper.py | couchbase/testrunner | train | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.