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
96256c6313535fe999db544fc520cc470bfe1edf
[ "if 'scannerSessionDir' in scannerSettings.allSettings:\n self.sessionDir = scannerSettings.allSettings['scannerSessionDir']\nelse:\n print('No scannerSessionDir found in scannerConfig file')\n sys.exit()", "if self.sessionDir is None:\n self.findSessionDir()\nprint('Session Dir: ')\nprint('{}'.format...
<|body_start_0|> if 'scannerSessionDir' in scannerSettings.allSettings: self.sessionDir = scannerSettings.allSettings['scannerSessionDir'] else: print('No scannerSessionDir found in scannerConfig file') sys.exit() <|end_body_0|> <|body_start_1|> if self.sessi...
Finding the names and paths of series directories in a Siemens scanning environment. In Siemens environments, using the ideacmdtool, the scanner is set up to export data in real-time to a shared directory that is accessible from a remote workstation (running Pyneal Scanner). For functional data, Siemens scanners store ...
Siemens_DirStructure
[ "MIT", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Siemens_DirStructure: """Finding the names and paths of series directories in a Siemens scanning environment. In Siemens environments, using the ideacmdtool, the scanner is set up to export data in real-time to a shared directory that is accessible from a remote workstation (running Pyneal Scanne...
stack_v2_sparse_classes_75kplus_train_071800
30,222
permissive
[ { "docstring": "Initialize the class Parameters ---------- scannerSettings : object class attributes represent all of the settings unique to the current scanning environment (many of them read from `scannerConfig.yaml`) See Also -------- general_utils.ScannerSettings", "name": "__init__", "signature": "...
4
null
Implement the Python class `Siemens_DirStructure` described below. Class description: Finding the names and paths of series directories in a Siemens scanning environment. In Siemens environments, using the ideacmdtool, the scanner is set up to export data in real-time to a shared directory that is accessible from a re...
Implement the Python class `Siemens_DirStructure` described below. Class description: Finding the names and paths of series directories in a Siemens scanning environment. In Siemens environments, using the ideacmdtool, the scanner is set up to export data in real-time to a shared directory that is accessible from a re...
750f0ec5a231ccfa77aea960242de9b5019ba493
<|skeleton|> class Siemens_DirStructure: """Finding the names and paths of series directories in a Siemens scanning environment. In Siemens environments, using the ideacmdtool, the scanner is set up to export data in real-time to a shared directory that is accessible from a remote workstation (running Pyneal Scanne...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Siemens_DirStructure: """Finding the names and paths of series directories in a Siemens scanning environment. In Siemens environments, using the ideacmdtool, the scanner is set up to export data in real-time to a shared directory that is accessible from a remote workstation (running Pyneal Scanner). For funct...
the_stack_v2_python_sparse
pyneal_scanner/utils/Siemens_utils.py
jeffmacinnes/pyneal
train
36
0010f8d914ccbf9b6f37a4eefa8f563159bc7b2c
[ "Frame.__init__(self, master)\nself.pack()\nself.createArtistWidgets()", "Album_Cover_Frame = Frame(self)\nself.labelInputAlbumCover = Label(Album_Cover_Frame, text='Get Album Cover Name')\nself.labelResult = Label(Album_Cover_Frame, text='Album Cover Result')\nself.text_in_Album_Cover = Entry(Album_Cover_Frame)\...
<|body_start_0|> Frame.__init__(self, master) self.pack() self.createArtistWidgets() <|end_body_0|> <|body_start_1|> Album_Cover_Frame = Frame(self) self.labelInputAlbumCover = Label(Album_Cover_Frame, text='Get Album Cover Name') self.labelResult = Label(Album_Cover_Fra...
Application main window class.
Application
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Application: """Application main window class.""" def __init__(self, master=None): """Main frame initialization (mostly delegated)""" <|body_0|> def createArtistWidgets(self): """Add all the widgets to the main frame.""" <|body_1|> def handle(self): ...
stack_v2_sparse_classes_75kplus_train_071801
1,963
no_license
[ { "docstring": "Main frame initialization (mostly delegated)", "name": "__init__", "signature": "def __init__(self, master=None)" }, { "docstring": "Add all the widgets to the main frame.", "name": "createArtistWidgets", "signature": "def createArtistWidgets(self)" }, { "docstrin...
3
stack_v2_sparse_classes_30k_train_023306
Implement the Python class `Application` described below. Class description: Application main window class. Method signatures and docstrings: - def __init__(self, master=None): Main frame initialization (mostly delegated) - def createArtistWidgets(self): Add all the widgets to the main frame. - def handle(self): Hand...
Implement the Python class `Application` described below. Class description: Application main window class. Method signatures and docstrings: - def __init__(self, master=None): Main frame initialization (mostly delegated) - def createArtistWidgets(self): Add all the widgets to the main frame. - def handle(self): Hand...
2dba11861f91e4bdc1ef28279132a6d8dd4ccf54
<|skeleton|> class Application: """Application main window class.""" def __init__(self, master=None): """Main frame initialization (mostly delegated)""" <|body_0|> def createArtistWidgets(self): """Add all the widgets to the main frame.""" <|body_1|> def handle(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Application: """Application main window class.""" def __init__(self, master=None): """Main frame initialization (mostly delegated)""" Frame.__init__(self, master) self.pack() self.createArtistWidgets() def createArtistWidgets(self): """Add all the widgets to t...
the_stack_v2_python_sparse
Mux_Gui/Get_Album_Cover_Gui.py
rduvalwa5/Mux
train
0
a882fa8a40c0ccfb6f84b73582bf3cc90d9e8bee
[ "Graph.__init__(self, n, nodeData)\nself._adjMatrix = []\nrow = [None] * n\nfor i in range(n):\n self._adjMatrix.append(row[:])", "if node1 < self._numVerts and node2 < self._numVerts:\n self._adjMatrix[node1][node2] = True\n self._adjMatrix[node2][node1] = True\n return True\nelif node1 >= self._numV...
<|body_start_0|> Graph.__init__(self, n, nodeData) self._adjMatrix = [] row = [None] * n for i in range(n): self._adjMatrix.append(row[:]) <|end_body_0|> <|body_start_1|> if node1 < self._numVerts and node2 < self._numVerts: self._adjMatrix[node1][node2] ...
A graph contains vertices and edges: This implementation uses an adjacency matrix to represent edges.
MatrixGraph
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MatrixGraph: """A graph contains vertices and edges: This implementation uses an adjacency matrix to represent edges.""" def __init__(self, n, nodeData=[]): """Takes the number of nodes in the graph, and optionally a list of data to associate with each node. The data is assigned to n...
stack_v2_sparse_classes_75kplus_train_071802
16,606
no_license
[ { "docstring": "Takes the number of nodes in the graph, and optionally a list of data to associate with each node. The data is assigned to nodes in numeric order, starting with node 0. The edge information is represented using an adjacency matrix. This is initialized, but contains no edges; edges must be added ...
5
stack_v2_sparse_classes_30k_train_017389
Implement the Python class `MatrixGraph` described below. Class description: A graph contains vertices and edges: This implementation uses an adjacency matrix to represent edges. Method signatures and docstrings: - def __init__(self, n, nodeData=[]): Takes the number of nodes in the graph, and optionally a list of da...
Implement the Python class `MatrixGraph` described below. Class description: A graph contains vertices and edges: This implementation uses an adjacency matrix to represent edges. Method signatures and docstrings: - def __init__(self, n, nodeData=[]): Takes the number of nodes in the graph, and optionally a list of da...
97bb378a325b1639110de06b88d6e237dffc7330
<|skeleton|> class MatrixGraph: """A graph contains vertices and edges: This implementation uses an adjacency matrix to represent edges.""" def __init__(self, n, nodeData=[]): """Takes the number of nodes in the graph, and optionally a list of data to associate with each node. The data is assigned to n...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MatrixGraph: """A graph contains vertices and edges: This implementation uses an adjacency matrix to represent edges.""" def __init__(self, n, nodeData=[]): """Takes the number of nodes in the graph, and optionally a list of data to associate with each node. The data is assigned to nodes in numer...
the_stack_v2_python_sparse
backups/speedy_nav-2/scripts/Graphs.py
FoxRobotLab/catkin_ws
train
6
83600cc91e7b63d81b341cee88a7aeb8c2d577f5
[ "if not root:\n return True\n\ndef recursive(l, r):\n if not l and (not r):\n return True\n elif l and r:\n return l.val == r.val and recursive(l.left, r.right) and recursive(l.right, r.left)\n else:\n return False\nreturn recursive(root.left, root.right)", "if not root:\n retu...
<|body_start_0|> if not root: return True def recursive(l, r): if not l and (not r): return True elif l and r: return l.val == r.val and recursive(l.left, r.right) and recursive(l.right, r.left) else: return...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: return True ...
stack_v2_sparse_classes_75kplus_train_071803
1,394
no_license
[ { "docstring": ":type root: TreeNode :rtype: bool", "name": "isSymmetric", "signature": "def isSymmetric(self, root)" }, { "docstring": ":type root: TreeNode :rtype: bool", "name": "isSymmetric", "signature": "def isSymmetric(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_045258
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSymmetric(self, root): :type root: TreeNode :rtype: bool - def isSymmetric(self, root): :type root: TreeNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSymmetric(self, root): :type root: TreeNode :rtype: bool - def isSymmetric(self, root): :type root: TreeNode :rtype: bool <|skeleton|> class Solution: def isSymmetric...
63b7eedc720c1ce14880b80744dcd5ef7107065c
<|skeleton|> class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" if not root: return True def recursive(l, r): if not l and (not r): return True elif l and r: return l.val == r.val and recursive(l.left, ...
the_stack_v2_python_sparse
problems/isSymmetric.py
joddiy/leetcode
train
1
9c92fbd9297794a203831d22c596a06ad3f1623d
[ "Presentation.__init__(self, pere, detail, attribut, False)\nif pere and detail:\n self.construire(detail)", "detail = self.objet\nsalle = detail.parent\nnouveau_nom = supprimer_accents(arguments)\nif not nouveau_nom:\n self.pere << '|err|Vous devez indiquer un nouveau nom.|ff|'\n return\nif nouveau_nom ...
<|body_start_0|> Presentation.__init__(self, pere, detail, attribut, False) if pere and detail: self.construire(detail) <|end_body_0|> <|body_start_1|> detail = self.objet salle = detail.parent nouveau_nom = supprimer_accents(arguments) if not nouveau_nom: ...
Ce contexte permet d'éditer un detail observable d'une salle.
EdtDetail
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EdtDetail: """Ce contexte permet d'éditer un detail observable d'une salle.""" def __init__(self, pere, detail=None, attribut=None): """Constructeur de l'éditeur""" <|body_0|> def opt_renommer_detail(self, arguments): """Renomme le détail courant. Syntaxe : /n <n...
stack_v2_sparse_classes_75kplus_train_071804
7,487
permissive
[ { "docstring": "Constructeur de l'éditeur", "name": "__init__", "signature": "def __init__(self, pere, detail=None, attribut=None)" }, { "docstring": "Renomme le détail courant. Syntaxe : /n <nouveau nom>", "name": "opt_renommer_detail", "signature": "def opt_renommer_detail(self, argume...
4
stack_v2_sparse_classes_30k_train_038086
Implement the Python class `EdtDetail` described below. Class description: Ce contexte permet d'éditer un detail observable d'une salle. Method signatures and docstrings: - def __init__(self, pere, detail=None, attribut=None): Constructeur de l'éditeur - def opt_renommer_detail(self, arguments): Renomme le détail cou...
Implement the Python class `EdtDetail` described below. Class description: Ce contexte permet d'éditer un detail observable d'une salle. Method signatures and docstrings: - def __init__(self, pere, detail=None, attribut=None): Constructeur de l'éditeur - def opt_renommer_detail(self, arguments): Renomme le détail cou...
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class EdtDetail: """Ce contexte permet d'éditer un detail observable d'une salle.""" def __init__(self, pere, detail=None, attribut=None): """Constructeur de l'éditeur""" <|body_0|> def opt_renommer_detail(self, arguments): """Renomme le détail courant. Syntaxe : /n <n...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EdtDetail: """Ce contexte permet d'éditer un detail observable d'une salle.""" def __init__(self, pere, detail=None, attribut=None): """Constructeur de l'éditeur""" Presentation.__init__(self, pere, detail, attribut, False) if pere and detail: self.construire(detail) ...
the_stack_v2_python_sparse
src/primaires/salle/editeurs/redit/edt_detail.py
vincent-lg/tsunami
train
5
c43098e360efe030c96e00170f5b328229875bdf
[ "self.username = username\nself.password = md5(password.encode('utf-8')).hexdigest()\nself.base_params = {'user': self.username, 'pass2': self.password, 'softid': '895210'}\nself.headers = {'Connection': 'Keep-Alive', 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)'}", "params = {'c...
<|body_start_0|> self.username = username self.password = md5(password.encode('utf-8')).hexdigest() self.base_params = {'user': self.username, 'pass2': self.password, 'softid': '895210'} self.headers = {'Connection': 'Keep-Alive', 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows...
GtClickShot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GtClickShot: def __init__(self, username, password): """初始化超级鹰 softid已固化到程序 args: username(str):超级鹰普通用户名 password(str):超级鹰密码""" <|body_0|> def PostPic(self, im, codetype): """发送图片至打码平台 args: im(Byte): 图片字节 codetype(str): 题目类型 参考 http://www.chaojiying.com/price.html r...
stack_v2_sparse_classes_75kplus_train_071805
26,194
no_license
[ { "docstring": "初始化超级鹰 softid已固化到程序 args: username(str):超级鹰普通用户名 password(str):超级鹰密码", "name": "__init__", "signature": "def __init__(self, username, password)" }, { "docstring": "发送图片至打码平台 args: im(Byte): 图片字节 codetype(str): 题目类型 参考 http://www.chaojiying.com/price.html return(json):返回打码信息,包含坐标信...
3
stack_v2_sparse_classes_30k_train_027487
Implement the Python class `GtClickShot` described below. Class description: Implement the GtClickShot class. Method signatures and docstrings: - def __init__(self, username, password): 初始化超级鹰 softid已固化到程序 args: username(str):超级鹰普通用户名 password(str):超级鹰密码 - def PostPic(self, im, codetype): 发送图片至打码平台 args: im(Byte): 图片...
Implement the Python class `GtClickShot` described below. Class description: Implement the GtClickShot class. Method signatures and docstrings: - def __init__(self, username, password): 初始化超级鹰 softid已固化到程序 args: username(str):超级鹰普通用户名 password(str):超级鹰密码 - def PostPic(self, im, codetype): 发送图片至打码平台 args: im(Byte): 图片...
dc9dbbb5bf5e3d29cd664219826ca334916b953f
<|skeleton|> class GtClickShot: def __init__(self, username, password): """初始化超级鹰 softid已固化到程序 args: username(str):超级鹰普通用户名 password(str):超级鹰密码""" <|body_0|> def PostPic(self, im, codetype): """发送图片至打码平台 args: im(Byte): 图片字节 codetype(str): 题目类型 参考 http://www.chaojiying.com/price.html r...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GtClickShot: def __init__(self, username, password): """初始化超级鹰 softid已固化到程序 args: username(str):超级鹰普通用户名 password(str):超级鹰密码""" self.username = username self.password = md5(password.encode('utf-8')).hexdigest() self.base_params = {'user': self.username, 'pass2': self.password, ...
the_stack_v2_python_sparse
skill/crawler_gov.py
mj3428/python_for_practice
train
1
36d80e990968519d7bcb23a1410b4e3f6210bf11
[ "super(LSTMEvolutionSequence, self).__init__(builder, state_size, init_states=init_states, num_inputs=num_inputs, name=name, mode=mode)\nself.init_inode, self.init_hidden_state = (init_states[0], init_states[1])\nbuilder.addDirectedLink(self.init_inode, self, islot=0)\nbuilder.addDirectedLink(self.init_hidden_state...
<|body_start_0|> super(LSTMEvolutionSequence, self).__init__(builder, state_size, init_states=init_states, num_inputs=num_inputs, name=name, mode=mode) self.init_inode, self.init_hidden_state = (init_states[0], init_states[1]) builder.addDirectedLink(self.init_inode, self, islot=0) build...
LSTMEvolutionSequence
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSTMEvolutionSequence: def __init__(self, builder, state_size, init_states, num_inputs=3, name=None, mode='forward', **dirs): """Initialize the LSTMEvolutionSequence""" <|body_0|> def _update_default_directives(self, **dirs): """Update the default directives""" ...
stack_v2_sparse_classes_75kplus_train_071806
10,836
no_license
[ { "docstring": "Initialize the LSTMEvolutionSequence", "name": "__init__", "signature": "def __init__(self, builder, state_size, init_states, num_inputs=3, name=None, mode='forward', **dirs)" }, { "docstring": "Update the default directives", "name": "_update_default_directives", "signat...
3
stack_v2_sparse_classes_30k_train_026330
Implement the Python class `LSTMEvolutionSequence` described below. Class description: Implement the LSTMEvolutionSequence class. Method signatures and docstrings: - def __init__(self, builder, state_size, init_states, num_inputs=3, name=None, mode='forward', **dirs): Initialize the LSTMEvolutionSequence - def _updat...
Implement the Python class `LSTMEvolutionSequence` described below. Class description: Implement the LSTMEvolutionSequence class. Method signatures and docstrings: - def __init__(self, builder, state_size, init_states, num_inputs=3, name=None, mode='forward', **dirs): Initialize the LSTMEvolutionSequence - def _updat...
0fe8b6be763ff22e1f301a06d076347e3997224a
<|skeleton|> class LSTMEvolutionSequence: def __init__(self, builder, state_size, init_states, num_inputs=3, name=None, mode='forward', **dirs): """Initialize the LSTMEvolutionSequence""" <|body_0|> def _update_default_directives(self, **dirs): """Update the default directives""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LSTMEvolutionSequence: def __init__(self, builder, state_size, init_states, num_inputs=3, name=None, mode='forward', **dirs): """Initialize the LSTMEvolutionSequence""" super(LSTMEvolutionSequence, self).__init__(builder, state_size, init_states=init_states, num_inputs=num_inputs, name=name, m...
the_stack_v2_python_sparse
neurolib/encoder/sequence.py
dhernandd/_neurolib
train
0
0e9e4c12f04365116929e4b34e34f80e6ff9d198
[ "self.resource_group = resource_group\nself.storage_account = storage_account\nself.storage_container = storage_container\nself.storage_resource_group = storage_resource_group", "if dictionary is None:\n return None\nresource_group = cohesity_management_sdk.models.entity_proto.EntityProto.from_dictionary(dicti...
<|body_start_0|> self.resource_group = resource_group self.storage_account = storage_account self.storage_container = storage_container self.storage_resource_group = storage_resource_group <|end_body_0|> <|body_start_1|> if dictionary is None: return None res...
Implementation of the 'ReplicateSnapshotsToAzureParams' model. This is populated for Azure snapshot manager replication. Attributes: resource_group (EntityProto): Resource group to filter regions in UX. storage_account (EntityProto): Name of the storage account that will contain the storage container within which we wi...
ReplicateSnapshotsToAzureParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReplicateSnapshotsToAzureParams: """Implementation of the 'ReplicateSnapshotsToAzureParams' model. This is populated for Azure snapshot manager replication. Attributes: resource_group (EntityProto): Resource group to filter regions in UX. storage_account (EntityProto): Name of the storage account...
stack_v2_sparse_classes_75kplus_train_071807
3,133
permissive
[ { "docstring": "Constructor for the ReplicateSnapshotsToAzureParams class", "name": "__init__", "signature": "def __init__(self, resource_group=None, storage_account=None, storage_container=None, storage_resource_group=None)" }, { "docstring": "Creates an instance of this model from a dictionary...
2
stack_v2_sparse_classes_30k_train_028487
Implement the Python class `ReplicateSnapshotsToAzureParams` described below. Class description: Implementation of the 'ReplicateSnapshotsToAzureParams' model. This is populated for Azure snapshot manager replication. Attributes: resource_group (EntityProto): Resource group to filter regions in UX. storage_account (En...
Implement the Python class `ReplicateSnapshotsToAzureParams` described below. Class description: Implementation of the 'ReplicateSnapshotsToAzureParams' model. This is populated for Azure snapshot manager replication. Attributes: resource_group (EntityProto): Resource group to filter regions in UX. storage_account (En...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ReplicateSnapshotsToAzureParams: """Implementation of the 'ReplicateSnapshotsToAzureParams' model. This is populated for Azure snapshot manager replication. Attributes: resource_group (EntityProto): Resource group to filter regions in UX. storage_account (EntityProto): Name of the storage account...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReplicateSnapshotsToAzureParams: """Implementation of the 'ReplicateSnapshotsToAzureParams' model. This is populated for Azure snapshot manager replication. Attributes: resource_group (EntityProto): Resource group to filter regions in UX. storage_account (EntityProto): Name of the storage account that will co...
the_stack_v2_python_sparse
cohesity_management_sdk/models/replicate_snapshots_to_azure_params.py
cohesity/management-sdk-python
train
24
afafaf9b7a3f6c1ee49d2ce0c3913d2c06766e4f
[ "super(Attention, self).__init__()\nself.e = nn.Linear(n_hidden_enc * 2 + n_hidden_dec, n_hidden_dec)\nself.v = nn.Linear(n_hidden_dec, 1, bias=False)", "hidden = h.unsqueeze(1).repeat(1, o.shape[0], 1)\nencoder_outputs = o.permute(1, 0, 2)\nenergy = torch.tanh(self.e(torch.cat((hidden, encoder_outputs), dim=2)))...
<|body_start_0|> super(Attention, self).__init__() self.e = nn.Linear(n_hidden_enc * 2 + n_hidden_dec, n_hidden_dec) self.v = nn.Linear(n_hidden_dec, 1, bias=False) <|end_body_0|> <|body_start_1|> hidden = h.unsqueeze(1).repeat(1, o.shape[0], 1) encoder_outputs = o.permute(1, 0,...
An Attention class is used to provide attention-based mechanisms in a neural network layer. References: D. Bahdanau, K. Cho, Y. Bengio. Neural machine translation by jointly learning to align and translate. Preprint arXiv:1409.0473 (2014).
Attention
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Attention: """An Attention class is used to provide attention-based mechanisms in a neural network layer. References: D. Bahdanau, K. Cho, Y. Bengio. Neural machine translation by jointly learning to align and translate. Preprint arXiv:1409.0473 (2014).""" def __init__(self, n_hidden_enc, n_...
stack_v2_sparse_classes_75kplus_train_071808
1,748
permissive
[ { "docstring": "Initialization method. Args: n_hidden_enc (int): Number of hidden units in the Encoder. n_hidden_dec (int): Number of hidden units in the Decoder.", "name": "__init__", "signature": "def __init__(self, n_hidden_enc, n_hidden_dec)" }, { "docstring": "Performs a forward pass over t...
2
stack_v2_sparse_classes_30k_train_041144
Implement the Python class `Attention` described below. Class description: An Attention class is used to provide attention-based mechanisms in a neural network layer. References: D. Bahdanau, K. Cho, Y. Bengio. Neural machine translation by jointly learning to align and translate. Preprint arXiv:1409.0473 (2014). Met...
Implement the Python class `Attention` described below. Class description: An Attention class is used to provide attention-based mechanisms in a neural network layer. References: D. Bahdanau, K. Cho, Y. Bengio. Neural machine translation by jointly learning to align and translate. Preprint arXiv:1409.0473 (2014). Met...
cccc670d48995fa0bfbdf9fc8013d13a90ea5e84
<|skeleton|> class Attention: """An Attention class is used to provide attention-based mechanisms in a neural network layer. References: D. Bahdanau, K. Cho, Y. Bengio. Neural machine translation by jointly learning to align and translate. Preprint arXiv:1409.0473 (2014).""" def __init__(self, n_hidden_enc, n_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Attention: """An Attention class is used to provide attention-based mechanisms in a neural network layer. References: D. Bahdanau, K. Cho, Y. Bengio. Neural machine translation by jointly learning to align and translate. Preprint arXiv:1409.0473 (2014).""" def __init__(self, n_hidden_enc, n_hidden_dec): ...
the_stack_v2_python_sparse
textformer/models/layers/attention.py
gugarosa/textformer
train
3
aeca4e325ffb2dba641107fa5ee94232d1d0690a
[ "url = 'http://web.ornl.gov/sci/landscan/' + 'landscan2011/LS11sample_Cyprus.zip'\nzip_dir = os.path.join(self.tmp_dir, 'landscan.zip')\nurlretrieve(url, zip_dir)\nzip_ref = zipfile.ZipFile(zip_dir, 'r')\nlandscan_dir = os.path.join(self.tmp_dir, 'landscan')\nzip_ref.extractall(landscan_dir)\nzip_ref.close()\nretur...
<|body_start_0|> url = 'http://web.ornl.gov/sci/landscan/' + 'landscan2011/LS11sample_Cyprus.zip' zip_dir = os.path.join(self.tmp_dir, 'landscan.zip') urlretrieve(url, zip_dir) zip_ref = zipfile.ZipFile(zip_dir, 'r') landscan_dir = os.path.join(self.tmp_dir, 'landscan') z...
Class for processing sample Landscan data
LandscanProcessor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LandscanProcessor: """Class for processing sample Landscan data""" def get_landscan(self): """Downloads the sample landscan image for Cyprus""" <|body_0|> def convert_landscan(self, landscan_dir): """Converts arcgrid into a tiff file""" <|body_1|> de...
stack_v2_sparse_classes_75kplus_train_071809
3,635
permissive
[ { "docstring": "Downloads the sample landscan image for Cyprus", "name": "get_landscan", "signature": "def get_landscan(self)" }, { "docstring": "Converts arcgrid into a tiff file", "name": "convert_landscan", "signature": "def convert_landscan(self, landscan_dir)" }, { "docstrin...
4
null
Implement the Python class `LandscanProcessor` described below. Class description: Class for processing sample Landscan data Method signatures and docstrings: - def get_landscan(self): Downloads the sample landscan image for Cyprus - def convert_landscan(self, landscan_dir): Converts arcgrid into a tiff file - def im...
Implement the Python class `LandscanProcessor` described below. Class description: Class for processing sample Landscan data Method signatures and docstrings: - def get_landscan(self): Downloads the sample landscan image for Cyprus - def convert_landscan(self, landscan_dir): Converts arcgrid into a tiff file - def im...
9b938f3c2f2b15b75c149f8dd06083f2d888f77d
<|skeleton|> class LandscanProcessor: """Class for processing sample Landscan data""" def get_landscan(self): """Downloads the sample landscan image for Cyprus""" <|body_0|> def convert_landscan(self, landscan_dir): """Converts arcgrid into a tiff file""" <|body_1|> de...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LandscanProcessor: """Class for processing sample Landscan data""" def get_landscan(self): """Downloads the sample landscan image for Cyprus""" url = 'http://web.ornl.gov/sci/landscan/' + 'landscan2011/LS11sample_Cyprus.zip' zip_dir = os.path.join(self.tmp_dir, 'landscan.zip') ...
the_stack_v2_python_sparse
dataqs/landscan/landscan.py
dorukozturk/dataqs
train
1
f3c3bcb01f2dbd3316d0cc48eed846e1b6da41bc
[ "while N:\n if self.isMonotone(N):\n return N\n else:\n N -= 1", "pre_digit = num % 10\nnum = num / 10\nwhile num:\n digit = num % 10\n if digit > pre_digit:\n return False\n num /= 10\n pre_digit = digit\nreturn True" ]
<|body_start_0|> while N: if self.isMonotone(N): return N else: N -= 1 <|end_body_0|> <|body_start_1|> pre_digit = num % 10 num = num / 10 while num: digit = num % 10 if digit > pre_digit: re...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def monotoneIncreasingDigits(self, N): """:type N: int :rtype: int""" <|body_0|> def isMonotone(self, num): """:type num: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> while N: if self.isMonotone(N): ...
stack_v2_sparse_classes_75kplus_train_071810
733
no_license
[ { "docstring": ":type N: int :rtype: int", "name": "monotoneIncreasingDigits", "signature": "def monotoneIncreasingDigits(self, N)" }, { "docstring": ":type num: int :rtype: bool", "name": "isMonotone", "signature": "def isMonotone(self, num)" } ]
2
stack_v2_sparse_classes_30k_train_039179
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def monotoneIncreasingDigits(self, N): :type N: int :rtype: int - def isMonotone(self, num): :type num: int :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def monotoneIncreasingDigits(self, N): :type N: int :rtype: int - def isMonotone(self, num): :type num: int :rtype: bool <|skeleton|> class Solution: def monotoneIncreasing...
f93380721b8383817fe2b0d728deca1321c9ef45
<|skeleton|> class Solution: def monotoneIncreasingDigits(self, N): """:type N: int :rtype: int""" <|body_0|> def isMonotone(self, num): """:type num: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def monotoneIncreasingDigits(self, N): """:type N: int :rtype: int""" while N: if self.isMonotone(N): return N else: N -= 1 def isMonotone(self, num): """:type num: int :rtype: bool""" pre_digit = num % 10 ...
the_stack_v2_python_sparse
problems/0738.0_Monotone_Increasing_Digits.py
lixiang2017/leetcode
train
5
14fd75d115a16cf9c84127e66b755a3686f0939c
[ "if not os.path.isdir(path + 'univariate_timeseries'):\n print('Creating univariate_timeseries Directory')\n os.mkdir(path + 'univariate_timeseries')\nif not os.path.exists(path + 'univariate_timeseries/Univariate2018_arff.zip'):\n td = time.time()\n print('Creating univariate timeseries')\n url = 'h...
<|body_start_0|> if not os.path.isdir(path + 'univariate_timeseries'): print('Creating univariate_timeseries Directory') os.mkdir(path + 'univariate_timeseries') if not os.path.exists(path + 'univariate_timeseries/Univariate2018_arff.zip'): td = time.time() ...
univariate_timeseries
univariate_timeseries
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class univariate_timeseries: """univariate_timeseries""" def download(path): """Download the univariate_timeseries dataset path Parameters ---------- path: str the path where the downloaded files will be stored. If the directory does not exist, it is created.""" <|body_0|> def...
stack_v2_sparse_classes_75kplus_train_071811
2,541
permissive
[ { "docstring": "Download the univariate_timeseries dataset path Parameters ---------- path: str the path where the downloaded files will be stored. If the directory does not exist, it is created.", "name": "download", "signature": "def download(path)" }, { "docstring": "Parameters ---------- pat...
2
null
Implement the Python class `univariate_timeseries` described below. Class description: univariate_timeseries Method signatures and docstrings: - def download(path): Download the univariate_timeseries dataset path Parameters ---------- path: str the path where the downloaded files will be stored. If the directory does...
Implement the Python class `univariate_timeseries` described below. Class description: univariate_timeseries Method signatures and docstrings: - def download(path): Download the univariate_timeseries dataset path Parameters ---------- path: str the path where the downloaded files will be stored. If the directory does...
d8778c2eb3254b478cef4f45d934bf921e695619
<|skeleton|> class univariate_timeseries: """univariate_timeseries""" def download(path): """Download the univariate_timeseries dataset path Parameters ---------- path: str the path where the downloaded files will be stored. If the directory does not exist, it is created.""" <|body_0|> def...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class univariate_timeseries: """univariate_timeseries""" def download(path): """Download the univariate_timeseries dataset path Parameters ---------- path: str the path where the downloaded files will be stored. If the directory does not exist, it is created.""" if not os.path.isdir(path + 'uni...
the_stack_v2_python_sparse
symjax/data/univariate_timeseries.py
SymJAX/SymJAX
train
52
de13dacf90e4b5555d21cd0688e668da22e90a43
[ "self.max_depth = max_depth\nself.timesToRun = timesToRun\nself.limit = limit_time", "def evaluator(node):\n return node.path_cost + heuristic.evaluate(node.state)\n\ndef queue_generator():\n return PriorityQueue(evaluator)\nsearch = GraphSearch(queue_generator, self.limit, self.max_depth)\nstart = time.clo...
<|body_start_0|> self.max_depth = max_depth self.timesToRun = timesToRun self.limit = limit_time <|end_body_0|> <|body_start_1|> def evaluator(node): return node.path_cost + heuristic.evaluate(node.state) def queue_generator(): return PriorityQueue(evalu...
Implementation of the A* search algorithm for the Problem. It may also take a maximum depth at which to stop, if needed.
AStarAndGreedyHelp
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AStarAndGreedyHelp: """Implementation of the A* search algorithm for the Problem. It may also take a maximum depth at which to stop, if needed.""" def __init__(self, timesToRun=infinity, limit_time=infinity, max_depth=infinity): """Constructs the A* search. Optionally, a maximum dept...
stack_v2_sparse_classes_75kplus_train_071812
5,977
no_license
[ { "docstring": "Constructs the A* search. Optionally, a maximum depth may be provided at which to stop looking for the goal state.", "name": "__init__", "signature": "def __init__(self, timesToRun=infinity, limit_time=infinity, max_depth=infinity)" }, { "docstring": "A* search is best-first grap...
2
stack_v2_sparse_classes_30k_train_054099
Implement the Python class `AStarAndGreedyHelp` described below. Class description: Implementation of the A* search algorithm for the Problem. It may also take a maximum depth at which to stop, if needed. Method signatures and docstrings: - def __init__(self, timesToRun=infinity, limit_time=infinity, max_depth=infini...
Implement the Python class `AStarAndGreedyHelp` described below. Class description: Implementation of the A* search algorithm for the Problem. It may also take a maximum depth at which to stop, if needed. Method signatures and docstrings: - def __init__(self, timesToRun=infinity, limit_time=infinity, max_depth=infini...
656f76259e12c7303600671278a51e7b75a83770
<|skeleton|> class AStarAndGreedyHelp: """Implementation of the A* search algorithm for the Problem. It may also take a maximum depth at which to stop, if needed.""" def __init__(self, timesToRun=infinity, limit_time=infinity, max_depth=infinity): """Constructs the A* search. Optionally, a maximum dept...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AStarAndGreedyHelp: """Implementation of the A* search algorithm for the Problem. It may also take a maximum depth at which to stop, if needed.""" def __init__(self, timesToRun=infinity, limit_time=infinity, max_depth=infinity): """Constructs the A* search. Optionally, a maximum depth may be prov...
the_stack_v2_python_sparse
Artificial Intelligence/AI Multi Robot/Multi_robot/src/search/astar_and_greedy.py
saedmansour/University-Code
train
0
adf57788e58a7b728876a4017d7cc24de0c2c609
[ "logger.info('Add new directory to Datary.', path=os.path.join(path, dirname))\nurl = urljoin(self.URL_BASE, 'workdirs/{}/changes'.format(wdir_uuid))\npayload = {'action': 'add', 'filemode': 40000, 'dirname': path, 'basename': dirname}\nresponse = self.request(url, 'POST', **{'data': payload, 'headers': self.header...
<|body_start_0|> logger.info('Add new directory to Datary.', path=os.path.join(path, dirname)) url = urljoin(self.URL_BASE, 'workdirs/{}/changes'.format(wdir_uuid)) payload = {'action': 'add', 'filemode': 40000, 'dirname': path, 'basename': dirname} response = self.request(url, 'POST', *...
Datary AddOperation module class
DataryAddOperation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataryAddOperation: """Datary AddOperation module class""" def add_dir(self, wdir_uuid, path, dirname): """(DEPRECATED) Creates a new directory. ================ ============= ==================================== Parameter Type Description ================ ============= =============...
stack_v2_sparse_classes_75kplus_train_071813
3,778
permissive
[ { "docstring": "(DEPRECATED) Creates a new directory. ================ ============= ==================================== Parameter Type Description ================ ============= ==================================== wdir_uuid str working directory uuid path str path to the new directory dirname str name of the...
2
stack_v2_sparse_classes_30k_train_018111
Implement the Python class `DataryAddOperation` described below. Class description: Datary AddOperation module class Method signatures and docstrings: - def add_dir(self, wdir_uuid, path, dirname): (DEPRECATED) Creates a new directory. ================ ============= ==================================== Parameter Type...
Implement the Python class `DataryAddOperation` described below. Class description: Datary AddOperation module class Method signatures and docstrings: - def add_dir(self, wdir_uuid, path, dirname): (DEPRECATED) Creates a new directory. ================ ============= ==================================== Parameter Type...
2790a50e1ad262cbe3210665dc34f497625e923d
<|skeleton|> class DataryAddOperation: """Datary AddOperation module class""" def add_dir(self, wdir_uuid, path, dirname): """(DEPRECATED) Creates a new directory. ================ ============= ==================================== Parameter Type Description ================ ============= =============...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DataryAddOperation: """Datary AddOperation module class""" def add_dir(self, wdir_uuid, path, dirname): """(DEPRECATED) Creates a new directory. ================ ============= ==================================== Parameter Type Description ================ ============= ==========================...
the_stack_v2_python_sparse
datary/operations/add.py
Datary/python-sdk
train
0
12f1a10b58e738cf333837249ba81bb4dc30f4f0
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
AuthServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthServicer: def CreateDataset(self, request, context): """CreateDataset from a given Dataset wrapped in a CreateDatasetRequest""" <|body_0|> def SetPermission(self, request, context): """SetPermission sets a permission for a dataset using a SetPermissionRequest."""...
stack_v2_sparse_classes_75kplus_train_071814
16,615
permissive
[ { "docstring": "CreateDataset from a given Dataset wrapped in a CreateDatasetRequest", "name": "CreateDataset", "signature": "def CreateDataset(self, request, context)" }, { "docstring": "SetPermission sets a permission for a dataset using a SetPermissionRequest.", "name": "SetPermission", ...
5
stack_v2_sparse_classes_30k_train_017481
Implement the Python class `AuthServicer` described below. Class description: Implement the AuthServicer class. Method signatures and docstrings: - def CreateDataset(self, request, context): CreateDataset from a given Dataset wrapped in a CreateDatasetRequest - def SetPermission(self, request, context): SetPermission...
Implement the Python class `AuthServicer` described below. Class description: Implement the AuthServicer class. Method signatures and docstrings: - def CreateDataset(self, request, context): CreateDataset from a given Dataset wrapped in a CreateDatasetRequest - def SetPermission(self, request, context): SetPermission...
d93b5f66a00b1e3710257d607d62f9d43736304e
<|skeleton|> class AuthServicer: def CreateDataset(self, request, context): """CreateDataset from a given Dataset wrapped in a CreateDatasetRequest""" <|body_0|> def SetPermission(self, request, context): """SetPermission sets a permission for a dataset using a SetPermissionRequest."""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AuthServicer: def CreateDataset(self, request, context): """CreateDataset from a given Dataset wrapped in a CreateDatasetRequest""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!'...
the_stack_v2_python_sparse
CVP_API/Snapshot_Utils/getSnapshots_Resource_API/cloudvision-python/cloudvision/Connector/gen/router_pb2_grpc.py
Hugh-Adams/Example_Scripts
train
4
3151162f42ae7ddae2bbe036ac009894e81715dc
[ "if s[i] in self.required:\n self.required[s[i]] -= 1\n if self.required[s[i]] >= 0:\n self.requires -= 1", "if s[i] in self.required:\n self.required[s[i]] += 1\n if self.required[s[i]] > 0:\n self.requires += 1", "if not s or not t:\n return 0\nself.required.clear()\nself.requires...
<|body_start_0|> if s[i] in self.required: self.required[s[i]] -= 1 if self.required[s[i]] >= 0: self.requires -= 1 <|end_body_0|> <|body_start_1|> if s[i] in self.required: self.required[s[i]] += 1 if self.required[s[i]] > 0: ...
Solution2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution2: def add(self, s, i): """Add a character into the window""" <|body_0|> def remove(self, s, i): """Remove a character from the window""" <|body_1|> def minWindow(self, s, t): """:type s: str :type t: str :rtype: str""" <|body_2|>...
stack_v2_sparse_classes_75kplus_train_071815
3,732
no_license
[ { "docstring": "Add a character into the window", "name": "add", "signature": "def add(self, s, i)" }, { "docstring": "Remove a character from the window", "name": "remove", "signature": "def remove(self, s, i)" }, { "docstring": ":type s: str :type t: str :rtype: str", "name...
3
stack_v2_sparse_classes_30k_test_001549
Implement the Python class `Solution2` described below. Class description: Implement the Solution2 class. Method signatures and docstrings: - def add(self, s, i): Add a character into the window - def remove(self, s, i): Remove a character from the window - def minWindow(self, s, t): :type s: str :type t: str :rtype:...
Implement the Python class `Solution2` described below. Class description: Implement the Solution2 class. Method signatures and docstrings: - def add(self, s, i): Add a character into the window - def remove(self, s, i): Remove a character from the window - def minWindow(self, s, t): :type s: str :type t: str :rtype:...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Solution2: def add(self, s, i): """Add a character into the window""" <|body_0|> def remove(self, s, i): """Remove a character from the window""" <|body_1|> def minWindow(self, s, t): """:type s: str :type t: str :rtype: str""" <|body_2|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution2: def add(self, s, i): """Add a character into the window""" if s[i] in self.required: self.required[s[i]] -= 1 if self.required[s[i]] >= 0: self.requires -= 1 def remove(self, s, i): """Remove a character from the window""" ...
the_stack_v2_python_sparse
code76MinimumWindowSubstring.py
cybelewang/leetcode-python
train
0
12902aac3f09bed3547f4be6c5aef26623f1117b
[ "self.face_net = cv.dnn.readNet('FaceNet.prototxt', 'FaceNet.caffemodel')\nself.mask_net = load_model('mask_detector.model')\nself.confidence = confidence", "h, w = frame.shape[:2]\nblob = cv.dnn.blobFromImage(frame, 1.0, (235, 350))\nself.face_net.setInput(blob)\ndetections = self.face_net.forward()\nfaces = []\...
<|body_start_0|> self.face_net = cv.dnn.readNet('FaceNet.prototxt', 'FaceNet.caffemodel') self.mask_net = load_model('mask_detector.model') self.confidence = confidence <|end_body_0|> <|body_start_1|> h, w = frame.shape[:2] blob = cv.dnn.blobFromImage(frame, 1.0, (235, 350)) ...
Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network.
FaceAndMaskDetector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FaceAndMaskDetector: """Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network.""" def __init__(self, confidence: float): """Loads the face and mask models and sets the confidence level.""" <|body_0|> d...
stack_v2_sparse_classes_75kplus_train_071816
3,436
no_license
[ { "docstring": "Loads the face and mask models and sets the confidence level.", "name": "__init__", "signature": "def __init__(self, confidence: float)" }, { "docstring": "Gets the current frame and returns the predictions and their corresponding locations.", "name": "detect_and_predict", ...
2
stack_v2_sparse_classes_30k_train_038557
Implement the Python class `FaceAndMaskDetector` described below. Class description: Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network. Method signatures and docstrings: - def __init__(self, confidence: float): Loads the face and mask models an...
Implement the Python class `FaceAndMaskDetector` described below. Class description: Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network. Method signatures and docstrings: - def __init__(self, confidence: float): Loads the face and mask models an...
8ca1d270d2d382c48c138bb78e0ea7f8e04cffee
<|skeleton|> class FaceAndMaskDetector: """Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network.""" def __init__(self, confidence: float): """Loads the face and mask models and sets the confidence level.""" <|body_0|> d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FaceAndMaskDetector: """Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network.""" def __init__(self, confidence: float): """Loads the face and mask models and sets the confidence level.""" self.face_net = cv.dnn.readNet...
the_stack_v2_python_sparse
utils/face_and_mask_detector.py
rajatrawal/tiago-mask-checker
train
0
c678bf6e311c441d9545e094dd1cb14e85c4091c
[ "self.problem = problem\nself.pp = post.PostProcessor(dict(casedir='Results', clean_casedir=True))\nself.pp.add_field(post.SolutionField('Solution', dict(save=True, save_as=['hdf5', 'xdmf'], plot=True, plot_args=dict(range_min=float(u_min), range_max=float(u_max)))))\nself.pp.add_field(post.SolutionField('Flux', di...
<|body_start_0|> self.problem = problem self.pp = post.PostProcessor(dict(casedir='Results', clean_casedir=True)) self.pp.add_field(post.SolutionField('Solution', dict(save=True, save_as=['hdf5', 'xdmf'], plot=True, plot_args=dict(range_min=float(u_min), range_max=float(u_max))))) self.p...
user_action function for storing the solution and flux.
ProcessSolution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProcessSolution: """user_action function for storing the solution and flux.""" def __init__(self, problem, u_min=0, u_max=1): """Define fields to be stored/plotted.""" <|body_0|> def __call__(self, t, u, timestep): """Store u and its flux to file.""" <|bo...
stack_v2_sparse_classes_75kplus_train_071817
19,607
no_license
[ { "docstring": "Define fields to be stored/plotted.", "name": "__init__", "signature": "def __init__(self, problem, u_min=0, u_max=1)" }, { "docstring": "Store u and its flux to file.", "name": "__call__", "signature": "def __call__(self, t, u, timestep)" } ]
2
stack_v2_sparse_classes_30k_train_044939
Implement the Python class `ProcessSolution` described below. Class description: user_action function for storing the solution and flux. Method signatures and docstrings: - def __init__(self, problem, u_min=0, u_max=1): Define fields to be stored/plotted. - def __call__(self, t, u, timestep): Store u and its flux to ...
Implement the Python class `ProcessSolution` described below. Class description: user_action function for storing the solution and flux. Method signatures and docstrings: - def __init__(self, problem, u_min=0, u_max=1): Define fields to be stored/plotted. - def __call__(self, t, u, timestep): Store u and its flux to ...
5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95
<|skeleton|> class ProcessSolution: """user_action function for storing the solution and flux.""" def __init__(self, problem, u_min=0, u_max=1): """Define fields to be stored/plotted.""" <|body_0|> def __call__(self, t, u, timestep): """Store u and its flux to file.""" <|bo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProcessSolution: """user_action function for storing the solution and flux.""" def __init__(self, problem, u_min=0, u_max=1): """Define fields to be stored/plotted.""" self.problem = problem self.pp = post.PostProcessor(dict(casedir='Results', clean_casedir=True)) self.pp....
the_stack_v2_python_sparse
Solving_PDEs_in_Python_Langtangen/src/src/heat_class.py
burakbayramli/books
train
223
a52aab58d71f16daf3a946b0ef0b0fb7583617d7
[ "self.count, self.result = (0, 0)\ntry:\n self.get_kth_smallest(root, k)\nexcept:\n return self.result", "if root:\n self.get_kth_smallest(root.left, k)\n self.count += 1\n if self.count == k:\n self.result = root.key\n raise Exception()\n self.get_kth_smallest(root.right, k)" ]
<|body_start_0|> self.count, self.result = (0, 0) try: self.get_kth_smallest(root, k) except: return self.result <|end_body_0|> <|body_start_1|> if root: self.get_kth_smallest(root.left, k) self.count += 1 if self.count == k: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def kth_smallest(self, root: TreeNode, k: int) -> int: """Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space: O(H) :return: value of kth smallest node""" <|body_0|> def get_kth_smallest(self, r...
stack_v2_sparse_classes_75kplus_train_071818
2,127
no_license
[ { "docstring": "Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space: O(H) :return: value of kth smallest node", "name": "kth_smallest", "signature": "def kth_smallest(self, root: TreeNode, k: int) -> int" }, { "docstring": "A...
2
stack_v2_sparse_classes_30k_train_052149
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kth_smallest(self, root: TreeNode, k: int) -> int: Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kth_smallest(self, root: TreeNode, k: int) -> int: Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space:...
de685690745a5a322e6233e1a3fd10a2d9539076
<|skeleton|> class Solution: def kth_smallest(self, root: TreeNode, k: int) -> int: """Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space: O(H) :return: value of kth smallest node""" <|body_0|> def get_kth_smallest(self, r...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def kth_smallest(self, root: TreeNode, k: int) -> int: """Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space: O(H) :return: value of kth smallest node""" self.count, self.result = (0, 0) try: ...
the_stack_v2_python_sparse
questions/trees_graphs/BSTKthSmallest.py
aksh0001/algorithms-journal
train
17
90e3d66ea7b36248c213bcae2c8fd2a12a388b1c
[ "self.config = get_config()\nself.config[STATES_KEYWORD] = {'attrs': self.config[STATES_KEYWORD]['attrs'], 'subset': [0]}\nself.base_path = path_to_base_field\nif randomizer is not None:\n self.randomizer = {}\n for key, def_r in self.default_randomizer.items():\n if key not in randomizer.keys() or ran...
<|body_start_0|> self.config = get_config() self.config[STATES_KEYWORD] = {'attrs': self.config[STATES_KEYWORD]['attrs'], 'subset': [0]} self.base_path = path_to_base_field if randomizer is not None: self.randomizer = {} for key, def_r in self.default_randomizer.i...
Randomization of Fields, based on some base model.
FieldRandomizer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FieldRandomizer: """Randomization of Fields, based on some base model.""" def __init__(self, path_to_base_field, randomizer=None): """Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around. randomizer: dict Dict with instances of randomizers for...
stack_v2_sparse_classes_75kplus_train_071819
13,810
permissive
[ { "docstring": "Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around. randomizer: dict Dict with instances of randomizers for states, rock and control (wells) Should have keys the following form: randomizer = { 'states': states_rand, 'rock': rock_rand, 'wells': control_r...
4
stack_v2_sparse_classes_30k_train_035860
Implement the Python class `FieldRandomizer` described below. Class description: Randomization of Fields, based on some base model. Method signatures and docstrings: - def __init__(self, path_to_base_field, randomizer=None): Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around...
Implement the Python class `FieldRandomizer` described below. Class description: Randomization of Fields, based on some base model. Method signatures and docstrings: - def __init__(self, path_to_base_field, randomizer=None): Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around...
3b336ed110ff806316f1f6a99b212f99256a6b56
<|skeleton|> class FieldRandomizer: """Randomization of Fields, based on some base model.""" def __init__(self, path_to_base_field, randomizer=None): """Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around. randomizer: dict Dict with instances of randomizers for...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FieldRandomizer: """Randomization of Fields, based on some base model.""" def __init__(self, path_to_base_field, randomizer=None): """Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around. randomizer: dict Dict with instances of randomizers for states, rock...
the_stack_v2_python_sparse
deepfield/datasets/randomize.py
scuervo91/DeepField
train
0
fd8e2a7a758f8308cefd394c7ef1a3d62a97fc29
[ "regex = InvenTree.helpers.str2bool(request.query_params.get('search_regex', False))\nsearch_fields = super().get_search_fields(view, request)\nfields = []\nif search_fields:\n for field in search_fields:\n if regex:\n field = '$' + field\n fields.append(field)\nreturn fields", "whole ...
<|body_start_0|> regex = InvenTree.helpers.str2bool(request.query_params.get('search_regex', False)) search_fields = super().get_search_fields(view, request) fields = [] if search_fields: for field in search_fields: if regex: field = '$' + ...
Custom search filter which allows adjusting of search terms dynamically
InvenTreeSearchFilter
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InvenTreeSearchFilter: """Custom search filter which allows adjusting of search terms dynamically""" def get_search_fields(self, view, request): """Return a set of search fields for the request, adjusted based on request params. The following query params are available to 'augment' t...
stack_v2_sparse_classes_75kplus_train_071820
4,204
permissive
[ { "docstring": "Return a set of search fields for the request, adjusted based on request params. The following query params are available to 'augment' the search (in decreasing order of priority) - search_regex: If True, search is performed on 'regex' comparison", "name": "get_search_fields", "signature...
2
stack_v2_sparse_classes_30k_train_032537
Implement the Python class `InvenTreeSearchFilter` described below. Class description: Custom search filter which allows adjusting of search terms dynamically Method signatures and docstrings: - def get_search_fields(self, view, request): Return a set of search fields for the request, adjusted based on request params...
Implement the Python class `InvenTreeSearchFilter` described below. Class description: Custom search filter which allows adjusting of search terms dynamically Method signatures and docstrings: - def get_search_fields(self, view, request): Return a set of search fields for the request, adjusted based on request params...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class InvenTreeSearchFilter: """Custom search filter which allows adjusting of search terms dynamically""" def get_search_fields(self, view, request): """Return a set of search fields for the request, adjusted based on request params. The following query params are available to 'augment' t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InvenTreeSearchFilter: """Custom search filter which allows adjusting of search terms dynamically""" def get_search_fields(self, view, request): """Return a set of search fields for the request, adjusted based on request params. The following query params are available to 'augment' the search (in...
the_stack_v2_python_sparse
InvenTree/InvenTree/filters.py
inventree/InvenTree
train
3,077
c71555d50d8ecacdeb15c3f2ad0a8e83faf454e4
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EdiscoveryCase()", "from ..identity_set import IdentitySet\nfrom .case import Case\nfrom .case_operation import CaseOperation\nfrom .ediscovery_case_settings import EdiscoveryCaseSettings\nfrom .ediscovery_custodian import EdiscoveryCu...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return EdiscoveryCase() <|end_body_0|> <|body_start_1|> from ..identity_set import IdentitySet from .case import Case from .case_operation import CaseOperation from .ediscovery_...
EdiscoveryCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EdiscoveryCase: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryCase: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur...
stack_v2_sparse_classes_75kplus_train_071821
6,513
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: EdiscoveryCase", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_valu...
3
stack_v2_sparse_classes_30k_val_000111
Implement the Python class `EdiscoveryCase` described below. Class description: Implement the EdiscoveryCase class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryCase: Creates a new instance of the appropriate class based on discriminator va...
Implement the Python class `EdiscoveryCase` described below. Class description: Implement the EdiscoveryCase class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryCase: Creates a new instance of the appropriate class based on discriminator va...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class EdiscoveryCase: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryCase: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EdiscoveryCase: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryCase: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Ediscovery...
the_stack_v2_python_sparse
msgraph/generated/models/security/ediscovery_case.py
microsoftgraph/msgraph-sdk-python
train
135
7cbf2015f363bdc69003436862a65a41531440ab
[ "super().__init__()\nself.norm = torch.nn.InstanceNorm1d(in_channels)\nself.aux_conv = torch.nn.Sequential(torch.nn.Conv1d(aux_channels, in_channels, kernel_size, 1, bias=bias, padding=(kernel_size - 1) // 2))\nself.gated_conv = torch.nn.Sequential(torch.nn.Conv1d(in_channels, in_channels * 2, kernel_size, 1, bias=...
<|body_start_0|> super().__init__() self.norm = torch.nn.InstanceNorm1d(in_channels) self.aux_conv = torch.nn.Sequential(torch.nn.Conv1d(aux_channels, in_channels, kernel_size, 1, bias=bias, padding=(kernel_size - 1) // 2)) self.gated_conv = torch.nn.Sequential(torch.nn.Conv1d(in_channel...
TADE Layer module.
TADELayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TADELayer: """TADE Layer module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest'): """Initilize TADELayer module. Args: in_channels (int): Number of input channles. aux_channels...
stack_v2_sparse_classes_75kplus_train_071822
5,864
permissive
[ { "docstring": "Initilize TADELayer module. Args: in_channels (int): Number of input channles. aux_channels (int): Number of auxirialy channles. kernel_size (int): Kernel size. bias (bool): Whether to use bias parameter in conv. upsample_factor (int): Upsample factor. upsample_mode (str): Upsample mode.", "...
2
stack_v2_sparse_classes_30k_train_050418
Implement the Python class `TADELayer` described below. Class description: TADE Layer module. Method signatures and docstrings: - def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest'): Initilize TADELayer module. Args: ...
Implement the Python class `TADELayer` described below. Class description: TADE Layer module. Method signatures and docstrings: - def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest'): Initilize TADELayer module. Args: ...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class TADELayer: """TADE Layer module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest'): """Initilize TADELayer module. Args: in_channels (int): Number of input channles. aux_channels...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TADELayer: """TADE Layer module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest'): """Initilize TADELayer module. Args: in_channels (int): Number of input channles. aux_channels (int): Numbe...
the_stack_v2_python_sparse
espnet2/gan_tts/style_melgan/tade_res_block.py
espnet/espnet
train
7,242
3fd5af0e201731f08aaf0fdb8aa11e066b959a02
[ "self.name = name\nself.hw = {}\nself.acron_dofs = []\nself.eid_dofids = []\nself.num_dof = 0\nself.hw_rss = []\nself.read_hwlist()", "with open(self.name, 'r') as f:\n for line in f:\n if line.__len__() > 20 and line[0] != '$':\n acron = line[0:8].strip()\n if acron not in self.hw...
<|body_start_0|> self.name = name self.hw = {} self.acron_dofs = [] self.eid_dofids = [] self.num_dof = 0 self.hw_rss = [] self.read_hwlist() <|end_body_0|> <|body_start_1|> with open(self.name, 'r') as f: for line in f: if lin...
Hardware List Class
HWLIST
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HWLIST: """Hardware List Class""" def __init__(self, name): """Initializing the HWLIST class.""" <|body_0|> def read_hwlist(self): """Method to read in the HWLIST attributes. Ex: HWLIST.read_hwlist()""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_071823
2,195
no_license
[ { "docstring": "Initializing the HWLIST class.", "name": "__init__", "signature": "def __init__(self, name)" }, { "docstring": "Method to read in the HWLIST attributes. Ex: HWLIST.read_hwlist()", "name": "read_hwlist", "signature": "def read_hwlist(self)" } ]
2
null
Implement the Python class `HWLIST` described below. Class description: Hardware List Class Method signatures and docstrings: - def __init__(self, name): Initializing the HWLIST class. - def read_hwlist(self): Method to read in the HWLIST attributes. Ex: HWLIST.read_hwlist()
Implement the Python class `HWLIST` described below. Class description: Hardware List Class Method signatures and docstrings: - def __init__(self, name): Initializing the HWLIST class. - def read_hwlist(self): Method to read in the HWLIST attributes. Ex: HWLIST.read_hwlist() <|skeleton|> class HWLIST: """Hardwar...
6b37842203ff4318a48dbf0258cbe2b253436e7d
<|skeleton|> class HWLIST: """Hardware List Class""" def __init__(self, name): """Initializing the HWLIST class.""" <|body_0|> def read_hwlist(self): """Method to read in the HWLIST attributes. Ex: HWLIST.read_hwlist()""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HWLIST: """Hardware List Class""" def __init__(self, name): """Initializing the HWLIST class.""" self.name = name self.hw = {} self.acron_dofs = [] self.eid_dofids = [] self.num_dof = 0 self.hw_rss = [] self.read_hwlist() def read_hwlis...
the_stack_v2_python_sparse
loads/hwlist.py
tslowery78/PyLnD
train
0
2fe5e1aa02b31005092dcd43d6f3fb2d697408d6
[ "self.base_image = pygame.image.load(image)\nself.images = []\nself.duration = duration\nself.last_change = time()\nself.selected_image = 0\nsprite_w = self.base_image.get_width() / w\nsprite_h = self.base_image.get_height() / h\nself.final_size = final_size\nself.invisible_color = invisible_color\nif final_size is...
<|body_start_0|> self.base_image = pygame.image.load(image) self.images = [] self.duration = duration self.last_change = time() self.selected_image = 0 sprite_w = self.base_image.get_width() / w sprite_h = self.base_image.get_height() / h self.final_size =...
SpriteSheet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpriteSheet: def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): """This class is for creating spritesheets :param image: the path to the image of the sheet :param w: the width of each frame in the sheet :param h...
stack_v2_sparse_classes_75kplus_train_071824
2,468
no_license
[ { "docstring": "This class is for creating spritesheets :param image: the path to the image of the sheet :param w: the width of each frame in the sheet :param h: the height of each frame in the sheet :param duration: the number of seconds to stay on each frame :param final_size: the final size to scale the imag...
3
stack_v2_sparse_classes_30k_train_042184
Implement the Python class `SpriteSheet` described below. Class description: Implement the SpriteSheet class. Method signatures and docstrings: - def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): This class is for creating spritesheets :par...
Implement the Python class `SpriteSheet` described below. Class description: Implement the SpriteSheet class. Method signatures and docstrings: - def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): This class is for creating spritesheets :par...
e9e68cf3ba4f9f12e66eae81893ca9dcc534835c
<|skeleton|> class SpriteSheet: def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): """This class is for creating spritesheets :param image: the path to the image of the sheet :param w: the width of each frame in the sheet :param h...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SpriteSheet: def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): """This class is for creating spritesheets :param image: the path to the image of the sheet :param w: the width of each frame in the sheet :param h: the height o...
the_stack_v2_python_sparse
Objects/SpriteSheet.py
john-palazzolo/PyGE
train
0
61d0b3819e5ac37ac4b5f5b9c19ababe7fbf21c2
[ "s, t = (sorted(s), sorted(t))\nn = len(s)\nfor i in range(n):\n if s[i] != t[i]:\n return t[i]\nreturn t[-1]", "char_count = Counter(s)\nfor char in t:\n if not char_count[char] or char not in char_count:\n return char\n char_count[char] -= 1", "value = 0\nn = len(s)\nfor i in range(n):\...
<|body_start_0|> s, t = (sorted(s), sorted(t)) n = len(s) for i in range(n): if s[i] != t[i]: return t[i] return t[-1] <|end_body_0|> <|body_start_1|> char_count = Counter(s) for char in t: if not char_count[char] or char not in ch...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def find_diff_1(self, s, t): """Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s).""" <|body_0|> def find_diff_2(self, s, t): """Use hash map to count the characters in string s, then compar...
stack_v2_sparse_classes_75kplus_train_071825
2,403
no_license
[ { "docstring": "Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s).", "name": "find_diff_1", "signature": "def find_diff_1(self, s, t)" }, { "docstring": "Use hash map to count the characters in string s, then compare it with char...
4
stack_v2_sparse_classes_30k_train_050778
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_diff_1(self, s, t): Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s). - def find_diff_2(self, s, t): ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_diff_1(self, s, t): Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s). - def find_diff_2(self, s, t): ...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def find_diff_1(self, s, t): """Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s).""" <|body_0|> def find_diff_2(self, s, t): """Use hash map to count the characters in string s, then compar...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def find_diff_1(self, s, t): """Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s).""" s, t = (sorted(s), sorted(t)) n = len(s) for i in range(n): if s[i] != t[i]: return t[i...
the_stack_v2_python_sparse
Bit_Manipulation/find_difference.py
vladn90/Algorithms
train
0
ee48606eaea3b7d522ad62fa25e218c9830d544f
[ "new_article = Article()\nnew_article.title = request.data['title']\nnew_article.synopsis = request.data['synopsis']\nnew_article.link = request.data['link']\nnew_article.reference = request.data['reference']\nnew_article.coder = Coder.objects.get(user=request.auth.user)\nnew_article.save()\nserializer = ArticleSer...
<|body_start_0|> new_article = Article() new_article.title = request.data['title'] new_article.synopsis = request.data['synopsis'] new_article.link = request.data['link'] new_article.reference = request.data['reference'] new_article.coder = Coder.objects.get(user=request....
Articles for codeArchive
Articles
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Articles: """Articles for codeArchive""" def create(self, request): """Handle POST operations Returns: Response -- JSON serialized Article instance""" <|body_0|> def destroy(self, request, pk=None): """Handle DELETE requests for a single article Returns: Response...
stack_v2_sparse_classes_75kplus_train_071826
3,493
no_license
[ { "docstring": "Handle POST operations Returns: Response -- JSON serialized Article instance", "name": "create", "signature": "def create(self, request)" }, { "docstring": "Handle DELETE requests for a single article Returns: Response -- 200, 404, or 500 status code", "name": "destroy", ...
5
stack_v2_sparse_classes_30k_train_013573
Implement the Python class `Articles` described below. Class description: Articles for codeArchive Method signatures and docstrings: - def create(self, request): Handle POST operations Returns: Response -- JSON serialized Article instance - def destroy(self, request, pk=None): Handle DELETE requests for a single arti...
Implement the Python class `Articles` described below. Class description: Articles for codeArchive Method signatures and docstrings: - def create(self, request): Handle POST operations Returns: Response -- JSON serialized Article instance - def destroy(self, request, pk=None): Handle DELETE requests for a single arti...
2bd984d13baaa9e12bba63a3bf39c2ff93619e59
<|skeleton|> class Articles: """Articles for codeArchive""" def create(self, request): """Handle POST operations Returns: Response -- JSON serialized Article instance""" <|body_0|> def destroy(self, request, pk=None): """Handle DELETE requests for a single article Returns: Response...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Articles: """Articles for codeArchive""" def create(self, request): """Handle POST operations Returns: Response -- JSON serialized Article instance""" new_article = Article() new_article.title = request.data['title'] new_article.synopsis = request.data['synopsis'] ...
the_stack_v2_python_sparse
codearchiveAPIapp/views/article_view.py
shanemiller89/codeArchive_API
train
0
9f2bccb03081cbc1a28beaa34f1547455e602dd9
[ "threading.Thread.__init__(self)\nself.daemon = True\nself.queue = queue\nself.processedUrls = processedUrls\nself.selectedDomains = selectedDomains\nself.selectedUrls = selectedUrls\nself.baseFileName = baseFileName\nself.parseTimeout = parseTimeout", "global parseCancelled\nstartTime = time.time()\nlastActionTi...
<|body_start_0|> threading.Thread.__init__(self) self.daemon = True self.queue = queue self.processedUrls = processedUrls self.selectedDomains = selectedDomains self.selectedUrls = selectedUrls self.baseFileName = baseFileName self.parseTimeout = parseTime...
SpiderMonitor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpiderMonitor: def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): """Инициализация""" <|body_0|> def run(self): """Каждые 5 секунд сохраняем базу в файл и выводим текущую информацию. По истечении тайматута завершаем в...
stack_v2_sparse_classes_75kplus_train_071827
5,227
no_license
[ { "docstring": "Инициализация", "name": "__init__", "signature": "def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout)" }, { "docstring": "Каждые 5 секунд сохраняем базу в файл и выводим текущую информацию. По истечении тайматута завершаем выполнени...
2
stack_v2_sparse_classes_30k_train_016827
Implement the Python class `SpiderMonitor` described below. Class description: Implement the SpiderMonitor class. Method signatures and docstrings: - def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): Инициализация - def run(self): Каждые 5 секунд сохраняем базу в фай...
Implement the Python class `SpiderMonitor` described below. Class description: Implement the SpiderMonitor class. Method signatures and docstrings: - def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): Инициализация - def run(self): Каждые 5 секунд сохраняем базу в фай...
d2771bf04aa187dda6d468883a5a167237589369
<|skeleton|> class SpiderMonitor: def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): """Инициализация""" <|body_0|> def run(self): """Каждые 5 секунд сохраняем базу в файл и выводим текущую информацию. По истечении тайматута завершаем в...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SpiderMonitor: def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): """Инициализация""" threading.Thread.__init__(self) self.daemon = True self.queue = queue self.processedUrls = processedUrls self.selectedDomains ...
the_stack_v2_python_sparse
doorsagents/baseparser.py
cash2one/doorscenter
train
0
2623e01b133e2afcce17d60a49ee127907cea704
[ "test_treatment = Treatment(treatment='Test Treatment', diet=Diet.objects.get(pk=1), environment=Environment.objects.get(pk=1))\ntest_treatment.save()\ntest_treatment.animals.add(Animal.objects.get(pk=1))\ntest_treatment.researchers.add(Researcher.objects.get(pk=1))\nself.assertEqual(test_treatment.pk, 1)", "test...
<|body_start_0|> test_treatment = Treatment(treatment='Test Treatment', diet=Diet.objects.get(pk=1), environment=Environment.objects.get(pk=1)) test_treatment.save() test_treatment.animals.add(Animal.objects.get(pk=1)) test_treatment.researchers.add(Researcher.objects.get(pk=1)) ...
These tests test the functionality of :class:`~mousedb.data.models.Treatment` objects.
TreatmentModelTests
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TreatmentModelTests: """These tests test the functionality of :class:`~mousedb.data.models.Treatment` objects.""" def test_create_treatment_minimum(self): """This test creates a :class:`~mousedb.data.models.Treatment` with the required information only.""" <|body_0|> def...
stack_v2_sparse_classes_75kplus_train_071828
29,846
permissive
[ { "docstring": "This test creates a :class:`~mousedb.data.models.Treatment` with the required information only.", "name": "test_create_treatment_minimum", "signature": "def test_create_treatment_minimum(self)" }, { "docstring": "This test creates a :class:`~mousedb.data.models.Treatment` with al...
4
stack_v2_sparse_classes_30k_train_022760
Implement the Python class `TreatmentModelTests` described below. Class description: These tests test the functionality of :class:`~mousedb.data.models.Treatment` objects. Method signatures and docstrings: - def test_create_treatment_minimum(self): This test creates a :class:`~mousedb.data.models.Treatment` with the ...
Implement the Python class `TreatmentModelTests` described below. Class description: These tests test the functionality of :class:`~mousedb.data.models.Treatment` objects. Method signatures and docstrings: - def test_create_treatment_minimum(self): This test creates a :class:`~mousedb.data.models.Treatment` with the ...
7e423991f72c89468010c99865e3c70c22044df3
<|skeleton|> class TreatmentModelTests: """These tests test the functionality of :class:`~mousedb.data.models.Treatment` objects.""" def test_create_treatment_minimum(self): """This test creates a :class:`~mousedb.data.models.Treatment` with the required information only.""" <|body_0|> def...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TreatmentModelTests: """These tests test the functionality of :class:`~mousedb.data.models.Treatment` objects.""" def test_create_treatment_minimum(self): """This test creates a :class:`~mousedb.data.models.Treatment` with the required information only.""" test_treatment = Treatment(treat...
the_stack_v2_python_sparse
mousedb/data/tests.py
BridgesLab/mousedb
train
0
fa0dd20d461e5a73e43759c6ac927d45b3eff850
[ "self.game = Game()\nself.grid = Grid()\nself.file_manager = FileManager()", "return_1 = 'Correct!'\nstring_1 = self.game.correct_answer_response()\nself.assertEqual(string_1, return_1)", "correct_answer = '2014'\nreturn_1 = 'The correct answer is 2014.'\nstring_1 = self.game.incorrect_answer_response(correct_a...
<|body_start_0|> self.game = Game() self.grid = Grid() self.file_manager = FileManager() <|end_body_0|> <|body_start_1|> return_1 = 'Correct!' string_1 = self.game.correct_answer_response() self.assertEqual(string_1, return_1) <|end_body_1|> <|body_start_2|> cor...
TestGame
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestGame: def setUp(self): """setUp class""" <|body_0|> def test_correct_answer_response(self): """test correct_answer_response functionality""" <|body_1|> def test_incorrect_answer_response(self): """test incorrect_answer_response functionality"...
stack_v2_sparse_classes_75kplus_train_071829
1,533
permissive
[ { "docstring": "setUp class", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "test correct_answer_response functionality", "name": "test_correct_answer_response", "signature": "def test_correct_answer_response(self)" }, { "docstring": "test incorrect_answer_res...
4
stack_v2_sparse_classes_30k_train_023226
Implement the Python class `TestGame` described below. Class description: Implement the TestGame class. Method signatures and docstrings: - def setUp(self): setUp class - def test_correct_answer_response(self): test correct_answer_response functionality - def test_incorrect_answer_response(self): test incorrect_answe...
Implement the Python class `TestGame` described below. Class description: Implement the TestGame class. Method signatures and docstrings: - def setUp(self): setUp class - def test_correct_answer_response(self): test correct_answer_response functionality - def test_incorrect_answer_response(self): test incorrect_answe...
24372001de9281cb37310f12c318a1b5c7f44190
<|skeleton|> class TestGame: def setUp(self): """setUp class""" <|body_0|> def test_correct_answer_response(self): """test correct_answer_response functionality""" <|body_1|> def test_incorrect_answer_response(self): """test incorrect_answer_response functionality"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestGame: def setUp(self): """setUp class""" self.game = Game() self.grid = Grid() self.file_manager = FileManager() def test_correct_answer_response(self): """test correct_answer_response functionality""" return_1 = 'Correct!' string_1 = self.game....
the_stack_v2_python_sparse
test_game.py
xkb1984/Pico-Escape-Room
train
0
b75e555a1bbc1cdea21510304b331ee3440a0c15
[ "res = 0\nfor i, c in enumerate(s):\n add = 0\n if c == 'I':\n add = 1\n elif c == 'V':\n add = add + 3 if i > 0 and s[i - 1] == 'I' else add + 5\n elif c == 'X':\n add = add + 8 if i > 0 and s[i - 1] == 'I' else add + 10\n elif c == 'L':\n add = add + 30 if i > 0 and s[i ...
<|body_start_0|> res = 0 for i, c in enumerate(s): add = 0 if c == 'I': add = 1 elif c == 'V': add = add + 3 if i > 0 and s[i - 1] == 'I' else add + 5 elif c == 'X': add = add + 8 if i > 0 and s[i - 1] == 'I'...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def romanToInt(self, s: str) -> int: """Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.""" <|body_0|> def romanToInt(self, s): """Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_75kplus_train_071830
2,062
no_license
[ { "docstring": "Input: \"LVIII\" Output: 58 Explanation: L = 50, V= 5, III = 3.", "name": "romanToInt", "signature": "def romanToInt(self, s: str) -> int" }, { "docstring": "Input: \"LVIII\" Output: 58 Explanation: L = 50, V= 5, III = 3.", "name": "romanToInt", "signature": "def romanToI...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def romanToInt(self, s: str) -> int: Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. - def romanToInt(self, s): Input: "LVIII" Output: 58 Explanation: L = 50, V= 5,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def romanToInt(self, s: str) -> int: Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. - def romanToInt(self, s): Input: "LVIII" Output: 58 Explanation: L = 50, V= 5,...
5d3e0b727b0294ecd1099818cbd9c85a0da56de2
<|skeleton|> class Solution: def romanToInt(self, s: str) -> int: """Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.""" <|body_0|> def romanToInt(self, s): """Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def romanToInt(self, s: str) -> int: """Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.""" res = 0 for i, c in enumerate(s): add = 0 if c == 'I': add = 1 elif c == 'V': add = add + 3 if i > 0 an...
the_stack_v2_python_sparse
Python/13_roman_to_integer.py
havefuncoding/Leetcode
train
0
01db017178fc4890f753e3df1645a759394b93bf
[ "self.goal_map = []\nfor i in range(16):\n self.goal_map.append(i)\nself.goal_lists = goal.tiles\nfor row in range(4):\n for col in range(4):\n self.goal_map[goal.tiles[row][col]] = (row, col)\nself.col_conflicts = []\nfor col in range(4):\n col_list = []\n for row in range(4):\n col_list....
<|body_start_0|> self.goal_map = [] for i in range(16): self.goal_map.append(i) self.goal_lists = goal.tiles for row in range(4): for col in range(4): self.goal_map[goal.tiles[row][col]] = (row, col) self.col_conflicts = [] for col ...
Object used to preprocess goal position for heuristic function
HeuristicObj
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HeuristicObj: """Object used to preprocess goal position for heuristic function""" def __init__(self, goal): """Preprocess goal position to setup internal data structures that can be used to speed up heuristic.""" <|body_0|> def heuristic(self, start): """Estimat...
stack_v2_sparse_classes_75kplus_train_071831
19,259
permissive
[ { "docstring": "Preprocess goal position to setup internal data structures that can be used to speed up heuristic.", "name": "__init__", "signature": "def __init__(self, goal)" }, { "docstring": "Estimates the number of moves from start to goal. The goal was preprocessed in __init__.", "name...
2
null
Implement the Python class `HeuristicObj` described below. Class description: Object used to preprocess goal position for heuristic function Method signatures and docstrings: - def __init__(self, goal): Preprocess goal position to setup internal data structures that can be used to speed up heuristic. - def heuristic(...
Implement the Python class `HeuristicObj` described below. Class description: Object used to preprocess goal position for heuristic function Method signatures and docstrings: - def __init__(self, goal): Preprocess goal position to setup internal data structures that can be used to speed up heuristic. - def heuristic(...
85ef834ce1c48bd725893bb29d820236aac98752
<|skeleton|> class HeuristicObj: """Object used to preprocess goal position for heuristic function""" def __init__(self, goal): """Preprocess goal position to setup internal data structures that can be used to speed up heuristic.""" <|body_0|> def heuristic(self, start): """Estimat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HeuristicObj: """Object used to preprocess goal position for heuristic function""" def __init__(self, goal): """Preprocess goal position to setup internal data structures that can be used to speed up heuristic.""" self.goal_map = [] for i in range(16): self.goal_map.ap...
the_stack_v2_python_sparse
old/astar.py
bobbydurrett/my15puzzlesolver
train
0
2dd4b252ddc1859a7d8702f4e77a4cd05bb7df94
[ "self.PATH = 'data/{}'.format(file)\nself._config = config\nself._load_rawdata()\nself._employee_process()\nself._demand_process()\nself._predict_samples_process()", "log.info('loading the excel file ......')\ntry:\n self._employees = pd.read_excel(self.PATH, sheet_name='小哥信息')\n self._demands = pd.read_exc...
<|body_start_0|> self.PATH = 'data/{}'.format(file) self._config = config self._load_rawdata() self._employee_process() self._demand_process() self._predict_samples_process() <|end_body_0|> <|body_start_1|> log.info('loading the excel file ......') try: ...
DataHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataHandler: def __init__(self, file, config): """file:文件名 :param file: :param config""" <|body_0|> def _load_rawdata(self): """加载原始文件 :return:""" <|body_1|> def _employee_process(self): """处理小哥的信息 :return:""" <|body_2|> def _demand_...
stack_v2_sparse_classes_75kplus_train_071832
5,771
no_license
[ { "docstring": "file:文件名 :param file: :param config", "name": "__init__", "signature": "def __init__(self, file, config)" }, { "docstring": "加载原始文件 :return:", "name": "_load_rawdata", "signature": "def _load_rawdata(self)" }, { "docstring": "处理小哥的信息 :return:", "name": "_emplo...
5
stack_v2_sparse_classes_30k_val_001965
Implement the Python class `DataHandler` described below. Class description: Implement the DataHandler class. Method signatures and docstrings: - def __init__(self, file, config): file:文件名 :param file: :param config - def _load_rawdata(self): 加载原始文件 :return: - def _employee_process(self): 处理小哥的信息 :return: - def _dema...
Implement the Python class `DataHandler` described below. Class description: Implement the DataHandler class. Method signatures and docstrings: - def __init__(self, file, config): file:文件名 :param file: :param config - def _load_rawdata(self): 加载原始文件 :return: - def _employee_process(self): 处理小哥的信息 :return: - def _dema...
a8933767f4fea431e316b5cf0c9828f703548035
<|skeleton|> class DataHandler: def __init__(self, file, config): """file:文件名 :param file: :param config""" <|body_0|> def _load_rawdata(self): """加载原始文件 :return:""" <|body_1|> def _employee_process(self): """处理小哥的信息 :return:""" <|body_2|> def _demand_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DataHandler: def __init__(self, file, config): """file:文件名 :param file: :param config""" self.PATH = 'data/{}'.format(file) self._config = config self._load_rawdata() self._employee_process() self._demand_process() self._predict_samples_process() de...
the_stack_v2_python_sparse
SF_Technology_Algorithm/OR_Own/datahandle.py
perry-xy/SF
train
0
ffe0e7769c7e2b597fd6fbd3f4c59a209fb5d718
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
BrokerServicer
[ "Unlicense", "BSD-3-Clause", "LLVM-exception", "Apache-2.0", "BSD-2-Clause", "MIT", "CC0-1.0", "Apache-1.1", "W3C-19980720", "MPL-1.1", "Unicode-TOU", "W3C", "LGPL-2.1-or-later", "CDDL-1.1", "EPL-1.0", "GPL-1.0-or-later", "Classpath-exception-2.0", "LGPL-2.1-only", "CC-BY-SA-2.5"...
stack_v2_sparse_python_classes_v1
<|skeleton|> class BrokerServicer: """Missing associated documentation comment in .proto file.""" def GetDatapoints(self, request, context): """Request a set of datapoints (values) Returns a list of requested data points. InvalidArgument is returned if the request is malformed.""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_071833
6,449
permissive
[ { "docstring": "Request a set of datapoints (values) Returns a list of requested data points. InvalidArgument is returned if the request is malformed.", "name": "GetDatapoints", "signature": "def GetDatapoints(self, request, context)" }, { "docstring": "Subscribe to a set of data points or condi...
3
stack_v2_sparse_classes_30k_train_006366
Implement the Python class `BrokerServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def GetDatapoints(self, request, context): Request a set of datapoints (values) Returns a list of requested data points. InvalidArgument is retur...
Implement the Python class `BrokerServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def GetDatapoints(self, request, context): Request a set of datapoints (values) Returns a list of requested data points. InvalidArgument is retur...
90b10ec52983a96f7675c9bd8fd9aeac345e882b
<|skeleton|> class BrokerServicer: """Missing associated documentation comment in .proto file.""" def GetDatapoints(self, request, context): """Request a set of datapoints (values) Returns a list of requested data points. InvalidArgument is returned if the request is malformed.""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BrokerServicer: """Missing associated documentation comment in .proto file.""" def GetDatapoints(self, request, context): """Request a set of datapoints (values) Returns a list of requested data points. InvalidArgument is returned if the request is malformed.""" context.set_code(grpc.Stat...
the_stack_v2_python_sparse
kuksa_databroker/integration_test/gen_proto/sdv/databroker/v1/broker_pb2_grpc.py
eclipse/kuksa.val
train
74
bce9c8b433c7d1742efad2838438560505c55176
[ "Log.info('Actual value: ' + str(actual))\nLog.info('Expected value: ' + str(expected))\nreturn expected - expected * tolerance <= actual <= expected + expected * tolerance", "total_time = 0\nfor _ in range(0, retry_count):\n total_time = total_time + operation(*args, **kwargs).duration\nreturn total_time / re...
<|body_start_0|> Log.info('Actual value: ' + str(actual)) Log.info('Expected value: ' + str(expected)) return expected - expected * tolerance <= actual <= expected + expected * tolerance <|end_body_0|> <|body_start_1|> total_time = 0 for _ in range(0, retry_count): t...
PerfUtils
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PerfUtils: def is_value_in_range(actual, expected, tolerance=0.25): """Check if value is in range :param actual: Number value. :param expected: Number value. :param tolerance: Tolerance as percent.""" <|body_0|> def get_average_time(operation, retry_count=3, *args, **kwargs)...
stack_v2_sparse_classes_75kplus_train_071834
1,102
no_license
[ { "docstring": "Check if value is in range :param actual: Number value. :param expected: Number value. :param tolerance: Tolerance as percent.", "name": "is_value_in_range", "signature": "def is_value_in_range(actual, expected, tolerance=0.25)" }, { "docstring": "Get average time of Run.command(...
2
null
Implement the Python class `PerfUtils` described below. Class description: Implement the PerfUtils class. Method signatures and docstrings: - def is_value_in_range(actual, expected, tolerance=0.25): Check if value is in range :param actual: Number value. :param expected: Number value. :param tolerance: Tolerance as p...
Implement the Python class `PerfUtils` described below. Class description: Implement the PerfUtils class. Method signatures and docstrings: - def is_value_in_range(actual, expected, tolerance=0.25): Check if value is in range :param actual: Number value. :param expected: Number value. :param tolerance: Tolerance as p...
85e9662ab85c68a472b407e890656bcb73a87e70
<|skeleton|> class PerfUtils: def is_value_in_range(actual, expected, tolerance=0.25): """Check if value is in range :param actual: Number value. :param expected: Number value. :param tolerance: Tolerance as percent.""" <|body_0|> def get_average_time(operation, retry_count=3, *args, **kwargs)...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PerfUtils: def is_value_in_range(actual, expected, tolerance=0.25): """Check if value is in range :param actual: Number value. :param expected: Number value. :param tolerance: Tolerance as percent.""" Log.info('Actual value: ' + str(actual)) Log.info('Expected value: ' + str(expected))...
the_stack_v2_python_sparse
core/utils/perf_utils.py
NativeScript/nativescript-tooling-qa
train
5
4a85a19f015a9cde3d0bd7a1e7009215166250e0
[ "super(TarProgressFile, self).__init__(path)\nself._steps = set()\nself._total_size = os.path.getsize(path)\nself._logger = logger", "percent = self.tell() / self._total_size\ntens = int(math.floor(percent * 10)) * 10\nif tens not in self._steps:\n self._steps.add(tens)\n message = 'Overall process: %d of %...
<|body_start_0|> super(TarProgressFile, self).__init__(path) self._steps = set() self._total_size = os.path.getsize(path) self._logger = logger <|end_body_0|> <|body_start_1|> percent = self.tell() / self._total_size tens = int(math.floor(percent * 10)) * 10 if t...
An object which is used in TAR callbacks to log extraction progress. This object prints every 10% of the extraction, to avoid being too spammy.
TarProgressFile
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TarProgressFile: """An object which is used in TAR callbacks to log extraction progress. This object prints every 10% of the extraction, to avoid being too spammy.""" def __init__(self, path, logger=None): """Create the object and store the given logger. Args: path (str): The absolut...
stack_v2_sparse_classes_75kplus_train_071835
3,538
permissive
[ { "docstring": "Create the object and store the given logger. Args: path (str): The absolute path to the TAR file to extract. logger (`logging.Logger` or NoneType, optional): Some logger to use to print the progress. If no logger is given, the progress messages are printed, instead. Default is None.", "name...
2
stack_v2_sparse_classes_30k_train_000568
Implement the Python class `TarProgressFile` described below. Class description: An object which is used in TAR callbacks to log extraction progress. This object prints every 10% of the extraction, to avoid being too spammy. Method signatures and docstrings: - def __init__(self, path, logger=None): Create the object ...
Implement the Python class `TarProgressFile` described below. Class description: An object which is used in TAR callbacks to log extraction progress. This object prints every 10% of the extraction, to avoid being too spammy. Method signatures and docstrings: - def __init__(self, path, logger=None): Create the object ...
e7efafcd1d7a44ed732e217182388dfa9190f2d0
<|skeleton|> class TarProgressFile: """An object which is used in TAR callbacks to log extraction progress. This object prints every 10% of the extraction, to avoid being too spammy.""" def __init__(self, path, logger=None): """Create the object and store the given logger. Args: path (str): The absolut...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TarProgressFile: """An object which is used in TAR callbacks to log extraction progress. This object prints every 10% of the extraction, to avoid being too spammy.""" def __init__(self, path, logger=None): """Create the object and store the given logger. Args: path (str): The absolute path to the...
the_stack_v2_python_sparse
utils/progressbar.py
demon7x/rezzurect
train
0
a042af3e690113cc78c03301f42a1775c95ac229
[ "if mnemonic_type is not None and (not isinstance(mnemonic_type, ElectrumV2MnemonicTypes)):\n raise TypeError('Mnemonic type is not an enumerative of ElectrumV2MnemonicTypes')\nif lang is not None and (not isinstance(lang, ElectrumV2Languages)):\n raise TypeError('Language is not an enumerative of ElectrumV2L...
<|body_start_0|> if mnemonic_type is not None and (not isinstance(mnemonic_type, ElectrumV2MnemonicTypes)): raise TypeError('Mnemonic type is not an enumerative of ElectrumV2MnemonicTypes') if lang is not None and (not isinstance(lang, ElectrumV2Languages)): raise TypeError('Lang...
Electrum v2 mnemonic decoder class. It decodes a mnemonic phrase to bytes.
ElectrumV2MnemonicDecoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElectrumV2MnemonicDecoder: """Electrum v2 mnemonic decoder class. It decodes a mnemonic phrase to bytes.""" def __init__(self, mnemonic_type: Optional[ElectrumV2MnemonicTypes]=None, lang: Optional[ElectrumV2Languages]=None) -> None: """Construct class. Args: mnemonic_type (ElectrumV2...
stack_v2_sparse_classes_75kplus_train_071836
4,394
permissive
[ { "docstring": "Construct class. Args: mnemonic_type (ElectrumV2MnemonicTypes, optional): Mnemonic type, None for all types lang (ElectrumV2Languages, optional) : Language, None for automatic detection Raises: TypeError: If the language is not a ElectrumV2Languages enum ValueError: If loaded words list is not v...
2
null
Implement the Python class `ElectrumV2MnemonicDecoder` described below. Class description: Electrum v2 mnemonic decoder class. It decodes a mnemonic phrase to bytes. Method signatures and docstrings: - def __init__(self, mnemonic_type: Optional[ElectrumV2MnemonicTypes]=None, lang: Optional[ElectrumV2Languages]=None) ...
Implement the Python class `ElectrumV2MnemonicDecoder` described below. Class description: Electrum v2 mnemonic decoder class. It decodes a mnemonic phrase to bytes. Method signatures and docstrings: - def __init__(self, mnemonic_type: Optional[ElectrumV2MnemonicTypes]=None, lang: Optional[ElectrumV2Languages]=None) ...
d15c75ddd74e4838c396a0d036ef6faf11b06a4b
<|skeleton|> class ElectrumV2MnemonicDecoder: """Electrum v2 mnemonic decoder class. It decodes a mnemonic phrase to bytes.""" def __init__(self, mnemonic_type: Optional[ElectrumV2MnemonicTypes]=None, lang: Optional[ElectrumV2Languages]=None) -> None: """Construct class. Args: mnemonic_type (ElectrumV2...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ElectrumV2MnemonicDecoder: """Electrum v2 mnemonic decoder class. It decodes a mnemonic phrase to bytes.""" def __init__(self, mnemonic_type: Optional[ElectrumV2MnemonicTypes]=None, lang: Optional[ElectrumV2Languages]=None) -> None: """Construct class. Args: mnemonic_type (ElectrumV2MnemonicTypes...
the_stack_v2_python_sparse
bip_utils/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.py
ebellocchia/bip_utils
train
244
8c11a5fda007282b39b69846cd6acaaec9141609
[ "self.nmap_services_file = 'nemo/common/utils/nmap-services'\nself.port_service = {}\nself.custom_service_file = 'nemo/common/utils/custom-services.txt'\nself.custom_port_service = {}\nself.__load_services()", "try:\n with open(self.nmap_services_file) as f:\n for line in f:\n if line.startsw...
<|body_start_0|> self.nmap_services_file = 'nemo/common/utils/nmap-services' self.port_service = {} self.custom_service_file = 'nemo/common/utils/custom-services.txt' self.custom_port_service = {} self.__load_services() <|end_body_0|> <|body_start_1|> try: wi...
解析端口的Service名称 包括通用定义和自定义
ParsePortService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParsePortService: """解析端口的Service名称 包括通用定义和自定义""" def __init__(self): """默认参数""" <|body_0|> def __load_services(self): """读取映射关系:nmap-services""" <|body_1|> def get_service(self, port, port_type='tcp'): """根据端口号查找Service名称""" <|body_2...
stack_v2_sparse_classes_75kplus_train_071837
2,419
no_license
[ { "docstring": "默认参数", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "读取映射关系:nmap-services", "name": "__load_services", "signature": "def __load_services(self)" }, { "docstring": "根据端口号查找Service名称", "name": "get_service", "signature": "def get_se...
3
stack_v2_sparse_classes_30k_train_017647
Implement the Python class `ParsePortService` described below. Class description: 解析端口的Service名称 包括通用定义和自定义 Method signatures and docstrings: - def __init__(self): 默认参数 - def __load_services(self): 读取映射关系:nmap-services - def get_service(self, port, port_type='tcp'): 根据端口号查找Service名称
Implement the Python class `ParsePortService` described below. Class description: 解析端口的Service名称 包括通用定义和自定义 Method signatures and docstrings: - def __init__(self): 默认参数 - def __load_services(self): 读取映射关系:nmap-services - def get_service(self, port, port_type='tcp'): 根据端口号查找Service名称 <|skeleton|> class ParsePortServi...
ac9b63c60a64677d4d070afe069af04be591dfcc
<|skeleton|> class ParsePortService: """解析端口的Service名称 包括通用定义和自定义""" def __init__(self): """默认参数""" <|body_0|> def __load_services(self): """读取映射关系:nmap-services""" <|body_1|> def get_service(self, port, port_type='tcp'): """根据端口号查找Service名称""" <|body_2...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ParsePortService: """解析端口的Service名称 包括通用定义和自定义""" def __init__(self): """默认参数""" self.nmap_services_file = 'nemo/common/utils/nmap-services' self.port_service = {} self.custom_service_file = 'nemo/common/utils/custom-services.txt' self.custom_port_service = {} ...
the_stack_v2_python_sparse
nemo/common/utils/parseservice.py
xiaolushuo/nemo
train
0
190da7317440f3bf7f063bddfff4be87af038d97
[ "if not node:\n return None\nnode_map = dict()\nqueue = [node]\nin_queue = set([node.val])\nclone_head = None\nwhile queue:\n curr = queue.pop(0)\n val = curr.val\n if val not in node_map:\n node_map[val] = curr_clone = Node(val)\n if clone_head is None:\n clone_head = curr_clon...
<|body_start_0|> if not node: return None node_map = dict() queue = [node] in_queue = set([node.val]) clone_head = None while queue: curr = queue.pop(0) val = curr.val if val not in node_map: node_map[val] = ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def cloneGraph_v1(self, node: Node) -> Node: """Use a queue.""" <|body_0|> def cloneGraph_v2(self, node: Node) -> Node: """Use recurssion.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not node: return None node_ma...
stack_v2_sparse_classes_75kplus_train_071838
4,045
no_license
[ { "docstring": "Use a queue.", "name": "cloneGraph_v1", "signature": "def cloneGraph_v1(self, node: Node) -> Node" }, { "docstring": "Use recurssion.", "name": "cloneGraph_v2", "signature": "def cloneGraph_v2(self, node: Node) -> Node" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def cloneGraph_v1(self, node: Node) -> Node: Use a queue. - def cloneGraph_v2(self, node: Node) -> Node: Use recurssion.
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def cloneGraph_v1(self, node: Node) -> Node: Use a queue. - def cloneGraph_v2(self, node: Node) -> Node: Use recurssion. <|skeleton|> class Solution: def cloneGraph_v1(self...
97a2386f5e3adbd7138fd123810c3232bdf7f622
<|skeleton|> class Solution: def cloneGraph_v1(self, node: Node) -> Node: """Use a queue.""" <|body_0|> def cloneGraph_v2(self, node: Node) -> Node: """Use recurssion.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def cloneGraph_v1(self, node: Node) -> Node: """Use a queue.""" if not node: return None node_map = dict() queue = [node] in_queue = set([node.val]) clone_head = None while queue: curr = queue.pop(0) val = cu...
the_stack_v2_python_sparse
python3/trees_and_graphs/clone_undirected_graph.py
victorchu/algorithms
train
0
8dd83da0fd67b0a131220d441fbafda02da776d7
[ "super(Encoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",...
<|body_start_0|> super(Encoder, self).__init__() self.N = N self.dm = dm self.embedding = tf.keras.layers.Embedding(input_vocab, dm) self.positional_encoding = positional_encoding(max_seq_len, self.dm) self.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N...
Encoder class for machine translation
Encoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Encoder: """Encoder class for machine translation""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of...
stack_v2_sparse_classes_75kplus_train_071839
16,008
no_license
[ { "docstring": "Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of hidden units in the fully connected layer :param input_vocab: size of the input vocabulary :param max_seq_len: maximum sequence length possible :p...
2
stack_v2_sparse_classes_30k_test_002144
Implement the Python class `Encoder` described below. Class description: Encoder class for machine translation Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the...
Implement the Python class `Encoder` described below. Class description: Encoder class for machine translation Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the...
f83a60babb1d2a510a4a0e0f58aa3880fd9f93a7
<|skeleton|> class Encoder: """Encoder class for machine translation""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Encoder: """Encoder class for machine translation""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of hidden units...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/5-transformer.py
jalondono/holbertonschool-machine_learning
train
2
aa0cc171ae3fe4d89fde92d096dd4a5ac3a3be91
[ "kwargs.setdefault('is_staff', True)\nkwargs.setdefault('is_superuser', True)\nkwargs.setdefault('is_active', True)\nif kwargs.get('is_staff') is not True:\n raise ValueError('Superuser must be assigned to is_staff=True')\nif kwargs.get('is_superuser') is not True:\n raise ValueError('Superuser must be assign...
<|body_start_0|> kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if kwargs.get('is_superuser') is no...
AccountManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountManager: def create_superuser(self, email, username, password, **kwargs): """Create superuser Creates a new superuser. Will default `is_staff`, `is_superuser` and `is_active` Args: email (str): The email of the new user username (str): The username of the new user password (str): ...
stack_v2_sparse_classes_75kplus_train_071840
2,438
no_license
[ { "docstring": "Create superuser Creates a new superuser. Will default `is_staff`, `is_superuser` and `is_active` Args: email (str): The email of the new user username (str): The username of the new user password (str): The password of the new user Optional Args: is_staff (bool): Flag to indicate if the unew us...
2
null
Implement the Python class `AccountManager` described below. Class description: Implement the AccountManager class. Method signatures and docstrings: - def create_superuser(self, email, username, password, **kwargs): Create superuser Creates a new superuser. Will default `is_staff`, `is_superuser` and `is_active` Arg...
Implement the Python class `AccountManager` described below. Class description: Implement the AccountManager class. Method signatures and docstrings: - def create_superuser(self, email, username, password, **kwargs): Create superuser Creates a new superuser. Will default `is_staff`, `is_superuser` and `is_active` Arg...
3fa600d67c82559694612a0634590a205b1790eb
<|skeleton|> class AccountManager: def create_superuser(self, email, username, password, **kwargs): """Create superuser Creates a new superuser. Will default `is_staff`, `is_superuser` and `is_active` Args: email (str): The email of the new user username (str): The username of the new user password (str): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AccountManager: def create_superuser(self, email, username, password, **kwargs): """Create superuser Creates a new superuser. Will default `is_staff`, `is_superuser` and `is_active` Args: email (str): The email of the new user username (str): The username of the new user password (str): The password o...
the_stack_v2_python_sparse
backend/accounts/manager.py
aaronsnig501/drams
train
0
5baba72b0b871f1940e2a59e77a40b993d2eaa55
[ "super(Pendulum, self).__init__()\nself._mass = mass\nself._length = length\nself._friction = friction\nself._g = gravity", "x1 = state[..., 0:1]\nx2 = state[..., 1:2]\nif p is None:\n mass = self._mass\n length = self._length\n friction = self._friction\nelse:\n assert len(p) == 3\n mass = p[0]\n ...
<|body_start_0|> super(Pendulum, self).__init__() self._mass = mass self._length = length self._friction = friction self._g = gravity <|end_body_0|> <|body_start_1|> x1 = state[..., 0:1] x2 = state[..., 1:2] if p is None: mass = self._mass ...
Ground dynamics for a pendulum with friction. The state is two dimensional and represents angular position and velocity.
Pendulum
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pendulum: """Ground dynamics for a pendulum with friction. The state is two dimensional and represents angular position and velocity.""" def __init__(self, mass: float=1.0, length: float=1.0, friction: float=0.1, gravity: float=9.80665) -> None: """Initialize a pendulum system. Param...
stack_v2_sparse_classes_75kplus_train_071841
9,729
permissive
[ { "docstring": "Initialize a pendulum system. Parameters ---------- mass : float, default=1.0 The mass of the pendulum. length : float, default=1.0 The length of the pendulum. friction : float, default=0.1 The friction coefficient. gravity : float, default=9.80665 Gravity.", "name": "__init__", "signatu...
3
stack_v2_sparse_classes_30k_train_016150
Implement the Python class `Pendulum` described below. Class description: Ground dynamics for a pendulum with friction. The state is two dimensional and represents angular position and velocity. Method signatures and docstrings: - def __init__(self, mass: float=1.0, length: float=1.0, friction: float=0.1, gravity: fl...
Implement the Python class `Pendulum` described below. Class description: Ground dynamics for a pendulum with friction. The state is two dimensional and represents angular position and velocity. Method signatures and docstrings: - def __init__(self, mass: float=1.0, length: float=1.0, friction: float=0.1, gravity: fl...
184b1537c22ebc2f614677be8fe171de785bda42
<|skeleton|> class Pendulum: """Ground dynamics for a pendulum with friction. The state is two dimensional and represents angular position and velocity.""" def __init__(self, mass: float=1.0, length: float=1.0, friction: float=0.1, gravity: float=9.80665) -> None: """Initialize a pendulum system. Param...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Pendulum: """Ground dynamics for a pendulum with friction. The state is two dimensional and represents angular position and velocity.""" def __init__(self, mass: float=1.0, length: float=1.0, friction: float=0.1, gravity: float=9.80665) -> None: """Initialize a pendulum system. Parameters -------...
the_stack_v2_python_sparse
dynamics_learning/networks/dynamics.py
cristovaoiglesias/replay-overshooting
train
0
ed846e615602f0e5c4f9087e6f59dae5e34e1d30
[ "self.file_name = file_name\nself.file_handler = None\nreturn", "print('enter:', self.file_name)\nself.file_handler = open(self.file_name, 'r')\nreturn self.file_handler", "print('exit:', exc_type, exc_val, exc_tb)\nif self.file_handler:\n self.file_handler.close()\nreturn False" ]
<|body_start_0|> self.file_name = file_name self.file_handler = None return <|end_body_0|> <|body_start_1|> print('enter:', self.file_name) self.file_handler = open(self.file_name, 'r') return self.file_handler <|end_body_1|> <|body_start_2|> print('exit:', exc_...
MyOpen
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyOpen: def __init__(self, file_name): """初始化方法""" <|body_0|> def __enter__(self): """enter方法,返回file_handler""" <|body_1|> def __exit__(self, exc_type, exc_val, exc_tb): """exit方法,关闭文件并返回True""" <|body_2|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_75kplus_train_071842
910
no_license
[ { "docstring": "初始化方法", "name": "__init__", "signature": "def __init__(self, file_name)" }, { "docstring": "enter方法,返回file_handler", "name": "__enter__", "signature": "def __enter__(self)" }, { "docstring": "exit方法,关闭文件并返回True", "name": "__exit__", "signature": "def __exi...
3
stack_v2_sparse_classes_30k_train_006094
Implement the Python class `MyOpen` described below. Class description: Implement the MyOpen class. Method signatures and docstrings: - def __init__(self, file_name): 初始化方法 - def __enter__(self): enter方法,返回file_handler - def __exit__(self, exc_type, exc_val, exc_tb): exit方法,关闭文件并返回True
Implement the Python class `MyOpen` described below. Class description: Implement the MyOpen class. Method signatures and docstrings: - def __init__(self, file_name): 初始化方法 - def __enter__(self): enter方法,返回file_handler - def __exit__(self, exc_type, exc_val, exc_tb): exit方法,关闭文件并返回True <|skeleton|> class MyOpen: ...
a0202c81372758922128dc6e4c8911849f2663ad
<|skeleton|> class MyOpen: def __init__(self, file_name): """初始化方法""" <|body_0|> def __enter__(self): """enter方法,返回file_handler""" <|body_1|> def __exit__(self, exc_type, exc_val, exc_tb): """exit方法,关闭文件并返回True""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyOpen: def __init__(self, file_name): """初始化方法""" self.file_name = file_name self.file_handler = None return def __enter__(self): """enter方法,返回file_handler""" print('enter:', self.file_name) self.file_handler = open(self.file_name, 'r') ret...
the_stack_v2_python_sparse
核心编程_2/chapter_10_error/10.4_context_management/10.4.2_context_management_protocol/My_with.py
MonsterDragon/play_python
train
1
f0364dc0b2b690913cdd4e02c100e26e3b54cb4f
[ "super().__init__(env)\nself.num_envs = getattr(env, 'num_envs', 1)\nself.t0 = time.perf_counter()\nself.episode_count = 0\nself.episode_returns: Optional[np.ndarray] = None\nself.episode_lengths: Optional[np.ndarray] = None\nself.return_queue = deque(maxlen=deque_size)\nself.length_queue = deque(maxlen=deque_size)...
<|body_start_0|> super().__init__(env) self.num_envs = getattr(env, 'num_envs', 1) self.t0 = time.perf_counter() self.episode_count = 0 self.episode_returns: Optional[np.ndarray] = None self.episode_lengths: Optional[np.ndarray] = None self.return_queue = deque(ma...
This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``_episode`` is used which indicates whether the env at the respective index has the episode...
RecordEpisodeStatistics
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RecordEpisodeStatistics: """This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``_episode`` is used which indicates whet...
stack_v2_sparse_classes_75kplus_train_071843
5,650
permissive
[ { "docstring": "This wrapper will keep track of cumulative rewards and episode lengths. Args: env (Env): The environment to apply the wrapper deque_size: The size of the buffers :attr:`return_queue` and :attr:`length_queue`", "name": "__init__", "signature": "def __init__(self, env: gym.Env, deque_size:...
3
stack_v2_sparse_classes_30k_train_054325
Implement the Python class `RecordEpisodeStatistics` described below. Class description: This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``...
Implement the Python class `RecordEpisodeStatistics` described below. Class description: This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``...
53d784eafed28d31ec41c36ebd9eee14b0dc6d41
<|skeleton|> class RecordEpisodeStatistics: """This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``_episode`` is used which indicates whet...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RecordEpisodeStatistics: """This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``_episode`` is used which indicates whether the env a...
the_stack_v2_python_sparse
gym/wrappers/record_episode_statistics.py
thomascherickal/gym
train
2
4ab317c298f1eea37897b20be341e5d8a27b3110
[ "if data is None:\n n = int(n)\n p = float(p)\n if n <= 0:\n raise ValueError('n must be a positive value')\n if p <= 0 or p >= 1:\n raise ValueError('p must be greater than 0 and less than 1')\n self.p = p\n self.n = n\nelse:\n if type(data) is not list:\n raise TypeError(...
<|body_start_0|> if data is None: n = int(n) p = float(p) if n <= 0: raise ValueError('n must be a positive value') if p <= 0 or p >= 1: raise ValueError('p must be greater than 0 and less than 1') self.p = p ...
class Binomial
Binomial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binomial: """class Binomial""" def __init__(self, data=None, n=1, p=0.5): """constructor""" <|body_0|> def pmf(self, k): """Probability Mass Function PMF""" <|body_1|> def cdf(self, k): """Cumulative Distribution Function CDF""" <|bod...
stack_v2_sparse_classes_75kplus_train_071844
1,891
no_license
[ { "docstring": "constructor", "name": "__init__", "signature": "def __init__(self, data=None, n=1, p=0.5)" }, { "docstring": "Probability Mass Function PMF", "name": "pmf", "signature": "def pmf(self, k)" }, { "docstring": "Cumulative Distribution Function CDF", "name": "cdf"...
3
stack_v2_sparse_classes_30k_train_014125
Implement the Python class `Binomial` described below. Class description: class Binomial Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): constructor - def pmf(self, k): Probability Mass Function PMF - def cdf(self, k): Cumulative Distribution Function CDF
Implement the Python class `Binomial` described below. Class description: class Binomial Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): constructor - def pmf(self, k): Probability Mass Function PMF - def cdf(self, k): Cumulative Distribution Function CDF <|skeleton|> class Binomial: ...
8ad4c2594ff78b345dbd92e9d54d2a143ac4071a
<|skeleton|> class Binomial: """class Binomial""" def __init__(self, data=None, n=1, p=0.5): """constructor""" <|body_0|> def pmf(self, k): """Probability Mass Function PMF""" <|body_1|> def cdf(self, k): """Cumulative Distribution Function CDF""" <|bod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Binomial: """class Binomial""" def __init__(self, data=None, n=1, p=0.5): """constructor""" if data is None: n = int(n) p = float(p) if n <= 0: raise ValueError('n must be a positive value') if p <= 0 or p >= 1: ...
the_stack_v2_python_sparse
math/0x03-probability/graphs/binomial.py
jorgezafra94/holbertonschool-machine_learning
train
1
98f16f954ead872ae1f5f0ddad6fc6eba9818c7e
[ "def inorder(r: TreeNode) -> List[int]:\n return inorder(r.left) + [r.val] + inorder(r.right) if r else []\nreturn inorder(root)[k - 1]", "stack = []\nwhile True:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n k -= 1\n if not k:\n return root.val\n...
<|body_start_0|> def inorder(r: TreeNode) -> List[int]: return inorder(r.left) + [r.val] + inorder(r.right) if r else [] return inorder(root)[k - 1] <|end_body_0|> <|body_start_1|> stack = [] while True: while root: stack.append(root) ...
OfficialSolution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OfficialSolution: def ktn_smallest(self, root: TreeNode, k: int) -> int: """递归(中序遍历)。""" <|body_0|> def ktn_smallest_2(self, root: TreeNode, k: int) -> int: """root 是二叉搜索树, 使用迭代来中序遍历树,不用像递归那样遍历整棵树,可以在找到答案后停止。""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_071845
4,935
no_license
[ { "docstring": "递归(中序遍历)。", "name": "ktn_smallest", "signature": "def ktn_smallest(self, root: TreeNode, k: int) -> int" }, { "docstring": "root 是二叉搜索树, 使用迭代来中序遍历树,不用像递归那样遍历整棵树,可以在找到答案后停止。", "name": "ktn_smallest_2", "signature": "def ktn_smallest_2(self, root: TreeNode, k: int) -> int" ...
2
stack_v2_sparse_classes_30k_train_044293
Implement the Python class `OfficialSolution` described below. Class description: Implement the OfficialSolution class. Method signatures and docstrings: - def ktn_smallest(self, root: TreeNode, k: int) -> int: 递归(中序遍历)。 - def ktn_smallest_2(self, root: TreeNode, k: int) -> int: root 是二叉搜索树, 使用迭代来中序遍历树,不用像递归那样遍历整棵树,可...
Implement the Python class `OfficialSolution` described below. Class description: Implement the OfficialSolution class. Method signatures and docstrings: - def ktn_smallest(self, root: TreeNode, k: int) -> int: 递归(中序遍历)。 - def ktn_smallest_2(self, root: TreeNode, k: int) -> int: root 是二叉搜索树, 使用迭代来中序遍历树,不用像递归那样遍历整棵树,可...
6932d69353b94ec824dd0ddc86a92453f6673232
<|skeleton|> class OfficialSolution: def ktn_smallest(self, root: TreeNode, k: int) -> int: """递归(中序遍历)。""" <|body_0|> def ktn_smallest_2(self, root: TreeNode, k: int) -> int: """root 是二叉搜索树, 使用迭代来中序遍历树,不用像递归那样遍历整棵树,可以在找到答案后停止。""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OfficialSolution: def ktn_smallest(self, root: TreeNode, k: int) -> int: """递归(中序遍历)。""" def inorder(r: TreeNode) -> List[int]: return inorder(r.left) + [r.val] + inorder(r.right) if r else [] return inorder(root)[k - 1] def ktn_smallest_2(self, root: TreeNode, k: int)...
the_stack_v2_python_sparse
0230_kth-smallest-element-in-a-bst.py
Nigirimeshi/leetcode
train
0
de15db075e6f7a57a3b944d75654fd4d9c333642
[ "self.metrics = format_metrics(metrics)\nself.do_score = do_score\nself.__in_fold = in_fold if in_fold else []\nself.__oof = oof if oof else []\nself.__holdout = holdout if holdout else []\nself._validate_metrics_list_parameters()\nself.last_evaluation_results = dict(in_fold=None, oof=None, holdout=None)", "for _...
<|body_start_0|> self.metrics = format_metrics(metrics) self.do_score = do_score self.__in_fold = in_fold if in_fold else [] self.__oof = oof if oof else [] self.__holdout = holdout if holdout else [] self._validate_metrics_list_parameters() self.last_evaluation_r...
ScoringMixIn
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScoringMixIn: def __init__(self, metrics, in_fold='all', oof='all', holdout='all', do_score=True): """MixIn class to manage metrics to record for each dataset type, and perform evaluations Parameters ---------- metrics: Dict, List Specifies all metrics to be used by their id keys, along ...
stack_v2_sparse_classes_75kplus_train_071846
23,341
permissive
[ { "docstring": "MixIn class to manage metrics to record for each dataset type, and perform evaluations Parameters ---------- metrics: Dict, List Specifies all metrics to be used by their id keys, along with a means to compute the metric. If list, all values must be strings that are attributes in :mod:`sklearn.m...
3
null
Implement the Python class `ScoringMixIn` described below. Class description: Implement the ScoringMixIn class. Method signatures and docstrings: - def __init__(self, metrics, in_fold='all', oof='all', holdout='all', do_score=True): MixIn class to manage metrics to record for each dataset type, and perform evaluation...
Implement the Python class `ScoringMixIn` described below. Class description: Implement the ScoringMixIn class. Method signatures and docstrings: - def __init__(self, metrics, in_fold='all', oof='all', holdout='all', do_score=True): MixIn class to manage metrics to record for each dataset type, and perform evaluation...
bfbd1faf63272a62e6f971d7e9a0487d71aea8f6
<|skeleton|> class ScoringMixIn: def __init__(self, metrics, in_fold='all', oof='all', holdout='all', do_score=True): """MixIn class to manage metrics to record for each dataset type, and perform evaluations Parameters ---------- metrics: Dict, List Specifies all metrics to be used by their id keys, along ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ScoringMixIn: def __init__(self, metrics, in_fold='all', oof='all', holdout='all', do_score=True): """MixIn class to manage metrics to record for each dataset type, and perform evaluations Parameters ---------- metrics: Dict, List Specifies all metrics to be used by their id keys, along with a means t...
the_stack_v2_python_sparse
hyperparameter_hunter/metrics.py
mdjabc/hyperparameter_hunter
train
1
778fb8755ea8a1899219b17128acb489e8095a1d
[ "self.expdf = assign_rxn_types(selected_df.copy())\nself.expdf = add_interpreted_columns(self.expdf)\nif alldf is not None:\n self.alldf = assign_rxn_types(alldf.copy())\n self.alldf = add_interpreted_columns(self.alldf)\nif expname is not None:\n self.expname = expname\nelse:\n self.expname = str(self....
<|body_start_0|> self.expdf = assign_rxn_types(selected_df.copy()) self.expdf = add_interpreted_columns(self.expdf) if alldf is not None: self.alldf = assign_rxn_types(alldf.copy()) self.alldf = add_interpreted_columns(self.alldf) if expname is not None: ...
CAZyExperiment2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CAZyExperiment2: def __init__(self, selected_df, alldf=None, expname=None): """Takes a tecan dataframe, makes a copy and adds fields needed for activity calculations (inc baseline subtractions) Arguments: selected_df: the dataframe Kewyord arguments: alldf: the dataframe with all activit...
stack_v2_sparse_classes_75kplus_train_071847
17,357
no_license
[ { "docstring": "Takes a tecan dataframe, makes a copy and adds fields needed for activity calculations (inc baseline subtractions) Arguments: selected_df: the dataframe Kewyord arguments: alldf: the dataframe with all activities (default None) expname: name for this experiment (otherwise use date)- default None...
2
stack_v2_sparse_classes_30k_test_002099
Implement the Python class `CAZyExperiment2` described below. Class description: Implement the CAZyExperiment2 class. Method signatures and docstrings: - def __init__(self, selected_df, alldf=None, expname=None): Takes a tecan dataframe, makes a copy and adds fields needed for activity calculations (inc baseline subt...
Implement the Python class `CAZyExperiment2` described below. Class description: Implement the CAZyExperiment2 class. Method signatures and docstrings: - def __init__(self, selected_df, alldf=None, expname=None): Takes a tecan dataframe, makes a copy and adds fields needed for activity calculations (inc baseline subt...
458822d7f5221e04387bd53d6539d290b7e1630a
<|skeleton|> class CAZyExperiment2: def __init__(self, selected_df, alldf=None, expname=None): """Takes a tecan dataframe, makes a copy and adds fields needed for activity calculations (inc baseline subtractions) Arguments: selected_df: the dataframe Kewyord arguments: alldf: the dataframe with all activit...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CAZyExperiment2: def __init__(self, selected_df, alldf=None, expname=None): """Takes a tecan dataframe, makes a copy and adds fields needed for activity calculations (inc baseline subtractions) Arguments: selected_df: the dataframe Kewyord arguments: alldf: the dataframe with all activities (default N...
the_stack_v2_python_sparse
tecanpack/tecandata.py
KirkVM/kdatapack
train
0
eedf072f38a5bd0cf24c5bde2febdee1785981fa
[ "self._disable_patching = True\nself._validate_base(self)\nself._disable_patching = False", "self._validate()\nresult = method(*args, **kwargs)\nself._validate()\nreturn result", "attr = super().__getattribute__(name)\nif name in ('_patched_method', '_validate', '_validate_base', '_disable_patching'):\n retu...
<|body_start_0|> self._disable_patching = True self._validate_base(self) self._disable_patching = False <|end_body_0|> <|body_start_1|> self._validate() result = method(*args, **kwargs) self._validate() return result <|end_body_1|> <|body_start_2|> attr ...
InvariantedClass
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InvariantedClass: def _validate(self) -> None: """Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.""" <|body_0|> def _patched_method(self, method: Callable, *args, **kwargs): """Step 4 (1st flow). Call method""" <|body_1|> def __getat...
stack_v2_sparse_classes_75kplus_train_071848
3,490
permissive
[ { "docstring": "Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.", "name": "_validate", "signature": "def _validate(self) -> None" }, { "docstring": "Step 4 (1st flow). Call method", "name": "_patched_method", "signature": "def _patched_method(self, method: Callable, ...
4
stack_v2_sparse_classes_30k_train_028257
Implement the Python class `InvariantedClass` described below. Class description: Implement the InvariantedClass class. Method signatures and docstrings: - def _validate(self) -> None: Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object. - def _patched_method(self, method: Callable, *args, **kwargs): ...
Implement the Python class `InvariantedClass` described below. Class description: Implement the InvariantedClass class. Method signatures and docstrings: - def _validate(self) -> None: Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object. - def _patched_method(self, method: Callable, *args, **kwargs): ...
9dff86e1dc5c8607f02ded34b6d64e770f1959fa
<|skeleton|> class InvariantedClass: def _validate(self) -> None: """Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.""" <|body_0|> def _patched_method(self, method: Callable, *args, **kwargs): """Step 4 (1st flow). Call method""" <|body_1|> def __getat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InvariantedClass: def _validate(self) -> None: """Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.""" self._disable_patching = True self._validate_base(self) self._disable_patching = False def _patched_method(self, method: Callable, *args, **kwargs): ...
the_stack_v2_python_sparse
deal/_decorators/inv.py
toonarmycaptain/deal
train
0
dd6fb69a0c1d23d068dec2e74c66a484ccbfbd8f
[ "super(FilterSpinAgent, self).__init__(parent, datatree)\nself.addRequest('spinfield')\nself.requestUpdatedSignal.connect(self.buildSpin)\nself.spin_values = list()\nself.spin_field = ''\nself.spin_selected = -1", "if len(indexList) > 1:\n indexList = list(indexList[0])\nself.requestAddIndices('spinfield', ind...
<|body_start_0|> super(FilterSpinAgent, self).__init__(parent, datatree) self.addRequest('spinfield') self.requestUpdatedSignal.connect(self.buildSpin) self.spin_values = list() self.spin_field = '' self.spin_selected = -1 <|end_body_0|> <|body_start_1|> if len(i...
Agent for all FilterSpin modules, associates filters with modules. The Filter Spin takes a single numeric field and adds a filter setting all data under it to whatever a specific value in that field is. The idea is that using a spin control, the user can move through all the values of the field separately. For example,...
FilterSpinAgent
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FilterSpinAgent: """Agent for all FilterSpin modules, associates filters with modules. The Filter Spin takes a single numeric field and adds a filter setting all data under it to whatever a specific value in that field is. The idea is that using a spin control, the user can move through all the v...
stack_v2_sparse_classes_75kplus_train_071849
6,795
no_license
[ { "docstring": "Constructor for FilterSpinAgent.", "name": "__init__", "signature": "def __init__(self, parent, datatree)" }, { "docstring": "This function handles an added list of DataTree indices by associated them with the agent's Request. We only accept a single index in the Filter Spin so w...
4
stack_v2_sparse_classes_30k_train_051497
Implement the Python class `FilterSpinAgent` described below. Class description: Agent for all FilterSpin modules, associates filters with modules. The Filter Spin takes a single numeric field and adds a filter setting all data under it to whatever a specific value in that field is. The idea is that using a spin contr...
Implement the Python class `FilterSpinAgent` described below. Class description: Agent for all FilterSpin modules, associates filters with modules. The Filter Spin takes a single numeric field and adds a filter setting all data under it to whatever a specific value in that field is. The idea is that using a spin contr...
afa9c9547716909d806a0bd8165bfe896617ca7e
<|skeleton|> class FilterSpinAgent: """Agent for all FilterSpin modules, associates filters with modules. The Filter Spin takes a single numeric field and adds a filter setting all data under it to whatever a specific value in that field is. The idea is that using a spin control, the user can move through all the v...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FilterSpinAgent: """Agent for all FilterSpin modules, associates filters with modules. The Filter Spin takes a single numeric field and adds a filter setting all data under it to whatever a specific value in that field is. The idea is that using a spin control, the user can move through all the values of the ...
the_stack_v2_python_sparse
boxfish/FilterSpin.py
LLNL/boxfish
train
4
4d3951c9086673f5c536c16ea668685ce67ed6b1
[ "try:\n _file = os.path.join(TRANSFORMED_DATA_DIR, file_name)\n if mode == 'a':\n if not os.path.isfile(_file):\n data.to_csv(_file, mode='a', index=False)\n else:\n data.to_csv(_file, mode='a', header=False, index=False)\n elif mode == 'w':\n data.to_csv(_file, m...
<|body_start_0|> try: _file = os.path.join(TRANSFORMED_DATA_DIR, file_name) if mode == 'a': if not os.path.isfile(_file): data.to_csv(_file, mode='a', index=False) else: data.to_csv(_file, mode='a', header=False, ind...
This class contains methods to Extract data from pre-decided sources and Transform them according to the project needs. Then writes the data sources to a predefined location as stated in TRANSFORMED_DATA_DIR.
ExtractTransform
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtractTransform: """This class contains methods to Extract data from pre-decided sources and Transform them according to the project needs. Then writes the data sources to a predefined location as stated in TRANSFORMED_DATA_DIR.""" def _perform_write(self, data, file_name, mode='w'): ...
stack_v2_sparse_classes_75kplus_train_071850
2,911
permissive
[ { "docstring": "Writes the data to disk", "name": "_perform_write", "signature": "def _perform_write(self, data, file_name, mode='w')" }, { "docstring": "Fetches data from each of the sources serially.", "name": "pipeline", "signature": "def pipeline(self, mode='w')" } ]
2
stack_v2_sparse_classes_30k_train_015826
Implement the Python class `ExtractTransform` described below. Class description: This class contains methods to Extract data from pre-decided sources and Transform them according to the project needs. Then writes the data sources to a predefined location as stated in TRANSFORMED_DATA_DIR. Method signatures and docst...
Implement the Python class `ExtractTransform` described below. Class description: This class contains methods to Extract data from pre-decided sources and Transform them according to the project needs. Then writes the data sources to a predefined location as stated in TRANSFORMED_DATA_DIR. Method signatures and docst...
8f33a8b0194eb77e3018f16c153291bd451fb072
<|skeleton|> class ExtractTransform: """This class contains methods to Extract data from pre-decided sources and Transform them according to the project needs. Then writes the data sources to a predefined location as stated in TRANSFORMED_DATA_DIR.""" def _perform_write(self, data, file_name, mode='w'): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExtractTransform: """This class contains methods to Extract data from pre-decided sources and Transform them according to the project needs. Then writes the data sources to a predefined location as stated in TRANSFORMED_DATA_DIR.""" def _perform_write(self, data, file_name, mode='w'): """Writes t...
the_stack_v2_python_sparse
src/etl/extract_transform.py
gunnerVivek/Abusive-language-detection-in-Online-content
train
0
706ef83f8504f257c5a7d287bf342f597038bd88
[ "cpacs_path = mif.get_toolinput_file_path('SMUse')\ntixi = cpsf.open_tixi(cpacs_path)\nself.Model = smu.load_surrogate(tixi)\ncpsf.close_tixi(tixi, cpacs_path)\ndf = self.Model.df\ndf.set_index('Name', inplace=True)\nfor name in df.index:\n if df.loc[name, 'type'] == 'obj':\n self.add_output(name)\n el...
<|body_start_0|> cpacs_path = mif.get_toolinput_file_path('SMUse') tixi = cpsf.open_tixi(cpacs_path) self.Model = smu.load_surrogate(tixi) cpsf.close_tixi(tixi, cpacs_path) df = self.Model.df df.set_index('Name', inplace=True) for name in df.index: if ...
Uses a surrogate model to make a prediction
SmComp
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmComp: """Uses a surrogate model to make a prediction""" def setup(self): """Setup inputs and outputs""" <|body_0|> def compute(self, inputs, outputs): """Make a prediction""" <|body_1|> <|end_skeleton|> <|body_start_0|> cpacs_path = mif.get_to...
stack_v2_sparse_classes_75kplus_train_071851
21,151
permissive
[ { "docstring": "Setup inputs and outputs", "name": "setup", "signature": "def setup(self)" }, { "docstring": "Make a prediction", "name": "compute", "signature": "def compute(self, inputs, outputs)" } ]
2
stack_v2_sparse_classes_30k_train_024581
Implement the Python class `SmComp` described below. Class description: Uses a surrogate model to make a prediction Method signatures and docstrings: - def setup(self): Setup inputs and outputs - def compute(self, inputs, outputs): Make a prediction
Implement the Python class `SmComp` described below. Class description: Uses a surrogate model to make a prediction Method signatures and docstrings: - def setup(self): Setup inputs and outputs - def compute(self, inputs, outputs): Make a prediction <|skeleton|> class SmComp: """Uses a surrogate model to make a ...
3cc211507caab176a76213e442238abfa43afa42
<|skeleton|> class SmComp: """Uses a surrogate model to make a prediction""" def setup(self): """Setup inputs and outputs""" <|body_0|> def compute(self, inputs, outputs): """Make a prediction""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SmComp: """Uses a surrogate model to make a prediction""" def setup(self): """Setup inputs and outputs""" cpacs_path = mif.get_toolinput_file_path('SMUse') tixi = cpsf.open_tixi(cpacs_path) self.Model = smu.load_surrogate(tixi) cpsf.close_tixi(tixi, cpacs_path) ...
the_stack_v2_python_sparse
ceasiompy/Optimisation/optimisation.py
schneo/CEASIOMpy
train
0
3edee89c120048c8326d2ad98a278301d369d2e9
[ "assert isinstance(node, Node)\nmethod = 'visit_' + node.__class__.__name__\nvisitor = getattr(self, method, self.generic_visit)\nreturn visitor(node)", "assert isinstance(node, Node)\nfor child in node.children():\n self.visit(child)" ]
<|body_start_0|> assert isinstance(node, Node) method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node) <|end_body_0|> <|body_start_1|> assert isinstance(node, Node) for child in node.children(): sel...
A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. Per default the visitor functions for the nodes are ...
NodeVisitor
[ "BSD-2-Clause-Views" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NodeVisitor: """A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. Per default t...
stack_v2_sparse_classes_75kplus_train_071852
1,431
permissive
[ { "docstring": "Visit a node.", "name": "visit", "signature": "def visit(self, node)" }, { "docstring": "Called if no explicit visitor function exists for a node. Implements preorder visiting of the node.", "name": "generic_visit", "signature": "def generic_visit(self, node)" } ]
2
stack_v2_sparse_classes_30k_train_025679
Implement the Python class `NodeVisitor` described below. Class description: A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclas...
Implement the Python class `NodeVisitor` described below. Class description: A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclas...
230fc9df874d20739bb98273dc45e45519f0402c
<|skeleton|> class NodeVisitor: """A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. Per default t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NodeVisitor: """A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. Per default the visitor fu...
the_stack_v2_python_sparse
cvx4py/ast/node_visitor.py
ssarkar2/cvx4py_2
train
0
9aac3f9e15d04d21001cfcf25b61b9058b719cee
[ "super().__init__()\nself.WRD_EMB_DIM = WRD_EMB_DIM\nself.ENC_DIM = ENC_DIM\nself.bilstm = torch.nn.LSTM(input_size=self.WRD_EMB_DIM, hidden_size=self.ENC_DIM // 2, num_layers=1, batch_first=True, bidirectional=True)\nd = self.ENC_DIM // 2\nfan_avg = (d * 4 + (d + self.WRD_EMB_DIM)) / 2.0\nbound = np.sqrt(3.0 / fan...
<|body_start_0|> super().__init__() self.WRD_EMB_DIM = WRD_EMB_DIM self.ENC_DIM = ENC_DIM self.bilstm = torch.nn.LSTM(input_size=self.WRD_EMB_DIM, hidden_size=self.ENC_DIM // 2, num_layers=1, batch_first=True, bidirectional=True) d = self.ENC_DIM // 2 fan_avg = (d * 4 + (...
BiLSTM
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BiLSTM: def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None: """Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimension of the encoder for BiLSTM, which is twice of the hidden state dimension forget_gate_bias:(o...
stack_v2_sparse_classes_75kplus_train_071853
5,915
permissive
[ { "docstring": "Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimension of the encoder for BiLSTM, which is twice of the hidden state dimension forget_gate_bias:(optional):the initialization of the forget-gate bias", "name": "__init__", "signature": "def __init__...
2
stack_v2_sparse_classes_30k_train_033330
Implement the Python class `BiLSTM` described below. Class description: Implement the BiLSTM class. Method signatures and docstrings: - def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None: Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimens...
Implement the Python class `BiLSTM` described below. Class description: Implement the BiLSTM class. Method signatures and docstrings: - def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None: Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimens...
af87a17275f02c94932bb2e29f132a84db812002
<|skeleton|> class BiLSTM: def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None: """Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimension of the encoder for BiLSTM, which is twice of the hidden state dimension forget_gate_bias:(o...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BiLSTM: def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None: """Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimension of the encoder for BiLSTM, which is twice of the hidden state dimension forget_gate_bias:(optional):the i...
the_stack_v2_python_sparse
imix/models/encoder/lcgnencoder.py
linxi1158/iMIX
train
0
bd5a1d63333b2f3b11af9f73a0f5c2b9751ed557
[ "word = self.sentence[i]\nnew_indexes = self.indexes + (i,)\nfor subtree in self.ngram_tree.iter_subtrees_matching_word(word):\n yield NgramPartialMatch(subtree, self.sentence, self.n_available_gaps, new_indexes)\nif self.n_available_gaps > 0 and self.indexes:\n yield NgramPartialMatch(self.ngram_tree, self.s...
<|body_start_0|> word = self.sentence[i] new_indexes = self.indexes + (i,) for subtree in self.ngram_tree.iter_subtrees_matching_word(word): yield NgramPartialMatch(subtree, self.sentence, self.n_available_gaps, new_indexes) if self.n_available_gaps > 0 and self.indexes: ...
Instances of NgramPartialMatch represent a partial match of a sentence fragment as a path in an NgramTree. You need to use this class when: * You want to find matches with gaps; or * You want to have multiple matches with many different starting indexes in a sentence; or * You want a list of all matched indexes. Argume...
NgramPartialMatch
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NgramPartialMatch: """Instances of NgramPartialMatch represent a partial match of a sentence fragment as a path in an NgramTree. You need to use this class when: * You want to find matches with gaps; or * You want to have multiple matches with many different starting indexes in a sentence; or * Y...
stack_v2_sparse_classes_75kplus_train_071854
6,098
no_license
[ { "docstring": "For a given sentence index `i`, walk the tree and yield new NgramPartialMatch instances.", "name": "matching_at", "signature": "def matching_at(self, i)" }, { "docstring": "For a given sentence index `i`, check if the current tree position is associated with Ngram instances and y...
2
stack_v2_sparse_classes_30k_train_014019
Implement the Python class `NgramPartialMatch` described below. Class description: Instances of NgramPartialMatch represent a partial match of a sentence fragment as a path in an NgramTree. You need to use this class when: * You want to find matches with gaps; or * You want to have multiple matches with many different...
Implement the Python class `NgramPartialMatch` described below. Class description: Instances of NgramPartialMatch represent a partial match of a sentence fragment as a path in an NgramTree. You need to use this class when: * You want to find matches with gaps; or * You want to have multiple matches with many different...
e53ed9ff78640a2e579a23aca8bf94543cb58545
<|skeleton|> class NgramPartialMatch: """Instances of NgramPartialMatch represent a partial match of a sentence fragment as a path in an NgramTree. You need to use this class when: * You want to find matches with gaps; or * You want to have multiple matches with many different starting indexes in a sentence; or * Y...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NgramPartialMatch: """Instances of NgramPartialMatch represent a partial match of a sentence fragment as a path in an NgramTree. You need to use this class when: * You want to find matches with gaps; or * You want to have multiple matches with many different starting indexes in a sentence; or * You want a lis...
the_stack_v2_python_sparse
TP01-corpus/bin/libs/base/ngramtree.py
LicenceInformatique3/Licence3LangageNaturelTD-TP
train
0
09840e39a2c9da557345d141cc92efcedf96aae5
[ "super(MLPSubNet, self).__init__()\nself.norm = nn.BatchNorm1d(in_size)\nself.drop = nn.Dropout(p=dropout)\nself.linear_1 = nn.Linear(in_size, hidden_size)\nself.linear_2 = nn.Linear(hidden_size, hidden_size)\nself.linear_3 = nn.Linear(hidden_size, hidden_size)", "x = torch.mean(x, dim=1, keepdim=False)\nnormed =...
<|body_start_0|> super(MLPSubNet, self).__init__() self.norm = nn.BatchNorm1d(in_size) self.drop = nn.Dropout(p=dropout) self.linear_1 = nn.Linear(in_size, hidden_size) self.linear_2 = nn.Linear(hidden_size, hidden_size) self.linear_3 = nn.Linear(hidden_size, hidden_size)...
The subnetwork that is used in TFN for video and audio in the pre-fusion stage
MLPSubNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MLPSubNet: """The subnetwork that is used in TFN for video and audio in the pre-fusion stage""" def __init__(self, in_size, hidden_size, dropout): """Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a te...
stack_v2_sparse_classes_75kplus_train_071855
4,871
no_license
[ { "docstring": "Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tensor of shape (batch_size, hidden_size)", "name": "__init__", "signature": "def __init__(self, in_size, hidden_size, dropout)" }, { "docstring": "...
2
stack_v2_sparse_classes_30k_train_053636
Implement the Python class `MLPSubNet` described below. Class description: The subnetwork that is used in TFN for video and audio in the pre-fusion stage Method signatures and docstrings: - def __init__(self, in_size, hidden_size, dropout): Args: in_size: input dimension hidden_size: hidden layer dimension dropout: d...
Implement the Python class `MLPSubNet` described below. Class description: The subnetwork that is used in TFN for video and audio in the pre-fusion stage Method signatures and docstrings: - def __init__(self, in_size, hidden_size, dropout): Args: in_size: input dimension hidden_size: hidden layer dimension dropout: d...
1291ba64cd2e6e723abf290e6feef1392da7ee82
<|skeleton|> class MLPSubNet: """The subnetwork that is used in TFN for video and audio in the pre-fusion stage""" def __init__(self, in_size, hidden_size, dropout): """Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MLPSubNet: """The subnetwork that is used in TFN for video and audio in the pre-fusion stage""" def __init__(self, in_size, hidden_size, dropout): """Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tensor of shape...
the_stack_v2_python_sparse
models/.ipynb_checkpoints/TFN-checkpoint.py
littlehacker26/diasenti
train
0
8490fd537ed5d3c28cd597e45f54b5668d6934b4
[ "super().__init__()\nassert method in ('max', 'avg', 'sum')\nself._method = method", "assert x.dim() == 3, 'Requires x shape (batch_size x seq_len x feature_dim)'\nb, t = (x.shape[0], x.shape[1])\nif mask is None:\n mask = torch.ones((b, t), dtype=torch.bool)\nif self._method == 'max':\n x[~mask, :] = float...
<|body_start_0|> super().__init__() assert method in ('max', 'avg', 'sum') self._method = method <|end_body_0|> <|body_start_1|> assert x.dim() == 3, 'Requires x shape (batch_size x seq_len x feature_dim)' b, t = (x.shape[0], x.shape[1]) if mask is None: mask...
Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored.
MaskedTemporalPooling
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaskedTemporalPooling: """Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored.""" def __init__(self, method: str): """method (str): the method of pooling to use. Options: 'max': reduces temporal dimension to each valid max va...
stack_v2_sparse_classes_75kplus_train_071856
13,032
permissive
[ { "docstring": "method (str): the method of pooling to use. Options: 'max': reduces temporal dimension to each valid max value. 'avg': averages valid values in the temporal dimension. 'sum': sums valid values in the temporal dimension. Note if all batch row elements are invalid, the temporal dimension is pooled...
2
stack_v2_sparse_classes_30k_train_018408
Implement the Python class `MaskedTemporalPooling` described below. Class description: Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored. Method signatures and docstrings: - def __init__(self, method: str): method (str): the method of pooling to use. Option...
Implement the Python class `MaskedTemporalPooling` described below. Class description: Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored. Method signatures and docstrings: - def __init__(self, method: str): method (str): the method of pooling to use. Option...
16f2abf2f8aa174915316007622bbb260215dee8
<|skeleton|> class MaskedTemporalPooling: """Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored.""" def __init__(self, method: str): """method (str): the method of pooling to use. Options: 'max': reduces temporal dimension to each valid max va...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MaskedTemporalPooling: """Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored.""" def __init__(self, method: str): """method (str): the method of pooling to use. Options: 'max': reduces temporal dimension to each valid max value. 'avg': a...
the_stack_v2_python_sparse
pytorchvideo/models/masked_multistream.py
xchani/pytorchvideo
train
0
51e9825fcc6c272dee0a5941a4b6b82e6335c8b2
[ "ref = set('01689')\n\ndef transform(num):\n trans = ''\n for each in num[::-1]:\n if each == '0':\n trans += '0'\n elif each == '6':\n trans += '9'\n elif each == '9':\n trans += '6'\n elif each == '8':\n trans += '8'\n elif each ...
<|body_start_0|> ref = set('01689') def transform(num): trans = '' for each in num[::-1]: if each == '0': trans += '0' elif each == '6': trans += '9' elif each == '9': tra...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isStrobogrammatic(self, num): """:type num: str :rtype: bool""" <|body_0|> def isStrobogrammatic(self, num): """:type num: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> ref = set('01689') def transform(num):...
stack_v2_sparse_classes_75kplus_train_071857
1,533
no_license
[ { "docstring": ":type num: str :rtype: bool", "name": "isStrobogrammatic", "signature": "def isStrobogrammatic(self, num)" }, { "docstring": ":type num: str :rtype: bool", "name": "isStrobogrammatic", "signature": "def isStrobogrammatic(self, num)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isStrobogrammatic(self, num): :type num: str :rtype: bool - def isStrobogrammatic(self, num): :type num: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isStrobogrammatic(self, num): :type num: str :rtype: bool - def isStrobogrammatic(self, num): :type num: str :rtype: bool <|skeleton|> class Solution: def isStrobogramm...
8bb17099be02d997d554519be360ef4aa1c028e3
<|skeleton|> class Solution: def isStrobogrammatic(self, num): """:type num: str :rtype: bool""" <|body_0|> def isStrobogrammatic(self, num): """:type num: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isStrobogrammatic(self, num): """:type num: str :rtype: bool""" ref = set('01689') def transform(num): trans = '' for each in num[::-1]: if each == '0': trans += '0' elif each == '6': ...
the_stack_v2_python_sparse
Google/1. easy/246. Strobogrammatic Number.py
yemao616/summer18
train
0
d61e244dc98461ad386353ac916b535d7681454e
[ "IO_files = {}\nfile_names = set()\nfor fl in in_dir.files:\n if self.name not in fl.users:\n if utils.splitext(fl.name)[-1] in self.input_types:\n IO_files['-!i'] = os.path.join(in_dir.path, fl.name)\n command_ids = [utils.infer_path_id(IO_files['-!i'])]\n in_dir.use_file...
<|body_start_0|> IO_files = {} file_names = set() for fl in in_dir.files: if self.name not in fl.users: if utils.splitext(fl.name)[-1] in self.input_types: IO_files['-!i'] = os.path.join(in_dir.path, fl.name) command_ids = [util...
Class for using psmc2history. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the function. input_type: Input types accepted by...
psmc2history
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class psmc2history: """Class for using psmc2history. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the funct...
stack_v2_sparse_classes_75kplus_train_071858
19,984
permissive
[ { "docstring": "Infers the input and output file paths. This method must keep the directory objects up to date of the file edits! Parameters: in_cmd: A dict containing the command line. in_dir: Input directory (instance of filetypes.Directory). out_dir: Output directory (instance of filetypes.Directory). Return...
2
stack_v2_sparse_classes_30k_train_021516
Implement the Python class `psmc2history` described below. Class description: Class for using psmc2history. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edi...
Implement the Python class `psmc2history` described below. Class description: Class for using psmc2history. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edi...
fd83eee4be0bb78c67a111fd1c1c1dff4c16aefe
<|skeleton|> class psmc2history: """Class for using psmc2history. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the funct...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class psmc2history: """Class for using psmc2history. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the function. input_ty...
the_stack_v2_python_sparse
modules/psmc.py
tyrmi/STAPLER
train
4
e7d8f8aee7912478c24376017d6fa0e23ce9e49a
[ "if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(email=email, password=password, **extra_fields)\nuser.is_admin = True\nuser...
<|body_start_0|> if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> user = s...
A custom user manager for sef.
CustomUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomUserManager: """A custom user manager for sef.""" def create_user(self, email=None, password=None, **extra_fields): """Create and save a User with the given email, password.""" <|body_0|> def create_superuser(self, email=None, password=None, **extra_fields): ...
stack_v2_sparse_classes_75kplus_train_071859
2,020
no_license
[ { "docstring": "Create and save a User with the given email, password.", "name": "create_user", "signature": "def create_user(self, email=None, password=None, **extra_fields)" }, { "docstring": "Create and save a User.", "name": "create_superuser", "signature": "def create_superuser(self...
2
stack_v2_sparse_classes_30k_train_006000
Implement the Python class `CustomUserManager` described below. Class description: A custom user manager for sef. Method signatures and docstrings: - def create_user(self, email=None, password=None, **extra_fields): Create and save a User with the given email, password. - def create_superuser(self, email=None, passwo...
Implement the Python class `CustomUserManager` described below. Class description: A custom user manager for sef. Method signatures and docstrings: - def create_user(self, email=None, password=None, **extra_fields): Create and save a User with the given email, password. - def create_superuser(self, email=None, passwo...
345e6f4964c6223c5765793e1d04ba73a499d935
<|skeleton|> class CustomUserManager: """A custom user manager for sef.""" def create_user(self, email=None, password=None, **extra_fields): """Create and save a User with the given email, password.""" <|body_0|> def create_superuser(self, email=None, password=None, **extra_fields): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomUserManager: """A custom user manager for sef.""" def create_user(self, email=None, password=None, **extra_fields): """Create and save a User with the given email, password.""" if not email: raise ValueError('Users must have an email address') user = self.model(e...
the_stack_v2_python_sparse
sef/user/models/models.py
dmbuguah/sef-api
train
0
73039ce8069918e0f2192da82ae9276e38581553
[ "if dtype not in NUMERIC_TYPES:\n raise ValueError(\"invalid numeric type '{}'\".format(dtype))\nsuper(Numeric, self).__init__(dtype=dtype, name=name, index=index, label=label, help=help, default=default, required=required, group=group)\nself.constraint = constraint", "if value in ['-inf', 'inf']:\n value =...
<|body_start_0|> if dtype not in NUMERIC_TYPES: raise ValueError("invalid numeric type '{}'".format(dtype)) super(Numeric, self).__init__(dtype=dtype, name=name, index=index, label=label, help=help, default=default, required=required, group=group) self.constraint = constraint <|end_b...
Base class for numeric parameter types. Extends the base class with an optional range constraint.
Numeric
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Numeric: """Base class for numeric parameter types. Extends the base class with an optional range constraint.""" def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Union[int, float]]=None, required: Optiona...
stack_v2_sparse_classes_75kplus_train_071860
16,105
permissive
[ { "docstring": "Initialize the base properties for a numeric parameter declaration. Parameters ---------- dtype: string Parameter type identifier. name: string Unique parameter identifier index: int Index position of the parameter (for display purposes). label: string Human-readable parameter name. help: string...
4
stack_v2_sparse_classes_30k_train_013935
Implement the Python class `Numeric` described below. Class description: Base class for numeric parameter types. Extends the base class with an optional range constraint. Method signatures and docstrings: - def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str...
Implement the Python class `Numeric` described below. Class description: Base class for numeric parameter types. Extends the base class with an optional range constraint. Method signatures and docstrings: - def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str...
7116b7060aa68ab36bf08e6393be166dc5db955f
<|skeleton|> class Numeric: """Base class for numeric parameter types. Extends the base class with an optional range constraint.""" def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Union[int, float]]=None, required: Optiona...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Numeric: """Base class for numeric parameter types. Extends the base class with an optional range constraint.""" def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Union[int, float]]=None, required: Optional[bool]=False...
the_stack_v2_python_sparse
flowserv/model/parameter/numeric.py
anrunw/flowserv-core-1
train
0
e93e366ca062494ce59a1196eb02a3ae4e63152c
[ "super(ReactorEnumerate, self).__init__(achem, mols)\nself.maxmols = len(mols)\nself.mols = []\nself.tested = []\nself.untested = []\nfor mol in mols:\n self.add_mol(mol)", "if mol not in self.mols:\n self.mols.append(mol)\n noreactants = self.achem.noreactants\n try:\n noreactants = set(noreac...
<|body_start_0|> super(ReactorEnumerate, self).__init__(achem, mols) self.maxmols = len(mols) self.mols = [] self.tested = [] self.untested = [] for mol in mols: self.add_mol(mol) <|end_body_0|> <|body_start_1|> if mol not in self.mols: se...
Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear.
ReactorEnumerate
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReactorEnumerate: """Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear.""" def __init__(self, achem, mols): """:param achem: :py:class:`achemkit.achem.AChem` object or equivalent. :param mols: ...
stack_v2_sparse_classes_75kplus_train_071861
7,950
permissive
[ { "docstring": ":param achem: :py:class:`achemkit.achem.AChem` object or equivalent. :param mols: Initial molecular species.", "name": "__init__", "signature": "def __init__(self, achem, mols)" }, { "docstring": "Internal utility function used to ensure molecular species have the relevant reacti...
3
stack_v2_sparse_classes_30k_train_049006
Implement the Python class `ReactorEnumerate` described below. Class description: Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear. Method signatures and docstrings: - def __init__(self, achem, mols): :param achem: :py:class:`...
Implement the Python class `ReactorEnumerate` described below. Class description: Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear. Method signatures and docstrings: - def __init__(self, achem, mols): :param achem: :py:class:`...
4800044693fdf8a228430eae5ee8b0283fde9920
<|skeleton|> class ReactorEnumerate: """Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear.""" def __init__(self, achem, mols): """:param achem: :py:class:`achemkit.achem.AChem` object or equivalent. :param mols: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReactorEnumerate: """Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear.""" def __init__(self, achem, mols): """:param achem: :py:class:`achemkit.achem.AChem` object or equivalent. :param mols: Initial molec...
the_stack_v2_python_sparse
achemkit/sim/simple.py
afaulconbridge/PyAChemKit
train
2
41a3ca75c0fd3236909dcfa66b645d06b1a80273
[ "if len(key) not in key_size:\n raise ValueError('Incorrect key length for Salsa20 (%d bytes)' % len(key))\nif len(nonce) != 8:\n raise ValueError('Incorrect nonce length for Salsa20 (%d bytes)' % len(nonce))\nself.nonce = nonce\nexpect_byte_string(key)\nexpect_byte_string(nonce)\nself._state = VoidPointer()\...
<|body_start_0|> if len(key) not in key_size: raise ValueError('Incorrect key length for Salsa20 (%d bytes)' % len(key)) if len(nonce) != 8: raise ValueError('Incorrect nonce length for Salsa20 (%d bytes)' % len(nonce)) self.nonce = nonce expect_byte_string(key) ...
Salsa20 cipher object
Salsa20Cipher
[ "LicenseRef-scancode-python-cwi", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-free-unknown", "Python-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Salsa20Cipher: """Salsa20 cipher object""" def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" <|body_0|> def encrypt(self, plaintext): """Encrypt a piece of data. :Parameters: plaintext : byte string The...
stack_v2_sparse_classes_75kplus_train_071862
5,685
permissive
[ { "docstring": "Initialize a Salsa20 cipher object See also `new()` at the module level.", "name": "__init__", "signature": "def __init__(self, key, nonce)" }, { "docstring": "Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Retu...
3
null
Implement the Python class `Salsa20Cipher` described below. Class description: Salsa20 cipher object Method signatures and docstrings: - def __init__(self, key, nonce): Initialize a Salsa20 cipher object See also `new()` at the module level. - def encrypt(self, plaintext): Encrypt a piece of data. :Parameters: plaint...
Implement the Python class `Salsa20Cipher` described below. Class description: Salsa20 cipher object Method signatures and docstrings: - def __init__(self, key, nonce): Initialize a Salsa20 cipher object See also `new()` at the module level. - def encrypt(self, plaintext): Encrypt a piece of data. :Parameters: plaint...
d9741aafd54126f05ba43e6f4ad6517755797c76
<|skeleton|> class Salsa20Cipher: """Salsa20 cipher object""" def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" <|body_0|> def encrypt(self, plaintext): """Encrypt a piece of data. :Parameters: plaintext : byte string The...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Salsa20Cipher: """Salsa20 cipher object""" def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" if len(key) not in key_size: raise ValueError('Incorrect key length for Salsa20 (%d bytes)' % len(key)) if len(nonc...
the_stack_v2_python_sparse
venv/lib/python3.7/site-packages/Crypto/Cipher/Salsa20.py
basemanbase/Animal-Health
train
0
f650c8c5f1375cca1005c5beaf6ff3341f6ecbcf
[ "values = super(CustomerPortal, self)._prepare_home_portal_values()\nvalues['student_count'] = request.env['student.student'].search_count([])\nvalues['application_count'] = request.env['job.application'].search_count([])\nreturn values", "values = self._prepare_portal_layout_values()\nStudentStudent = request.en...
<|body_start_0|> values = super(CustomerPortal, self)._prepare_home_portal_values() values['student_count'] = request.env['student.student'].search_count([]) values['application_count'] = request.env['job.application'].search_count([]) return values <|end_body_0|> <|body_start_1|> ...
CustomerPortal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomerPortal: def _prepare_home_portal_values(self): """Returns the count of the student and job applications""" <|body_0|> def portal_my_students(self, page=1, sortby=None, **kw): """Sortby values and pager functionality""" <|body_1|> def portal_my_ap...
stack_v2_sparse_classes_75kplus_train_071863
3,836
no_license
[ { "docstring": "Returns the count of the student and job applications", "name": "_prepare_home_portal_values", "signature": "def _prepare_home_portal_values(self)" }, { "docstring": "Sortby values and pager functionality", "name": "portal_my_students", "signature": "def portal_my_student...
3
null
Implement the Python class `CustomerPortal` described below. Class description: Implement the CustomerPortal class. Method signatures and docstrings: - def _prepare_home_portal_values(self): Returns the count of the student and job applications - def portal_my_students(self, page=1, sortby=None, **kw): Sortby values ...
Implement the Python class `CustomerPortal` described below. Class description: Implement the CustomerPortal class. Method signatures and docstrings: - def _prepare_home_portal_values(self): Returns the count of the student and job applications - def portal_my_students(self, page=1, sortby=None, **kw): Sortby values ...
36239c223224ae57fb58942a74d09d643c288a14
<|skeleton|> class CustomerPortal: def _prepare_home_portal_values(self): """Returns the count of the student and job applications""" <|body_0|> def portal_my_students(self, page=1, sortby=None, **kw): """Sortby values and pager functionality""" <|body_1|> def portal_my_ap...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomerPortal: def _prepare_home_portal_values(self): """Returns the count of the student and job applications""" values = super(CustomerPortal, self)._prepare_home_portal_values() values['student_count'] = request.env['student.student'].search_count([]) values['application_co...
the_stack_v2_python_sparse
controllers/portal.py
dhruv-suthar-aktiv/school-module
train
0
874ac81b7f3c374c4c879a8cf346bd15b116d482
[ "services_interval = kwargs.pop('services_interval', DEFAULT_SERVICES_INTERVAL)\nsuper().__init__(tick_interval=services_interval, **kwargs)\nself._registered_service_description = None\nself.is_items_created = False\nself.is_items_minted = False\nself.token_ids = []", "strategy = cast(Strategy, self.context.stra...
<|body_start_0|> services_interval = kwargs.pop('services_interval', DEFAULT_SERVICES_INTERVAL) super().__init__(tick_interval=services_interval, **kwargs) self._registered_service_description = None self.is_items_created = False self.is_items_minted = False self.token_id...
This class implements a behaviour.
ServiceRegistrationBehaviour
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceRegistrationBehaviour: """This class implements a behaviour.""" def __init__(self, **kwargs): """Initialise the behaviour.""" <|body_0|> def setup(self) -> None: """Implement the setup. :return: None""" <|body_1|> def act(self) -> None: ...
stack_v2_sparse_classes_75kplus_train_071864
8,205
permissive
[ { "docstring": "Initialise the behaviour.", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "Implement the setup. :return: None", "name": "setup", "signature": "def setup(self) -> None" }, { "docstring": "Implement the act. :return: None", "n...
6
stack_v2_sparse_classes_30k_train_038270
Implement the Python class `ServiceRegistrationBehaviour` described below. Class description: This class implements a behaviour. Method signatures and docstrings: - def __init__(self, **kwargs): Initialise the behaviour. - def setup(self) -> None: Implement the setup. :return: None - def act(self) -> None: Implement ...
Implement the Python class `ServiceRegistrationBehaviour` described below. Class description: This class implements a behaviour. Method signatures and docstrings: - def __init__(self, **kwargs): Initialise the behaviour. - def setup(self) -> None: Implement the setup. :return: None - def act(self) -> None: Implement ...
6636decff2b1c4a4b62152912d631afe6d287b5c
<|skeleton|> class ServiceRegistrationBehaviour: """This class implements a behaviour.""" def __init__(self, **kwargs): """Initialise the behaviour.""" <|body_0|> def setup(self) -> None: """Implement the setup. :return: None""" <|body_1|> def act(self) -> None: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServiceRegistrationBehaviour: """This class implements a behaviour.""" def __init__(self, **kwargs): """Initialise the behaviour.""" services_interval = kwargs.pop('services_interval', DEFAULT_SERVICES_INTERVAL) super().__init__(tick_interval=services_interval, **kwargs) s...
the_stack_v2_python_sparse
packages/fetchai/skills/erc1155_deploy/behaviours.py
yangjue-han/agents-aea
train
0
a0298bbe517ebf59679dc7adb45fa3094f95502d
[ "self.driver.get(url)\nself.driver.max_window()\nself.driver.find_element(locator.HeaderLocator.qgg).click()\nself.driver.pause(3)\nself.driver.switch_to_window()\ntag_is_dispayed = self.driver.is_display(locator.HeaderLocator.qgg_tag)\nself.driver.pause(3)\ntt_check.assertTrue(tag_is_dispayed, '列表页全国购签是否显示:%s' % t...
<|body_start_0|> self.driver.get(url) self.driver.max_window() self.driver.find_element(locator.HeaderLocator.qgg).click() self.driver.pause(3) self.driver.switch_to_window() tag_is_dispayed = self.driver.is_display(locator.HeaderLocator.qgg_tag) self.driver.pause...
qgg_floor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class qgg_floor: def test_qgg(self): """测试首页全国购楼层跳转,@author:xulanzhong""" <|body_0|> def test_qgg(self): """测试首页全国购楼层-查看全部跳转,@author:xulanzhong""" <|body_1|> def test_qgg_img(self): """测试首页全国购楼层-车图-跳转,@author:xulanzhong""" <|body_2|> def t...
stack_v2_sparse_classes_75kplus_train_071865
2,392
no_license
[ { "docstring": "测试首页全国购楼层跳转,@author:xulanzhong", "name": "test_qgg", "signature": "def test_qgg(self)" }, { "docstring": "测试首页全国购楼层-查看全部跳转,@author:xulanzhong", "name": "test_qgg", "signature": "def test_qgg(self)" }, { "docstring": "测试首页全国购楼层-车图-跳转,@author:xulanzhong", "name"...
4
stack_v2_sparse_classes_30k_train_046548
Implement the Python class `qgg_floor` described below. Class description: Implement the qgg_floor class. Method signatures and docstrings: - def test_qgg(self): 测试首页全国购楼层跳转,@author:xulanzhong - def test_qgg(self): 测试首页全国购楼层-查看全部跳转,@author:xulanzhong - def test_qgg_img(self): 测试首页全国购楼层-车图-跳转,@author:xulanzhong - def ...
Implement the Python class `qgg_floor` described below. Class description: Implement the qgg_floor class. Method signatures and docstrings: - def test_qgg(self): 测试首页全国购楼层跳转,@author:xulanzhong - def test_qgg(self): 测试首页全国购楼层-查看全部跳转,@author:xulanzhong - def test_qgg_img(self): 测试首页全国购楼层-车图-跳转,@author:xulanzhong - def ...
204856bd33c06d25f2970eba13799db75d4fd4fe
<|skeleton|> class qgg_floor: def test_qgg(self): """测试首页全国购楼层跳转,@author:xulanzhong""" <|body_0|> def test_qgg(self): """测试首页全国购楼层-查看全部跳转,@author:xulanzhong""" <|body_1|> def test_qgg_img(self): """测试首页全国购楼层-车图-跳转,@author:xulanzhong""" <|body_2|> def t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class qgg_floor: def test_qgg(self): """测试首页全国购楼层跳转,@author:xulanzhong""" self.driver.get(url) self.driver.max_window() self.driver.find_element(locator.HeaderLocator.qgg).click() self.driver.pause(3) self.driver.switch_to_window() tag_is_dispayed = self.drive...
the_stack_v2_python_sparse
mc/taochePC/test_crawler/test_homepage/test_qgg.py
boeai/mc
train
0
539c85f03c6c4eb2cbe2d6760142ecf37b91434f
[ "left, right = (1, n)\nnum = int(math.log(n, 2))\nsum = 0\nwhile num:\n mid = (left + right) / 2 + 1\n sum += mid\n left = mid + 1\n num -= 1\nreturn sum", "dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]\nfor start in range(1, n + 1):\n for j in range(start, n + 1):\n i = j - start\n...
<|body_start_0|> left, right = (1, n) num = int(math.log(n, 2)) sum = 0 while num: mid = (left + right) / 2 + 1 sum += mid left = mid + 1 num -= 1 return sum <|end_body_0|> <|body_start_1|> dp = [[0 for _ in range(n + 1)] f...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" <|body_0|> def getMoneyAmount2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> left, right = (1, n) num = int(math.log(n, 2)) ...
stack_v2_sparse_classes_75kplus_train_071866
1,610
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "getMoneyAmount", "signature": "def getMoneyAmount(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "getMoneyAmount2", "signature": "def getMoneyAmount2(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_044742
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMoneyAmount(self, n): :type n: int :rtype: int - def getMoneyAmount2(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMoneyAmount(self, n): :type n: int :rtype: int - def getMoneyAmount2(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def getMoneyAmount(self, n): ...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" <|body_0|> def getMoneyAmount2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" left, right = (1, n) num = int(math.log(n, 2)) sum = 0 while num: mid = (left + right) / 2 + 1 sum += mid left = mid + 1 num -= 1 return sum ...
the_stack_v2_python_sparse
375. Guess Number Higher or Lower II/guess2.py
Macielyoung/LeetCode
train
1
75cb25c365b813ffbfc8189c1425049cbaaf5847
[ "i2c = I2C(scl=scl_pin, sda=sda_pin)\nself.roll = 0\nself.pitch = 0\nself.xyz_calib_factor = {'AcX': 1, 'AcY': 1, 'AcZ': 1}\nself.xyz_calib_offset = {'AcX': 0.0, 'AcY': 0.4, 'AcZ': 0.0}\nself.gyro_calib_offset = {'AcX': -14, 'AcY': 2.6, 'AcZ': 1.4}\nself.accelerometer = accel(i2c)\nself.time = 0\nself.crash_detecti...
<|body_start_0|> i2c = I2C(scl=scl_pin, sda=sda_pin) self.roll = 0 self.pitch = 0 self.xyz_calib_factor = {'AcX': 1, 'AcY': 1, 'AcZ': 1} self.xyz_calib_offset = {'AcX': 0.0, 'AcY': 0.4, 'AcZ': 0.0} self.gyro_calib_offset = {'AcX': -14, 'AcY': 2.6, 'AcZ': 1.4} self...
MpuSensor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MpuSensor: def __init__(self, scl_pin, sda_pin): """Initialise the MPU6050 sensor to read accelerometer and gyroscope data. :param scl_pin: A Pin object connected to SCL on the sensor. :param sda_pin: A Pin object connected to SDA on the sensor. :param samples: An integer representing nu...
stack_v2_sparse_classes_75kplus_train_071867
5,290
no_license
[ { "docstring": "Initialise the MPU6050 sensor to read accelerometer and gyroscope data. :param scl_pin: A Pin object connected to SCL on the sensor. :param sda_pin: A Pin object connected to SDA on the sensor. :param samples: An integer representing number of readings to take the average of.", "name": "__in...
4
stack_v2_sparse_classes_30k_train_000287
Implement the Python class `MpuSensor` described below. Class description: Implement the MpuSensor class. Method signatures and docstrings: - def __init__(self, scl_pin, sda_pin): Initialise the MPU6050 sensor to read accelerometer and gyroscope data. :param scl_pin: A Pin object connected to SCL on the sensor. :para...
Implement the Python class `MpuSensor` described below. Class description: Implement the MpuSensor class. Method signatures and docstrings: - def __init__(self, scl_pin, sda_pin): Initialise the MPU6050 sensor to read accelerometer and gyroscope data. :param scl_pin: A Pin object connected to SCL on the sensor. :para...
1029f1eb50c0f3a220a12b467bb9f6a0dbcb02bd
<|skeleton|> class MpuSensor: def __init__(self, scl_pin, sda_pin): """Initialise the MPU6050 sensor to read accelerometer and gyroscope data. :param scl_pin: A Pin object connected to SCL on the sensor. :param sda_pin: A Pin object connected to SDA on the sensor. :param samples: An integer representing nu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MpuSensor: def __init__(self, scl_pin, sda_pin): """Initialise the MPU6050 sensor to read accelerometer and gyroscope data. :param scl_pin: A Pin object connected to SCL on the sensor. :param sda_pin: A Pin object connected to SDA on the sensor. :param samples: An integer representing number of readin...
the_stack_v2_python_sparse
wireless_modules/sensors/mpu_sensor.py
monash-human-power/data-acquisition-system
train
2
4695784a3f157e9a6d3e17212f1f079d42b282fc
[ "assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nBOARDS = ['Shore Fishing']\nURLS = ['http://www.nesa.co.uk/forums/shore-fishing/']\nPAGES = [501]\nassert len(BOARDS) == len(URLS) == len(PAGES), 'Setup list lengths DO NOT match'\nfor i, root_url in enumerate(URLS):\n curboard = BOARDS[i]\n ...
<|body_start_0|> assert isinstance(response, scrapy.http.response.html.HtmlResponse) BOARDS = ['Shore Fishing'] URLS = ['http://www.nesa.co.uk/forums/shore-fishing/'] PAGES = [501] assert len(BOARDS) == len(URLS) == len(PAGES), 'Setup list lengths DO NOT match' for i, roo...
scrape reports from angling addicts forum
NESASpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NESASpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" <|body_0|> def crawl_board_threads(self, response): """crawl""" <|body_1|> def parse_thread(self, response): """op...
stack_v2_sparse_classes_75kplus_train_071868
13,051
no_license
[ { "docstring": "generate links to pages in a board", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "crawl", "name": "crawl_board_threads", "signature": "def crawl_board_threads(self, response)" }, { "docstring": "open a report thread and parse first ...
3
stack_v2_sparse_classes_30k_train_029064
Implement the Python class `NESASpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board - def crawl_board_threads(self, response): crawl - def parse_thread(self, response): open a report thr...
Implement the Python class `NESASpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board - def crawl_board_threads(self, response): crawl - def parse_thread(self, response): open a report thr...
9123aa6baf538b662143b9098d963d55165e8409
<|skeleton|> class NESASpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" <|body_0|> def crawl_board_threads(self, response): """crawl""" <|body_1|> def parse_thread(self, response): """op...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NESASpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" assert isinstance(response, scrapy.http.response.html.HtmlResponse) BOARDS = ['Shore Fishing'] URLS = ['http://www.nesa.co.uk/forums/shore-fishin...
the_stack_v2_python_sparse
imgscrape/spiders/nesa.py
gmonkman/python
train
0
c55368d7f7f25a9f08c079abd77c5f4db0d74b50
[ "array = [head]\nwhile array[-1].next:\n array.append(array[-1].next)\nreturn array[len(array) // 2]", "n, cur = (0, head)\nwhile cur:\n n += 1\n cur = cur.next\nk, cur = (0, head)\nwhile k < n // 2:\n k += 1\n cur = cur.next\nreturn cur", "fast = slow = head\nwhile fast and fast.next:\n slow ...
<|body_start_0|> array = [head] while array[-1].next: array.append(array[-1].next) return array[len(array) // 2] <|end_body_0|> <|body_start_1|> n, cur = (0, head) while cur: n += 1 cur = cur.next k, cur = (0, head) while k < n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def middle_node(cls, head: ListNode) -> ListNode: """数组""" <|body_0|> def middle_node_v2(cls, head: ListNode) -> ListNode: """单指针""" <|body_1|> def middle_node_v3(cls, head: ListNode) -> ListNode: """快慢指针""" <|body_2|> <|end_sk...
stack_v2_sparse_classes_75kplus_train_071869
1,920
no_license
[ { "docstring": "数组", "name": "middle_node", "signature": "def middle_node(cls, head: ListNode) -> ListNode" }, { "docstring": "单指针", "name": "middle_node_v2", "signature": "def middle_node_v2(cls, head: ListNode) -> ListNode" }, { "docstring": "快慢指针", "name": "middle_node_v3"...
3
stack_v2_sparse_classes_30k_train_012771
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def middle_node(cls, head: ListNode) -> ListNode: 数组 - def middle_node_v2(cls, head: ListNode) -> ListNode: 单指针 - def middle_node_v3(cls, head: ListNode) -> ListNode: 快慢指针
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def middle_node(cls, head: ListNode) -> ListNode: 数组 - def middle_node_v2(cls, head: ListNode) -> ListNode: 单指针 - def middle_node_v3(cls, head: ListNode) -> ListNode: 快慢指针 <|ske...
1d1876620a55ff88af7bc390cf1a4fd4350d8d16
<|skeleton|> class Solution: def middle_node(cls, head: ListNode) -> ListNode: """数组""" <|body_0|> def middle_node_v2(cls, head: ListNode) -> ListNode: """单指针""" <|body_1|> def middle_node_v3(cls, head: ListNode) -> ListNode: """快慢指针""" <|body_2|> <|end_sk...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def middle_node(cls, head: ListNode) -> ListNode: """数组""" array = [head] while array[-1].next: array.append(array[-1].next) return array[len(array) // 2] def middle_node_v2(cls, head: ListNode) -> ListNode: """单指针""" n, cur = (0, head...
the_stack_v2_python_sparse
01-数据结构/链表/876.链表的中间结点.py
jh-lau/leetcode_in_python
train
0
b61b07855853756ae65f18936035b9d828f6706e
[ "super(StandardBlock, self).__init__()\nself.main_mapping = nn.Sequential(convolution(in_channels=in_channels, out_channels=in_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=True), normalization(num_features=in_channels, affine=True, track_running_stats=True), activation(), convolution(in_channel...
<|body_start_0|> super(StandardBlock, self).__init__() self.main_mapping = nn.Sequential(convolution(in_channels=in_channels, out_channels=in_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=True), normalization(num_features=in_channels, affine=True, track_running_stats=True), activatio...
This class implements a standard convolution block including two convolutions, each followed by a normalization and an activation function.
StandardBlock
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StandardBlock: """This class implements a standard convolution block including two convolutions, each followed by a normalization and an activation function.""" def __init__(self, in_channels: int, out_channels: int, convolution: Type=nn.Conv2d, normalization: Type=nn.InstanceNorm2d, activat...
stack_v2_sparse_classes_75kplus_train_071870
10,361
permissive
[ { "docstring": "Constructor method :param in_channels: (int) Number of input channels :param out_channels: (int) Number of output channels :param convolution: (Type) Type of convolution to be utilized :param normalization: (Type) Type of normalization to be utilized :param activation: (Type) Type of activation ...
2
null
Implement the Python class `StandardBlock` described below. Class description: This class implements a standard convolution block including two convolutions, each followed by a normalization and an activation function. Method signatures and docstrings: - def __init__(self, in_channels: int, out_channels: int, convolu...
Implement the Python class `StandardBlock` described below. Class description: This class implements a standard convolution block including two convolutions, each followed by a normalization and an activation function. Method signatures and docstrings: - def __init__(self, in_channels: int, out_channels: int, convolu...
7b43b3e021ffad0a516571d7af92c718dd82fb2a
<|skeleton|> class StandardBlock: """This class implements a standard convolution block including two convolutions, each followed by a normalization and an activation function.""" def __init__(self, in_channels: int, out_channels: int, convolution: Type=nn.Conv2d, normalization: Type=nn.InstanceNorm2d, activat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StandardBlock: """This class implements a standard convolution block including two convolutions, each followed by a normalization and an activation function.""" def __init__(self, in_channels: int, out_channels: int, convolution: Type=nn.Conv2d, normalization: Type=nn.InstanceNorm2d, activation: Type=nn....
the_stack_v2_python_sparse
backbone.py
ChristophReich1996/Cell-DETR
train
89
6a6c77da9c880f4f5751ccd10b67a89561471698
[ "self.cfg_index = cfg_index\nself.conditions = conditions\nself.pars_dir = pars_dir\nself.step_title = step_title\nself.use_defaults = use_defaults\nself.input_cfg_json_data = input_cfg_json_data\nif not self.input_cfg_json_data:\n self._get_params()", "self.outpars = {}\nfor cfg_key in self.pars_multidict.key...
<|body_start_0|> self.cfg_index = cfg_index self.conditions = conditions self.pars_dir = pars_dir self.step_title = step_title self.use_defaults = use_defaults self.input_cfg_json_data = input_cfg_json_data if not self.input_cfg_json_data: self._get_pa...
Par
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Par: def __init__(self, cfg_index, conditions, pars_dir, step_title, use_defaults, input_cfg_json_data): """Parent class for alignment_pars, astrodrizzle_pars, catalog_generation_pars, and quality_control_pars Parameters ---------- cfg_index : dictionary portion of the index config file ...
stack_v2_sparse_classes_75kplus_train_071871
24,456
permissive
[ { "docstring": "Parent class for alignment_pars, astrodrizzle_pars, catalog_generation_pars, and quality_control_pars Parameters ---------- cfg_index : dictionary portion of the index config file returned for a specific step conditions : list list of observing conditions that will be used to build the final com...
6
stack_v2_sparse_classes_30k_test_001508
Implement the Python class `Par` described below. Class description: Implement the Par class. Method signatures and docstrings: - def __init__(self, cfg_index, conditions, pars_dir, step_title, use_defaults, input_cfg_json_data): Parent class for alignment_pars, astrodrizzle_pars, catalog_generation_pars, and quality...
Implement the Python class `Par` described below. Class description: Implement the Par class. Method signatures and docstrings: - def __init__(self, cfg_index, conditions, pars_dir, step_title, use_defaults, input_cfg_json_data): Parent class for alignment_pars, astrodrizzle_pars, catalog_generation_pars, and quality...
490574e16571cd60d5cb3f9910ec08042dcaec09
<|skeleton|> class Par: def __init__(self, cfg_index, conditions, pars_dir, step_title, use_defaults, input_cfg_json_data): """Parent class for alignment_pars, astrodrizzle_pars, catalog_generation_pars, and quality_control_pars Parameters ---------- cfg_index : dictionary portion of the index config file ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Par: def __init__(self, cfg_index, conditions, pars_dir, step_title, use_defaults, input_cfg_json_data): """Parent class for alignment_pars, astrodrizzle_pars, catalog_generation_pars, and quality_control_pars Parameters ---------- cfg_index : dictionary portion of the index config file returned for a...
the_stack_v2_python_sparse
drizzlepac/hlautils/config_utils.py
eslavich/drizzlepac
train
0
30f5da1e8c105f688997e87cb4a598a63ef4cf17
[ "self.countTable = ChainingHashMap(1000)\nself.totalTable = ChainingHashMap(1000)\nself.totalWords = 0", "textList = text.split()\nfor i in range(len(textList) - 1):\n self.totalWords += 1\n if self.totalTable[textList[i]] == None:\n self.totalTable[textList[i]] = 1\n else:\n self.totalTabl...
<|body_start_0|> self.countTable = ChainingHashMap(1000) self.totalTable = ChainingHashMap(1000) self.totalWords = 0 <|end_body_0|> <|body_start_1|> textList = text.split() for i in range(len(textList) - 1): self.totalWords += 1 if self.totalTable[textLis...
A class that allows one to generate random text in the style of some provided source text
TextGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextGenerator: """A class that allows one to generate random text in the style of some provided source text""" def __init__(self): """Initializes the text generator""" <|body_0|> def train(self, text): """Takes a body of text (as a string) and increases the appro...
stack_v2_sparse_classes_75kplus_train_071872
6,228
no_license
[ { "docstring": "Initializes the text generator", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Takes a body of text (as a string) and increases the appropriate frequency counts", "name": "train", "signature": "def train(self, text)" }, { "docstring": "C...
4
stack_v2_sparse_classes_30k_train_047617
Implement the Python class `TextGenerator` described below. Class description: A class that allows one to generate random text in the style of some provided source text Method signatures and docstrings: - def __init__(self): Initializes the text generator - def train(self, text): Takes a body of text (as a string) an...
Implement the Python class `TextGenerator` described below. Class description: A class that allows one to generate random text in the style of some provided source text Method signatures and docstrings: - def __init__(self): Initializes the text generator - def train(self, text): Takes a body of text (as a string) an...
0290deb3e1f008305fb2da353eda86210a7ba1e6
<|skeleton|> class TextGenerator: """A class that allows one to generate random text in the style of some provided source text""" def __init__(self): """Initializes the text generator""" <|body_0|> def train(self, text): """Takes a body of text (as a string) and increases the appro...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TextGenerator: """A class that allows one to generate random text in the style of some provided source text""" def __init__(self): """Initializes the text generator""" self.countTable = ChainingHashMap(1000) self.totalTable = ChainingHashMap(1000) self.totalWords = 0 ...
the_stack_v2_python_sparse
Random Text Generation/textgenerator.py
mbastola/Algorithms-Data-Structures-in-Python
train
0
a1dd273127380c8f645f0ec31338f73ba141b04e
[ "Uniligne.__init__(self, pere, objet, attribut)\nself.ajouter_option('u', self.opt_bouger_up)\nself.ajouter_option('d', self.opt_bouger_down)", "sujet = self.objet\ncle_fils = arguments\nsujet_fils = importeur.information.sujets.get(cle_fils)\nif not sujet_fils or not sujet.est_fils(sujet_fils):\n self.pere <<...
<|body_start_0|> Uniligne.__init__(self, pere, objet, attribut) self.ajouter_option('u', self.opt_bouger_up) self.ajouter_option('d', self.opt_bouger_down) <|end_body_0|> <|body_start_1|> sujet = self.objet cle_fils = arguments sujet_fils = importeur.information.sujets.g...
Classe définissant le contexte-éditeur 'fils'. Ce contexte permet de hiérarchiser les sujets d'aide.
EdtFils
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EdtFils: """Classe définissant le contexte-éditeur 'fils'. Ce contexte permet de hiérarchiser les sujets d'aide.""" def __init__(self, pere, objet=None, attribut=None): """Constructeur de l'éditeur.""" <|body_0|> def opt_bouger_up(self, arguments): """Option perm...
stack_v2_sparse_classes_75kplus_train_071873
4,546
permissive
[ { "docstring": "Constructeur de l'éditeur.", "name": "__init__", "signature": "def __init__(self, pere, objet=None, attribut=None)" }, { "docstring": "Option permettant de bouger un sujet vers le haut de la liste. Syntaxe : /u <sujet>", "name": "opt_bouger_up", "signature": "def opt_boug...
4
null
Implement the Python class `EdtFils` described below. Class description: Classe définissant le contexte-éditeur 'fils'. Ce contexte permet de hiérarchiser les sujets d'aide. Method signatures and docstrings: - def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur. - def opt_bouger_up(self, ar...
Implement the Python class `EdtFils` described below. Class description: Classe définissant le contexte-éditeur 'fils'. Ce contexte permet de hiérarchiser les sujets d'aide. Method signatures and docstrings: - def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur. - def opt_bouger_up(self, ar...
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class EdtFils: """Classe définissant le contexte-éditeur 'fils'. Ce contexte permet de hiérarchiser les sujets d'aide.""" def __init__(self, pere, objet=None, attribut=None): """Constructeur de l'éditeur.""" <|body_0|> def opt_bouger_up(self, arguments): """Option perm...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EdtFils: """Classe définissant le contexte-éditeur 'fils'. Ce contexte permet de hiérarchiser les sujets d'aide.""" def __init__(self, pere, objet=None, attribut=None): """Constructeur de l'éditeur.""" Uniligne.__init__(self, pere, objet, attribut) self.ajouter_option('u', self.op...
the_stack_v2_python_sparse
src/primaires/information/editeurs/hedit/edt_fils.py
vincent-lg/tsunami
train
5
56ce47752cabfbc1604a1d051a305a6a741bfae4
[ "res = 0\nn = len(nums)\nevs = [nums[x] for x in range(n) if x % 2 == 0]\nods = [nums[x] for x in range(n) if x % 2 != 0]\nreturn sum((min(evs[x], ods[x]) for x in range(n / 2)))", "nums.sort()\nneg = []\nres = 0\nres += self.get_sum(nums)\nreturn res" ]
<|body_start_0|> res = 0 n = len(nums) evs = [nums[x] for x in range(n) if x % 2 == 0] ods = [nums[x] for x in range(n) if x % 2 != 0] return sum((min(evs[x], ods[x]) for x in range(n / 2))) <|end_body_0|> <|body_start_1|> nums.sort() neg = [] res = 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def get_sum(self, nums): """Doc""" <|body_0|> def arrayPairSum(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = 0 n = len(nums) evs = [nums[x] for x in range(n) if x % ...
stack_v2_sparse_classes_75kplus_train_071874
517
no_license
[ { "docstring": "Doc", "name": "get_sum", "signature": "def get_sum(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "arrayPairSum", "signature": "def arrayPairSum(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_043512
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def get_sum(self, nums): Doc - def arrayPairSum(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 get_sum(self, nums): Doc - def arrayPairSum(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def get_sum(self, nums): """Doc""" ...
b00f649598a6e57af30b517baa304f3094345f6d
<|skeleton|> class Solution: def get_sum(self, nums): """Doc""" <|body_0|> def arrayPairSum(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 get_sum(self, nums): """Doc""" res = 0 n = len(nums) evs = [nums[x] for x in range(n) if x % 2 == 0] ods = [nums[x] for x in range(n) if x % 2 != 0] return sum((min(evs[x], ods[x]) for x in range(n / 2))) def arrayPairSum(self, nums): ...
the_stack_v2_python_sparse
array_pair_sum.py
grewy/practice_py
train
0
8141b39e473bac486091d05e3fdfc659d8f6e57f
[ "sortedBuilding = sorted([(L, -H, R) for L, R, H in buildings] + list({(R, 0, None) for _, R, _ in buildings}))\nres, hp = ([[0, 0]], [(0, float('inf'))])\nfor x, negH, R in sortedBuilding:\n while x >= hp[0][1]:\n heapq.heappop(hp)\n if negH:\n heapq.heappush(hp, (negH, R))\n if res[-1][1] +...
<|body_start_0|> sortedBuilding = sorted([(L, -H, R) for L, R, H in buildings] + list({(R, 0, None) for _, R, _ in buildings})) res, hp = ([[0, 0]], [(0, float('inf'))]) for x, negH, R in sortedBuilding: while x >= hp[0][1]: heapq.heappop(hp) if negH: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getSkyline(self, buildings): """:type buildings: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def getSkylineSlow(self, buildings): """:type buildings: List[List[int]] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_75kplus_train_071875
1,831
no_license
[ { "docstring": ":type buildings: List[List[int]] :rtype: List[List[int]]", "name": "getSkyline", "signature": "def getSkyline(self, buildings)" }, { "docstring": ":type buildings: List[List[int]] :rtype: List[List[int]]", "name": "getSkylineSlow", "signature": "def getSkylineSlow(self, b...
2
stack_v2_sparse_classes_30k_test_001760
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getSkyline(self, buildings): :type buildings: List[List[int]] :rtype: List[List[int]] - def getSkylineSlow(self, buildings): :type buildings: List[List[int]] :rtype: List[Lis...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getSkyline(self, buildings): :type buildings: List[List[int]] :rtype: List[List[int]] - def getSkylineSlow(self, buildings): :type buildings: List[List[int]] :rtype: List[Lis...
75aef2f6c42aeb51261b9450a24099957a084d51
<|skeleton|> class Solution: def getSkyline(self, buildings): """:type buildings: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def getSkylineSlow(self, buildings): """:type buildings: List[List[int]] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def getSkyline(self, buildings): """:type buildings: List[List[int]] :rtype: List[List[int]]""" sortedBuilding = sorted([(L, -H, R) for L, R, H in buildings] + list({(R, 0, None) for _, R, _ in buildings})) res, hp = ([[0, 0]], [(0, float('inf'))]) for x, negH, R in s...
the_stack_v2_python_sparse
Python/0218_TheSkylineProblem/getSkyline.py
mtmmy/Leetcode
train
3
80e130debf343b1ea7769e77323115739ddc4391
[ "if not graph.is_directed():\n raise ValueError('the graph is not directed')\nself.graph = graph\nself.T = dict()\nfor source in self.graph.iternodes():\n self.T[source] = dict()\n for target in self.graph.iternodes():\n self.T[source][target] = False\n self.T[source][source] = True", "for sour...
<|body_start_0|> if not graph.is_directed(): raise ValueError('the graph is not directed') self.graph = graph self.T = dict() for source in self.graph.iternodes(): self.T[source] = dict() for target in self.graph.iternodes(): self.T[sou...
Based on the BFS, O(V*(V+E)) time.
TransitiveClosureBFS
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransitiveClosureBFS: """Based on the BFS, O(V*(V+E)) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" <|body_0|> def run(self): """Executable pseudocode.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if no...
stack_v2_sparse_classes_75kplus_train_071876
3,816
permissive
[ { "docstring": "The algorithm initialization, O(V**2) time.", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Executable pseudocode.", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_029218
Implement the Python class `TransitiveClosureBFS` described below. Class description: Based on the BFS, O(V*(V+E)) time. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization, O(V**2) time. - def run(self): Executable pseudocode.
Implement the Python class `TransitiveClosureBFS` described below. Class description: Based on the BFS, O(V*(V+E)) time. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization, O(V**2) time. - def run(self): Executable pseudocode. <|skeleton|> class TransitiveClosureBFS: """B...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class TransitiveClosureBFS: """Based on the BFS, O(V*(V+E)) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" <|body_0|> def run(self): """Executable pseudocode.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TransitiveClosureBFS: """Based on the BFS, O(V*(V+E)) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" if not graph.is_directed(): raise ValueError('the graph is not directed') self.graph = graph self.T = dict() for ...
the_stack_v2_python_sparse
graphtheory/algorithms/closure.py
kgashok/graphs-dict
train
0
462ecb3196a7c99896ebfdb0eb28f4dcad84f6ad
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
BasicServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicServiceServicer: """Missing associated documentation comment in .proto file.""" def InferenceItem(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def ChangeThreads(self, request, context): """Missing associa...
stack_v2_sparse_classes_75kplus_train_071877
3,873
permissive
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "InferenceItem", "signature": "def InferenceItem(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "ChangeThreads", "signature": "def ChangeThre...
2
stack_v2_sparse_classes_30k_train_007113
Implement the Python class `BasicServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def InferenceItem(self, request, context): Missing associated documentation comment in .proto file. - def ChangeThreads(self, request, cont...
Implement the Python class `BasicServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def InferenceItem(self, request, context): Missing associated documentation comment in .proto file. - def ChangeThreads(self, request, cont...
ac090279109f4975f253e3c3f37772b6bb20aad3
<|skeleton|> class BasicServiceServicer: """Missing associated documentation comment in .proto file.""" def InferenceItem(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def ChangeThreads(self, request, context): """Missing associa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BasicServiceServicer: """Missing associated documentation comment in .proto file.""" def InferenceItem(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemente...
the_stack_v2_python_sparse
vision/classification_and_detection/python/basic_pb2_grpc.py
omarnaman/inference
train
0
78d14cf55078c93108950c6e5aef9377914cdd2b
[ "if root:\n head, tail = self.helper(root)\n return head\nreturn None", "head, tail = (root, root)\nif root.left:\n lh, lt = self.helper(root.left)\n lt.right = root\n root.left = lt\n head = lh\nif root.right:\n rh, rt = self.helper(root.right)\n rh.left = root\n root.right = rh\n t...
<|body_start_0|> if root: head, tail = self.helper(root) return head return None <|end_body_0|> <|body_start_1|> head, tail = (root, root) if root.left: lh, lt = self.helper(root.left) lt.right = root root.left = lt ...
Solution3
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution3: def treeToDoublyList(self, root): """:type root: Node :rtype: Node""" <|body_0|> def helper(self, root): """Idea: Construct a DLL for each subtree, then return the head and tail""" <|body_1|> <|end_skeleton|> <|body_start_0|> if root: ...
stack_v2_sparse_classes_75kplus_train_071878
3,060
no_license
[ { "docstring": ":type root: Node :rtype: Node", "name": "treeToDoublyList", "signature": "def treeToDoublyList(self, root)" }, { "docstring": "Idea: Construct a DLL for each subtree, then return the head and tail", "name": "helper", "signature": "def helper(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_047624
Implement the Python class `Solution3` described below. Class description: Implement the Solution3 class. Method signatures and docstrings: - def treeToDoublyList(self, root): :type root: Node :rtype: Node - def helper(self, root): Idea: Construct a DLL for each subtree, then return the head and tail
Implement the Python class `Solution3` described below. Class description: Implement the Solution3 class. Method signatures and docstrings: - def treeToDoublyList(self, root): :type root: Node :rtype: Node - def helper(self, root): Idea: Construct a DLL for each subtree, then return the head and tail <|skeleton|> cl...
11d6bf2ba7b50c07e048df37c4e05c8f46b92241
<|skeleton|> class Solution3: def treeToDoublyList(self, root): """:type root: Node :rtype: Node""" <|body_0|> def helper(self, root): """Idea: Construct a DLL for each subtree, then return the head and tail""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution3: def treeToDoublyList(self, root): """:type root: Node :rtype: Node""" if root: head, tail = self.helper(root) return head return None def helper(self, root): """Idea: Construct a DLL for each subtree, then return the head and tail""" ...
the_stack_v2_python_sparse
LeetCodes/facebook/Convert Binary SearchTreetoSortedDoublyLinkedList.py
chutianwen/LeetCodes
train
0
30494a7b1a538396380a9897b4209b08a10edfaa
[ "try:\n ScfUser.objects.get(username=data)\n raise ValidationError('User {} name already exist'.format(data))\nexcept ScfUser.DoesNotExist:\n return data", "try:\n ScfUser.objects.get(email=data)\n raise ValidationError('User {} email already exist'.format(data))\nexcept ScfUser.DoesNotExist:\n ...
<|body_start_0|> try: ScfUser.objects.get(username=data) raise ValidationError('User {} name already exist'.format(data)) except ScfUser.DoesNotExist: return data <|end_body_0|> <|body_start_1|> try: ScfUser.objects.get(email=data) rai...
Signup with mandatory fields
SignupSerializer
[ "Apache-2.0", "GPL-3.0-only", "BSD-3-Clause", "AGPL-3.0-only", "GPL-1.0-or-later", "Python-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignupSerializer: """Signup with mandatory fields""" def validate_username(self, data): """check user name is exist or not""" <|body_0|> def validate_email(self, data): """check email is exist or not""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_071879
4,134
permissive
[ { "docstring": "check user name is exist or not", "name": "validate_username", "signature": "def validate_username(self, data)" }, { "docstring": "check email is exist or not", "name": "validate_email", "signature": "def validate_email(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_044676
Implement the Python class `SignupSerializer` described below. Class description: Signup with mandatory fields Method signatures and docstrings: - def validate_username(self, data): check user name is exist or not - def validate_email(self, data): check email is exist or not
Implement the Python class `SignupSerializer` described below. Class description: Signup with mandatory fields Method signatures and docstrings: - def validate_username(self, data): check user name is exist or not - def validate_email(self, data): check email is exist or not <|skeleton|> class SignupSerializer: ...
4df3f46e35eb8fcab796be27fc1cc7fa7ed561f3
<|skeleton|> class SignupSerializer: """Signup with mandatory fields""" def validate_username(self, data): """check user name is exist or not""" <|body_0|> def validate_email(self, data): """check email is exist or not""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SignupSerializer: """Signup with mandatory fields""" def validate_username(self, data): """check user name is exist or not""" try: ScfUser.objects.get(username=data) raise ValidationError('User {} name already exist'.format(data)) except ScfUser.DoesNotExis...
the_stack_v2_python_sparse
SCRM/ums/serializers.py
aricent/secure-cloud-native-fabric
train
2
7b2b1c18377a9cb3b9cf0ce37624c37013f4c92c
[ "items = self.node(parent)\nif items and kwargs:\n for item in items:\n for key, value in kwargs.iteritems():\n setattr(item, key, value)\nreturn items", "try:\n return self.node.scope[name]\nexcept KeyError:\n msg = \"'%s' object has no attribute '%s'\"\n raise AttributeError(msg % ...
<|body_start_0|> items = self.node(parent) if items and kwargs: for item in items: for key, value in kwargs.iteritems(): setattr(item, key, value) return items <|end_body_0|> <|body_start_1|> try: return self.node.scope[name] ...
A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code.
TemplateInstance
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemplateInstance: """A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code.""" def __call__(self, parent=None, **kwargs): """Instantiate the list of items for the template. Paramet...
stack_v2_sparse_classes_75kplus_train_071880
8,361
permissive
[ { "docstring": "Instantiate the list of items for the template. Parameters ---------- parent : Object, optional The parent object for the generated objects. **kwargs Additional keyword arguments to apply to the returned items. Returns ------- result : list The list of objects generated by the template.", "n...
2
stack_v2_sparse_classes_30k_test_001990
Implement the Python class `TemplateInstance` described below. Class description: A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code. Method signatures and docstrings: - def __call__(self, parent=None, **kwargs)...
Implement the Python class `TemplateInstance` described below. Class description: A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code. Method signatures and docstrings: - def __call__(self, parent=None, **kwargs)...
1544e7fb371b8f941cfa2fde682795e479380284
<|skeleton|> class TemplateInstance: """A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code.""" def __call__(self, parent=None, **kwargs): """Instantiate the list of items for the template. Paramet...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TemplateInstance: """A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code.""" def __call__(self, parent=None, **kwargs): """Instantiate the list of items for the template. Parameters ---------...
the_stack_v2_python_sparse
enaml/core/template.py
MatthieuDartiailh/enaml
train
26
1f5e3faf3330b45c3fec6323424104ff061d18fc
[ "starttime = int(time.time())\ncount = 0\nwhile True:\n elements = self.find_elements(by=by, value=value)\n if not elements:\n time.sleep(0.1)\n nowtime = int(time.time())\n if nowtime - starttime > outtime:\n raise TypeError('此xpath未找到元素:{}'.format(value))\n continue\n ...
<|body_start_0|> starttime = int(time.time()) count = 0 while True: elements = self.find_elements(by=by, value=value) if not elements: time.sleep(0.1) nowtime = int(time.time()) if nowtime - starttime > outtime: ...
Driver
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Driver: def getelement(self, value=None, by=By.XPATH, outtime=10): """返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的需求定义 :param outtime: 一个作用是等待元素出现,第二是配置了超时时间,不能低于2s,有可能会导致元素获取不到 :return: webelemnet元素""" ...
stack_v2_sparse_classes_75kplus_train_071881
6,948
no_license
[ { "docstring": "返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的需求定义 :param outtime: 一个作用是等待元素出现,第二是配置了超时时间,不能低于2s,有可能会导致元素获取不到 :return: webelemnet元素", "name": "getelement", "signature": "def getelement(self, value=None, by=By.XP...
4
stack_v2_sparse_classes_30k_train_027112
Implement the Python class `Driver` described below. Class description: Implement the Driver class. Method signatures and docstrings: - def getelement(self, value=None, by=By.XPATH, outtime=10): 返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的...
Implement the Python class `Driver` described below. Class description: Implement the Driver class. Method signatures and docstrings: - def getelement(self, value=None, by=By.XPATH, outtime=10): 返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的...
504a454503895371a7c5d679684560d4239b81bf
<|skeleton|> class Driver: def getelement(self, value=None, by=By.XPATH, outtime=10): """返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的需求定义 :param outtime: 一个作用是等待元素出现,第二是配置了超时时间,不能低于2s,有可能会导致元素获取不到 :return: webelemnet元素""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Driver: def getelement(self, value=None, by=By.XPATH, outtime=10): """返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的需求定义 :param outtime: 一个作用是等待元素出现,第二是配置了超时时间,不能低于2s,有可能会导致元素获取不到 :return: webelemnet元素""" starttime = ...
the_stack_v2_python_sparse
autotest.py
xiaoshihu/learn
train
2
cf586e2b98dd52477c0779f45bc3eb91dbe87816
[ "super(HybridAlluviumModel, self).__init__(input_file=input_file, params=params)\nself.flow_router = FlowRouter(self.grid, **self.params)\nself.lake_filler = DepressionFinderAndRouter(self.grid, **self.params)\nif self.params['discharge_method'] is not None:\n if self.params['discharge_method'] == 'area_field':\...
<|body_start_0|> super(HybridAlluviumModel, self).__init__(input_file=input_file, params=params) self.flow_router = FlowRouter(self.grid, **self.params) self.lake_filler = DepressionFinderAndRouter(self.grid, **self.params) if self.params['discharge_method'] is not None: if s...
A HybridAlluviumModel computes erosion of sediment and bedrock using dual mass conservation on the bed and in the water column. It applies exponential entrainment rules to account for bed cover.
HybridAlluviumModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HybridAlluviumModel: """A HybridAlluviumModel computes erosion of sediment and bedrock using dual mass conservation on the bed and in the water column. It applies exponential entrainment rules to account for bed cover.""" def __init__(self, input_file=None, params=None): """Initializ...
stack_v2_sparse_classes_75kplus_train_071882
3,512
no_license
[ { "docstring": "Initialize the HybridAlluviumModel.", "name": "__init__", "signature": "def __init__(self, input_file=None, params=None)" }, { "docstring": "Advance model for one time-step of duration dt.", "name": "run_one_step", "signature": "def run_one_step(self, dt)" } ]
2
null
Implement the Python class `HybridAlluviumModel` described below. Class description: A HybridAlluviumModel computes erosion of sediment and bedrock using dual mass conservation on the bed and in the water column. It applies exponential entrainment rules to account for bed cover. Method signatures and docstrings: - de...
Implement the Python class `HybridAlluviumModel` described below. Class description: A HybridAlluviumModel computes erosion of sediment and bedrock using dual mass conservation on the bed and in the water column. It applies exponential entrainment rules to account for bed cover. Method signatures and docstrings: - de...
3506ec741a7c8a170ea654d40c6119fefe1b93ba
<|skeleton|> class HybridAlluviumModel: """A HybridAlluviumModel computes erosion of sediment and bedrock using dual mass conservation on the bed and in the water column. It applies exponential entrainment rules to account for bed cover.""" def __init__(self, input_file=None, params=None): """Initializ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HybridAlluviumModel: """A HybridAlluviumModel computes erosion of sediment and bedrock using dual mass conservation on the bed and in the water column. It applies exponential entrainment rules to account for bed cover.""" def __init__(self, input_file=None, params=None): """Initialize the HybridA...
the_stack_v2_python_sparse
erosion_modeling_suite/erosion_model/single_component/hybrid_alluvium/hybrid_alluvium_model.py
kbarnhart/inverting_topography_postglacial
train
4
22e3916e150a9d46ab71c346c824bd3d63c807ef
[ "self.found = found\nself.displaying = displaying\nself.more_available = more_available\nself.created_date = created_date\nself.institutions = institutions\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nfound = dictionary.get('found')\ndisplaying = dictionary.get('...
<|body_start_0|> self.found = found self.displaying = displaying self.more_available = more_available self.created_date = created_date self.institutions = institutions self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionar...
Implementation of the 'Get Certified Institutions Response' model. TODO: type model description here. Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indicates if there are more institutions to display that match the parameters created_date (int): Date th...
GetCertifiedInstitutionsResponse
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetCertifiedInstitutionsResponse: """Implementation of the 'Get Certified Institutions Response' model. TODO: type model description here. Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indicates if there are more institutions to d...
stack_v2_sparse_classes_75kplus_train_071883
3,106
permissive
[ { "docstring": "Constructor for the GetCertifiedInstitutionsResponse class", "name": "__init__", "signature": "def __init__(self, found=None, displaying=None, more_available=None, created_date=None, institutions=None, additional_properties={})" }, { "docstring": "Creates an instance of this mode...
2
stack_v2_sparse_classes_30k_train_039924
Implement the Python class `GetCertifiedInstitutionsResponse` described below. Class description: Implementation of the 'Get Certified Institutions Response' model. TODO: type model description here. Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indica...
Implement the Python class `GetCertifiedInstitutionsResponse` described below. Class description: Implementation of the 'Get Certified Institutions Response' model. TODO: type model description here. Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indica...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class GetCertifiedInstitutionsResponse: """Implementation of the 'Get Certified Institutions Response' model. TODO: type model description here. Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indicates if there are more institutions to d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GetCertifiedInstitutionsResponse: """Implementation of the 'Get Certified Institutions Response' model. TODO: type model description here. Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indicates if there are more institutions to display that m...
the_stack_v2_python_sparse
finicityapi/models/get_certified_institutions_response.py
monarchmoney/finicity-python
train
0
3fd636b94e876d923862d5c30b36c30fcef28fdf
[ "li.append(root.val)\nif not root.left and (not root.right):\n if root.val == sum:\n self.li.append(li)\n return\n else:\n return\nsum -= root.val\n'\\n There is a more clear way:\\n \\n '\ntmp_left = li[:]\ntmp_right = li[:]\nif root.left:\n self.DFS(root.left, tm...
<|body_start_0|> li.append(root.val) if not root.left and (not root.right): if root.val == sum: self.li.append(li) return else: return sum -= root.val '\n There is a more clear way:\n \n ' ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def DFS(self, root, li, sum): """More clear way if not root.left and not root.right: if root.val==sum: self.li.append(li+[root.val]) sum-=root.val if root.left:self.DFS(root.left, [root.val]+li,sum) if root.right:self.DFS(root.right, [root.val]+li,sum)""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_071884
1,469
no_license
[ { "docstring": "More clear way if not root.left and not root.right: if root.val==sum: self.li.append(li+[root.val]) sum-=root.val if root.left:self.DFS(root.left, [root.val]+li,sum) if root.right:self.DFS(root.right, [root.val]+li,sum)", "name": "DFS", "signature": "def DFS(self, root, li, sum)" }, ...
2
stack_v2_sparse_classes_30k_train_011913
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def DFS(self, root, li, sum): More clear way if not root.left and not root.right: if root.val==sum: self.li.append(li+[root.val]) sum-=root.val if root.left:self.DFS(root.left, [...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def DFS(self, root, li, sum): More clear way if not root.left and not root.right: if root.val==sum: self.li.append(li+[root.val]) sum-=root.val if root.left:self.DFS(root.left, [...
1c427934dc4ee4dce76fefbe1c1d7caeefe09946
<|skeleton|> class Solution: def DFS(self, root, li, sum): """More clear way if not root.left and not root.right: if root.val==sum: self.li.append(li+[root.val]) sum-=root.val if root.left:self.DFS(root.left, [root.val]+li,sum) if root.right:self.DFS(root.right, [root.val]+li,sum)""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def DFS(self, root, li, sum): """More clear way if not root.left and not root.right: if root.val==sum: self.li.append(li+[root.val]) sum-=root.val if root.left:self.DFS(root.left, [root.val]+li,sum) if root.right:self.DFS(root.right, [root.val]+li,sum)""" li.append(root.val) ...
the_stack_v2_python_sparse
113_path_sum_2.py
tek-life/algorithm-practice
train
0
b4bfaa705ed7e4580a6799aa47c50f45c3df0ebf
[ "queryset = super().get_queryset()\nif self.request.GET.get('empresa'):\n queryset = queryset.filter(name__icontains=self.request.GET['empresa'])\n return queryset", "context = super().get_context_data(**kwargs)\ncompanies = context['companies'] or []\ncompany_user_profiles = [company.users.all() for compan...
<|body_start_0|> queryset = super().get_queryset() if self.request.GET.get('empresa'): queryset = queryset.filter(name__icontains=self.request.GET['empresa']) return queryset <|end_body_0|> <|body_start_1|> context = super().get_context_data(**kwargs) companies =...
CompanyAssociationListView
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompanyAssociationListView: def get_queryset(self): """Filter companies if 'empresa' is passed as query param with the search value""" <|body_0|> def get_context_data(self, **kwargs): """Add 'busqueda' to context if 'empresa' is passed as query param, in order to set...
stack_v2_sparse_classes_75kplus_train_071885
10,214
permissive
[ { "docstring": "Filter companies if 'empresa' is passed as query param with the search value", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Add 'busqueda' to context if 'empresa' is passed as query param, in order to set the search input previous value.", ...
2
stack_v2_sparse_classes_30k_train_000022
Implement the Python class `CompanyAssociationListView` described below. Class description: Implement the CompanyAssociationListView class. Method signatures and docstrings: - def get_queryset(self): Filter companies if 'empresa' is passed as query param with the search value - def get_context_data(self, **kwargs): A...
Implement the Python class `CompanyAssociationListView` described below. Class description: Implement the CompanyAssociationListView class. Method signatures and docstrings: - def get_queryset(self): Filter companies if 'empresa' is passed as query param with the search value - def get_context_data(self, **kwargs): A...
5f88d1ea0cea9bd67547b70dc2c8bbaa3b8b9d03
<|skeleton|> class CompanyAssociationListView: def get_queryset(self): """Filter companies if 'empresa' is passed as query param with the search value""" <|body_0|> def get_context_data(self, **kwargs): """Add 'busqueda' to context if 'empresa' is passed as query param, in order to set...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CompanyAssociationListView: def get_queryset(self): """Filter companies if 'empresa' is passed as query param with the search value""" queryset = super().get_queryset() if self.request.GET.get('empresa'): queryset = queryset.filter(name__icontains=self.request.GET['empresa'...
the_stack_v2_python_sparse
pycompanies/views.py
PyAr/pyarweb
train
64
95f8d5cdb04db131eec782075bf3a3abf601f4e7
[ "self.momentum = momentum\nvelocitys = dict()\nfor k, v in model.params.items():\n velocitys[k] = np.zeros_like(v)\nself.velocitys = velocitys", "momentum = self.momentum\nvelocitys = self.velocitys\nparams = model.params\ngrads = model.grads\nfor k in grads:\n velocitys[k] = momentum * velocitys[k] + learn...
<|body_start_0|> self.momentum = momentum velocitys = dict() for k, v in model.params.items(): velocitys[k] = np.zeros_like(v) self.velocitys = velocitys <|end_body_0|> <|body_start_1|> momentum = self.momentum velocitys = self.velocitys params = mode...
SGDmomentumOptim
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SGDmomentumOptim: def __init__(self, model, momentum=0.5): """Inputs: :param model: a neural netowrk class object :param momentum: (float)""" <|body_0|> def step(self, model, learning_rate): """Implement a one-step SGD+momentum update on network's parameters Inputs: ...
stack_v2_sparse_classes_75kplus_train_071886
9,004
no_license
[ { "docstring": "Inputs: :param model: a neural netowrk class object :param momentum: (float)", "name": "__init__", "signature": "def __init__(self, model, momentum=0.5)" }, { "docstring": "Implement a one-step SGD+momentum update on network's parameters Inputs: :param model: a neural network cla...
2
stack_v2_sparse_classes_30k_train_004696
Implement the Python class `SGDmomentumOptim` described below. Class description: Implement the SGDmomentumOptim class. Method signatures and docstrings: - def __init__(self, model, momentum=0.5): Inputs: :param model: a neural netowrk class object :param momentum: (float) - def step(self, model, learning_rate): Impl...
Implement the Python class `SGDmomentumOptim` described below. Class description: Implement the SGDmomentumOptim class. Method signatures and docstrings: - def __init__(self, model, momentum=0.5): Inputs: :param model: a neural netowrk class object :param momentum: (float) - def step(self, model, learning_rate): Impl...
a401d09c28432109e9ced10e5011bff97dda05b9
<|skeleton|> class SGDmomentumOptim: def __init__(self, model, momentum=0.5): """Inputs: :param model: a neural netowrk class object :param momentum: (float)""" <|body_0|> def step(self, model, learning_rate): """Implement a one-step SGD+momentum update on network's parameters Inputs: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SGDmomentumOptim: def __init__(self, model, momentum=0.5): """Inputs: :param model: a neural netowrk class object :param momentum: (float)""" self.momentum = momentum velocitys = dict() for k, v in model.params.items(): velocitys[k] = np.zeros_like(v) self.v...
the_stack_v2_python_sparse
assignment2/E4040.2017.Assign2.xw2501/E4040.2017.Assign2.xw2501/ecbm4040/optimizers.py
xw2501/Deep_Learning_study
train
7
814e5fcc0d1f13731b57488fba287ebc4e3d681a
[ "self._stage_pool = collections.deque()\nif timeout is None:\n self._cvar = threading.Condition()\nelse:\n from . import shared_queue\n self._cvar = shared_queue.HeartbeatCondition(timeout)\nself._timeout = timeout\nfor _ in range(N_stages):\n self._stage_pool.append(StagePool.StagePoolWrapper(dataset.c...
<|body_start_0|> self._stage_pool = collections.deque() if timeout is None: self._cvar = threading.Condition() else: from . import shared_queue self._cvar = shared_queue.HeartbeatCondition(timeout) self._timeout = timeout for _ in range(N_stage...
Manages a pool from which stages can be acquired and returned.
StagePool
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StagePool: """Manages a pool from which stages can be acquired and returned.""" def __init__(self, dataset, stage_size, N_stages, timeout=None): """Create a stage pool based on a given dataset. :param dataset: Parent dataset that is used to calculate the size of the member stage elem...
stack_v2_sparse_classes_75kplus_train_071887
4,636
permissive
[ { "docstring": "Create a stage pool based on a given dataset. :param dataset: Parent dataset that is used to calculate the size of the member stage elements. :stage_size: Size of each stage in the pool, this is passed to the constructor for the stage. :N_stages: The number of stages to be allocated in the pool....
3
stack_v2_sparse_classes_30k_train_054046
Implement the Python class `StagePool` described below. Class description: Manages a pool from which stages can be acquired and returned. Method signatures and docstrings: - def __init__(self, dataset, stage_size, N_stages, timeout=None): Create a stage pool based on a given dataset. :param dataset: Parent dataset th...
Implement the Python class `StagePool` described below. Class description: Manages a pool from which stages can be acquired and returned. Method signatures and docstrings: - def __init__(self, dataset, stage_size, N_stages, timeout=None): Create a stage pool based on a given dataset. :param dataset: Parent dataset th...
43a48122c70917761c04e178d11132ccadbc28b6
<|skeleton|> class StagePool: """Manages a pool from which stages can be acquired and returned.""" def __init__(self, dataset, stage_size, N_stages, timeout=None): """Create a stage pool based on a given dataset. :param dataset: Parent dataset that is used to calculate the size of the member stage elem...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StagePool: """Manages a pool from which stages can be acquired and returned.""" def __init__(self, dataset, stage_size, N_stages, timeout=None): """Create a stage pool based on a given dataset. :param dataset: Parent dataset that is used to calculate the size of the member stage elements. :stage_...
the_stack_v2_python_sparse
multitables/stage.py
ghcollin/multitables
train
15
47c1372c924a27b39091b5582b11ed75eb85d0cb
[ "key_string = 'sqlite_version'\nerror_strings = ['fts3tokenize', 'unknown tokenizer', 'file error', 'unable to delete/modify user-function due to active statements', 'DISTINCT is not supported for window functions', 'ORDER BY clause', 'abbreviated query algorithm search']\nkey_error_strings = [error_strings[0], err...
<|body_start_0|> key_string = 'sqlite_version' error_strings = ['fts3tokenize', 'unknown tokenizer', 'file error', 'unable to delete/modify user-function due to active statements', 'DISTINCT is not supported for window functions', 'ORDER BY clause', 'abbreviated query algorithm search'] key_erro...
Seeker (Identifier) for the zlib open source library.
SqliteSeeker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SqliteSeeker: """Seeker (Identifier) for the zlib open source library.""" def searchLib(self, logger): """Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Return Value: number of library instances that were found i...
stack_v2_sparse_classes_75kplus_train_071888
3,269
permissive
[ { "docstring": "Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Return Value: number of library instances that were found in the binary", "name": "searchLib", "signature": "def searchLib(self, logger)" }, { "docstring": "Iden...
2
stack_v2_sparse_classes_30k_train_052879
Implement the Python class `SqliteSeeker` described below. Class description: Seeker (Identifier) for the zlib open source library. Method signatures and docstrings: - def searchLib(self, logger): Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Re...
Implement the Python class `SqliteSeeker` described below. Class description: Seeker (Identifier) for the zlib open source library. Method signatures and docstrings: - def searchLib(self, logger): Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Re...
03adda0775bfa338bfc61bfac14fe457b283a85c
<|skeleton|> class SqliteSeeker: """Seeker (Identifier) for the zlib open source library.""" def searchLib(self, logger): """Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Return Value: number of library instances that were found i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SqliteSeeker: """Seeker (Identifier) for the zlib open source library.""" def searchLib(self, logger): """Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Return Value: number of library instances that were found in the binary"...
the_stack_v2_python_sparse
src/libs/sqlite.py
MITRE-Reversing-Internship/Karta-Modified
train
1
1b6299249952c91c17556548319bdf85b8e5809f
[ "system = Atoms(cell=[[3.3, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 3.0]], scaled_positions=[[0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.0, 0.0], [0.0, 0.5, 0.5]], symbols=['C', 'H', 'C', 'H'], pbc=True)\ncorrect_state = ['d', 'a', 'd', 'a']\nanalyzer = SymmetryAnalyzer(system)\norig_wyckoffs = analyzer.get_wyckoff_l...
<|body_start_0|> system = Atoms(cell=[[3.3, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 3.0]], scaled_positions=[[0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.0, 0.0], [0.0, 0.5, 0.5]], symbols=['C', 'H', 'C', 'H'], pbc=True) correct_state = ['d', 'a', 'd', 'a'] analyzer = SymmetryAnalyzer(system) ...
Tests that the correct normalizer is applied to reach minimal configuration score that defines the Wyckoff positions.
GroundStateTests
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroundStateTests: """Tests that the correct normalizer is applied to reach minimal configuration score that defines the Wyckoff positions.""" def test_translation(self): """Test a transform that translates atoms.""" <|body_0|> def test_transformation_affine(self): ...
stack_v2_sparse_classes_75kplus_train_071889
41,331
permissive
[ { "docstring": "Test a transform that translates atoms.", "name": "test_translation", "signature": "def test_translation(self)" }, { "docstring": "Test a transform where the transformation is a proper rigid transformation in the scaled cell basis, but will be non-rigid in the cartesian basis. Th...
3
stack_v2_sparse_classes_30k_train_013453
Implement the Python class `GroundStateTests` described below. Class description: Tests that the correct normalizer is applied to reach minimal configuration score that defines the Wyckoff positions. Method signatures and docstrings: - def test_translation(self): Test a transform that translates atoms. - def test_tra...
Implement the Python class `GroundStateTests` described below. Class description: Tests that the correct normalizer is applied to reach minimal configuration score that defines the Wyckoff positions. Method signatures and docstrings: - def test_translation(self): Test a transform that translates atoms. - def test_tra...
ae7c5ee1912b58a32fc7ea6edbf2fa2dc9155146
<|skeleton|> class GroundStateTests: """Tests that the correct normalizer is applied to reach minimal configuration score that defines the Wyckoff positions.""" def test_translation(self): """Test a transform that translates atoms.""" <|body_0|> def test_transformation_affine(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GroundStateTests: """Tests that the correct normalizer is applied to reach minimal configuration score that defines the Wyckoff positions.""" def test_translation(self): """Test a transform that translates atoms.""" system = Atoms(cell=[[3.3, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 3.0]],...
the_stack_v2_python_sparse
regtests/symmetrytests.py
SINGROUP/matid
train
25
1807ab34f2edb6d249c1c488a59fb9fa964fdeec
[ "self.resume_command = a.get_command_message(resume_args)\nself.command = get_log_reversed(command_log, stack_level)\nself.output_dir = get_log_reversed(dirs_log, stack_level)\nself.defaults_file = os.path.join(self.output_dir, DEFAULTS_FILE)\nself.args = [arg.decode(u.BIGML_SYS_ENCODING) for arg in shlex.split(sel...
<|body_start_0|> self.resume_command = a.get_command_message(resume_args) self.command = get_log_reversed(command_log, stack_level) self.output_dir = get_log_reversed(dirs_log, stack_level) self.defaults_file = os.path.join(self.output_dir, DEFAULTS_FILE) self.args = [arg.decode(...
Objects derived from a stored bigmler command
StoredCommand
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StoredCommand: """Objects derived from a stored bigmler command""" def __init__(self, resume_args, command_log, dirs_log, stack_level=0): """Constructor that extracts the command from the file ``command_log``: file for stored commands ``dirs_log``: file for associated work directorie...
stack_v2_sparse_classes_75kplus_train_071890
13,144
permissive
[ { "docstring": "Constructor that extracts the command from the file ``command_log``: file for stored commands ``dirs_log``: file for associated work directories ``stack_level``: index in the stack for the command to be retrieved", "name": "__init__", "signature": "def __init__(self, resume_args, command...
2
stack_v2_sparse_classes_30k_train_002329
Implement the Python class `StoredCommand` described below. Class description: Objects derived from a stored bigmler command Method signatures and docstrings: - def __init__(self, resume_args, command_log, dirs_log, stack_level=0): Constructor that extracts the command from the file ``command_log``: file for stored c...
Implement the Python class `StoredCommand` described below. Class description: Objects derived from a stored bigmler command Method signatures and docstrings: - def __init__(self, resume_args, command_log, dirs_log, stack_level=0): Constructor that extracts the command from the file ``command_log``: file for stored c...
bbf221e41ef04e8d37a511a35a63216b64689449
<|skeleton|> class StoredCommand: """Objects derived from a stored bigmler command""" def __init__(self, resume_args, command_log, dirs_log, stack_level=0): """Constructor that extracts the command from the file ``command_log``: file for stored commands ``dirs_log``: file for associated work directorie...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StoredCommand: """Objects derived from a stored bigmler command""" def __init__(self, resume_args, command_log, dirs_log, stack_level=0): """Constructor that extracts the command from the file ``command_log``: file for stored commands ``dirs_log``: file for associated work directories ``stack_lev...
the_stack_v2_python_sparse
bigmler/command.py
jaor/bigmler
train
0
b81ccd7caa88effd27e064c47ab46646502c6348
[ "self = super(DataPlane.PollSuccess, cls).__new__(cls, device, port, packet, time)\nself.expected_packet = expected_packet\nreturn self", "try:\n stdout_save = sys.stdout\n sys.stdout = StringIO()\n print('========== RECEIVED ==========')\n if isinstance(self.expected_packet, packet.Packet):\n ...
<|body_start_0|> self = super(DataPlane.PollSuccess, cls).__new__(cls, device, port, packet, time) self.expected_packet = expected_packet return self <|end_body_0|> <|body_start_1|> try: stdout_save = sys.stdout sys.stdout = StringIO() print('========...
Returned by poll() when it successfully finds a matching packet.
PollSuccess
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PollSuccess: """Returned by poll() when it successfully finds a matching packet.""" def __new__(cls, device, port, packet, expected_packet, time): """Initialize. (We're an immutable tuple, so we can't use __init__.)""" <|body_0|> def format(self): """Returns a st...
stack_v2_sparse_classes_75kplus_train_071891
35,906
permissive
[ { "docstring": "Initialize. (We're an immutable tuple, so we can't use __init__.)", "name": "__new__", "signature": "def __new__(cls, device, port, packet, expected_packet, time)" }, { "docstring": "Returns a string containing a nice (but verbose) representation of this packet. If the expected p...
2
null
Implement the Python class `PollSuccess` described below. Class description: Returned by poll() when it successfully finds a matching packet. Method signatures and docstrings: - def __new__(cls, device, port, packet, expected_packet, time): Initialize. (We're an immutable tuple, so we can't use __init__.) - def forma...
Implement the Python class `PollSuccess` described below. Class description: Returned by poll() when it successfully finds a matching packet. Method signatures and docstrings: - def __new__(cls, device, port, packet, expected_packet, time): Initialize. (We're an immutable tuple, so we can't use __init__.) - def forma...
d2e2d8ad005a451ad11f9d21af50079a0552921a
<|skeleton|> class PollSuccess: """Returned by poll() when it successfully finds a matching packet.""" def __new__(cls, device, port, packet, expected_packet, time): """Initialize. (We're an immutable tuple, so we can't use __init__.)""" <|body_0|> def format(self): """Returns a st...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PollSuccess: """Returned by poll() when it successfully finds a matching packet.""" def __new__(cls, device, port, packet, expected_packet, time): """Initialize. (We're an immutable tuple, so we can't use __init__.)""" self = super(DataPlane.PollSuccess, cls).__new__(cls, device, port, pa...
the_stack_v2_python_sparse
src/ptf/dataplane.py
p4lang/ptf
train
131
790b4ef362190da006623b1aa1a5ce396ecd9608
[ "self._build_info_path = control.get('build_info_path')\nself._build_label_pattern = control.get('build_label_pattern')\nself._build_version_pattern = control.get('build_version_pattern')\nself._capture_groups = control.get('capture_groups')\nself._fallback_build_label = control.get('fallback_build_label') or None\...
<|body_start_0|> self._build_info_path = control.get('build_info_path') self._build_label_pattern = control.get('build_label_pattern') self._build_version_pattern = control.get('build_version_pattern') self._capture_groups = control.get('capture_groups') self._fallback_build_labe...
Implements the core functionality of the versioning tool.
VersionTool
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VersionTool: """Implements the core functionality of the versioning tool.""" def __init__(self, control): """Initializes VersionTool with the given control options. Args: control: The dictionary of options used to control the tool. Please see the moduledoc for a description of the fo...
stack_v2_sparse_classes_75kplus_train_071892
9,887
permissive
[ { "docstring": "Initializes VersionTool with the given control options. Args: control: The dictionary of options used to control the tool. Please see the moduledoc for a description of the format of this dictionary.", "name": "__init__", "signature": "def __init__(self, control)" }, { "docstring...
4
stack_v2_sparse_classes_30k_train_015559
Implement the Python class `VersionTool` described below. Class description: Implements the core functionality of the versioning tool. Method signatures and docstrings: - def __init__(self, control): Initializes VersionTool with the given control options. Args: control: The dictionary of options used to control the t...
Implement the Python class `VersionTool` described below. Class description: Implements the core functionality of the versioning tool. Method signatures and docstrings: - def __init__(self, control): Initializes VersionTool with the given control options. Args: control: The dictionary of options used to control the t...
55cf5c2bec04b05b9ab435e24174834c5681be12
<|skeleton|> class VersionTool: """Implements the core functionality of the versioning tool.""" def __init__(self, control): """Initializes VersionTool with the given control options. Args: control: The dictionary of options used to control the tool. Please see the moduledoc for a description of the fo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VersionTool: """Implements the core functionality of the versioning tool.""" def __init__(self, control): """Initializes VersionTool with the given control options. Args: control: The dictionary of options used to control the tool. Please see the moduledoc for a description of the format of this ...
the_stack_v2_python_sparse
tools/versiontool/versiontool.py
bazelbuild/rules_apple
train
449
c1e0980c580a973589e2c9b9dc4500cf2002ec27
[ "if not features.has('organizations:incidents', project.organization, actor=request.user):\n raise ResourceDoesNotExist\nreturn self.paginate(request, queryset=AlertRule.objects.fetch_for_project(project), order_by='-date_added', paginator_cls=OffsetPaginator, on_results=lambda x: serialize(x, request.user), def...
<|body_start_0|> if not features.has('organizations:incidents', project.organization, actor=request.user): raise ResourceDoesNotExist return self.paginate(request, queryset=AlertRule.objects.fetch_for_project(project), order_by='-date_added', paginator_cls=OffsetPaginator, on_results=lambda ...
ProjectAlertRuleIndexEndpoint
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectAlertRuleIndexEndpoint: def get(self, request, project): """Fetches alert rules for a project""" <|body_0|> def post(self, request, project): """Create an alert rule""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not features.has('organiz...
stack_v2_sparse_classes_75kplus_train_071893
1,640
permissive
[ { "docstring": "Fetches alert rules for a project", "name": "get", "signature": "def get(self, request, project)" }, { "docstring": "Create an alert rule", "name": "post", "signature": "def post(self, request, project)" } ]
2
stack_v2_sparse_classes_30k_train_041426
Implement the Python class `ProjectAlertRuleIndexEndpoint` described below. Class description: Implement the ProjectAlertRuleIndexEndpoint class. Method signatures and docstrings: - def get(self, request, project): Fetches alert rules for a project - def post(self, request, project): Create an alert rule
Implement the Python class `ProjectAlertRuleIndexEndpoint` described below. Class description: Implement the ProjectAlertRuleIndexEndpoint class. Method signatures and docstrings: - def get(self, request, project): Fetches alert rules for a project - def post(self, request, project): Create an alert rule <|skeleton|...
c0d9ea9be63887654f9bf3bcc386969f2fb0b8a4
<|skeleton|> class ProjectAlertRuleIndexEndpoint: def get(self, request, project): """Fetches alert rules for a project""" <|body_0|> def post(self, request, project): """Create an alert rule""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProjectAlertRuleIndexEndpoint: def get(self, request, project): """Fetches alert rules for a project""" if not features.has('organizations:incidents', project.organization, actor=request.user): raise ResourceDoesNotExist return self.paginate(request, queryset=AlertRule.obje...
the_stack_v2_python_sparse
src/sentry/incidents/endpoints/project_alert_rule_index.py
kiranps/sentry
train
1
50fc99b90c935089ead7d3ea45ba25f2c45fe583
[ "data = etree.Element('data')\nfor key, value in result.items():\n room = etree.SubElement(data, 'room', id=str(key))\n room.text = value['name']\n for stud in value['students']:\n student = etree.SubElement(room, 'student')\n student.text = stud\ndata = etree.ElementTree(data)\nreturn data",...
<|body_start_0|> data = etree.Element('data') for key, value in result.items(): room = etree.SubElement(data, 'room', id=str(key)) room.text = value['name'] for stud in value['students']: student = etree.SubElement(room, 'student') stud...
XMLSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XMLSerializer: def create_xml_data(self, result: dict): """Creating structure XML file""" <|body_0|> def output_xml(result: dict, name_file: str): """Output data to a XML file""" <|body_1|> <|end_skeleton|> <|body_start_0|> data = etree.Element('dat...
stack_v2_sparse_classes_75kplus_train_071894
1,321
no_license
[ { "docstring": "Creating structure XML file", "name": "create_xml_data", "signature": "def create_xml_data(self, result: dict)" }, { "docstring": "Output data to a XML file", "name": "output_xml", "signature": "def output_xml(result: dict, name_file: str)" } ]
2
stack_v2_sparse_classes_30k_test_000792
Implement the Python class `XMLSerializer` described below. Class description: Implement the XMLSerializer class. Method signatures and docstrings: - def create_xml_data(self, result: dict): Creating structure XML file - def output_xml(result: dict, name_file: str): Output data to a XML file
Implement the Python class `XMLSerializer` described below. Class description: Implement the XMLSerializer class. Method signatures and docstrings: - def create_xml_data(self, result: dict): Creating structure XML file - def output_xml(result: dict, name_file: str): Output data to a XML file <|skeleton|> class XMLSe...
949161970d842e35b364c590b6d8e22bd8f0a1b6
<|skeleton|> class XMLSerializer: def create_xml_data(self, result: dict): """Creating structure XML file""" <|body_0|> def output_xml(result: dict, name_file: str): """Output data to a XML file""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class XMLSerializer: def create_xml_data(self, result: dict): """Creating structure XML file""" data = etree.Element('data') for key, value in result.items(): room = etree.SubElement(data, 'room', id=str(key)) room.text = value['name'] for stud in value['s...
the_stack_v2_python_sparse
task1/serializer.py
INVICTA1/LeverX
train
0
4649897dee9754b1070f95959e1a17b932f164df
[ "area, left, right = (0, 0, len(height) - 1)\nwhile left < right:\n new_area = (right - left) * min(height[left], height[right])\n area = max(area, new_area)\n if height[left] <= height[right]:\n left += 1\n else:\n right -= 1\nreturn area", "max_index = height.index(max(height))\nprint(...
<|body_start_0|> area, left, right = (0, 0, len(height) - 1) while left < right: new_area = (right - left) * min(height[left], height[right]) area = max(area, new_area) if height[left] <= height[right]: left += 1 else: right...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_0|> def maxArea_v2(self, height): """NOTE: This doesnt work for all cases: For example: [1, 2, 1] :type height: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_75kplus_train_071895
1,697
permissive
[ { "docstring": ":type height: List[int] :rtype: int", "name": "maxArea", "signature": "def maxArea(self, height)" }, { "docstring": "NOTE: This doesnt work for all cases: For example: [1, 2, 1] :type height: List[int] :rtype: int", "name": "maxArea_v2", "signature": "def maxArea_v2(self,...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxArea(self, height): :type height: List[int] :rtype: int - def maxArea_v2(self, height): NOTE: This doesnt work for all cases: For example: [1, 2, 1] :type height: List[int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxArea(self, height): :type height: List[int] :rtype: int - def maxArea_v2(self, height): NOTE: This doesnt work for all cases: For example: [1, 2, 1] :type height: List[int...
547c200b627c774535bc22880b16d5390183aeba
<|skeleton|> class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_0|> def maxArea_v2(self, height): """NOTE: This doesnt work for all cases: For example: [1, 2, 1] :type height: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" area, left, right = (0, 0, len(height) - 1) while left < right: new_area = (right - left) * min(height[left], height[right]) area = max(area, new_area) if height[left] <= ...
the_stack_v2_python_sparse
medium/11_container_with_most_waters.py
Sukhrobjon/leetcode
train
0
18f3c4e9f1ec2dd0cde3e8094f3c21404dfb3a85
[ "super().__init__()\nself._id = request_id\nself._project_name = project_name\nself._model_path = model_path\nself._input_precision = input_precision\nself._model_output_path = model_output_path\nself._output_precision = output_precision\nself._mode = mode\nself._workload_path = workload_path\nself._status = status...
<|body_start_0|> super().__init__() self._id = request_id self._project_name = project_name self._model_path = model_path self._input_precision = input_precision self._model_output_path = model_output_path self._output_precision = output_precision self._mo...
Create template for workload_list entity.
WorkloadInfo
[ "MIT", "Intel", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkloadInfo: """Create template for workload_list entity.""" def __init__(self, request_id: str, project_name: Optional[str], workload_path: Optional[str], model_path: Optional[str], input_precision: Optional[str], model_output_path: Optional[str], output_precision: Optional[str], mode: Opt...
stack_v2_sparse_classes_75kplus_train_071896
12,851
permissive
[ { "docstring": "Initialize configuration WorkloadInfo class.", "name": "__init__", "signature": "def __init__(self, request_id: str, project_name: Optional[str], workload_path: Optional[str], model_path: Optional[str], input_precision: Optional[str], model_output_path: Optional[str], output_precision: O...
3
stack_v2_sparse_classes_30k_train_011536
Implement the Python class `WorkloadInfo` described below. Class description: Create template for workload_list entity. Method signatures and docstrings: - def __init__(self, request_id: str, project_name: Optional[str], workload_path: Optional[str], model_path: Optional[str], input_precision: Optional[str], model_ou...
Implement the Python class `WorkloadInfo` described below. Class description: Create template for workload_list entity. Method signatures and docstrings: - def __init__(self, request_id: str, project_name: Optional[str], workload_path: Optional[str], model_path: Optional[str], input_precision: Optional[str], model_ou...
3976edc4215398e69ce0213f87ec295f5dc96e0e
<|skeleton|> class WorkloadInfo: """Create template for workload_list entity.""" def __init__(self, request_id: str, project_name: Optional[str], workload_path: Optional[str], model_path: Optional[str], input_precision: Optional[str], model_output_path: Optional[str], output_precision: Optional[str], mode: Opt...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WorkloadInfo: """Create template for workload_list entity.""" def __init__(self, request_id: str, project_name: Optional[str], workload_path: Optional[str], model_path: Optional[str], input_precision: Optional[str], model_output_path: Optional[str], output_precision: Optional[str], mode: Optional[str], m...
the_stack_v2_python_sparse
neural_compressor/ux/utils/workload/workloads_list.py
Skp80/neural-compressor
train
0
c183d223ccbbf9f2619c866a42cb99e4bd9ef6dc
[ "assert isinstance(output_size, (int, tuple))\nif isinstance(output_size, int):\n self.output_size = (output_size,)\n for _ in range(out_dim - 1):\n self.output_size += (output_size,)\nelse:\n assert len(output_size) == out_dim\n self.output_size = output_size\nself.out_dim = out_dim", "mask = ...
<|body_start_0|> assert isinstance(output_size, (int, tuple)) if isinstance(output_size, int): self.output_size = (output_size,) for _ in range(out_dim - 1): self.output_size += (output_size,) else: assert len(output_size) == out_dim ...
base class for crop transform
CropBase
[ "CC-BY-3.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CropBase: """base class for crop transform""" def __init__(self, out_dim: int, output_size: Union[tuple, int]): """provide the common functionality for RandomCrop2D and RandomCrop3D""" <|body_0|> def _get_sample_idxs(self, img: np.ndarray) -> Tuple[int, int, int]: ...
stack_v2_sparse_classes_75kplus_train_071897
17,484
permissive
[ { "docstring": "provide the common functionality for RandomCrop2D and RandomCrop3D", "name": "__init__", "signature": "def __init__(self, out_dim: int, output_size: Union[tuple, int])" }, { "docstring": "get the set of indices from which to sample (foreground)", "name": "_get_sample_idxs", ...
2
stack_v2_sparse_classes_30k_test_000927
Implement the Python class `CropBase` described below. Class description: base class for crop transform Method signatures and docstrings: - def __init__(self, out_dim: int, output_size: Union[tuple, int]): provide the common functionality for RandomCrop2D and RandomCrop3D - def _get_sample_idxs(self, img: np.ndarray)...
Implement the Python class `CropBase` described below. Class description: base class for crop transform Method signatures and docstrings: - def __init__(self, out_dim: int, output_size: Union[tuple, int]): provide the common functionality for RandomCrop2D and RandomCrop3D - def _get_sample_idxs(self, img: np.ndarray)...
b17509aa1cc8029b7de702971a7ad3a9dcd3c7f4
<|skeleton|> class CropBase: """base class for crop transform""" def __init__(self, out_dim: int, output_size: Union[tuple, int]): """provide the common functionality for RandomCrop2D and RandomCrop3D""" <|body_0|> def _get_sample_idxs(self, img: np.ndarray) -> Tuple[int, int, int]: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CropBase: """base class for crop transform""" def __init__(self, out_dim: int, output_size: Union[tuple, int]): """provide the common functionality for RandomCrop2D and RandomCrop3D""" assert isinstance(output_size, (int, tuple)) if isinstance(output_size, int): self.o...
the_stack_v2_python_sparse
DeepNormalize/io/transforms.py
pldelisle/deepNormalize
train
0
4cb57cab5178e80faf3156cd7422bc0a309559fe
[ "self.K = K\nself.X, self.T = ([], [])\nself.flagKLinReg = flagKLinReg", "self.X, self.T = (np.array(X), np.array(T))\nself.N, self.D = self.X.shape\nself.kdtree = scipy.spatial.KDTree(self.X)", "if K == None:\n K = self.K\nif flagKLinReg == None:\n flagKLinReg = self.flagKLinReg\nnn = self.kdtree.query(x...
<|body_start_0|> self.K = K self.X, self.T = ([], []) self.flagKLinReg = flagKLinReg <|end_body_0|> <|body_start_1|> self.X, self.T = (np.array(X), np.array(T)) self.N, self.D = self.X.shape self.kdtree = scipy.spatial.KDTree(self.X) <|end_body_1|> <|body_start_2|> ...
Class for fast K-Nearest-Neighbor-Regression using KD-trees
KNNRegressifier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KNNRegressifier: """Class for fast K-Nearest-Neighbor-Regression using KD-trees""" def __init__(self, K, flagKLinReg=0): """Constructor of class KNNRegressifier :param K: number of nearest neighbors that are used to compute prediction :flagKLinReg: if >0 then the do a linear (least s...
stack_v2_sparse_classes_75kplus_train_071898
21,971
no_license
[ { "docstring": "Constructor of class KNNRegressifier :param K: number of nearest neighbors that are used to compute prediction :flagKLinReg: if >0 then the do a linear (least squares) regression on the the K nearest neighbors and their target values otherwise just take the mean of the K nearest neighbors target...
3
stack_v2_sparse_classes_30k_test_000414
Implement the Python class `KNNRegressifier` described below. Class description: Class for fast K-Nearest-Neighbor-Regression using KD-trees Method signatures and docstrings: - def __init__(self, K, flagKLinReg=0): Constructor of class KNNRegressifier :param K: number of nearest neighbors that are used to compute pre...
Implement the Python class `KNNRegressifier` described below. Class description: Class for fast K-Nearest-Neighbor-Regression using KD-trees Method signatures and docstrings: - def __init__(self, K, flagKLinReg=0): Constructor of class KNNRegressifier :param K: number of nearest neighbors that are used to compute pre...
de2ba4e2afdad7e2e1ba0c145edbd341f8555802
<|skeleton|> class KNNRegressifier: """Class for fast K-Nearest-Neighbor-Regression using KD-trees""" def __init__(self, K, flagKLinReg=0): """Constructor of class KNNRegressifier :param K: number of nearest neighbors that are used to compute prediction :flagKLinReg: if >0 then the do a linear (least s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KNNRegressifier: """Class for fast K-Nearest-Neighbor-Regression using KD-trees""" def __init__(self, K, flagKLinReg=0): """Constructor of class KNNRegressifier :param K: number of nearest neighbors that are used to compute prediction :flagKLinReg: if >0 then the do a linear (least squares) regre...
the_stack_v2_python_sparse
versuch2/src/V2A2_Regression.py
xsjad0/ias-neuronale-netze
train
1
5b4777008ee54e4f6e24402e464a6fc765465c62
[ "if hasattr(cls, name):\n return getattr(cls, name)\nelse:\n return default", "out = {}\nfor att_name in dir(cls):\n if att_name.isupper():\n out[att_name] = getattr(cls, att_name)\nreturn out", "base_path = os.path.dirname(__file__)\nfull_path = os.path.join(base_path, 'default_policy.json')\nf...
<|body_start_0|> if hasattr(cls, name): return getattr(cls, name) else: return default <|end_body_0|> <|body_start_1|> out = {} for att_name in dir(cls): if att_name.isupper(): out[att_name] = getattr(cls, att_name) return out ...
BaseConfig
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseConfig: def get(cls, name, default=None): """Emulate get method from dict""" <|body_0|> def to_dict(cls): """Return dict of all uppercase attributes""" <|body_1|> def setup_policies(cls): """Read default policy file""" <|body_2|> <|e...
stack_v2_sparse_classes_75kplus_train_071899
2,610
permissive
[ { "docstring": "Emulate get method from dict", "name": "get", "signature": "def get(cls, name, default=None)" }, { "docstring": "Return dict of all uppercase attributes", "name": "to_dict", "signature": "def to_dict(cls)" }, { "docstring": "Read default policy file", "name": ...
3
stack_v2_sparse_classes_30k_test_002368
Implement the Python class `BaseConfig` described below. Class description: Implement the BaseConfig class. Method signatures and docstrings: - def get(cls, name, default=None): Emulate get method from dict - def to_dict(cls): Return dict of all uppercase attributes - def setup_policies(cls): Read default policy file
Implement the Python class `BaseConfig` described below. Class description: Implement the BaseConfig class. Method signatures and docstrings: - def get(cls, name, default=None): Emulate get method from dict - def to_dict(cls): Return dict of all uppercase attributes - def setup_policies(cls): Read default policy file...
8841c069bb5a53ae18affc0222356956220bbd47
<|skeleton|> class BaseConfig: def get(cls, name, default=None): """Emulate get method from dict""" <|body_0|> def to_dict(cls): """Return dict of all uppercase attributes""" <|body_1|> def setup_policies(cls): """Read default policy file""" <|body_2|> <|e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseConfig: def get(cls, name, default=None): """Emulate get method from dict""" if hasattr(cls, name): return getattr(cls, name) else: return default def to_dict(cls): """Return dict of all uppercase attributes""" out = {} for att_n...
the_stack_v2_python_sparse
kqueen/config/base.py
Mirantis/kqueen
train
146