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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
da4a76dbd5fa9d888c29bf18cce8ecdc28d41353 | [
"if DEBUG is True:\n messages.set_level(request, messages.DEBUG)\ntry:\n game = Game.objects.get(gameID=gameID)\n gameItems = GameItemLink.objects.filter(game=game).order_by('itemOrder')\n categories = Category.objects.filter(game=game)\nexcept Game.DoesNotExist:\n messages.add_message(request, messa... | <|body_start_0|>
if DEBUG is True:
messages.set_level(request, messages.DEBUG)
try:
game = Game.objects.get(gameID=gameID)
gameItems = GameItemLink.objects.filter(game=game).order_by('itemOrder')
categories = Category.objects.filter(game=game)
exce... | Edit the settings of a game. Categories and items are also displayed. | Edit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Edit:
"""Edit the settings of a game. Categories and items are also displayed."""
def get(self, request, gameID):
"""Render the game form and display the categories/game items"""
<|body_0|>
def post(self, request, gameID):
"""Update the game using the form"""
... | stack_v2_sparse_classes_75kplus_train_071700 | 12,215 | no_license | [
{
"docstring": "Render the game form and display the categories/game items",
"name": "get",
"signature": "def get(self, request, gameID)"
},
{
"docstring": "Update the game using the form",
"name": "post",
"signature": "def post(self, request, gameID)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028632 | Implement the Python class `Edit` described below.
Class description:
Edit the settings of a game. Categories and items are also displayed.
Method signatures and docstrings:
- def get(self, request, gameID): Render the game form and display the categories/game items
- def post(self, request, gameID): Update the game ... | Implement the Python class `Edit` described below.
Class description:
Edit the settings of a game. Categories and items are also displayed.
Method signatures and docstrings:
- def get(self, request, gameID): Render the game form and display the categories/game items
- def post(self, request, gameID): Update the game ... | 7fcb23e8034937713f82155c4176abfb3c57c22d | <|skeleton|>
class Edit:
"""Edit the settings of a game. Categories and items are also displayed."""
def get(self, request, gameID):
"""Render the game form and display the categories/game items"""
<|body_0|>
def post(self, request, gameID):
"""Update the game using the form"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Edit:
"""Edit the settings of a game. Categories and items are also displayed."""
def get(self, request, gameID):
"""Render the game form and display the categories/game items"""
if DEBUG is True:
messages.set_level(request, messages.DEBUG)
try:
game = Game... | the_stack_v2_python_sparse | game/views/admin_views/game.py | MarcelKolen/QuantumRules | train | 0 |
6d893bdd9c23dae4a8e214c517b4a1d2764e53f7 | [
"self.foods = []\nfor fx, fy in food:\n self.foods.append((fx, fy))\nself.food_index = 0\nself.width = width\nself.height = height\nself.body = [[0, 0]]",
"head_x, head_y = self.body[0]\nnext_x = head_x\nnext_y = head_y\nif direction == 'U':\n next_x -= 1\nelif direction == 'L':\n next_y -= 1\nelif direc... | <|body_start_0|>
self.foods = []
for fx, fy in food:
self.foods.append((fx, fy))
self.food_index = 0
self.width = width
self.height = height
self.body = [[0, 0]]
<|end_body_0|>
<|body_start_1|>
head_x, head_y = self.body[0]
next_x = head_x
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_75kplus_train_071701 | 1,998 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_train_038479 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | 696a25f8597e2a5bc5ab788924418d6423160af1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | 353_design_snake_game.py | tooyoungtoosimplesometimesnaive/probable-octo-potato | train | 0 | |
863bfa0255710eafce5655019c2ae5ecb715b6c0 | [
"l = graph.getEdges()\nl.sort()\nreturn l",
"graph = Graph()\nnodes = []\nfor i in range(num_nodes):\n nodes.append(graph.addNode(i))\nfor src in nodes:\n for dst in nodes:\n if dst.id > src.id:\n graph.insertEdge(src.id, dst.id, num_nodes - src.id)\nreturn graph"
] | <|body_start_0|>
l = graph.getEdges()
l.sort()
return l
<|end_body_0|>
<|body_start_1|>
graph = Graph()
nodes = []
for i in range(num_nodes):
nodes.append(graph.addNode(i))
for src in nodes:
for dst in nodes:
if dst.id > sr... | Utility functions for graph management. | GraphHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphHelper:
"""Utility functions for graph management."""
def sortEdges(graph):
"""Return the list of edges, sorted by their weight. :param graph: the graph. :return: the list of edges, sorted by their weight."""
<|body_0|>
def buildGraph(num_nodes):
"""Build a ... | stack_v2_sparse_classes_75kplus_train_071702 | 1,100 | no_license | [
{
"docstring": "Return the list of edges, sorted by their weight. :param graph: the graph. :return: the list of edges, sorted by their weight.",
"name": "sortEdges",
"signature": "def sortEdges(graph)"
},
{
"docstring": "Build a sample complete graph. :param num_nodes number of nodes. :return: a... | 2 | stack_v2_sparse_classes_30k_train_047290 | Implement the Python class `GraphHelper` described below.
Class description:
Utility functions for graph management.
Method signatures and docstrings:
- def sortEdges(graph): Return the list of edges, sorted by their weight. :param graph: the graph. :return: the list of edges, sorted by their weight.
- def buildGraph... | Implement the Python class `GraphHelper` described below.
Class description:
Utility functions for graph management.
Method signatures and docstrings:
- def sortEdges(graph): Return the list of edges, sorted by their weight. :param graph: the graph. :return: the list of edges, sorted by their weight.
- def buildGraph... | 56cc4aa6b6e8e90349190eab8ef660a305883b3f | <|skeleton|>
class GraphHelper:
"""Utility functions for graph management."""
def sortEdges(graph):
"""Return the list of edges, sorted by their weight. :param graph: the graph. :return: the list of edges, sorted by their weight."""
<|body_0|>
def buildGraph(num_nodes):
"""Build a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphHelper:
"""Utility functions for graph management."""
def sortEdges(graph):
"""Return the list of edges, sorted by their weight. :param graph: the graph. :return: the list of edges, sorted by their weight."""
l = graph.getEdges()
l.sort()
return l
def buildGraph(... | the_stack_v2_python_sparse | graph/GraphHelper.py | uniroma2-algorithms/ingegneria-algoritmi-2018 | train | 1 |
b03bd6914df61360403c762341af76b52b6b70fb | [
"self.datamover_image_location = datamover_image_location\nself.init_container_image_location = init_container_image_location\nself.kubernetes_distribution = kubernetes_distribution\nself.velero_aws_plugin_image_location = velero_aws_plugin_image_location\nself.velero_image_location = velero_image_location\nself.ve... | <|body_start_0|>
self.datamover_image_location = datamover_image_location
self.init_container_image_location = init_container_image_location
self.kubernetes_distribution = kubernetes_distribution
self.velero_aws_plugin_image_location = velero_aws_plugin_image_location
self.velero... | Implementation of the 'KubernetesParams' model. Specifies the parameters required to register Application Servers running in a Protection Source. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. init_container_image_location (string): Specifies the location o... | KubernetesParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KubernetesParams:
"""Implementation of the 'KubernetesParams' model. Specifies the parameters required to register Application Servers running in a Protection Source. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. init_container_image... | stack_v2_sparse_classes_75kplus_train_071703 | 3,848 | permissive | [
{
"docstring": "Constructor for the KubernetesParams class",
"name": "__init__",
"signature": "def __init__(self, datamover_image_location=None, init_container_image_location=None, kubernetes_distribution=None, velero_aws_plugin_image_location=None, velero_image_location=None, velero_openshift_plugin_im... | 2 | stack_v2_sparse_classes_30k_train_043393 | Implement the Python class `KubernetesParams` described below.
Class description:
Implementation of the 'KubernetesParams' model. Specifies the parameters required to register Application Servers running in a Protection Source. Attributes: datamover_image_location (string): Specifies the location of Datamover image in... | Implement the Python class `KubernetesParams` described below.
Class description:
Implementation of the 'KubernetesParams' model. Specifies the parameters required to register Application Servers running in a Protection Source. Attributes: datamover_image_location (string): Specifies the location of Datamover image in... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class KubernetesParams:
"""Implementation of the 'KubernetesParams' model. Specifies the parameters required to register Application Servers running in a Protection Source. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. init_container_image... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KubernetesParams:
"""Implementation of the 'KubernetesParams' model. Specifies the parameters required to register Application Servers running in a Protection Source. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. init_container_image_location (st... | the_stack_v2_python_sparse | cohesity_management_sdk/models/kubernetes_params.py | cohesity/management-sdk-python | train | 24 |
582aab6a5fcad6bbb027c3929c2d2c9c8a49b5d6 | [
"config = super(EtherpadStatusCollector, self).get_default_config()\nconfig.update({'url': 'http://localhost:9001/stats', 'path_prefix': 'etherpad', 'gauges': ['memoryUsage', 'totalUsers', 'pendingEdits'], 'counters': ['connects/count', 'disconnects/count', 'httpRequests/meter/count', 'edits/meter/count', 'failedCh... | <|body_start_0|>
config = super(EtherpadStatusCollector, self).get_default_config()
config.update({'url': 'http://localhost:9001/stats', 'path_prefix': 'etherpad', 'gauges': ['memoryUsage', 'totalUsers', 'pendingEdits'], 'counters': ['connects/count', 'disconnects/count', 'httpRequests/meter/count', 'ed... | EtherpadStatusCollector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EtherpadStatusCollector:
def get_default_config(self):
"""Returns the default collector settings"""
<|body_0|>
def collect(self):
"""Publishes stats to the configured path."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
config = super(EtherpadStatu... | stack_v2_sparse_classes_75kplus_train_071704 | 1,455 | no_license | [
{
"docstring": "Returns the default collector settings",
"name": "get_default_config",
"signature": "def get_default_config(self)"
},
{
"docstring": "Publishes stats to the configured path.",
"name": "collect",
"signature": "def collect(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043500 | Implement the Python class `EtherpadStatusCollector` described below.
Class description:
Implement the EtherpadStatusCollector class.
Method signatures and docstrings:
- def get_default_config(self): Returns the default collector settings
- def collect(self): Publishes stats to the configured path. | Implement the Python class `EtherpadStatusCollector` described below.
Class description:
Implement the EtherpadStatusCollector class.
Method signatures and docstrings:
- def get_default_config(self): Returns the default collector settings
- def collect(self): Publishes stats to the configured path.
<|skeleton|>
clas... | 75e0dd3698efa8e7cf95f6ef1348d16a299faa82 | <|skeleton|>
class EtherpadStatusCollector:
def get_default_config(self):
"""Returns the default collector settings"""
<|body_0|>
def collect(self):
"""Publishes stats to the configured path."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EtherpadStatusCollector:
def get_default_config(self):
"""Returns the default collector settings"""
config = super(EtherpadStatusCollector, self).get_default_config()
config.update({'url': 'http://localhost:9001/stats', 'path_prefix': 'etherpad', 'gauges': ['memoryUsage', 'totalUsers',... | the_stack_v2_python_sparse | modules/etherpad/files/etherpad.py | dkuspawono/puppet | train | 0 | |
9c7f70a54251a0f430c14271cac283b302a503e5 | [
"super().__init__(properties=properties, data=data, source=source, copy=copy, _use_data=_use_data)\nself._initialise_netcdf(source)\nself._initialise_original_filenames(source)",
"if _create_title and _title is None:\n _title = 'Index: ' + self.identity(default='')\nreturn super().dump(display=display, _key=_k... | <|body_start_0|>
super().__init__(properties=properties, data=data, source=source, copy=copy, _use_data=_use_data)
self._initialise_netcdf(source)
self._initialise_original_filenames(source)
<|end_body_0|>
<|body_start_1|>
if _create_title and _title is None:
_title = 'Index... | An index variable required to uncompress a ragged array. A collection of features stored using an indexed ragged array combines all features along a single dimension (the sample dimension) such that the values of each feature in the collection are interleaved. The information needed to uncompress the data is stored in ... | Index | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Index:
"""An index variable required to uncompress a ragged array. A collection of features stored using an indexed ragged array combines all features along a single dimension (the sample dimension) such that the values of each feature in the collection are interleaved. The information needed to ... | stack_v2_sparse_classes_75kplus_train_071705 | 3,716 | permissive | [
{
"docstring": "**Initialisation** :Parameters: {{init properties: `dict`, optional}} *Parameter example:* ``properties={'long_name': 'which station this obs is for'}`` {{init data: data_like, optional}} {{init source: optional}} {{init copy: `bool`, optional}}",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_027964 | Implement the Python class `Index` described below.
Class description:
An index variable required to uncompress a ragged array. A collection of features stored using an indexed ragged array combines all features along a single dimension (the sample dimension) such that the values of each feature in the collection are ... | Implement the Python class `Index` described below.
Class description:
An index variable required to uncompress a ragged array. A collection of features stored using an indexed ragged array combines all features along a single dimension (the sample dimension) such that the values of each feature in the collection are ... | 142accf27fbbc052473b4eee47daf0e81c88df3a | <|skeleton|>
class Index:
"""An index variable required to uncompress a ragged array. A collection of features stored using an indexed ragged array combines all features along a single dimension (the sample dimension) such that the values of each feature in the collection are interleaved. The information needed to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Index:
"""An index variable required to uncompress a ragged array. A collection of features stored using an indexed ragged array combines all features along a single dimension (the sample dimension) such that the values of each feature in the collection are interleaved. The information needed to uncompress th... | the_stack_v2_python_sparse | cfdm/index.py | NCAS-CMS/cfdm | train | 29 |
fcfdb776808c38d21374c4316d0a2c0d5c9b0af9 | [
"if request.user.is_authenticated:\n return HttpResponseRedirect(reverse('dashboard'))\nelse:\n return render(request, self.login_template_name, {})",
"username = request.POST.get('username', None)\npassword = request.POST.get('password', None)\nuser = authenticate(username=username, password=password)\nif ... | <|body_start_0|>
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('dashboard'))
else:
return render(request, self.login_template_name, {})
<|end_body_0|>
<|body_start_1|>
username = request.POST.get('username', None)
password = request.POST.g... | Login view. | LoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
"""Login view."""
def get(self, request):
"""If user will be already login then redirect to welcome page else redirect to login page."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Login user and redirect them to related template as per the... | stack_v2_sparse_classes_75kplus_train_071706 | 3,094 | no_license | [
{
"docstring": "If user will be already login then redirect to welcome page else redirect to login page.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Login user and redirect them to related template as per the condition.",
"name": "post",
"signature": "def po... | 2 | stack_v2_sparse_classes_30k_train_028992 | Implement the Python class `LoginView` described below.
Class description:
Login view.
Method signatures and docstrings:
- def get(self, request): If user will be already login then redirect to welcome page else redirect to login page.
- def post(self, request, *args, **kwargs): Login user and redirect them to relate... | Implement the Python class `LoginView` described below.
Class description:
Login view.
Method signatures and docstrings:
- def get(self, request): If user will be already login then redirect to welcome page else redirect to login page.
- def post(self, request, *args, **kwargs): Login user and redirect them to relate... | 46128d102a0550e4fcc8d941adc5159457674e87 | <|skeleton|>
class LoginView:
"""Login view."""
def get(self, request):
"""If user will be already login then redirect to welcome page else redirect to login page."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Login user and redirect them to related template as per the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginView:
"""Login view."""
def get(self, request):
"""If user will be already login then redirect to welcome page else redirect to login page."""
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('dashboard'))
else:
return render(reque... | the_stack_v2_python_sparse | users_profile/views.py | gautam-kumar-22/newincident | train | 3 |
b443b2586272040e2af9499257ba87b381b92745 | [
"if st == ed:\n if base == limit:\n ref = tmp[:]\n lst.append(ref)\n return\nfor i in xrange(step + 1, 10):\n tmp.append(i)\n self.CS(st + 1, ed, lst, tmp, base + i, i, limit)\n tmp.pop()",
"res, tmp = ([], [])\nself.CS(0, k, res, tmp, 0, 0, n)\nreturn res"
] | <|body_start_0|>
if st == ed:
if base == limit:
ref = tmp[:]
lst.append(ref)
return
for i in xrange(step + 1, 10):
tmp.append(i)
self.CS(st + 1, ed, lst, tmp, base + i, i, limit)
tmp.pop()
<|end_body_0|>
<|body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def CS(self, st, ed, lst, tmp, base, step, limit):
"""st和ed表示对k的控制,base和limit表示n的控制 step来表示不超过10的限制"""
<|body_0|>
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_071707 | 1,178 | no_license | [
{
"docstring": "st和ed表示对k的控制,base和limit表示n的控制 step来表示不超过10的限制",
"name": "CS",
"signature": "def CS(self, st, ed, lst, tmp, base, step, limit)"
},
{
"docstring": ":type k: int :type n: int :rtype: List[List[int]]",
"name": "combinationSum3",
"signature": "def combinationSum3(self, k, n)"
... | 2 | stack_v2_sparse_classes_30k_train_045796 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def CS(self, st, ed, lst, tmp, base, step, limit): st和ed表示对k的控制,base和limit表示n的控制 step来表示不超过10的限制
- def combinationSum3(self, k, n): :type k: int :type n: int :rtype: List[List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def CS(self, st, ed, lst, tmp, base, step, limit): st和ed表示对k的控制,base和limit表示n的控制 step来表示不超过10的限制
- def combinationSum3(self, k, n): :type k: int :type n: int :rtype: List[List[in... | 507ed2efeff7818ca9cf53a8ee7fb80d3c530d67 | <|skeleton|>
class Solution:
def CS(self, st, ed, lst, tmp, base, step, limit):
"""st和ed表示对k的控制,base和limit表示n的控制 step来表示不超过10的限制"""
<|body_0|>
def combinationSum3(self, k, n):
""":type k: int :type n: 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 CS(self, st, ed, lst, tmp, base, step, limit):
"""st和ed表示对k的控制,base和limit表示n的控制 step来表示不超过10的限制"""
if st == ed:
if base == limit:
ref = tmp[:]
lst.append(ref)
return
for i in xrange(step + 1, 10):
tmp.app... | the_stack_v2_python_sparse | Leetcode/Backtracking/#216-Combination Sum III/main.py | qizongjun/Algorithms-1 | train | 0 | |
b6a22bbc93ed7230e59269637a75b0a0a3282fae | [
"if mode == Mode.PLAYER:\n return True\nreturn False",
"if mode == Mode.RANDOM_AI or mode == Mode.AI_WITHOUT_FLAGS or mode == Mode.AI_WITH_FLAGS or (mode == Mode.AI_WITH_FLAGS2):\n return True\nreturn False"
] | <|body_start_0|>
if mode == Mode.PLAYER:
return True
return False
<|end_body_0|>
<|body_start_1|>
if mode == Mode.RANDOM_AI or mode == Mode.AI_WITHOUT_FLAGS or mode == Mode.AI_WITH_FLAGS or (mode == Mode.AI_WITH_FLAGS2):
return True
return False
<|end_body_1|>
| Mode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mode:
def is_player_mode(cls, mode):
"""Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise."""
<|body_0|>
def is_ai_mode(cls, mode):
"""Allow to know if a mode is an artificial intelligence mo... | stack_v2_sparse_classes_75kplus_train_071708 | 5,674 | no_license | [
{
"docstring": "Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise.",
"name": "is_player_mode",
"signature": "def is_player_mode(cls, mode)"
},
{
"docstring": "Allow to know if a mode is an artificial intelligence mode or... | 2 | stack_v2_sparse_classes_30k_train_012051 | Implement the Python class `Mode` described below.
Class description:
Implement the Mode class.
Method signatures and docstrings:
- def is_player_mode(cls, mode): Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise.
- def is_ai_mode(cls, mode):... | Implement the Python class `Mode` described below.
Class description:
Implement the Mode class.
Method signatures and docstrings:
- def is_player_mode(cls, mode): Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise.
- def is_ai_mode(cls, mode):... | e4601fbdd9f7cfdef6774f26c2850ec8cf3c562e | <|skeleton|>
class Mode:
def is_player_mode(cls, mode):
"""Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise."""
<|body_0|>
def is_ai_mode(cls, mode):
"""Allow to know if a mode is an artificial intelligence mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mode:
def is_player_mode(cls, mode):
"""Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise."""
if mode == Mode.PLAYER:
return True
return False
def is_ai_mode(cls, mode):
"""Allow to kno... | the_stack_v2_python_sparse | source/main.py | roundsace/Minesweeper_deep_learning | train | 0 | |
af788f1b33b24a6c2c3e80cb974c69b73c94106a | [
"request_json = request.get_json()\nvalid_format, errors = schema_utils.validate(request_json, 'org')\nif not valid_format:\n return ({'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST)\ntry:\n user = UserService.find_by_jwt_token()\n if user is None:\n response, status = ... | <|body_start_0|>
request_json = request.get_json()
valid_format, errors = schema_utils.validate(request_json, 'org')
if not valid_format:
return ({'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST)
try:
user = UserService.find_by_jwt_tok... | Resource for managing orgs. | Orgs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Orgs:
"""Resource for managing orgs."""
def post():
"""Post a new org using the request body. If the org already exists, update the attributes."""
<|body_0|>
def get():
"""Search orgs."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
request_json... | stack_v2_sparse_classes_75kplus_train_071709 | 30,185 | permissive | [
{
"docstring": "Post a new org using the request body. If the org already exists, update the attributes.",
"name": "post",
"signature": "def post()"
},
{
"docstring": "Search orgs.",
"name": "get",
"signature": "def get()"
}
] | 2 | stack_v2_sparse_classes_30k_train_052876 | Implement the Python class `Orgs` described below.
Class description:
Resource for managing orgs.
Method signatures and docstrings:
- def post(): Post a new org using the request body. If the org already exists, update the attributes.
- def get(): Search orgs. | Implement the Python class `Orgs` described below.
Class description:
Resource for managing orgs.
Method signatures and docstrings:
- def post(): Post a new org using the request body. If the org already exists, update the attributes.
- def get(): Search orgs.
<|skeleton|>
class Orgs:
"""Resource for managing or... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class Orgs:
"""Resource for managing orgs."""
def post():
"""Post a new org using the request body. If the org already exists, update the attributes."""
<|body_0|>
def get():
"""Search orgs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Orgs:
"""Resource for managing orgs."""
def post():
"""Post a new org using the request body. If the org already exists, update the attributes."""
request_json = request.get_json()
valid_format, errors = schema_utils.validate(request_json, 'org')
if not valid_format:
... | the_stack_v2_python_sparse | auth-api/src/auth_api/resources/org.py | bcgov/sbc-auth | train | 13 |
f540212a825692aa8ac31fb20ce6e8c2c007c989 | [
"if not email:\n raise ValueError(_('The Email must be set'))\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user",
"extra_fields.setdefault('is_staff', True)\nextra_fields.setdefault('is_superuser', True)\nextra_fields.set... | <|body_start_0|>
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
<|end_body_0|>
<|body_start_1|>
extra_fi... | Custom user model manager where email is the unique identifiers for authentication instead of username. | CustomUserManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of username."""
def create_user(self, email: str, password: str, **extra_fields: dict):
"""Create and save a User with the given email and password."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_071710 | 2,824 | permissive | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email: str, password: str, **extra_fields: dict)"
},
{
"docstring": "Create and save a SuperUser with the given email and password.",
"name": "create_superus... | 2 | null | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of username.
Method signatures and docstrings:
- def create_user(self, email: str, password: str, **extra_fields: dict): Create and save a User ... | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of username.
Method signatures and docstrings:
- def create_user(self, email: str, password: str, **extra_fields: dict): Create and save a User ... | 02c811c9178f338e081efbeacadb37c766dcb2db | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of username."""
def create_user(self, email: str, password: str, **extra_fields: dict):
"""Create and save a User with the given email and password."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of username."""
def create_user(self, email: str, password: str, **extra_fields: dict):
"""Create and save a User with the given email and password."""
if not email:
... | the_stack_v2_python_sparse | phasma_food_v2/users/models.py | VizLoreLabs/phasmaFoodPlatform | train | 0 |
d98a75f5bcd631506e8987df995b6d525c712b3f | [
"self.mlp = mlp\nself.epsilon = kwargs.pop('epsilon', 1e-08)\nself.gamma = kwargs.pop('gamma', 0.9)\nself.avg_w_list = [np.zeros(w.shape) for w in self.mlp.weights_list]\nself.avg_b_list = [np.zeros(b.shape) for b in self.mlp.biases_list]\nself.avg_delta_w_list = [np.zeros(w.shape) for w in self.mlp.weights_list]\n... | <|body_start_0|>
self.mlp = mlp
self.epsilon = kwargs.pop('epsilon', 1e-08)
self.gamma = kwargs.pop('gamma', 0.9)
self.avg_w_list = [np.zeros(w.shape) for w in self.mlp.weights_list]
self.avg_b_list = [np.zeros(b.shape) for b in self.mlp.biases_list]
self.avg_delta_w_list... | Class implementing Adadelta optimization Attributes ---------- mlp : MLP Multilayer Perceptron object to be trained epsilon : float Parameter used to update weights and biases gamma : float Parameter used to update weights and biases avg_w_list : np.array Average weights list for the MLP avg_b_list : np.array Average b... | Adadelta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adadelta:
"""Class implementing Adadelta optimization Attributes ---------- mlp : MLP Multilayer Perceptron object to be trained epsilon : float Parameter used to update weights and biases gamma : float Parameter used to update weights and biases avg_w_list : np.array Average weights list for the... | stack_v2_sparse_classes_75kplus_train_071711 | 20,458 | permissive | [
{
"docstring": "__init__ method for the Adadelta class Sets up hyperparameters for the Adadelta class Parameters ---------- mlp : MLP Multilayer Perceptron object to be trained **kwargs : Parameters used by the Adadelta method (epsilon, gamma)",
"name": "__init__",
"signature": "def __init__(self, mlp, ... | 2 | null | Implement the Python class `Adadelta` described below.
Class description:
Class implementing Adadelta optimization Attributes ---------- mlp : MLP Multilayer Perceptron object to be trained epsilon : float Parameter used to update weights and biases gamma : float Parameter used to update weights and biases avg_w_list ... | Implement the Python class `Adadelta` described below.
Class description:
Class implementing Adadelta optimization Attributes ---------- mlp : MLP Multilayer Perceptron object to be trained epsilon : float Parameter used to update weights and biases gamma : float Parameter used to update weights and biases avg_w_list ... | 3761ff4f2a68137ac196e75c8651260cb8c79e69 | <|skeleton|>
class Adadelta:
"""Class implementing Adadelta optimization Attributes ---------- mlp : MLP Multilayer Perceptron object to be trained epsilon : float Parameter used to update weights and biases gamma : float Parameter used to update weights and biases avg_w_list : np.array Average weights list for the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Adadelta:
"""Class implementing Adadelta optimization Attributes ---------- mlp : MLP Multilayer Perceptron object to be trained epsilon : float Parameter used to update weights and biases gamma : float Parameter used to update weights and biases avg_w_list : np.array Average weights list for the MLP avg_b_li... | the_stack_v2_python_sparse | pr3/mlpOptimizer.py | zentonllo/gcom | train | 1 |
2b3d96c9a0a381f183af0fe54ecbd57eae7b9e05 | [
"label = active_cell['column_id']\nif label in cols.keys():\n value = data[active_cell['row']][cols[label]]\n return (label, value)\nelse:\n return (None, None)",
"info = ctx.triggered[0]\nself._id_ = info['prop_id'].split('.')[0]\nvalue = info['value']\n\"if self._id_.split('_')[0] == 'ddl':\\n ... | <|body_start_0|>
label = active_cell['column_id']
if label in cols.keys():
value = data[active_cell['row']][cols[label]]
return (label, value)
else:
return (None, None)
<|end_body_0|>
<|body_start_1|>
info = ctx.triggered[0]
self._id_ = info['... | Get_Params | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Get_Params:
def Get_Value_DT(self, active_cell, data, cols):
"""Hỗ trợ lấy giá trị của datatable"""
<|body_0|>
def Get_Value(self, ctx, data=None):
"""Lấy giá trị của các loại biểu đồ, datatable"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
label ... | stack_v2_sparse_classes_75kplus_train_071712 | 1,625 | no_license | [
{
"docstring": "Hỗ trợ lấy giá trị của datatable",
"name": "Get_Value_DT",
"signature": "def Get_Value_DT(self, active_cell, data, cols)"
},
{
"docstring": "Lấy giá trị của các loại biểu đồ, datatable",
"name": "Get_Value",
"signature": "def Get_Value(self, ctx, data=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054516 | Implement the Python class `Get_Params` described below.
Class description:
Implement the Get_Params class.
Method signatures and docstrings:
- def Get_Value_DT(self, active_cell, data, cols): Hỗ trợ lấy giá trị của datatable
- def Get_Value(self, ctx, data=None): Lấy giá trị của các loại biểu đồ, datatable | Implement the Python class `Get_Params` described below.
Class description:
Implement the Get_Params class.
Method signatures and docstrings:
- def Get_Value_DT(self, active_cell, data, cols): Hỗ trợ lấy giá trị của datatable
- def Get_Value(self, ctx, data=None): Lấy giá trị của các loại biểu đồ, datatable
<|skelet... | 46d8a0b9df865e4db4bad05167a7e1b1d1e84d63 | <|skeleton|>
class Get_Params:
def Get_Value_DT(self, active_cell, data, cols):
"""Hỗ trợ lấy giá trị của datatable"""
<|body_0|>
def Get_Value(self, ctx, data=None):
"""Lấy giá trị của các loại biểu đồ, datatable"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Get_Params:
def Get_Value_DT(self, active_cell, data, cols):
"""Hỗ trợ lấy giá trị của datatable"""
label = active_cell['column_id']
if label in cols.keys():
value = data[active_cell['row']][cols[label]]
return (label, value)
else:
return (No... | the_stack_v2_python_sparse | QUACONTROL_DEMO/controller/get_params.py | NguyenThiMan44K212/QUACONTROL | train | 0 | |
a44acaa1c86f430e650f326c0bd36ba6b739a27d | [
"self.W = theano.shared(value=rng.uniform(low=-numpy.sqrt(6.0 / n_in), high=numpy.sqrt(6.0 / n_in), size=(n_in,)), name='W', borrow=True)\nself.b = theano.shared(value=0.0, name='b', borrow=True)\nself.L1 = abs(self.W).sum()\nself.L2_sqr = (self.W ** 2).sum()\nh_1 = T.dot(input, self.W) + self.b\nself.p_1 = 1 / (1 ... | <|body_start_0|>
self.W = theano.shared(value=rng.uniform(low=-numpy.sqrt(6.0 / n_in), high=numpy.sqrt(6.0 / n_in), size=(n_in,)), name='W', borrow=True)
self.b = theano.shared(value=0.0, name='b', borrow=True)
self.L1 = abs(self.W).sum()
self.L2_sqr = (self.W ** 2).sum()
h_1 = T... | Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership probability. | LogisticRegression | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticRegression:
"""Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership prob... | stack_v2_sparse_classes_75kplus_train_071713 | 4,246 | permissive | [
{
"docstring": "Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dimension of the space in which the datapoints lie :type... | 3 | stack_v2_sparse_classes_30k_train_020889 | Implement the Python class `LogisticRegression` described below.
Class description:
Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is us... | Implement the Python class `LogisticRegression` described below.
Class description:
Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is us... | 82e04d1b5beadda9c8c0b8a684fe0aa8230852e3 | <|skeleton|>
class LogisticRegression:
"""Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership prob... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogisticRegression:
"""Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership probability."""
... | the_stack_v2_python_sparse | tools/DependencyReordering/nnAdapt/models/logistic_sgd.py | nusnlp/neuralreord-aaai2017 | train | 3 |
f89e523d962fa1b2f4c4fb57fe4558e5d885f16c | [
"tag_name = 'iktomi_files'\nbody = self.body.markup\ntry:\n tree = html.fromstring(body)\nexcept XMLSyntaxError:\n return []\nexpr = '//{}'.format(tag_name)\ntags = tree.xpath(expr)\ninserted_file_block_ids = [int(tag.attrib['item_id']) for tag in tags]\nreturn [block for block in self.files_blocks if block.i... | <|body_start_0|>
tag_name = 'iktomi_files'
body = self.body.markup
try:
tree = html.fromstring(body)
except XMLSyntaxError:
return []
expr = '//{}'.format(tag_name)
tags = tree.xpath(expr)
inserted_file_block_ids = [int(tag.attrib['item_id'... | MFY_Page | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MFY_Page:
def hanging_file_blocks(self):
"""Return list of file blocks attached to event but not inserted in body."""
<|body_0|>
def hanging_link_blocks(self):
"""Return list of link blocks attached to event but not inserted in body."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_071714 | 1,656 | no_license | [
{
"docstring": "Return list of file blocks attached to event but not inserted in body.",
"name": "hanging_file_blocks",
"signature": "def hanging_file_blocks(self)"
},
{
"docstring": "Return list of link blocks attached to event but not inserted in body.",
"name": "hanging_link_blocks",
... | 2 | null | Implement the Python class `MFY_Page` described below.
Class description:
Implement the MFY_Page class.
Method signatures and docstrings:
- def hanging_file_blocks(self): Return list of file blocks attached to event but not inserted in body.
- def hanging_link_blocks(self): Return list of link blocks attached to even... | Implement the Python class `MFY_Page` described below.
Class description:
Implement the MFY_Page class.
Method signatures and docstrings:
- def hanging_file_blocks(self): Return list of file blocks attached to event but not inserted in body.
- def hanging_link_blocks(self): Return list of link blocks attached to even... | 229887486bcb12af7ad70d764f05b73acb7eda81 | <|skeleton|>
class MFY_Page:
def hanging_file_blocks(self):
"""Return list of file blocks attached to event but not inserted in body."""
<|body_0|>
def hanging_link_blocks(self):
"""Return list of link blocks attached to event but not inserted in body."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MFY_Page:
def hanging_file_blocks(self):
"""Return list of file blocks attached to event but not inserted in body."""
tag_name = 'iktomi_files'
body = self.body.markup
try:
tree = html.fromstring(body)
except XMLSyntaxError:
return []
exp... | the_stack_v2_python_sparse | cms34/resources/pages/models.py | motor23/cms34 | train | 0 | |
ca868d070f1d16c1075c53d77d6e97a54a3ceb75 | [
"q = Q(list_public=True)\nif userprofile:\n q |= Q(list_sharestuffers=True)\n q |= Q(list_watchers=True) & Q(donor__watchers__in=[userprofile])\nreturn self.filter(Q(live_status=True) & q).distinct()",
"donorprofile, latitude, longitude, max_distance, watched_users, asking_userprofile, tags = (params.get('d... | <|body_start_0|>
q = Q(list_public=True)
if userprofile:
q |= Q(list_sharestuffers=True)
q |= Q(list_watchers=True) & Q(donor__watchers__in=[userprofile])
return self.filter(Q(live_status=True) & q).distinct()
<|end_body_0|>
<|body_start_1|>
donorprofile, latitud... | QuerySet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuerySet:
def filter_by_user(self, userprofile):
"""Filter the list down to offers the user has permission to see listed"""
<|body_0|>
def filter_by(self, **params):
"""Function to grab a filtered queryset with added distance field. The current sql will scale abysmal... | stack_v2_sparse_classes_75kplus_train_071715 | 6,401 | no_license | [
{
"docstring": "Filter the list down to offers the user has permission to see listed",
"name": "filter_by_user",
"signature": "def filter_by_user(self, userprofile)"
},
{
"docstring": "Function to grab a filtered queryset with added distance field. The current sql will scale abysmally and will n... | 2 | stack_v2_sparse_classes_30k_train_008936 | Implement the Python class `QuerySet` described below.
Class description:
Implement the QuerySet class.
Method signatures and docstrings:
- def filter_by_user(self, userprofile): Filter the list down to offers the user has permission to see listed
- def filter_by(self, **params): Function to grab a filtered queryset ... | Implement the Python class `QuerySet` described below.
Class description:
Implement the QuerySet class.
Method signatures and docstrings:
- def filter_by_user(self, userprofile): Filter the list down to offers the user has permission to see listed
- def filter_by(self, **params): Function to grab a filtered queryset ... | 10a6c69ca8049443fd7714328cc30c3239dc5e63 | <|skeleton|>
class QuerySet:
def filter_by_user(self, userprofile):
"""Filter the list down to offers the user has permission to see listed"""
<|body_0|>
def filter_by(self, **params):
"""Function to grab a filtered queryset with added distance field. The current sql will scale abysmal... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuerySet:
def filter_by_user(self, userprofile):
"""Filter the list down to offers the user has permission to see listed"""
q = Q(list_public=True)
if userprofile:
q |= Q(list_sharestuffers=True)
q |= Q(list_watchers=True) & Q(donor__watchers__in=[userprofile])
... | the_stack_v2_python_sparse | goingspare/offers/models.py | Joeboy/django-sharestuff | train | 1 | |
14660005f0bd0171da03b1060b2681e0a17af3a4 | [
"super(Encoder, self).__init__()\nrnn_type = rnn_type.lower().strip()\nself.rnn_type = rnn_type\nself.vocab_size = vocab_size\nself.embedding_size = embedding_size\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.dropout_ = dropout_\nself.bidirectional_ = bidirectional_\nif rnn_type != 'gru' and ... | <|body_start_0|>
super(Encoder, self).__init__()
rnn_type = rnn_type.lower().strip()
self.rnn_type = rnn_type
self.vocab_size = vocab_size
self.embedding_size = embedding_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.dropout_ = drop... | Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, rnn_type, vocab_size, embedding_size, hidden_size, num_layers, dropout_=0, bidirectional_=True):
""":param rnn_type: type of rnn. supporting (RNN, LSTM, GRU). type: str :param vocab_size: size of vocabulary. type: int :param embedding_size: size of each embedd... | stack_v2_sparse_classes_75kplus_train_071716 | 12,036 | permissive | [
{
"docstring": ":param rnn_type: type of rnn. supporting (RNN, LSTM, GRU). type: str :param vocab_size: size of vocabulary. type: int :param embedding_size: size of each embedding vector :param hidden_size: hidden size in each rnn layers. type: int :param num_layers: number of rnn layers. type: int :param dropo... | 2 | null | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, rnn_type, vocab_size, embedding_size, hidden_size, num_layers, dropout_=0, bidirectional_=True): :param rnn_type: type of rnn. supporting (RNN, LSTM, GRU). type:... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, rnn_type, vocab_size, embedding_size, hidden_size, num_layers, dropout_=0, bidirectional_=True): :param rnn_type: type of rnn. supporting (RNN, LSTM, GRU). type:... | cbc5ad010ce04da7a82f05ad1a3b6c16f8467266 | <|skeleton|>
class Encoder:
def __init__(self, rnn_type, vocab_size, embedding_size, hidden_size, num_layers, dropout_=0, bidirectional_=True):
""":param rnn_type: type of rnn. supporting (RNN, LSTM, GRU). type: str :param vocab_size: size of vocabulary. type: int :param embedding_size: size of each embedd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
def __init__(self, rnn_type, vocab_size, embedding_size, hidden_size, num_layers, dropout_=0, bidirectional_=True):
""":param rnn_type: type of rnn. supporting (RNN, LSTM, GRU). type: str :param vocab_size: size of vocabulary. type: int :param embedding_size: size of each embedding vector :pa... | the_stack_v2_python_sparse | models/S2S_attention.py | FYYFU/NMT | train | 0 | |
57075916f7e244c45d7b3e3fe373e4ebfa04e094 | [
"w = AddText(None)\nyield w\nw.close()",
"assert isinstance(widget, QtWidgets.QDialog)\nassert isinstance(widget._font, QtGui.QFont)\nassert widget._color == 'black'",
"font_1 = QtGui.QFont('Helvetica', 15)\nmocker.patch.object(QtWidgets.QFontDialog, 'getFont', return_value=(font_1, True))\nwidget.onFontChange(... | <|body_start_0|>
w = AddText(None)
yield w
w.close()
<|end_body_0|>
<|body_start_1|>
assert isinstance(widget, QtWidgets.QDialog)
assert isinstance(widget._font, QtGui.QFont)
assert widget._color == 'black'
<|end_body_1|>
<|body_start_2|>
font_1 = QtGui.QFont('H... | Test the AddText | AddTextTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddTextTest:
"""Test the AddText"""
def widget(self, qapp):
"""Create/Destroy the AddText"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
def testOnFontChange(self, widget, mocker):
"""Test the... | stack_v2_sparse_classes_75kplus_train_071717 | 1,950 | permissive | [
{
"docstring": "Create/Destroy the AddText",
"name": "widget",
"signature": "def widget(self, qapp)"
},
{
"docstring": "Test the GUI in its default state",
"name": "testDefaults",
"signature": "def testDefaults(self, widget)"
},
{
"docstring": "Test the QFontDialog output",
"... | 4 | stack_v2_sparse_classes_30k_train_024100 | Implement the Python class `AddTextTest` described below.
Class description:
Test the AddText
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the AddText
- def testDefaults(self, widget): Test the GUI in its default state
- def testOnFontChange(self, widget, mocker): Test the QFontDialog ou... | Implement the Python class `AddTextTest` described below.
Class description:
Test the AddText
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the AddText
- def testDefaults(self, widget): Test the GUI in its default state
- def testOnFontChange(self, widget, mocker): Test the QFontDialog ou... | 55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7 | <|skeleton|>
class AddTextTest:
"""Test the AddText"""
def widget(self, qapp):
"""Create/Destroy the AddText"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
def testOnFontChange(self, widget, mocker):
"""Test the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddTextTest:
"""Test the AddText"""
def widget(self, qapp):
"""Create/Destroy the AddText"""
w = AddText(None)
yield w
w.close()
def testDefaults(self, widget):
"""Test the GUI in its default state"""
assert isinstance(widget, QtWidgets.QDialog)
... | the_stack_v2_python_sparse | src/sas/qtgui/Plotting/UnitTesting/AddTextTest.py | SasView/sasview | train | 48 |
9ba502b33efc0ba4b00625cba6bdf1d91a1e2e03 | [
"portfolio_book = PortfolioBookModel.find_by_portfolio_id(portfolioId)\nif portfolio_book:\n return ({'Portfolio Book of Portfolio {}'.format(portfolioId): list(map(lambda x: x.json(), portfolio_book))}, 201)\nelse:\n return ({'message': 'This portofolio does not exist or does not have any book in the portfol... | <|body_start_0|>
portfolio_book = PortfolioBookModel.find_by_portfolio_id(portfolioId)
if portfolio_book:
return ({'Portfolio Book of Portfolio {}'.format(portfolioId): list(map(lambda x: x.json(), portfolio_book))}, 201)
else:
return ({'message': 'This portofolio does no... | PortfolioBook. Resource that helps with dealing with Http request for a portfolio_book provided an id. HTTP GET call : /portfolios/<int:portfolioId>/books HTTP DELETE call : /portfolios/<int:portfolioId>/books | PortfolioBook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PortfolioBook:
"""PortfolioBook. Resource that helps with dealing with Http request for a portfolio_book provided an id. HTTP GET call : /portfolios/<int:portfolioId>/books HTTP DELETE call : /portfolios/<int:portfolioId>/books"""
def get(self, portfolioId):
"""GET request that deals... | stack_v2_sparse_classes_75kplus_train_071718 | 4,951 | permissive | [
{
"docstring": "GET request that deals with requests that look for a portfolio book relation given a portfolioId",
"name": "get",
"signature": "def get(self, portfolioId)"
},
{
"docstring": "DELETE request that deals with the deletion of all relations that belongs to a portfolioId",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_028830 | Implement the Python class `PortfolioBook` described below.
Class description:
PortfolioBook. Resource that helps with dealing with Http request for a portfolio_book provided an id. HTTP GET call : /portfolios/<int:portfolioId>/books HTTP DELETE call : /portfolios/<int:portfolioId>/books
Method signatures and docstri... | Implement the Python class `PortfolioBook` described below.
Class description:
PortfolioBook. Resource that helps with dealing with Http request for a portfolio_book provided an id. HTTP GET call : /portfolios/<int:portfolioId>/books HTTP DELETE call : /portfolios/<int:portfolioId>/books
Method signatures and docstri... | 42456ced804a2c9570227b393de662847283c76f | <|skeleton|>
class PortfolioBook:
"""PortfolioBook. Resource that helps with dealing with Http request for a portfolio_book provided an id. HTTP GET call : /portfolios/<int:portfolioId>/books HTTP DELETE call : /portfolios/<int:portfolioId>/books"""
def get(self, portfolioId):
"""GET request that deals... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PortfolioBook:
"""PortfolioBook. Resource that helps with dealing with Http request for a portfolio_book provided an id. HTTP GET call : /portfolios/<int:portfolioId>/books HTTP DELETE call : /portfolios/<int:portfolioId>/books"""
def get(self, portfolioId):
"""GET request that deals with request... | the_stack_v2_python_sparse | resources/portfolio_book.py | basgir/bibliotek | train | 0 |
6b996adf9dcae7e0d55eb5f561e1e83df5bfa869 | [
"extra_parts = ['CVS', 'SVN', 'GIT']\nkey_string = ': program compiled against libxml %d using older %d\\n'\nkey_indices = []\nfor idx, bin_str in enumerate(self._all_strings):\n if key_string in str(bin_str):\n logger.debug('Located a key string of %s in address 0x%x', self.NAME, bin_str.ea)\n key... | <|body_start_0|>
extra_parts = ['CVS', 'SVN', 'GIT']
key_string = ': program compiled against libxml %d using older %d\n'
key_indices = []
for idx, bin_str in enumerate(self._all_strings):
if key_string in str(bin_str):
logger.debug('Located a key string of %s... | Seeker (Identifier) for the libxml(2) open source library. | Libxml2Seeker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Libxml2Seeker:
"""Seeker (Identifier) for the libxml(2) 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 f... | stack_v2_sparse_classes_75kplus_train_071719 | 2,364 | 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 | null | Implement the Python class `Libxml2Seeker` described below.
Class description:
Seeker (Identifier) for the libxml(2) 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 insta... | Implement the Python class `Libxml2Seeker` described below.
Class description:
Seeker (Identifier) for the libxml(2) 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 insta... | 03adda0775bfa338bfc61bfac14fe457b283a85c | <|skeleton|>
class Libxml2Seeker:
"""Seeker (Identifier) for the libxml(2) 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 f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Libxml2Seeker:
"""Seeker (Identifier) for the libxml(2) 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 b... | the_stack_v2_python_sparse | src/libs/libxml2.py | MITRE-Reversing-Internship/Karta-Modified | train | 1 |
bf6e73075a59d349fada574767be26c20fe08869 | [
"len_nodetypes = float(Nodetype.published.count())\nself.cache_metatypes = {}\nfor cat in metatypes:\n if len_nodetypes:\n self.cache_metatypes[cat.pk] = cat.nodetypes_published().count() / len_nodetypes\n else:\n self.cache_metatypes[cat.pk] = 0.0",
"metatypes = Metatype.objects.all()\nself.c... | <|body_start_0|>
len_nodetypes = float(Nodetype.published.count())
self.cache_metatypes = {}
for cat in metatypes:
if len_nodetypes:
self.cache_metatypes[cat.pk] = cat.nodetypes_published().count() / len_nodetypes
else:
self.cache_metatypes... | Sitemap for metatypes | MetatypeSitemap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's nodetypes percent on total nodetypes"""
<|body_0|>
def items(self):
"""Return all metatypes with coeff"""
<|body_1|>
def lastmod(self, obj):
"""Retu... | stack_v2_sparse_classes_75kplus_train_071720 | 3,463 | permissive | [
{
"docstring": "Cache categorie's nodetypes percent on total nodetypes",
"name": "cache",
"signature": "def cache(self, metatypes)"
},
{
"docstring": "Return all metatypes with coeff",
"name": "items",
"signature": "def items(self)"
},
{
"docstring": "Return last modification of ... | 4 | stack_v2_sparse_classes_30k_train_041662 | Implement the Python class `MetatypeSitemap` described below.
Class description:
Sitemap for metatypes
Method signatures and docstrings:
- def cache(self, metatypes): Cache categorie's nodetypes percent on total nodetypes
- def items(self): Return all metatypes with coeff
- def lastmod(self, obj): Return last modific... | Implement the Python class `MetatypeSitemap` described below.
Class description:
Sitemap for metatypes
Method signatures and docstrings:
- def cache(self, metatypes): Cache categorie's nodetypes percent on total nodetypes
- def items(self): Return all metatypes with coeff
- def lastmod(self, obj): Return last modific... | d515883fc4ffe01dd8b4b876d5a3dd023f862d30 | <|skeleton|>
class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's nodetypes percent on total nodetypes"""
<|body_0|>
def items(self):
"""Return all metatypes with coeff"""
<|body_1|>
def lastmod(self, obj):
"""Retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's nodetypes percent on total nodetypes"""
len_nodetypes = float(Nodetype.published.count())
self.cache_metatypes = {}
for cat in metatypes:
if len_nodetypes:
... | the_stack_v2_python_sparse | gstudio/sitemaps.py | gnowgi/django-gstudio | train | 1 |
a8c9f5438970f8a96db50e9077261a9652e32f19 | [
"C = self.COEFFS[imt]\nmean = self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, rup.mag, dists.rrup) + self._get_style_of_faulting_term(C, rup.rake) + self._get_site_scaling_term(C, sites.vs30)\nstddevs = self._get_stddevs(imt, rup.mag, len(dists.rrup), stddev_types)\nreturn (mean, s... | <|body_start_0|>
C = self.COEFFS[imt]
mean = self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, rup.mag, dists.rrup) + self._get_style_of_faulting_term(C, rup.rake) + self._get_site_scaling_term(C, sites.vs30)
stddevs = self._get_stddevs(imt, rup.mag, len(dists.rru... | Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Idriss (2014) defines the GMPE only for the case in which Vs30 >= 450 m/s. In t... | Idriss2014 | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Idriss2014:
"""Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Idriss (2014) defines the GMPE only for t... | stack_v2_sparse_classes_75kplus_train_071721 | 8,985 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Returns the magnitu... | 6 | stack_v2_sparse_classes_30k_train_009552 | Implement the Python class `Idriss2014` described below.
Class description:
Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Id... | Implement the Python class `Idriss2014` described below.
Class description:
Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Id... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class Idriss2014:
"""Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Idriss (2014) defines the GMPE only for t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Idriss2014:
"""Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Idriss (2014) defines the GMPE only for the case in wh... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/idriss_2014.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
2f1f03360cdad3a250970ded40edfbef06276c91 | [
"if isinstance(objDict, list):\n for idx, value in enumerate(objDict):\n uriIdx = value['uid'] if 'uid' in value else idx\n subUri = '%s/%d' % (uri, uriIdx)\n self._decorateWithUris(value, subUri)\nelif isinstance(objDict, dict):\n innerListNames = []\n for name, value in objDict.iteri... | <|body_start_0|>
if isinstance(objDict, list):
for idx, value in enumerate(objDict):
uriIdx = value['uid'] if 'uid' in value else idx
subUri = '%s/%d' % (uri, uriIdx)
self._decorateWithUris(value, subUri)
elif isinstance(objDict, dict):
... | Extended JSON serializer. Also appends URIs. | JsonSerializerWithUris | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonSerializerWithUris:
"""Extended JSON serializer. Also appends URIs."""
def _decorateWithUris(self, objDict, uri):
"""Parse dict recursively and add uri to each member."""
<|body_0|>
def _removeUris(self, objDict):
"""Remove URI fields from dict so it can then... | stack_v2_sparse_classes_75kplus_train_071722 | 7,136 | no_license | [
{
"docstring": "Parse dict recursively and add uri to each member.",
"name": "_decorateWithUris",
"signature": "def _decorateWithUris(self, objDict, uri)"
},
{
"docstring": "Remove URI fields from dict so it can then be properly deserialized.",
"name": "_removeUris",
"signature": "def _r... | 4 | stack_v2_sparse_classes_30k_train_046934 | Implement the Python class `JsonSerializerWithUris` described below.
Class description:
Extended JSON serializer. Also appends URIs.
Method signatures and docstrings:
- def _decorateWithUris(self, objDict, uri): Parse dict recursively and add uri to each member.
- def _removeUris(self, objDict): Remove URI fields fro... | Implement the Python class `JsonSerializerWithUris` described below.
Class description:
Extended JSON serializer. Also appends URIs.
Method signatures and docstrings:
- def _decorateWithUris(self, objDict, uri): Parse dict recursively and add uri to each member.
- def _removeUris(self, objDict): Remove URI fields fro... | 8183d1bc5b557d39cdd0ea7ecf777cfd42754491 | <|skeleton|>
class JsonSerializerWithUris:
"""Extended JSON serializer. Also appends URIs."""
def _decorateWithUris(self, objDict, uri):
"""Parse dict recursively and add uri to each member."""
<|body_0|>
def _removeUris(self, objDict):
"""Remove URI fields from dict so it can then... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonSerializerWithUris:
"""Extended JSON serializer. Also appends URIs."""
def _decorateWithUris(self, objDict, uri):
"""Parse dict recursively and add uri to each member."""
if isinstance(objDict, list):
for idx, value in enumerate(objDict):
uriIdx = value['ui... | the_stack_v2_python_sparse | src/sensorsiesta-common/sensorsiestacommon/utils.py | AnnaDeak/SensorSiesta-ubbse2016 | train | 0 |
0e1dc6822c2b11ddf2569ecf334b825c61598c1d | [
"self.rule_name = rule_name\nself.rule_index = rule_index\nself.rule = rule",
"if self.rule['mode'] == _REQUIRED:\n if _required_sink_missing(self.rule['sink'], log_sinks):\n sink = self.rule['sink']\n yield self.RuleViolation(resource_name=resource.id, resource_type=resource.type, resource_id=re... | <|body_start_0|>
self.rule_name = rule_name
self.rule_index = rule_index
self.rule = rule
<|end_body_0|>
<|body_start_1|>
if self.rule['mode'] == _REQUIRED:
if _required_sink_missing(self.rule['sink'], log_sinks):
sink = self.rule['sink']
yiel... | Rule properties from the rule definition file. Also finds violations. | Rule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, rule_name, rule_index, rule):
"""Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of the rule from the rule definitions. rule (dict): The rule d... | stack_v2_sparse_classes_75kplus_train_071723 | 17,857 | permissive | [
{
"docstring": "Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of the rule from the rule definitions. rule (dict): The rule definition from the file.",
"name": "__init__",
"signature": "def __init__(self, rule_name, rule_index, rule)"
},
{
"docstring": "F... | 2 | null | Implement the Python class `Rule` described below.
Class description:
Rule properties from the rule definition file. Also finds violations.
Method signatures and docstrings:
- def __init__(self, rule_name, rule_index, rule): Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of th... | Implement the Python class `Rule` described below.
Class description:
Rule properties from the rule definition file. Also finds violations.
Method signatures and docstrings:
- def __init__(self, rule_name, rule_index, rule): Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of th... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, rule_name, rule_index, rule):
"""Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of the rule from the rule definitions. rule (dict): The rule d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, rule_name, rule_index, rule):
"""Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of the rule from the rule definitions. rule (dict): The rule definition fro... | the_stack_v2_python_sparse | google/cloud/forseti/scanner/audit/log_sink_rules_engine.py | kevensen/forseti-security | train | 1 |
22e32feb545e1283b4e6c112bdc21d53251ca26c | [
"json_text = {'msgtype': 'text', 'at': {'atMobiles': [''], 'isAtAll': False}, 'text': {'content': text}}\nheaders = {'Content-Type': 'application/json;charset=utf-8'}\napi_url = config.dingtalk\nresult = requests.post(api_url, json.dumps(json_text), headers=headers)\nlogger.debug('dingtalk text result:{} message:{}... | <|body_start_0|>
json_text = {'msgtype': 'text', 'at': {'atMobiles': [''], 'isAtAll': False}, 'text': {'content': text}}
headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url = config.dingtalk
result = requests.post(api_url, json.dumps(json_text), headers=headers)
... | DingTalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DingTalk:
def text(text):
"""推送文本类型信息至钉钉 :param data: 要推送的数据内容,字符串格式 :return:"""
<|body_0|>
def markdown(content):
"""推送markdown类型信息至钉钉 :param content:例如: content = "### 订单更新推送 " "> **订单ID:** 1096989546123445 " "> **订单状态:** FILLED " "> **时间戳:** 2021年1月2日" :return:推送结... | stack_v2_sparse_classes_75kplus_train_071724 | 2,002 | no_license | [
{
"docstring": "推送文本类型信息至钉钉 :param data: 要推送的数据内容,字符串格式 :return:",
"name": "text",
"signature": "def text(text)"
},
{
"docstring": "推送markdown类型信息至钉钉 :param content:例如: content = \"### 订单更新推送 \" \"> **订单ID:** 1096989546123445 \" \"> **订单状态:** FILLED \" \"> **时间戳:** 2021年1月2日\" :return:推送结果,例如推送成... | 2 | null | Implement the Python class `DingTalk` described below.
Class description:
Implement the DingTalk class.
Method signatures and docstrings:
- def text(text): 推送文本类型信息至钉钉 :param data: 要推送的数据内容,字符串格式 :return:
- def markdown(content): 推送markdown类型信息至钉钉 :param content:例如: content = "### 订单更新推送 " "> **订单ID:** 10969895461234... | Implement the Python class `DingTalk` described below.
Class description:
Implement the DingTalk class.
Method signatures and docstrings:
- def text(text): 推送文本类型信息至钉钉 :param data: 要推送的数据内容,字符串格式 :return:
- def markdown(content): 推送markdown类型信息至钉钉 :param content:例如: content = "### 订单更新推送 " "> **订单ID:** 10969895461234... | 07373ecade388119371e35fcbe541bb4ec182ac4 | <|skeleton|>
class DingTalk:
def text(text):
"""推送文本类型信息至钉钉 :param data: 要推送的数据内容,字符串格式 :return:"""
<|body_0|>
def markdown(content):
"""推送markdown类型信息至钉钉 :param content:例如: content = "### 订单更新推送 " "> **订单ID:** 1096989546123445 " "> **订单状态:** FILLED " "> **时间戳:** 2021年1月2日" :return:推送结... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DingTalk:
def text(text):
"""推送文本类型信息至钉钉 :param data: 要推送的数据内容,字符串格式 :return:"""
json_text = {'msgtype': 'text', 'at': {'atMobiles': [''], 'isAtAll': False}, 'text': {'content': text}}
headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url = config.dingtalk
... | the_stack_v2_python_sparse | stockquant/utils/dingtalk.py | xDaWenXi/stockquant_simple | train | 0 | |
9e7a32ae9f6da41d06b0a066bc8fd2ff2d931ced | [
"for testvalue, expected in self.knownvalues:\n p = project.Project()\n for d in self.directions:\n for s in self.seasons:\n for f in self.frames:\n for l in self.layers:\n result = p.image_path(d, s, f, l, testvalue, validate=True)\n self... | <|body_start_0|>
for testvalue, expected in self.knownvalues:
p = project.Project()
for d in self.directions:
for s in self.seasons:
for f in self.frames:
for l in self.layers:
result = p.image_path(d... | Test image path validator and image path settings | image_path | [
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class image_path:
"""Test image path validator and image path settings"""
def test_knownvalues_validate(self):
"""Test that known values are validated correctly"""
<|body_0|>
def test_knownvalues_set(self):
"""Test that known values are set correctly"""
<|body_... | stack_v2_sparse_classes_75kplus_train_071725 | 3,994 | permissive | [
{
"docstring": "Test that known values are validated correctly",
"name": "test_knownvalues_validate",
"signature": "def test_knownvalues_validate(self)"
},
{
"docstring": "Test that known values are set correctly",
"name": "test_knownvalues_set",
"signature": "def test_knownvalues_set(se... | 3 | stack_v2_sparse_classes_30k_train_006665 | Implement the Python class `image_path` described below.
Class description:
Test image path validator and image path settings
Method signatures and docstrings:
- def test_knownvalues_validate(self): Test that known values are validated correctly
- def test_knownvalues_set(self): Test that known values are set correct... | Implement the Python class `image_path` described below.
Class description:
Test image path validator and image path settings
Method signatures and docstrings:
- def test_knownvalues_validate(self): Test that known values are validated correctly
- def test_knownvalues_set(self): Test that known values are set correct... | 307a9de864566fece1a999888e19048aeef9734c | <|skeleton|>
class image_path:
"""Test image path validator and image path settings"""
def test_knownvalues_validate(self):
"""Test that known values are validated correctly"""
<|body_0|>
def test_knownvalues_set(self):
"""Test that known values are set correctly"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class image_path:
"""Test image path validator and image path settings"""
def test_knownvalues_validate(self):
"""Test that known values are validated correctly"""
for testvalue, expected in self.knownvalues:
p = project.Project()
for d in self.directions:
... | the_stack_v2_python_sparse | project_test.py | An-dz/tilecutter | train | 4 |
684d92dfddc21c01a55c788089e173b79e71fe19 | [
"super(AssignSample, self).setUp()\nschema = [('color1', str), ('predicted', str)]\nself.frame = self.context.frame.import_csv(self.get_file('model_color.csv'), schema=schema)",
"self.frame.assign_sample([0.6, 0.3, 0.1], ['one', 'two', 'three'], 'label_column', 2)\nbaseline = {'one': 0.6, 'two': 0.3, 'three': 0.1... | <|body_start_0|>
super(AssignSample, self).setUp()
schema = [('color1', str), ('predicted', str)]
self.frame = self.context.frame.import_csv(self.get_file('model_color.csv'), schema=schema)
<|end_body_0|>
<|body_start_1|>
self.frame.assign_sample([0.6, 0.3, 0.1], ['one', 'two', 'three']... | AssignSample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignSample:
def setUp(self):
"""Build test frame"""
<|body_0|>
def test_label_column(self):
"""Test splitting on the label column"""
<|body_1|>
def test_sample_bin(self):
"""Test splitting on the sample_bin column"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus_train_071726 | 3,247 | permissive | [
{
"docstring": "Build test frame",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test splitting on the label column",
"name": "test_label_column",
"signature": "def test_label_column(self)"
},
{
"docstring": "Test splitting on the sample_bin column",
"nam... | 5 | stack_v2_sparse_classes_30k_train_042287 | Implement the Python class `AssignSample` described below.
Class description:
Implement the AssignSample class.
Method signatures and docstrings:
- def setUp(self): Build test frame
- def test_label_column(self): Test splitting on the label column
- def test_sample_bin(self): Test splitting on the sample_bin column
-... | Implement the Python class `AssignSample` described below.
Class description:
Implement the AssignSample class.
Method signatures and docstrings:
- def setUp(self): Build test frame
- def test_label_column(self): Test splitting on the label column
- def test_sample_bin(self): Test splitting on the sample_bin column
-... | 5548fc925b5c278263cbdebbd9e8c7593320c2f4 | <|skeleton|>
class AssignSample:
def setUp(self):
"""Build test frame"""
<|body_0|>
def test_label_column(self):
"""Test splitting on the label column"""
<|body_1|>
def test_sample_bin(self):
"""Test splitting on the sample_bin column"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssignSample:
def setUp(self):
"""Build test frame"""
super(AssignSample, self).setUp()
schema = [('color1', str), ('predicted', str)]
self.frame = self.context.frame.import_csv(self.get_file('model_color.csv'), schema=schema)
def test_label_column(self):
"""Test s... | the_stack_v2_python_sparse | regression-tests/sparktkregtests/testcases/frames/assign_sample_test.py | trustedanalytics/spark-tk | train | 35 | |
488451854a3c0df8eaf4c34fbf79defc064719fc | [
"self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-sum' if model_name_or_path == '' else model_name_or_path, max_length=max_length, device=device, cache_dir=cache_dir)\nself.task = 'data2text'\nself.dimensions = ['naturalness', 'informativeness']",
"n_data = len(data)\neval_scores = [{} for _ in ra... | <|body_start_0|>
self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-sum' if model_name_or_path == '' else model_name_or_path, max_length=max_length, device=device, cache_dir=cache_dir)
self.task = 'data2text'
self.dimensions = ['naturalness', 'informativeness']
<|end_body_0|>
<|bo... | D2tEvaluator | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class D2tEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up evaluator for data-to-text"""
<|body_0|>
def evaluate(self, data, category, dims=None, overall=True):
"""Get the scores of all the given dimensions categ... | stack_v2_sparse_classes_75kplus_train_071727 | 14,573 | permissive | [
{
"docstring": "Set up evaluator for data-to-text",
"name": "__init__",
"signature": "def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None)"
},
{
"docstring": "Get the scores of all the given dimensions category: The category to be evaluated. dims: A list of di... | 2 | stack_v2_sparse_classes_30k_train_020146 | Implement the Python class `D2tEvaluator` described below.
Class description:
Implement the D2tEvaluator class.
Method signatures and docstrings:
- def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): Set up evaluator for data-to-text
- def evaluate(self, data, category, dims=None... | Implement the Python class `D2tEvaluator` described below.
Class description:
Implement the D2tEvaluator class.
Method signatures and docstrings:
- def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): Set up evaluator for data-to-text
- def evaluate(self, data, category, dims=None... | c7b60f75470f067d1342705708810a660eabd684 | <|skeleton|>
class D2tEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up evaluator for data-to-text"""
<|body_0|>
def evaluate(self, data, category, dims=None, overall=True):
"""Get the scores of all the given dimensions categ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class D2tEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up evaluator for data-to-text"""
self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-sum' if model_name_or_path == '' else model_name_or_path, max_length=max_length, devi... | the_stack_v2_python_sparse | applications/Chat/evaluate/unieval/evaluator.py | hpcaitech/ColossalAI | train | 32,044 | |
0a22cd06b17d3dbc585180f2889181fb46d747fd | [
"request = self.context.get('request')\nif obj:\n path = get_attachment_url(obj)\n return request.build_absolute_uri(path) if request else path\nreturn ''",
"request = self.context.get('request')\nif obj.mimetype.startswith('image'):\n path = get_attachment_url(obj, 'small')\n return request.build_abs... | <|body_start_0|>
request = self.context.get('request')
if obj:
path = get_attachment_url(obj)
return request.build_absolute_uri(path) if request else path
return ''
<|end_body_0|>
<|body_start_1|>
request = self.context.get('request')
if obj.mimetype.star... | Attachments serializer | AttachmentSerializer | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttachmentSerializer:
"""Attachments serializer"""
def get_download_url(self, obj):
"""Return attachment download url."""
<|body_0|>
def get_small_download_url(self, obj):
"""Return attachment download url for resized small image."""
<|body_1|>
def g... | stack_v2_sparse_classes_75kplus_train_071728 | 3,740 | permissive | [
{
"docstring": "Return attachment download url.",
"name": "get_download_url",
"signature": "def get_download_url(self, obj)"
},
{
"docstring": "Return attachment download url for resized small image.",
"name": "get_small_download_url",
"signature": "def get_small_download_url(self, obj)"... | 4 | stack_v2_sparse_classes_30k_train_005235 | Implement the Python class `AttachmentSerializer` described below.
Class description:
Attachments serializer
Method signatures and docstrings:
- def get_download_url(self, obj): Return attachment download url.
- def get_small_download_url(self, obj): Return attachment download url for resized small image.
- def get_m... | Implement the Python class `AttachmentSerializer` described below.
Class description:
Attachments serializer
Method signatures and docstrings:
- def get_download_url(self, obj): Return attachment download url.
- def get_small_download_url(self, obj): Return attachment download url for resized small image.
- def get_m... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class AttachmentSerializer:
"""Attachments serializer"""
def get_download_url(self, obj):
"""Return attachment download url."""
<|body_0|>
def get_small_download_url(self, obj):
"""Return attachment download url for resized small image."""
<|body_1|>
def g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttachmentSerializer:
"""Attachments serializer"""
def get_download_url(self, obj):
"""Return attachment download url."""
request = self.context.get('request')
if obj:
path = get_attachment_url(obj)
return request.build_absolute_uri(path) if request else pa... | the_stack_v2_python_sparse | onadata/libs/serializers/attachment_serializer.py | onaio/onadata | train | 177 |
ea9a9fa10e4b7a94a57fe2e8f0ea4cd47c546d8c | [
"follow = 0\nfor byte in data:\n if not byte & 128:\n if follow:\n return False\n elif byte & 192 == 128:\n if not follow:\n return False\n follow -= 1\n elif byte & 224 == 192:\n if follow:\n return False\n follow = 1\n elif byte & 240... | <|body_start_0|>
follow = 0
for byte in data:
if not byte & 128:
if follow:
return False
elif byte & 192 == 128:
if not follow:
return False
follow -= 1
elif byte & 224 == 192:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
<|body_0|>
def rewrite(self, data):
""":type data: List[int] :rtype: bool"""
<|body_1|>
def rewrite2(self, data):
""":type data: List[int] :rtype: bool"""
<|bod... | stack_v2_sparse_classes_75kplus_train_071729 | 6,087 | no_license | [
{
"docstring": ":type data: List[int] :rtype: bool",
"name": "validUtf8",
"signature": "def validUtf8(self, data)"
},
{
"docstring": ":type data: List[int] :rtype: bool",
"name": "rewrite",
"signature": "def rewrite(self, data)"
},
{
"docstring": ":type data: List[int] :rtype: bo... | 3 | stack_v2_sparse_classes_30k_train_020290 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validUtf8(self, data): :type data: List[int] :rtype: bool
- def rewrite(self, data): :type data: List[int] :rtype: bool
- def rewrite2(self, data): :type data: List[int] :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validUtf8(self, data): :type data: List[int] :rtype: bool
- def rewrite(self, data): :type data: List[int] :rtype: bool
- def rewrite2(self, data): :type data: List[int] :rty... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
<|body_0|>
def rewrite(self, data):
""":type data: List[int] :rtype: bool"""
<|body_1|>
def rewrite2(self, data):
""":type data: List[int] :rtype: bool"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
follow = 0
for byte in data:
if not byte & 128:
if follow:
return False
elif byte & 192 == 128:
if not follow:
r... | the_stack_v2_python_sparse | co_fb/393_UTF-8_Validation.py | vsdrun/lc_public | train | 6 | |
924200845cfe9b26f865ba88c256e354bb35d1bf | [
"with ops.Graph().as_default() as g:\n with self.session(graph=g):\n x = 2\n y = 5\n ops.add_to_collection('x', x)\n ops.add_to_collection('y', y)\n\n @polymorphic_function.function\n def fn():\n x_const = constant_op.constant(ops.get_collection('x')[0])\n ... | <|body_start_0|>
with ops.Graph().as_default() as g:
with self.session(graph=g):
x = 2
y = 5
ops.add_to_collection('x', x)
ops.add_to_collection('y', y)
@polymorphic_function.function
def fn():
... | FunctionCollectionTest | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionCollectionTest:
def testCollectionValueAccess(self):
"""Read values from graph collections inside of defun."""
<|body_0|>
def testCollectionVariableValueAccess(self):
"""Read variable value from graph collections inside of defun."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_071730 | 2,618 | permissive | [
{
"docstring": "Read values from graph collections inside of defun.",
"name": "testCollectionValueAccess",
"signature": "def testCollectionValueAccess(self)"
},
{
"docstring": "Read variable value from graph collections inside of defun.",
"name": "testCollectionVariableValueAccess",
"sig... | 2 | null | Implement the Python class `FunctionCollectionTest` described below.
Class description:
Implement the FunctionCollectionTest class.
Method signatures and docstrings:
- def testCollectionValueAccess(self): Read values from graph collections inside of defun.
- def testCollectionVariableValueAccess(self): Read variable ... | Implement the Python class `FunctionCollectionTest` described below.
Class description:
Implement the FunctionCollectionTest class.
Method signatures and docstrings:
- def testCollectionValueAccess(self): Read values from graph collections inside of defun.
- def testCollectionVariableValueAccess(self): Read variable ... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class FunctionCollectionTest:
def testCollectionValueAccess(self):
"""Read values from graph collections inside of defun."""
<|body_0|>
def testCollectionVariableValueAccess(self):
"""Read variable value from graph collections inside of defun."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionCollectionTest:
def testCollectionValueAccess(self):
"""Read values from graph collections inside of defun."""
with ops.Graph().as_default() as g:
with self.session(graph=g):
x = 2
y = 5
ops.add_to_collection('x', x)
... | the_stack_v2_python_sparse | tensorflow/python/eager/polymorphic_function/collection_test.py | tensorflow/tensorflow | train | 208,740 | |
74cd87827d18a9e0e2cb2f999a894ca92ee3fe42 | [
"self.num_vms_in_cluster = num_vms_in_cluster\nself.scaler_logic_called = False\nScale.__init__(self, sim=sim, scale_rate=scale_rate, startup_delay_func=startup_delay_func, shutdown_delay=shutdown_delay)",
"servers_to_stop = 0\nif self.scaler_logic_called is False:\n servers_to_start = self.num_vms_in_cluster\... | <|body_start_0|>
self.num_vms_in_cluster = num_vms_in_cluster
self.scaler_logic_called = False
Scale.__init__(self, sim=sim, scale_rate=scale_rate, startup_delay_func=startup_delay_func, shutdown_delay=shutdown_delay)
<|end_body_0|>
<|body_start_1|>
servers_to_stop = 0
if self.s... | Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request. | FixedSizePolicy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedSizePolicy:
"""Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_dela... | stack_v2_sparse_classes_75kplus_train_071731 | 1,645 | no_license | [
{
"docstring": "Initializes a FixedSizePolicy object parameters: sim -- The Simulation containing a cluster cluster object this scale function is managing scale_rate -- The interarrival time between scale events in seconds startup_delay_func -- A callable that returns the time a server spends in the booting sta... | 2 | stack_v2_sparse_classes_30k_train_043327 | Implement the Python class `FixedSizePolicy` described below.
Class description:
Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request.
Method signatures and docstrings:
- d... | Implement the Python class `FixedSizePolicy` described below.
Class description:
Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request.
Method signatures and docstrings:
- d... | 30dc0702f6189307ff776525a2f3006ec471de47 | <|skeleton|>
class FixedSizePolicy:
"""Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_dela... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FixedSizePolicy:
"""Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_delay, num_vms_in... | the_stack_v2_python_sparse | appsim/scaler/fixed_size_policy.py | bmbouter/vcl_simulation | train | 0 |
3fa660f36039d098d2c67ac30cbe66e7dd2c45b9 | [
"if sample <= 0 or sample > 1:\n raise Exception('sample {} should be > 0 and <= 1'.format(self.sample))\nself.ss = spark\nself.ac = ac\nself.sample = sample\nself.genotypeDataset = genotypeDataset\nself.variantsPerSampleDistribution = None\nself.hetHomRatioDistribution = None\nself.genotypeCallRatesDistribution... | <|body_start_0|>
if sample <= 0 or sample > 1:
raise Exception('sample {} should be > 0 and <= 1'.format(self.sample))
self.ss = spark
self.ac = ac
self.sample = sample
self.genotypeDataset = genotypeDataset
self.variantsPerSampleDistribution = None
se... | GenotypeSummary class. GenotypeSummary provides visualizations for genotype based summaries. | GenotypeSummary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenotypeSummary:
"""GenotypeSummary class. GenotypeSummary provides visualizations for genotype based summaries."""
def __init__(self, spark, ac, genotypeDataset, sample=1.0):
"""Initializes an GenotypeSummary class. Args: :param spark: SparkSession :param ac: genolake.adam.damContex... | stack_v2_sparse_classes_75kplus_train_071732 | 10,087 | permissive | [
{
"docstring": "Initializes an GenotypeSummary class. Args: :param spark: SparkSession :param ac: genolake.adam.damContext.ADAMContext :param genotypeDataset: genolake.adam.rdd.GenotypeDataset :param sample: fraction of reads to sample from",
"name": "__init__",
"signature": "def __init__(self, spark, a... | 5 | stack_v2_sparse_classes_30k_train_000739 | Implement the Python class `GenotypeSummary` described below.
Class description:
GenotypeSummary class. GenotypeSummary provides visualizations for genotype based summaries.
Method signatures and docstrings:
- def __init__(self, spark, ac, genotypeDataset, sample=1.0): Initializes an GenotypeSummary class. Args: :par... | Implement the Python class `GenotypeSummary` described below.
Class description:
GenotypeSummary class. GenotypeSummary provides visualizations for genotype based summaries.
Method signatures and docstrings:
- def __init__(self, spark, ac, genotypeDataset, sample=1.0): Initializes an GenotypeSummary class. Args: :par... | c9cab1848f7b2afc8055325f8076d2d60706ea23 | <|skeleton|>
class GenotypeSummary:
"""GenotypeSummary class. GenotypeSummary provides visualizations for genotype based summaries."""
def __init__(self, spark, ac, genotypeDataset, sample=1.0):
"""Initializes an GenotypeSummary class. Args: :param spark: SparkSession :param ac: genolake.adam.damContex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenotypeSummary:
"""GenotypeSummary class. GenotypeSummary provides visualizations for genotype based summaries."""
def __init__(self, spark, ac, genotypeDataset, sample=1.0):
"""Initializes an GenotypeSummary class. Args: :param spark: SparkSession :param ac: genolake.adam.damContext.ADAMContext... | the_stack_v2_python_sparse | tahoe-python/genolake/tahoe/genotypes.py | genolake/tahoe | train | 0 |
6c0fa090a6cfb14576aa2adc98c69dd5075836d5 | [
"res = deque()\nfor i in range(len(nums)):\n if nums[i] % 2 == 0:\n res.append(nums[i])\n else:\n res.appendleft(nums[i])\nreturn list(res)",
"i, j = (0, len(nums) - 1)\nwhile i < j:\n while i < j and nums[i] & 1 == 1:\n i += 1\n while i < j and nums[j] & 1 == 0:\n j -= 1\n... | <|body_start_0|>
res = deque()
for i in range(len(nums)):
if nums[i] % 2 == 0:
res.append(nums[i])
else:
res.appendleft(nums[i])
return list(res)
<|end_body_0|>
<|body_start_1|>
i, j = (0, len(nums) - 1)
while i < j:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def exchange_1(self, nums: List[int]) -> List[int]:
"""双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:"""
<|body_0|>
def exchange_2(self, nums: List[int]) -> List[int]:
"""双指针 时间复杂度 O(N) 空间复杂度 O(1) :param nums: :return:"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_071733 | 1,516 | no_license | [
{
"docstring": "双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:",
"name": "exchange_1",
"signature": "def exchange_1(self, nums: List[int]) -> List[int]"
},
{
"docstring": "双指针 时间复杂度 O(N) 空间复杂度 O(1) :param nums: :return:",
"name": "exchange_2",
"signature": "def exchange_2(self, nums: L... | 2 | stack_v2_sparse_classes_30k_train_033425 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exchange_1(self, nums: List[int]) -> List[int]: 双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:
- def exchange_2(self, nums: List[int]) -> List[int]: 双指针 时间复杂度 O(N) 空间复杂度 O(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exchange_1(self, nums: List[int]) -> List[int]: 双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:
- def exchange_2(self, nums: List[int]) -> List[int]: 双指针 时间复杂度 O(N) 空间复杂度 O(... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def exchange_1(self, nums: List[int]) -> List[int]:
"""双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:"""
<|body_0|>
def exchange_2(self, nums: List[int]) -> List[int]:
"""双指针 时间复杂度 O(N) 空间复杂度 O(1) :param nums: :return:"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def exchange_1(self, nums: List[int]) -> List[int]:
"""双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:"""
res = deque()
for i in range(len(nums)):
if nums[i] % 2 == 0:
res.append(nums[i])
else:
res.appendleft(nums[i])
... | the_stack_v2_python_sparse | 剑指 Offer(第 2 版)/exchange.py | MaoningGuan/LeetCode | train | 3 | |
484ed9a1fa36f8a8e1a19fe3ff7cf81e7175913e | [
"usage_string = '{} [-h] <stones> <dag> [--sparse <degree>]'\nparser.usage = usage_string.format(parser.prog)\nparser.add_argument('s', metavar='<stones>', type=positive_int, help='number of stones')\nparser.add_argument('D', metavar='<dag>', action=ObtainDirectedAcyclicGraph, help=\"a directed acyclic graph (see '... | <|body_start_0|>
usage_string = '{} [-h] <stones> <dag> [--sparse <degree>]'
parser.usage = usage_string.format(parser.prog)
parser.add_argument('s', metavar='<stones>', type=positive_int, help='number of stones')
parser.add_argument('D', metavar='<dag>', action=ObtainDirectedAcyclicGrap... | Command line helper for stone formulas | StoneCmdHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoneCmdHelper:
"""Command line helper for stone formulas"""
def setup_command_line(parser):
"""Setup the command line options for stone formulas Arguments: - `parser`: parser to load with options."""
<|body_0|>
def build_cnf(args):
"""Build the stone formula Arg... | stack_v2_sparse_classes_75kplus_train_071734 | 3,894 | no_license | [
{
"docstring": "Setup the command line options for stone formulas Arguments: - `parser`: parser to load with options.",
"name": "setup_command_line",
"signature": "def setup_command_line(parser)"
},
{
"docstring": "Build the stone formula Arguments: - `args`: command line options",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_021093 | Implement the Python class `StoneCmdHelper` described below.
Class description:
Command line helper for stone formulas
Method signatures and docstrings:
- def setup_command_line(parser): Setup the command line options for stone formulas Arguments: - `parser`: parser to load with options.
- def build_cnf(args): Build ... | Implement the Python class `StoneCmdHelper` described below.
Class description:
Command line helper for stone formulas
Method signatures and docstrings:
- def setup_command_line(parser): Setup the command line options for stone formulas Arguments: - `parser`: parser to load with options.
- def build_cnf(args): Build ... | f4dbc89eddaaf7fac1730685bc97d646cec06a1e | <|skeleton|>
class StoneCmdHelper:
"""Command line helper for stone formulas"""
def setup_command_line(parser):
"""Setup the command line options for stone formulas Arguments: - `parser`: parser to load with options."""
<|body_0|>
def build_cnf(args):
"""Build the stone formula Arg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StoneCmdHelper:
"""Command line helper for stone formulas"""
def setup_command_line(parser):
"""Setup the command line options for stone formulas Arguments: - `parser`: parser to load with options."""
usage_string = '{} [-h] <stones> <dag> [--sparse <degree>]'
parser.usage = usage... | the_stack_v2_python_sparse | Experiments/venv/lib/python3.7/site-packages/cnfgen/clihelpers/pebbling_helpers.py | souravskr/MS-Project | train | 0 |
da86f1464f8ebb39e2d076e0259ec3a609b5c09d | [
"self.site = page._link.site\nself.title = page._link.title\nself.loc_title = page._link.canonical_title()\nself.can_title = page._link.ns_title()\nself.outputlang = outputlang\nif outputlang is not None:\n if not hasattr(self, 'onsite'):\n self.onsite = pywikibot.Site(outputlang, self.site.family)\n t... | <|body_start_0|>
self.site = page._link.site
self.title = page._link.title
self.loc_title = page._link.canonical_title()
self.can_title = page._link.ns_title()
self.outputlang = outputlang
if outputlang is not None:
if not hasattr(self, 'onsite'):
... | Structure with Page attributes exposed for formatting from cmd line. | Formatter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Formatter:
"""Structure with Page attributes exposed for formatting from cmd line."""
def __init__(self, page, outputlang=None, default: str='******') -> None:
"""Initializer. :param page: the page to be formatted. :type page: Page object. :param outputlang: language code in which na... | stack_v2_sparse_classes_75kplus_train_071735 | 11,735 | permissive | [
{
"docstring": "Initializer. :param page: the page to be formatted. :type page: Page object. :param outputlang: language code in which namespace before title should be translated. Page ns will be searched in Site(outputlang, page.site.family) and, if found, its custom name will be used in page.title(). :type ou... | 2 | stack_v2_sparse_classes_30k_train_017048 | Implement the Python class `Formatter` described below.
Class description:
Structure with Page attributes exposed for formatting from cmd line.
Method signatures and docstrings:
- def __init__(self, page, outputlang=None, default: str='******') -> None: Initializer. :param page: the page to be formatted. :type page: ... | Implement the Python class `Formatter` described below.
Class description:
Structure with Page attributes exposed for formatting from cmd line.
Method signatures and docstrings:
- def __init__(self, page, outputlang=None, default: str='******') -> None: Initializer. :param page: the page to be formatted. :type page: ... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class Formatter:
"""Structure with Page attributes exposed for formatting from cmd line."""
def __init__(self, page, outputlang=None, default: str='******') -> None:
"""Initializer. :param page: the page to be formatted. :type page: Page object. :param outputlang: language code in which na... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Formatter:
"""Structure with Page attributes exposed for formatting from cmd line."""
def __init__(self, page, outputlang=None, default: str='******') -> None:
"""Initializer. :param page: the page to be formatted. :type page: Page object. :param outputlang: language code in which namespace befor... | the_stack_v2_python_sparse | scripts/listpages.py | wikimedia/pywikibot | train | 432 |
f25dcf55d91db37f3b40586cc8088d7854967933 | [
"assert isinstance(block_string, str)\nops = block_string.split('_')\noptions = {}\nfor op in ops:\n splits = re.split('(\\\\d.*)', op)\n if len(splits) >= 2:\n key, value = splits[:2]\n options[key] = value\nif 's' not in options or len(options['s']) != 2:\n raise ValueError('Strides options... | <|body_start_0|>
assert isinstance(block_string, str)
ops = block_string.split('_')
options = {}
for op in ops:
splits = re.split('(\\d.*)', op)
if len(splits) >= 2:
key, value = splits[:2]
options[key] = value
if 's' not in... | Block Decoder for readability | BlockDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockDecoder:
"""Block Decoder for readability"""
def _decode_block_string(block_string):
"""Gets a block through a string notation of arguments."""
<|body_0|>
def _encode_block_string(block):
"""Encodes a block to a string."""
<|body_1|>
def decode(... | stack_v2_sparse_classes_75kplus_train_071736 | 15,770 | no_license | [
{
"docstring": "Gets a block through a string notation of arguments.",
"name": "_decode_block_string",
"signature": "def _decode_block_string(block_string)"
},
{
"docstring": "Encodes a block to a string.",
"name": "_encode_block_string",
"signature": "def _encode_block_string(block)"
... | 4 | stack_v2_sparse_classes_30k_train_034634 | Implement the Python class `BlockDecoder` described below.
Class description:
Block Decoder for readability
Method signatures and docstrings:
- def _decode_block_string(block_string): Gets a block through a string notation of arguments.
- def _encode_block_string(block): Encodes a block to a string.
- def decode(self... | Implement the Python class `BlockDecoder` described below.
Class description:
Block Decoder for readability
Method signatures and docstrings:
- def _decode_block_string(block_string): Gets a block through a string notation of arguments.
- def _encode_block_string(block): Encodes a block to a string.
- def decode(self... | a81ab54a79466568700d98900faac28e753c0591 | <|skeleton|>
class BlockDecoder:
"""Block Decoder for readability"""
def _decode_block_string(block_string):
"""Gets a block through a string notation of arguments."""
<|body_0|>
def _encode_block_string(block):
"""Encodes a block to a string."""
<|body_1|>
def decode(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlockDecoder:
"""Block Decoder for readability"""
def _decode_block_string(block_string):
"""Gets a block through a string notation of arguments."""
assert isinstance(block_string, str)
ops = block_string.split('_')
options = {}
for op in ops:
splits = ... | the_stack_v2_python_sparse | image_seg_aliTianchi2021/model/modules/backbones/efficientnet.py | HAOYUANJIE123/ali_Tianchi_2021 | train | 1 |
da8ccc9e706518b82ad59d7d6a2af0e0e84ef5ff | [
"record = cls.get_or_none(cls.user_id == user_id, cls.group_id == group_id)\nif record is not None:\n return record.UserLevel\nelse:\n return None",
"record, _ = cls.get_or_create(user_id=user_id, group_id=group_id)\nrecord.UserLevel = level\nrecord.save()",
"record = cls.get_or_none(cls.user_id == user_i... | <|body_start_0|>
record = cls.get_or_none(cls.user_id == user_id, cls.group_id == group_id)
if record is not None:
return record.UserLevel
else:
return None
<|end_body_0|>
<|body_start_1|>
record, _ = cls.get_or_create(user_id=user_id, group_id=group_id)
... | UserLevel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserLevel:
async def get_uer_level(cls, user_id: int, group_id: int) -> int:
""":说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:"""
<|body_0|>
async def set_level(cls, user_id: int, group_id: int, level: int) -> None:
""":说明 设置权限,如果没有则... | stack_v2_sparse_classes_75kplus_train_071737 | 1,914 | permissive | [
{
"docstring": ":说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:",
"name": "get_uer_level",
"signature": "async def get_uer_level(cls, user_id: int, group_id: int) -> int"
},
{
"docstring": ":说明 设置权限,如果没有则创建记录 :参数 * user_id:用户QQ * group_id:QQ群号 * level:权限等级",
... | 3 | stack_v2_sparse_classes_30k_train_036583 | Implement the Python class `UserLevel` described below.
Class description:
Implement the UserLevel class.
Method signatures and docstrings:
- async def get_uer_level(cls, user_id: int, group_id: int) -> int: :说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:
- async def set_level(cls, us... | Implement the Python class `UserLevel` described below.
Class description:
Implement the UserLevel class.
Method signatures and docstrings:
- async def get_uer_level(cls, user_id: int, group_id: int) -> int: :说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:
- async def set_level(cls, us... | 8bb989aceb1a89569f2fcb804c73f7b650feb1f0 | <|skeleton|>
class UserLevel:
async def get_uer_level(cls, user_id: int, group_id: int) -> int:
""":说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:"""
<|body_0|>
async def set_level(cls, user_id: int, group_id: int, level: int) -> None:
""":说明 设置权限,如果没有则... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserLevel:
async def get_uer_level(cls, user_id: int, group_id: int) -> int:
""":说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:"""
record = cls.get_or_none(cls.user_id == user_id, cls.group_id == group_id)
if record is not None:
return recor... | the_stack_v2_python_sparse | modules/user_level.py | JustUndertaker/tuanzi_bot | train | 8 | |
018536ac164a3681c305732e9502e72f48efda42 | [
"stack = [root]\ntree = []\nwhile stack:\n node = stack.pop()\n if node:\n stack.append(node.right)\n stack.append(node.left)\n tree.append(str(node.val))\n else:\n tree.append(str(node))\nreturn ','.join(tree)",
"def decode(data):\n if not data:\n return None\n v... | <|body_start_0|>
stack = [root]
tree = []
while stack:
node = stack.pop()
if node:
stack.append(node.right)
stack.append(node.left)
tree.append(str(node.val))
else:
tree.append(str(node))
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_071738 | 1,255 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_val_001401 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | fb53fea229ac5a4d5ebce23216afaf7dc7214014 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
stack = [root]
tree = []
while stack:
node = stack.pop()
if node:
stack.append(node.right)
stack.append(node.left)... | the_stack_v2_python_sparse | Design_DataStructure/297_CodecBinaryTree.py | pondjames007/CodingPractice | train | 0 | |
b29caa455d03142877ec7278b79aa4b91265889f | [
"target_real_sample = torch.ones_like(output_real_sample)\ntarget_fake_sample = torch.zeros_like(output_fake_sample)\noutput = torch.cat([output_real_sample, output_fake_sample])\ntarget = torch.cat([target_real_sample, target_fake_sample])\nfooling_rate = metrics.accuracy(output_fake_sample, target_real_sample)\np... | <|body_start_0|>
target_real_sample = torch.ones_like(output_real_sample)
target_fake_sample = torch.zeros_like(output_fake_sample)
output = torch.cat([output_real_sample, output_fake_sample])
target = torch.cat([target_real_sample, target_fake_sample])
fooling_rate = metrics.acc... | General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this experiment split (list[float]): dataset split ratios in [0, 1] as [train, val] or [train, val,... | ImageTranslationExperiment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageTranslationExperiment:
"""General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this experiment split (list[float]): dataset ... | stack_v2_sparse_classes_75kplus_train_071739 | 12,405 | no_license | [
{
"docstring": "Computes metrics on discriminator classification power : fooling rate of generator, precision and recall Args: output_real_sample (torch.Tensor): discriminator prediction on real samples output_fake_sample (torch.Tensor): discriminator prediction on fake samples Returns: type: tuple[float]",
... | 2 | stack_v2_sparse_classes_30k_train_005326 | Implement the Python class `ImageTranslationExperiment` described below.
Class description:
General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this e... | Implement the Python class `ImageTranslationExperiment` described below.
Class description:
General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this e... | 08f8c3351ec4f2f666e05b75b1130b78005489d1 | <|skeleton|>
class ImageTranslationExperiment:
"""General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this experiment split (list[float]): dataset ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageTranslationExperiment:
"""General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this experiment split (list[float]): dataset split ratios ... | the_stack_v2_python_sparse | src/experiments/experiment.py | shahineb/ci-hackathon | train | 3 |
022e2b54fe769d082b7e89af8aa2bee3777a766a | [
"self.k = k\nself.nums = nums\nheapq.heapify(self.nums)\nwhile len(self.nums) > k:\n heapq.heappop(self.nums)",
"if len(self.nums) < self.k:\n heapq.heappush(self.nums, val)\nelif val > self.nums[0]:\n heapq.heapreplace(self.nums, val)\nreturn self.nums[0]"
] | <|body_start_0|>
self.k = k
self.nums = nums
heapq.heapify(self.nums)
while len(self.nums) > k:
heapq.heappop(self.nums)
<|end_body_0|>
<|body_start_1|>
if len(self.nums) < self.k:
heapq.heappush(self.nums, val)
elif val > self.nums[0]:
... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
"""初始化堆的过程,让堆的数量正好为K个 :type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.nums = nums
... | stack_v2_sparse_classes_75kplus_train_071740 | 3,113 | no_license | [
{
"docstring": "初始化堆的过程,让堆的数量正好为K个 :type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049440 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): 初始化堆的过程,让堆的数量正好为K个 :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): 初始化堆的过程,让堆的数量正好为K个 :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def _... | aa285d16bc96d30a632fae5c7578d0e7a5f51e7c | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
"""初始化堆的过程,让堆的数量正好为K个 :type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
"""初始化堆的过程,让堆的数量正好为K个 :type k: int :type nums: List[int]"""
self.k = k
self.nums = nums
heapq.heapify(self.nums)
while len(self.nums) > k:
heapq.heappop(self.nums)
def add(self, val):
""":type val: int :r... | the_stack_v2_python_sparse | package_701_800/package_701_720/703. Kth Largest Element in a Stream .py | morindaz/leecode_morindaz | train | 4 | |
dd6f483fd76f86b38f7d291007a9835738b9d4d4 | [
"self._out_pth = out_pth\nself._update_rpt = update_rpt\nself._func = func\nself._is_quiet = is_quiet\nself.parameter_names = list(param_dct.keys())\nself.parameter_values = list(param_dct.values())\nself.df_result, self._completeds = self._makeRestoreDF()\nself._update_cnt = 0",
"if os.path.isfile(self._out_pth)... | <|body_start_0|>
self._out_pth = out_pth
self._update_rpt = update_rpt
self._func = func
self._is_quiet = is_quiet
self.parameter_names = list(param_dct.keys())
self.parameter_values = list(param_dct.values())
self.df_result, self._completeds = self._makeRestoreDF... | ExperimentHarness | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExperimentHarness:
def __init__(self, param_dct, func, out_pth=OUT_PTH, update_rpt=5, is_quiet=False):
""":param dict param_dct: dictionary of parameter values :param Function func: function that takes keyword arguments of parameter values :param str out_pth: CSV file where intermediate ... | stack_v2_sparse_classes_75kplus_train_071741 | 3,835 | permissive | [
{
"docstring": ":param dict param_dct: dictionary of parameter values :param Function func: function that takes keyword arguments of parameter values :param str out_pth: CSV file where intermediate results are stored :param int update_rpt: number of times the function is run before results are written. :parm bo... | 4 | stack_v2_sparse_classes_30k_train_015643 | Implement the Python class `ExperimentHarness` described below.
Class description:
Implement the ExperimentHarness class.
Method signatures and docstrings:
- def __init__(self, param_dct, func, out_pth=OUT_PTH, update_rpt=5, is_quiet=False): :param dict param_dct: dictionary of parameter values :param Function func: ... | Implement the Python class `ExperimentHarness` described below.
Class description:
Implement the ExperimentHarness class.
Method signatures and docstrings:
- def __init__(self, param_dct, func, out_pth=OUT_PTH, update_rpt=5, is_quiet=False): :param dict param_dct: dictionary of parameter values :param Function func: ... | a57542245f117fe6c835cc9d7ad570b9853b7e6c | <|skeleton|>
class ExperimentHarness:
def __init__(self, param_dct, func, out_pth=OUT_PTH, update_rpt=5, is_quiet=False):
""":param dict param_dct: dictionary of parameter values :param Function func: function that takes keyword arguments of parameter values :param str out_pth: CSV file where intermediate ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExperimentHarness:
def __init__(self, param_dct, func, out_pth=OUT_PTH, update_rpt=5, is_quiet=False):
""":param dict param_dct: dictionary of parameter values :param Function func: function that takes keyword arguments of parameter values :param str out_pth: CSV file where intermediate results are st... | the_stack_v2_python_sparse | common_python/experiment/experiment_harness.py | ScienceStacks/common_python | train | 1 | |
3e4c626133b8560c62a8c08a517a6714e852a201 | [
"if protocol not in RULE_MAPPER:\n raise InvalidSecurityGroupRule('invalid protocol[%s]' % protocol)\nif not isinstance(priority, int) or priority < 0 or priority > 100:\n raise InvalidSecurityGroupRule('invalid priority[%s]' % priority)\nclazz = RULE_MAPPER[protocol]\ninst = clazz(**kw)\ninst.priority = prio... | <|body_start_0|>
if protocol not in RULE_MAPPER:
raise InvalidSecurityGroupRule('invalid protocol[%s]' % protocol)
if not isinstance(priority, int) or priority < 0 or priority > 100:
raise InvalidSecurityGroupRule('invalid priority[%s]' % priority)
clazz = RULE_MAPPER[pro... | Factory for security group rule Example: conn = qingcloud.iaas.connect_to_zone(....) security_group_id = 'sg-xxxxx' # Add security group rule ping_rule = SecurityGroupRuleFactory.create( protocol = SecurityGroupRuleFactory.PROTOCOL_ICMP, priority = 1, direction = SecurityGroupRuleFactory.INBOUND, action = 'accept', sec... | SecurityGroupRuleFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecurityGroupRuleFactory:
"""Factory for security group rule Example: conn = qingcloud.iaas.connect_to_zone(....) security_group_id = 'sg-xxxxx' # Add security group rule ping_rule = SecurityGroupRuleFactory.create( protocol = SecurityGroupRuleFactory.PROTOCOL_ICMP, priority = 1, direction = Secu... | stack_v2_sparse_classes_75kplus_train_071742 | 6,881 | permissive | [
{
"docstring": "Create security group rule. @param protocol: support protocol. @param priority: should be between 0 and 100.",
"name": "create",
"signature": "def create(cls, protocol, priority, direction=INBOUND, action='accept', security_group_rule_id='', security_group_rule_name='', **kw)"
},
{
... | 2 | null | Implement the Python class `SecurityGroupRuleFactory` described below.
Class description:
Factory for security group rule Example: conn = qingcloud.iaas.connect_to_zone(....) security_group_id = 'sg-xxxxx' # Add security group rule ping_rule = SecurityGroupRuleFactory.create( protocol = SecurityGroupRuleFactory.PROTOC... | Implement the Python class `SecurityGroupRuleFactory` described below.
Class description:
Factory for security group rule Example: conn = qingcloud.iaas.connect_to_zone(....) security_group_id = 'sg-xxxxx' # Add security group rule ping_rule = SecurityGroupRuleFactory.create( protocol = SecurityGroupRuleFactory.PROTOC... | 70992bf676983a0b1a5e9c80b453dec4ea0c2370 | <|skeleton|>
class SecurityGroupRuleFactory:
"""Factory for security group rule Example: conn = qingcloud.iaas.connect_to_zone(....) security_group_id = 'sg-xxxxx' # Add security group rule ping_rule = SecurityGroupRuleFactory.create( protocol = SecurityGroupRuleFactory.PROTOCOL_ICMP, priority = 1, direction = Secu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SecurityGroupRuleFactory:
"""Factory for security group rule Example: conn = qingcloud.iaas.connect_to_zone(....) security_group_id = 'sg-xxxxx' # Add security group rule ping_rule = SecurityGroupRuleFactory.create( protocol = SecurityGroupRuleFactory.PROTOCOL_ICMP, priority = 1, direction = SecurityGroupRule... | the_stack_v2_python_sparse | qingcloud/iaas/sg_rule.py | yunify/qingcloud-sdk-python | train | 56 |
f8ce0635166130eb8193a27fa562c2c885aa0f8e | [
"res = 0\nfor num in nums:\n res ^= num\nreturn res",
"hash_map = defaultdict(int)\nfor num in nums:\n hash_map[num] += 1\nfor num in hash_map:\n if hash_map[num] == 1:\n return num"
] | <|body_start_0|>
res = 0
for num in nums:
res ^= num
return res
<|end_body_0|>
<|body_start_1|>
hash_map = defaultdict(int)
for num in nums:
hash_map[num] += 1
for num in hash_map:
if hash_map[num] == 1:
return num
<|en... | SingleNumber | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleNumber:
def get(self, nums: List[int]) -> int:
"""Approach: Bit Manipulation Formulae: a xor b a xor a = 0 a xor 0 = a b xor 0 = b a xor 0 xor b Time Complexity: O(N) Space Complexity: O(1) :param nums: :return:"""
<|body_0|>
def get_(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_75kplus_train_071743 | 1,029 | no_license | [
{
"docstring": "Approach: Bit Manipulation Formulae: a xor b a xor a = 0 a xor 0 = a b xor 0 = b a xor 0 xor b Time Complexity: O(N) Space Complexity: O(1) :param nums: :return:",
"name": "get",
"signature": "def get(self, nums: List[int]) -> int"
},
{
"docstring": "Approach: Hash Map Time Compl... | 2 | stack_v2_sparse_classes_30k_train_022779 | Implement the Python class `SingleNumber` described below.
Class description:
Implement the SingleNumber class.
Method signatures and docstrings:
- def get(self, nums: List[int]) -> int: Approach: Bit Manipulation Formulae: a xor b a xor a = 0 a xor 0 = a b xor 0 = b a xor 0 xor b Time Complexity: O(N) Space Complexi... | Implement the Python class `SingleNumber` described below.
Class description:
Implement the SingleNumber class.
Method signatures and docstrings:
- def get(self, nums: List[int]) -> int: Approach: Bit Manipulation Formulae: a xor b a xor a = 0 a xor 0 = a b xor 0 = b a xor 0 xor b Time Complexity: O(N) Space Complexi... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class SingleNumber:
def get(self, nums: List[int]) -> int:
"""Approach: Bit Manipulation Formulae: a xor b a xor a = 0 a xor 0 = a b xor 0 = b a xor 0 xor b Time Complexity: O(N) Space Complexity: O(1) :param nums: :return:"""
<|body_0|>
def get_(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleNumber:
def get(self, nums: List[int]) -> int:
"""Approach: Bit Manipulation Formulae: a xor b a xor a = 0 a xor 0 = a b xor 0 = b a xor 0 xor b Time Complexity: O(N) Space Complexity: O(1) :param nums: :return:"""
res = 0
for num in nums:
res ^= num
return re... | the_stack_v2_python_sparse | revisited/math_and_strings/bitwise_operator/single_number_i.py | Shiv2157k/leet_code | train | 1 | |
58f4ac9eceef0801b376bd4b2e3daa7a17069aa7 | [
"self.reuse = False\nself.batch_size = batch_size\nself.layer_sizes = layer_sizes",
"with tf.name_scope('bid-lstm' + name), tf.variable_scope('bid-lstm', reuse=self.reuse):\n fw_lstm_cells = [rnn.LSTMCell(num_units=self.layer_sizes[i], activation=tf.nn.tanh) for i in range(len(self.layer_sizes))]\n bw_lstm_... | <|body_start_0|>
self.reuse = False
self.batch_size = batch_size
self.layer_sizes = layer_sizes
<|end_body_0|>
<|body_start_1|>
with tf.name_scope('bid-lstm' + name), tf.variable_scope('bid-lstm', reuse=self.reuse):
fw_lstm_cells = [rnn.LSTMCell(num_units=self.layer_sizes[i]... | BidirectionalLSTM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalLSTM:
def __init__(self, layer_sizes, batch_size):
"""Initializes a multi layer bidirectional LSTM :param layer_sizes: A list containing the neuron numbers per layer e.g. [100, 100, 100] returns a 3 layer, 100 neuron bid-LSTM :param batch_size: The experiments batch size"""
... | stack_v2_sparse_classes_75kplus_train_071744 | 35,259 | no_license | [
{
"docstring": "Initializes a multi layer bidirectional LSTM :param layer_sizes: A list containing the neuron numbers per layer e.g. [100, 100, 100] returns a 3 layer, 100 neuron bid-LSTM :param batch_size: The experiments batch size",
"name": "__init__",
"signature": "def __init__(self, layer_sizes, ba... | 2 | stack_v2_sparse_classes_30k_train_024507 | Implement the Python class `BidirectionalLSTM` described below.
Class description:
Implement the BidirectionalLSTM class.
Method signatures and docstrings:
- def __init__(self, layer_sizes, batch_size): Initializes a multi layer bidirectional LSTM :param layer_sizes: A list containing the neuron numbers per layer e.g... | Implement the Python class `BidirectionalLSTM` described below.
Class description:
Implement the BidirectionalLSTM class.
Method signatures and docstrings:
- def __init__(self, layer_sizes, batch_size): Initializes a multi layer bidirectional LSTM :param layer_sizes: A list containing the neuron numbers per layer e.g... | 6a8be5b79e0861067afd4e053cc534589d1311fb | <|skeleton|>
class BidirectionalLSTM:
def __init__(self, layer_sizes, batch_size):
"""Initializes a multi layer bidirectional LSTM :param layer_sizes: A list containing the neuron numbers per layer e.g. [100, 100, 100] returns a 3 layer, 100 neuron bid-LSTM :param batch_size: The experiments batch size"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BidirectionalLSTM:
def __init__(self, layer_sizes, batch_size):
"""Initializes a multi layer bidirectional LSTM :param layer_sizes: A list containing the neuron numbers per layer e.g. [100, 100, 100] returns a 3 layer, 100 neuron bid-LSTM :param batch_size: The experiments batch size"""
self.r... | the_stack_v2_python_sparse | model.py | Alice1820/RN_origin | train | 0 | |
74e18c46b02e2e1121b4867ea3509ee260bdade2 | [
"logger.info(u'开始执行测试用例:用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置')\nlogger.info(u'开始登录操作...')\nself.assertTrue(self.user_login_success())\nlogger.info(' 正在获得用例期望值...')\nexpected_value = get_expected_value('008')\nlogger.info('正在获得截图标题...')\ntitle = get_image_title('008')\nlogger.info('生成截图中...')\ninsert_img(self.driv... | <|body_start_0|>
logger.info(u'开始执行测试用例:用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置')
logger.info(u'开始登录操作...')
self.assertTrue(self.user_login_success())
logger.info(' 正在获得用例期望值...')
expected_value = get_expected_value('008')
logger.info('正在获得截图标题...')
title = get_ima... | mp 登录首页页面元素数据检查 | MainPageCheckTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainPageCheckTest:
"""mp 登录首页页面元素数据检查"""
def test_008_loc(self):
"""用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置"""
<|body_0|>
def test_009_service_name(self):
"""用例编号009:mp登录-用户名密码正确,且绑定了公众号,登录后检查公众号名称"""
<|body_1|>
def test_010_service_id(self):
... | stack_v2_sparse_classes_75kplus_train_071745 | 3,860 | no_license | [
{
"docstring": "用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置",
"name": "test_008_loc",
"signature": "def test_008_loc(self)"
},
{
"docstring": "用例编号009:mp登录-用户名密码正确,且绑定了公众号,登录后检查公众号名称",
"name": "test_009_service_name",
"signature": "def test_009_service_name(self)"
},
{
"docstring": "用... | 4 | stack_v2_sparse_classes_30k_train_009760 | Implement the Python class `MainPageCheckTest` described below.
Class description:
mp 登录首页页面元素数据检查
Method signatures and docstrings:
- def test_008_loc(self): 用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置
- def test_009_service_name(self): 用例编号009:mp登录-用户名密码正确,且绑定了公众号,登录后检查公众号名称
- def test_010_service_id(self): 用例编号010:mp登录... | Implement the Python class `MainPageCheckTest` described below.
Class description:
mp 登录首页页面元素数据检查
Method signatures and docstrings:
- def test_008_loc(self): 用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置
- def test_009_service_name(self): 用例编号009:mp登录-用户名密码正确,且绑定了公众号,登录后检查公众号名称
- def test_010_service_id(self): 用例编号010:mp登录... | 5db7dc1a10100721180f0cc66e4c96479ec69501 | <|skeleton|>
class MainPageCheckTest:
"""mp 登录首页页面元素数据检查"""
def test_008_loc(self):
"""用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置"""
<|body_0|>
def test_009_service_name(self):
"""用例编号009:mp登录-用户名密码正确,且绑定了公众号,登录后检查公众号名称"""
<|body_1|>
def test_010_service_id(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MainPageCheckTest:
"""mp 登录首页页面元素数据检查"""
def test_008_loc(self):
"""用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置"""
logger.info(u'开始执行测试用例:用例编号008:mp登录-用户名密码正确,且绑定了公众号,登录后检查首页位置')
logger.info(u'开始登录操作...')
self.assertTrue(self.user_login_success())
logger.info(' 正在获得用例期望... | the_stack_v2_python_sparse | mp/test_model/test_case/main_page_check_test.py | eatingM/kk_mp | train | 0 |
39c81aa88e781083993a89989929a4dfe630d226 | [
"if params is None:\n params = {}\napi_version = getattr(cls, '_api_version', None)\nif id is None:\n path = '{resource_name}/{action_name}'.format(resource_name=cls._resource_name, action_name=action_name)\nelse:\n path = '{resource_name}/{resource_id}/{action_name}'.format(resource_name=cls._resource_nam... | <|body_start_0|>
if params is None:
params = {}
api_version = getattr(cls, '_api_version', None)
if id is None:
path = '{resource_name}/{action_name}'.format(resource_name=cls._resource_name, action_name=action_name)
else:
path = '{resource_name}/{reso... | Actionable API Resource | ActionAPIResource | [
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionAPIResource:
"""Actionable API Resource"""
def _trigger_class_action(cls, method, action_name, id=None, params=None, **body):
"""Trigger an action :param method: HTTP method to use to contact API endpoint :type method: HTTP method string :param action_name: action name :type ac... | stack_v2_sparse_classes_75kplus_train_071746 | 16,128 | permissive | [
{
"docstring": "Trigger an action :param method: HTTP method to use to contact API endpoint :type method: HTTP method string :param action_name: action name :type action_name: string :param id: trigger the action for the specified resource object :type id: id :param params: action parameters :type params: dicti... | 2 | stack_v2_sparse_classes_30k_train_023255 | Implement the Python class `ActionAPIResource` described below.
Class description:
Actionable API Resource
Method signatures and docstrings:
- def _trigger_class_action(cls, method, action_name, id=None, params=None, **body): Trigger an action :param method: HTTP method to use to contact API endpoint :type method: HT... | Implement the Python class `ActionAPIResource` described below.
Class description:
Actionable API Resource
Method signatures and docstrings:
- def _trigger_class_action(cls, method, action_name, id=None, params=None, **body): Trigger an action :param method: HTTP method to use to contact API endpoint :type method: HT... | 11a38d0c8d6b156758e7500500d706b7159d18ed | <|skeleton|>
class ActionAPIResource:
"""Actionable API Resource"""
def _trigger_class_action(cls, method, action_name, id=None, params=None, **body):
"""Trigger an action :param method: HTTP method to use to contact API endpoint :type method: HTTP method string :param action_name: action name :type ac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActionAPIResource:
"""Actionable API Resource"""
def _trigger_class_action(cls, method, action_name, id=None, params=None, **body):
"""Trigger an action :param method: HTTP method to use to contact API endpoint :type method: HTTP method string :param action_name: action name :type action_name: st... | the_stack_v2_python_sparse | datadog/api/resources.py | DataDog/datadogpy | train | 602 |
42e91eefdf8259dff980748fbd4ee4c6839dd70d | [
"self.debug = debug\nself.rules_registry = rules_registry\nif self.debug:\n print('ProfileLoader - init' + lineno())",
"if self.debug:\n print('load' + lineno())\n print('vars: ' + str(vars(profile_definition)) + lineno())\nif not profile_definition:\n raise ParserError('Empty profile')\nnew_profile =... | <|body_start_0|>
self.debug = debug
self.rules_registry = rules_registry
if self.debug:
print('ProfileLoader - init' + lineno())
<|end_body_0|>
<|body_start_1|>
if self.debug:
print('load' + lineno())
print('vars: ' + str(vars(profile_definition)) + l... | Profile loader | ProfileLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileLoader:
"""Profile loader"""
def __init__(self, rules_registry, debug=False):
"""Initialize the ProfileLoader :param rules_registry: :param debug:"""
<|body_0|>
def load(self, profile_definition):
"""Load rules from a profile definition :param profile_defi... | stack_v2_sparse_classes_75kplus_train_071747 | 3,196 | permissive | [
{
"docstring": "Initialize the ProfileLoader :param rules_registry: :param debug:",
"name": "__init__",
"signature": "def __init__(self, rules_registry, debug=False)"
},
{
"docstring": "Load rules from a profile definition :param profile_definition: :return:",
"name": "load",
"signature"... | 5 | stack_v2_sparse_classes_30k_test_001021 | Implement the Python class `ProfileLoader` described below.
Class description:
Profile loader
Method signatures and docstrings:
- def __init__(self, rules_registry, debug=False): Initialize the ProfileLoader :param rules_registry: :param debug:
- def load(self, profile_definition): Load rules from a profile definitio... | Implement the Python class `ProfileLoader` described below.
Class description:
Profile loader
Method signatures and docstrings:
- def __init__(self, rules_registry, debug=False): Initialize the ProfileLoader :param rules_registry: :param debug:
- def load(self, profile_definition): Load rules from a profile definitio... | a9d0335a532acdb4070e5537155b03b34915b73e | <|skeleton|>
class ProfileLoader:
"""Profile loader"""
def __init__(self, rules_registry, debug=False):
"""Initialize the ProfileLoader :param rules_registry: :param debug:"""
<|body_0|>
def load(self, profile_definition):
"""Load rules from a profile definition :param profile_defi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileLoader:
"""Profile loader"""
def __init__(self, rules_registry, debug=False):
"""Initialize the ProfileLoader :param rules_registry: :param debug:"""
self.debug = debug
self.rules_registry = rules_registry
if self.debug:
print('ProfileLoader - init' + li... | the_stack_v2_python_sparse | terraform_validator/ProfileLoader.py | rubelw/terraform-validator | train | 7 |
cc862c9df8ce4e23fa69dcc0647f5b760894ba37 | [
"if not self.filter_backend:\n return queryset\nbackend = self.filter_backend()\nreturn backend.filter_queryset(self.request, queryset, self)",
"class SerializerClass(self.pagination_serializer_class):\n\n class Meta:\n object_serializer_class = self.get_serializer_class()\npagination_serializer_clas... | <|body_start_0|>
if not self.filter_backend:
return queryset
backend = self.filter_backend()
return backend.filter_queryset(self.request, queryset, self)
<|end_body_0|>
<|body_start_1|>
class SerializerClass(self.pagination_serializer_class):
class Meta:
... | Base class for generic views onto a queryset. | MultipleObjectAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultipleObjectAPIView:
"""Base class for generic views onto a queryset."""
def filter_queryset(self, queryset):
"""Given a queryset, filter it with whichever filter backend is in use."""
<|body_0|>
def get_pagination_serializer(self, page=None):
"""Return a seria... | stack_v2_sparse_classes_75kplus_train_071748 | 6,838 | permissive | [
{
"docstring": "Given a queryset, filter it with whichever filter backend is in use.",
"name": "filter_queryset",
"signature": "def filter_queryset(self, queryset)"
},
{
"docstring": "Return a serializer instance to use with paginated data.",
"name": "get_pagination_serializer",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_038558 | Implement the Python class `MultipleObjectAPIView` described below.
Class description:
Base class for generic views onto a queryset.
Method signatures and docstrings:
- def filter_queryset(self, queryset): Given a queryset, filter it with whichever filter backend is in use.
- def get_pagination_serializer(self, page=... | Implement the Python class `MultipleObjectAPIView` described below.
Class description:
Base class for generic views onto a queryset.
Method signatures and docstrings:
- def filter_queryset(self, queryset): Given a queryset, filter it with whichever filter backend is in use.
- def get_pagination_serializer(self, page=... | 6f1598be7793a8d4d0510a6559f9ec364f51cfab | <|skeleton|>
class MultipleObjectAPIView:
"""Base class for generic views onto a queryset."""
def filter_queryset(self, queryset):
"""Given a queryset, filter it with whichever filter backend is in use."""
<|body_0|>
def get_pagination_serializer(self, page=None):
"""Return a seria... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultipleObjectAPIView:
"""Base class for generic views onto a queryset."""
def filter_queryset(self, queryset):
"""Given a queryset, filter it with whichever filter backend is in use."""
if not self.filter_backend:
return queryset
backend = self.filter_backend()
... | the_stack_v2_python_sparse | thirdpart/rest_framework/generics.py | Open365/seahub | train | 1 |
985c1981365a5c9e7c886a5077741b078bd2fca3 | [
"self.var = var\nself.con = con\nself.var_descr = var_descr\nself.con_descr = con_descr",
"r = 'L-System Variables:\\n'\nfor i in range(0, len(self.var)):\n r += '{}: {}\\n'.format(self.var[i], self.var_descr[i])\nr += 'L-System Constants:\\n'\nfor i in range(0, len(self.con)):\n r += '{}: {}\\n'.format(sel... | <|body_start_0|>
self.var = var
self.con = con
self.var_descr = var_descr
self.con_descr = con_descr
<|end_body_0|>
<|body_start_1|>
r = 'L-System Variables:\n'
for i in range(0, len(self.var)):
r += '{}: {}\n'.format(self.var[i], self.var_descr[i])
r... | The L-system vocabulary | vocabulary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class vocabulary:
"""The L-system vocabulary"""
def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None:
"""Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The description of the vocabulary members"""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_071749 | 18,172 | permissive | [
{
"docstring": "Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The description of the vocabulary members",
"name": "__init__",
"signature": "def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None"
},
{
"docstring": "Format... | 2 | stack_v2_sparse_classes_30k_train_025362 | Implement the Python class `vocabulary` described below.
Class description:
The L-system vocabulary
Method signatures and docstrings:
- def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None: Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The d... | Implement the Python class `vocabulary` described below.
Class description:
The L-system vocabulary
Method signatures and docstrings:
- def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None: Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The d... | b47e951cc465f1d2d6ca4384b2bce05c6e96e2a0 | <|skeleton|>
class vocabulary:
"""The L-system vocabulary"""
def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None:
"""Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The description of the vocabulary members"""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class vocabulary:
"""The L-system vocabulary"""
def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None:
"""Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The description of the vocabulary members"""
self.var = var
... | the_stack_v2_python_sparse | Models/MarcMentat/evolve_soft_2d/evolve/lsystems.py | martinventer/Naude_Masters-Project | train | 0 |
cfa77988b8017324c9384e4080bba104396d72f1 | [
"super().__init__()\ninitialize(self, init_type)\nself.layers = nn.LayerList()\nassert len(kernel_sizes) == 4\nfor ks in kernel_sizes:\n assert ks % 2 == 1\nself.layers.append(nn.Sequential(nn.Conv1D(in_channels, channels, kernel_sizes[0], bias_attr=bias, padding=(kernel_sizes[0] - 1) // 2), get_activation(nonli... | <|body_start_0|>
super().__init__()
initialize(self, init_type)
self.layers = nn.LayerList()
assert len(kernel_sizes) == 4
for ks in kernel_sizes:
assert ks % 2 == 1
self.layers.append(nn.Sequential(nn.Conv1D(in_channels, channels, kernel_sizes[0], bias_attr=b... | HiFi-GAN scale discriminator module. | HiFiGANScaleDiscriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiFiGANScaleDiscriminator:
"""HiFi-GAN scale discriminator module."""
def __init__(self, in_channels: int=1, out_channels: int=1, kernel_sizes: List[int]=[15, 41, 5, 3], channels: int=128, max_downsample_channels: int=1024, max_groups: int=16, bias: bool=True, downsample_scales: List[int]=[2... | stack_v2_sparse_classes_75kplus_train_071750 | 30,988 | permissive | [
{
"docstring": "Initilize HiFiGAN scale discriminator module. Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. kernel_sizes (list): List of four kernel sizes. The first will be used for the first conv layer, and the second is for downsampling part, and the remain... | 4 | stack_v2_sparse_classes_30k_train_025751 | Implement the Python class `HiFiGANScaleDiscriminator` described below.
Class description:
HiFi-GAN scale discriminator module.
Method signatures and docstrings:
- def __init__(self, in_channels: int=1, out_channels: int=1, kernel_sizes: List[int]=[15, 41, 5, 3], channels: int=128, max_downsample_channels: int=1024, ... | Implement the Python class `HiFiGANScaleDiscriminator` described below.
Class description:
HiFi-GAN scale discriminator module.
Method signatures and docstrings:
- def __init__(self, in_channels: int=1, out_channels: int=1, kernel_sizes: List[int]=[15, 41, 5, 3], channels: int=128, max_downsample_channels: int=1024, ... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class HiFiGANScaleDiscriminator:
"""HiFi-GAN scale discriminator module."""
def __init__(self, in_channels: int=1, out_channels: int=1, kernel_sizes: List[int]=[15, 41, 5, 3], channels: int=128, max_downsample_channels: int=1024, max_groups: int=16, bias: bool=True, downsample_scales: List[int]=[2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HiFiGANScaleDiscriminator:
"""HiFi-GAN scale discriminator module."""
def __init__(self, in_channels: int=1, out_channels: int=1, kernel_sizes: List[int]=[15, 41, 5, 3], channels: int=128, max_downsample_channels: int=1024, max_groups: int=16, bias: bool=True, downsample_scales: List[int]=[2, 2, 4, 4, 1]... | the_stack_v2_python_sparse | paddlespeech/t2s/models/hifigan/hifigan.py | anniyanvr/DeepSpeech-1 | train | 0 |
0fa0ea1f827df1e408b6c01244fa749741c5af73 | [
"super().__init__()\nconv_filters = [n_mels] + [n_conv_filters] * (n_conv_layers - 1) + [n_mels]\nconv_activations = [nn.Tanh()] * (n_conv_layers - 1) + [None]\nself.convs = nn.ModuleList([ConvBatchNorm(in_filters, out_filters, kernel_size=conv_filter_size, dropout=conv_dropout, activation=act) for in_filters, out_... | <|body_start_0|>
super().__init__()
conv_filters = [n_mels] + [n_conv_filters] * (n_conv_layers - 1) + [n_mels]
conv_activations = [nn.Tanh()] * (n_conv_layers - 1) + [None]
self.convs = nn.ModuleList([ConvBatchNorm(in_filters, out_filters, kernel_size=conv_filter_size, dropout=conv_drop... | Post Processing Network | PostNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostNet:
"""Post Processing Network"""
def __init__(self, n_mels, n_conv_layers, n_conv_filters, conv_filter_size, conv_dropout):
"""Instantiate the PostNet"""
<|body_0|>
def forward(self, x):
"""Forward pass Args: x: [B, n_mels, T] returns: [B, n_mels, T]"""
... | stack_v2_sparse_classes_75kplus_train_071751 | 1,139 | permissive | [
{
"docstring": "Instantiate the PostNet",
"name": "__init__",
"signature": "def __init__(self, n_mels, n_conv_layers, n_conv_filters, conv_filter_size, conv_dropout)"
},
{
"docstring": "Forward pass Args: x: [B, n_mels, T] returns: [B, n_mels, T]",
"name": "forward",
"signature": "def fo... | 2 | null | Implement the Python class `PostNet` described below.
Class description:
Post Processing Network
Method signatures and docstrings:
- def __init__(self, n_mels, n_conv_layers, n_conv_filters, conv_filter_size, conv_dropout): Instantiate the PostNet
- def forward(self, x): Forward pass Args: x: [B, n_mels, T] returns: ... | Implement the Python class `PostNet` described below.
Class description:
Post Processing Network
Method signatures and docstrings:
- def __init__(self, n_mels, n_conv_layers, n_conv_filters, conv_filter_size, conv_dropout): Instantiate the PostNet
- def forward(self, x): Forward pass Args: x: [B, n_mels, T] returns: ... | cb0091241a9fb9b7e3fc88fbdbad8027a9d18928 | <|skeleton|>
class PostNet:
"""Post Processing Network"""
def __init__(self, n_mels, n_conv_layers, n_conv_filters, conv_filter_size, conv_dropout):
"""Instantiate the PostNet"""
<|body_0|>
def forward(self, x):
"""Forward pass Args: x: [B, n_mels, T] returns: [B, n_mels, T]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostNet:
"""Post Processing Network"""
def __init__(self, n_mels, n_conv_layers, n_conv_filters, conv_filter_size, conv_dropout):
"""Instantiate the PostNet"""
super().__init__()
conv_filters = [n_mels] + [n_conv_filters] * (n_conv_layers - 1) + [n_mels]
conv_activations =... | the_stack_v2_python_sparse | tacotron2/seq2seq/postnet.py | anandaswarup/TTS | train | 2 |
2b94cbf99366f4b45eb4aafad676506442ab8e06 | [
"threading.Thread.__init__(self)\nself.daemon = True\nself.parent = parent\nself.cleaner = TextsCleaner(True)",
"while not self.parent.queueLinks.empty():\n link = self.parent.queueLinks.get()\n text = self.Process(link)\n text = self.cleaner.Process(text)\n self.parent.queueTexts.put(text)\n self.... | <|body_start_0|>
threading.Thread.__init__(self)
self.daemon = True
self.parent = parent
self.cleaner = TextsCleaner(True)
<|end_body_0|>
<|body_start_1|>
while not self.parent.queueLinks.empty():
link = self.parent.queueLinks.get()
text = self.Process(li... | Поток скачивания текста | TextsDownloaderThreaded | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextsDownloaderThreaded:
"""Поток скачивания текста"""
def __init__(self, parent):
"""Инициализация"""
<|body_0|>
def run(self):
"""Обработка очередей"""
<|body_1|>
def Process(self, link):
"""Непосредственно скачивание"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_071752 | 14,806 | no_license | [
{
"docstring": "Инициализация",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Обработка очередей",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Непосредственно скачивание",
"name": "Process",
"signature": "def Process(s... | 3 | stack_v2_sparse_classes_30k_train_048200 | Implement the Python class `TextsDownloaderThreaded` described below.
Class description:
Поток скачивания текста
Method signatures and docstrings:
- def __init__(self, parent): Инициализация
- def run(self): Обработка очередей
- def Process(self, link): Непосредственно скачивание | Implement the Python class `TextsDownloaderThreaded` described below.
Class description:
Поток скачивания текста
Method signatures and docstrings:
- def __init__(self, parent): Инициализация
- def run(self): Обработка очередей
- def Process(self, link): Непосредственно скачивание
<|skeleton|>
class TextsDownloaderTh... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class TextsDownloaderThreaded:
"""Поток скачивания текста"""
def __init__(self, parent):
"""Инициализация"""
<|body_0|>
def run(self):
"""Обработка очередей"""
<|body_1|>
def Process(self, link):
"""Непосредственно скачивание"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextsDownloaderThreaded:
"""Поток скачивания текста"""
def __init__(self, parent):
"""Инициализация"""
threading.Thread.__init__(self)
self.daemon = True
self.parent = parent
self.cleaner = TextsCleaner(True)
def run(self):
"""Обработка очередей"""
... | the_stack_v2_python_sparse | tools/textparser.py | cash2one/doorscenter | train | 0 |
4649d5dafa9bc70f584568c36bdbfbe865c8a5b6 | [
"self.count = features.shape[0]\nself.features = np.copy(features)\nself.features_dim = features.shape[1]\nif isinstance(idx, np.ndarray):\n self.idx = idx\nelse:\n self.idx = np.arange(self.count)\nself.labels = np.array(labels)\nself.labels_dim = 1",
"fl_store = []\nskf = KFold(n_splits=k_folds, shuffle=s... | <|body_start_0|>
self.count = features.shape[0]
self.features = np.copy(features)
self.features_dim = features.shape[1]
if isinstance(idx, np.ndarray):
self.idx = idx
else:
self.idx = np.arange(self.count)
self.labels = np.array(labels)
sel... | Features_labels_grid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Features_labels_grid:
def __init__(self, features, labels, idx=None):
"""Creates fl class with a lot useful attributes for grid data classification :param features: :param labels: Labels as np array, no. of examples x dim :param idx: Used to keep track of the example index when performin... | stack_v2_sparse_classes_75kplus_train_071753 | 16,885 | no_license | [
{
"docstring": "Creates fl class with a lot useful attributes for grid data classification :param features: :param labels: Labels as np array, no. of examples x dim :param idx: Used to keep track of the example index when performing k-fold cv",
"name": "__init__",
"signature": "def __init__(self, featur... | 2 | stack_v2_sparse_classes_30k_train_029563 | Implement the Python class `Features_labels_grid` described below.
Class description:
Implement the Features_labels_grid class.
Method signatures and docstrings:
- def __init__(self, features, labels, idx=None): Creates fl class with a lot useful attributes for grid data classification :param features: :param labels:... | Implement the Python class `Features_labels_grid` described below.
Class description:
Implement the Features_labels_grid class.
Method signatures and docstrings:
- def __init__(self, features, labels, idx=None): Creates fl class with a lot useful attributes for grid data classification :param features: :param labels:... | e19037a75b2a077c40c16f8794a3777f3928a356 | <|skeleton|>
class Features_labels_grid:
def __init__(self, features, labels, idx=None):
"""Creates fl class with a lot useful attributes for grid data classification :param features: :param labels: Labels as np array, no. of examples x dim :param idx: Used to keep track of the example index when performin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Features_labels_grid:
def __init__(self, features, labels, idx=None):
"""Creates fl class with a lot useful attributes for grid data classification :param features: :param labels: Labels as np array, no. of examples x dim :param idx: Used to keep track of the example index when performing k-fold cv"""... | the_stack_v2_python_sparse | own_package/features_labels_setup.py | liqiaofeng1990/Automatic_Strain_Sensor_Design | train | 0 | |
cb4feb1da62f74309d986dc70452fd71228da0bb | [
"template_name = 'transaction/transactions.html'\nif request.user.role == CONSUMER:\n transactions = Transaction.objects.filter(user=request.user)\nelif request.user.role == PROFESSIONAL:\n professional = request.user.professional_profiles.first().professional\n ContentType.objects.get(model=professional.t... | <|body_start_0|>
template_name = 'transaction/transactions.html'
if request.user.role == CONSUMER:
transactions = Transaction.objects.filter(user=request.user)
elif request.user.role == PROFESSIONAL:
professional = request.user.professional_profiles.first().professional
... | TransactionsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionsView:
def get(self, request, *args, **kwargs):
"""show transaction list :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""create a new transaction :param request: :param args: :param kwargs: :r... | stack_v2_sparse_classes_75kplus_train_071754 | 8,409 | no_license | [
{
"docstring": "show transaction list :param request: :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "create a new transaction :param request: :param args: :param kwargs: :return:",
"name": "post",
"signature... | 2 | stack_v2_sparse_classes_30k_test_000267 | Implement the Python class `TransactionsView` described below.
Class description:
Implement the TransactionsView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): show transaction list :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): cr... | Implement the Python class `TransactionsView` described below.
Class description:
Implement the TransactionsView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): show transaction list :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): cr... | 078b468a8ccaa74e96e37237aa2f875f049ed581 | <|skeleton|>
class TransactionsView:
def get(self, request, *args, **kwargs):
"""show transaction list :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""create a new transaction :param request: :param args: :param kwargs: :r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransactionsView:
def get(self, request, *args, **kwargs):
"""show transaction list :param request: :param args: :param kwargs: :return:"""
template_name = 'transaction/transactions.html'
if request.user.role == CONSUMER:
transactions = Transaction.objects.filter(user=reque... | the_stack_v2_python_sparse | backend_core/transactions/views.py | HackerWithData/BackEnd | train | 0 | |
55d66298ccb3ecfa1070287fe780bf3563017231 | [
"self.head = ListNode(-1, -1)\nself.tail = self.head\nself.key2node = {}\nself.capacity = capacity\nself.length = 0",
"if key not in self.key2node:\n return -1\nnode = self.key2node[key]\nval = node.val\nif node.next:\n node.prev.next = node.next\n node.next.prev = node.prev\n self.tail.next = node\n ... | <|body_start_0|>
self.head = ListNode(-1, -1)
self.tail = self.head
self.key2node = {}
self.capacity = capacity
self.length = 0
<|end_body_0|>
<|body_start_1|>
if key not in self.key2node:
return -1
node = self.key2node[key]
val = node.val
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_071755 | 2,775 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_026619 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 5f71ba34f7198841fefaa68eee5b95f2f989296b | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.head = ListNode(-1, -1)
self.tail = self.head
self.key2node = {}
self.capacity = capacity
self.length = 0
def get(self, key):
""":type key: int :rtype: int"""
if key not ... | the_stack_v2_python_sparse | LeetCode/medium/17_LRUcache.py | Kohdz/Algorithms | train | 5 | |
e3f492243204bd0eb640795f1e12a36b45dd228f | [
"if not root:\n return '[]'\nres = []\ndeque = [root]\nwhile deque:\n curr = deque.pop(0)\n if curr:\n res.append(str(curr.val))\n deque.append(curr.left)\n deque.append(curr.right)\n else:\n res.append('null')\nwhile res[-1] == 'null':\n res.pop()\nreturn '[' + ','.join(r... | <|body_start_0|>
if not root:
return '[]'
res = []
deque = [root]
while deque:
curr = deque.pop(0)
if curr:
res.append(str(curr.val))
deque.append(curr.left)
deque.append(curr.right)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_071756 | 2,065 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_032943 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 8987859c4c3faedf7159b5a6ec3155609689760e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
res = []
deque = [root]
while deque:
curr = deque.pop(0)
if curr:
res.append(str(curr... | the_stack_v2_python_sparse | Python/Leetcodes/binary_tree/jianzhi_offer_37_serialize.py | ccc013/DataStructe-Algorithms_Study | train | 15 | |
a9e4992b2f4a0893666762e0259154d9befe541b | [
"self.private_key_path = None\nself.local_cert_path = None\nself.ca_certs_path = None",
"certs_dir = pathlib.Path(root_dir) / 'data' / 'certs'\ncerts_dir.mkdir(parents=True, exist_ok=True)\ncreated_certs = Certs()\nif private_key:\n private_key_file = certs_dir / 'client.key'\n private_key_file.write_text(p... | <|body_start_0|>
self.private_key_path = None
self.local_cert_path = None
self.ca_certs_path = None
<|end_body_0|>
<|body_start_1|>
certs_dir = pathlib.Path(root_dir) / 'data' / 'certs'
certs_dir.mkdir(parents=True, exist_ok=True)
created_certs = Certs()
if priva... | A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string containing the full path to the CA certificates. | Certs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Certs:
"""A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string containing the full path to the CA certificat... | stack_v2_sparse_classes_75kplus_train_071757 | 2,067 | permissive | [
{
"docstring": "Create an empty Certs object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create files that hold certificate data in a root_dir/data/certs folder (creating missing folders as appropriate). :param root_dir: root dir in which to create data/certs fold... | 2 | stack_v2_sparse_classes_30k_train_001699 | Implement the Python class `Certs` described below.
Class description:
A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string contai... | Implement the Python class `Certs` described below.
Class description:
A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string contai... | 8420d9d4b800223bff6a648015679684f5aba38c | <|skeleton|>
class Certs:
"""A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string containing the full path to the CA certificat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Certs:
"""A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string containing the full path to the CA certificates."""
d... | the_stack_v2_python_sparse | integration-tests/fake_spine/fake_spine/certs.py | nhsconnect/integration-adaptors | train | 15 |
89b289f1e77d348df3b4507a6d7584e26d1b9294 | [
"flag = Flag()\nassert not flag\n\ndef trigger_flag(after):\n yield env.timeout(after)\n yield flag.set()\nenv.process(trigger_flag(5))\nyield flag\nassert env.now == 5",
"assert env.now == 0\n\nasync def ping_pong(value):\n return value\nresult = (yield ping_pong(3))\nassert result == 3\nassert env.now ... | <|body_start_0|>
flag = Flag()
assert not flag
def trigger_flag(after):
yield env.timeout(after)
yield flag.set()
env.process(trigger_flag(5))
yield flag
assert env.now == 5
<|end_body_0|>
<|body_start_1|>
assert env.now == 0
asy... | TestUsim2Simpy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUsim2Simpy:
def test_flag(self, env):
"""Can trigger and set flags"""
<|body_0|>
def test_coroutine(self, env):
"""Can yield-as-await coroutines"""
<|body_1|>
def test_time(self, env):
"""Can yield-as-await time expressions"""
<|body_... | stack_v2_sparse_classes_75kplus_train_071758 | 2,166 | permissive | [
{
"docstring": "Can trigger and set flags",
"name": "test_flag",
"signature": "def test_flag(self, env)"
},
{
"docstring": "Can yield-as-await coroutines",
"name": "test_coroutine",
"signature": "def test_coroutine(self, env)"
},
{
"docstring": "Can yield-as-await time expression... | 6 | stack_v2_sparse_classes_30k_train_007051 | Implement the Python class `TestUsim2Simpy` described below.
Class description:
Implement the TestUsim2Simpy class.
Method signatures and docstrings:
- def test_flag(self, env): Can trigger and set flags
- def test_coroutine(self, env): Can yield-as-await coroutines
- def test_time(self, env): Can yield-as-await time... | Implement the Python class `TestUsim2Simpy` described below.
Class description:
Implement the TestUsim2Simpy class.
Method signatures and docstrings:
- def test_flag(self, env): Can trigger and set flags
- def test_coroutine(self, env): Can yield-as-await coroutines
- def test_time(self, env): Can yield-as-await time... | 28615825fbe23140bbf9efe63fb18410f9453441 | <|skeleton|>
class TestUsim2Simpy:
def test_flag(self, env):
"""Can trigger and set flags"""
<|body_0|>
def test_coroutine(self, env):
"""Can yield-as-await coroutines"""
<|body_1|>
def test_time(self, env):
"""Can yield-as-await time expressions"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestUsim2Simpy:
def test_flag(self, env):
"""Can trigger and set flags"""
flag = Flag()
assert not flag
def trigger_flag(after):
yield env.timeout(after)
yield flag.set()
env.process(trigger_flag(5))
yield flag
assert env.now == ... | the_stack_v2_python_sparse | usim_pytest/test_usimpy/test_compatibility.py | MaineKuehn/usim | train | 18 | |
dad2583c57fd5c45280eefbb9594f319d2dd80f5 | [
"boxsize = 10\noffset = 1\npixelsize = (self.getModuleCount() + offset + offset) * boxsize\ncanvas = PNGCanvas(pixelsize, pixelsize)\nfor row in range(self.getModuleCount()):\n for column in range(self.getModuleCount()):\n if self.isDark(row, column):\n pos_x = (column + offset) * boxsize\n ... | <|body_start_0|>
boxsize = 10
offset = 1
pixelsize = (self.getModuleCount() + offset + offset) * boxsize
canvas = PNGCanvas(pixelsize, pixelsize)
for row in range(self.getModuleCount()):
for column in range(self.getModuleCount()):
if self.isDark(row, c... | Class for generation QRCodes on Google App Engine in native Python | QRCode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QRCode:
"""Class for generation QRCodes on Google App Engine in native Python"""
def make_image(self):
"""Creates PNG image with QR Code"""
<|body_0|>
def get_type_for_string(string):
"""Get QRCode type (complexity) for a string @param string:"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_071759 | 3,292 | no_license | [
{
"docstring": "Creates PNG image with QR Code",
"name": "make_image",
"signature": "def make_image(self)"
},
{
"docstring": "Get QRCode type (complexity) for a string @param string:",
"name": "get_type_for_string",
"signature": "def get_type_for_string(string)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_040980 | Implement the Python class `QRCode` described below.
Class description:
Class for generation QRCodes on Google App Engine in native Python
Method signatures and docstrings:
- def make_image(self): Creates PNG image with QR Code
- def get_type_for_string(string): Get QRCode type (complexity) for a string @param string... | Implement the Python class `QRCode` described below.
Class description:
Class for generation QRCodes on Google App Engine in native Python
Method signatures and docstrings:
- def make_image(self): Creates PNG image with QR Code
- def get_type_for_string(string): Get QRCode type (complexity) for a string @param string... | ad41f3b92ffd46c49404ccc6f4a672cedd34c87d | <|skeleton|>
class QRCode:
"""Class for generation QRCodes on Google App Engine in native Python"""
def make_image(self):
"""Creates PNG image with QR Code"""
<|body_0|>
def get_type_for_string(string):
"""Get QRCode type (complexity) for a string @param string:"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QRCode:
"""Class for generation QRCodes on Google App Engine in native Python"""
def make_image(self):
"""Creates PNG image with QR Code"""
boxsize = 10
offset = 1
pixelsize = (self.getModuleCount() + offset + offset) * boxsize
canvas = PNGCanvas(pixelsize, pixelsi... | the_stack_v2_python_sparse | PyQRNativeGAE/PyQRNativeGAE.py | RITSTARClub/star-site | train | 1 |
ec3771014b5f6b58c75f3e156fe0144e44d7d46b | [
"super(PoseNet, self).__init__()\nself.backbone = torch.load(backbone_path)\nbackbone_dim = 1280\nlatent_dim = 1024\nself.fc1 = nn.Linear(backbone_dim, latent_dim)\nself.fc2 = nn.Linear(latent_dim, 3)\nself.fc3 = nn.Linear(latent_dim, 4)\nself.dropout = nn.Dropout(p=0.1)\nself.avg_pooling_2d = nn.AdaptiveAvgPool2d(... | <|body_start_0|>
super(PoseNet, self).__init__()
self.backbone = torch.load(backbone_path)
backbone_dim = 1280
latent_dim = 1024
self.fc1 = nn.Linear(backbone_dim, latent_dim)
self.fc2 = nn.Linear(latent_dim, 3)
self.fc3 = nn.Linear(latent_dim, 4)
self.dro... | A class to represent a classic pose regressor (PoseNet) with an efficient-net backbone PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization, Kendall et al., 2015 | PoseNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoseNet:
"""A class to represent a classic pose regressor (PoseNet) with an efficient-net backbone PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization, Kendall et al., 2015"""
def __init__(self, backbone_path):
"""Constructor :param backbone_path: backbone path... | stack_v2_sparse_classes_75kplus_train_071760 | 1,674 | no_license | [
{
"docstring": "Constructor :param backbone_path: backbone path to a resnet backbone",
"name": "__init__",
"signature": "def __init__(self, backbone_path)"
},
{
"docstring": "Forward pass :param data: (torch.Tensor) dictionary with key-value 'img' -- input image (N X C X H X W) :return: (torch.T... | 2 | null | Implement the Python class `PoseNet` described below.
Class description:
A class to represent a classic pose regressor (PoseNet) with an efficient-net backbone PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization, Kendall et al., 2015
Method signatures and docstrings:
- def __init__(self, backbo... | Implement the Python class `PoseNet` described below.
Class description:
A class to represent a classic pose regressor (PoseNet) with an efficient-net backbone PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization, Kendall et al., 2015
Method signatures and docstrings:
- def __init__(self, backbo... | 6744fdcf3e79f175971ded43d4728119d82eac95 | <|skeleton|>
class PoseNet:
"""A class to represent a classic pose regressor (PoseNet) with an efficient-net backbone PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization, Kendall et al., 2015"""
def __init__(self, backbone_path):
"""Constructor :param backbone_path: backbone path... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PoseNet:
"""A class to represent a classic pose regressor (PoseNet) with an efficient-net backbone PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization, Kendall et al., 2015"""
def __init__(self, backbone_path):
"""Constructor :param backbone_path: backbone path to a resnet ... | the_stack_v2_python_sparse | models/posenet/PoseNet.py | waterbearbee/multi-scene-pose-transformer | train | 0 |
1fe5f6896d624d2925ff2c7ed4184cd5b3339c6c | [
"logs.log_info('You are using the vgNa channel type: Nav1.2')\nself.time_unit = 1000.0\nself.vrev = 50\nmAlpha = 0.182 * (V - 10.0 - -35.0) / (1 - np.exp(-(V - 10.0 - -35.0) / 9))\nmBeta = 0.124 * (-(V - 10.0) - 35.0) / (1 - np.exp(-(-(V - 10.0) - 35.0) / 9))\nself.m = mAlpha / (mAlpha + mBeta)\nself.h = 1.0 / (1 +... | <|body_start_0|>
logs.log_info('You are using the vgNa channel type: Nav1.2')
self.time_unit = 1000.0
self.vrev = 50
mAlpha = 0.182 * (V - 10.0 - -35.0) / (1 - np.exp(-(V - 10.0 - -35.0) / 9))
mBeta = 0.124 * (-(V - 10.0) - 35.0) / (1 - np.exp(-(-(V - 10.0) - 35.0) / 9))
... | NaV model from Hammil et al 1991, derived from rat neocortical neurons. This channel produces well behaved action-potentials with a variety of vgK channels. Good general-purpose vgNa channel. Reference: Hammil, OP et al. Patch-clamp studies of voltage-gated currents in identified neurons of the rat cerebral cortex. Cer... | Nav1p2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nav1p2:
"""NaV model from Hammil et al 1991, derived from rat neocortical neurons. This channel produces well behaved action-potentials with a variety of vgK channels. Good general-purpose vgNa channel. Reference: Hammil, OP et al. Patch-clamp studies of voltage-gated currents in identified neuro... | stack_v2_sparse_classes_75kplus_train_071761 | 15,691 | no_license | [
{
"docstring": "Run initialization calculation for m and h gates of the channel at starting Vmem value.",
"name": "_init_state",
"signature": "def _init_state(self, V)"
},
{
"docstring": "Update the state of m and h gates of the channel given their present value and present simulation Vmem.",
... | 2 | stack_v2_sparse_classes_30k_train_050797 | Implement the Python class `Nav1p2` described below.
Class description:
NaV model from Hammil et al 1991, derived from rat neocortical neurons. This channel produces well behaved action-potentials with a variety of vgK channels. Good general-purpose vgNa channel. Reference: Hammil, OP et al. Patch-clamp studies of vol... | Implement the Python class `Nav1p2` described below.
Class description:
NaV model from Hammil et al 1991, derived from rat neocortical neurons. This channel produces well behaved action-potentials with a variety of vgK channels. Good general-purpose vgNa channel. Reference: Hammil, OP et al. Patch-clamp studies of vol... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class Nav1p2:
"""NaV model from Hammil et al 1991, derived from rat neocortical neurons. This channel produces well behaved action-potentials with a variety of vgK channels. Good general-purpose vgNa channel. Reference: Hammil, OP et al. Patch-clamp studies of voltage-gated currents in identified neuro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Nav1p2:
"""NaV model from Hammil et al 1991, derived from rat neocortical neurons. This channel produces well behaved action-potentials with a variety of vgK channels. Good general-purpose vgNa channel. Reference: Hammil, OP et al. Patch-clamp studies of voltage-gated currents in identified neurons of the rat... | the_stack_v2_python_sparse | betse/science/channels/vg_na.py | R-Stefano/betse-ml | train | 0 |
98fa8b67df707b130fc5cf6c16d8f75326c4458d | [
"app = self.app\nroot = self.root\nif not Path(root, FRONTEND).is_dir():\n app.display_info('frontend source missing, skipping cleaning compiled output')\n return\noutput_path = Path(root, APP_JS).parent\napp.display_info(f'cleaning {output_path.relative_to(root)}')\nif output_path.is_dir():\n shutil.rmtre... | <|body_start_0|>
app = self.app
root = self.root
if not Path(root, FRONTEND).is_dir():
app.display_info('frontend source missing, skipping cleaning compiled output')
return
output_path = Path(root, APP_JS).parent
app.display_info(f'cleaning {output_path.re... | Hatching build hook to compile our frontend JS. | FrontendBuildHook | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrontendBuildHook:
"""Hatching build hook to compile our frontend JS."""
def clean(self, versions):
"""Called at the beginning of each PEP 517 build, if HATCH_BUILD_CLEAN is set. This implementation deletes any compiled frontend code that may be present in the source tree."""
... | stack_v2_sparse_classes_75kplus_train_071762 | 2,643 | permissive | [
{
"docstring": "Called at the beginning of each PEP 517 build, if HATCH_BUILD_CLEAN is set. This implementation deletes any compiled frontend code that may be present in the source tree.",
"name": "clean",
"signature": "def clean(self, versions)"
},
{
"docstring": "Hook called before each packag... | 2 | stack_v2_sparse_classes_30k_train_050014 | Implement the Python class `FrontendBuildHook` described below.
Class description:
Hatching build hook to compile our frontend JS.
Method signatures and docstrings:
- def clean(self, versions): Called at the beginning of each PEP 517 build, if HATCH_BUILD_CLEAN is set. This implementation deletes any compiled fronten... | Implement the Python class `FrontendBuildHook` described below.
Class description:
Hatching build hook to compile our frontend JS.
Method signatures and docstrings:
- def clean(self, versions): Called at the beginning of each PEP 517 build, if HATCH_BUILD_CLEAN is set. This implementation deletes any compiled fronten... | 795a55cc1aeb31e63160c5b367fcd13a1c2a60ed | <|skeleton|>
class FrontendBuildHook:
"""Hatching build hook to compile our frontend JS."""
def clean(self, versions):
"""Called at the beginning of each PEP 517 build, if HATCH_BUILD_CLEAN is set. This implementation deletes any compiled frontend code that may be present in the source tree."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FrontendBuildHook:
"""Hatching build hook to compile our frontend JS."""
def clean(self, versions):
"""Called at the beginning of each PEP 517 build, if HATCH_BUILD_CLEAN is set. This implementation deletes any compiled frontend code that may be present in the source tree."""
app = self.a... | the_stack_v2_python_sparse | build_frontend.py | lektor/lektor | train | 4,246 |
86f281e80929c33a34ec8dc63e07c5478c3947c3 | [
"super().__init__(reduce, transfer_attributes)\nself._time_window = time_window\nself._cluster_method = DBSCAN(self._time_window, min_samples=1)\nself._keys = keys\nself._time_key = time_key",
"dom_index = group_by(data, self._keys)\nif data.batch is not None:\n features = data.features[0]\nelse:\n features... | <|body_start_0|>
super().__init__(reduce, transfer_attributes)
self._time_window = time_window
self._cluster_method = DBSCAN(self._time_window, min_samples=1)
self._keys = keys
self._time_key = time_key
<|end_body_0|>
<|body_start_1|>
dom_index = group_by(data, self._key... | Coarsen pulses to DOM-level, with additional time-window clustering. | DOMAndTimeWindowCoarsening | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DOMAndTimeWindowCoarsening:
"""Coarsen pulses to DOM-level, with additional time-window clustering."""
def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_y', 'dom_z', 'rde', 'pmt_area'], time_key: str='dom_time'):
... | stack_v2_sparse_classes_75kplus_train_071763 | 11,190 | permissive | [
{
"docstring": "Cluster pulses on the same DOM within `time_window`.",
"name": "__init__",
"signature": "def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_y', 'dom_z', 'rde', 'pmt_area'], time_key: str='dom_time')"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_006157 | Implement the Python class `DOMAndTimeWindowCoarsening` described below.
Class description:
Coarsen pulses to DOM-level, with additional time-window clustering.
Method signatures and docstrings:
- def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_... | Implement the Python class `DOMAndTimeWindowCoarsening` described below.
Class description:
Coarsen pulses to DOM-level, with additional time-window clustering.
Method signatures and docstrings:
- def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_... | f6e03282dd665c81d06eaa1ab55a07d138064e9a | <|skeleton|>
class DOMAndTimeWindowCoarsening:
"""Coarsen pulses to DOM-level, with additional time-window clustering."""
def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_y', 'dom_z', 'rde', 'pmt_area'], time_key: str='dom_time'):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DOMAndTimeWindowCoarsening:
"""Coarsen pulses to DOM-level, with additional time-window clustering."""
def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_y', 'dom_z', 'rde', 'pmt_area'], time_key: str='dom_time'):
"""Cluster pu... | the_stack_v2_python_sparse | src/graphnet/models/coarsening.py | graphnet-team/graphnet | train | 55 |
b5eb91990fa62ae34781bee91c9ceddf95dacd2d | [
"self.crypto = crypto\nself.liveness = liveness\nself.mailbox = mailbox\nself.agent_name = agent_name\nself.tac_version_id = tac_version_id",
"desc = Description({'version': self.tac_version_id}, data_model=CONTROLLER_DATAMODEL)\nlogger.debug('[{}]: Registering with {} data model'.format(self.agent_name, desc.dat... | <|body_start_0|>
self.crypto = crypto
self.liveness = liveness
self.mailbox = mailbox
self.agent_name = agent_name
self.tac_version_id = tac_version_id
<|end_body_0|>
<|body_start_1|>
desc = Description({'version': self.tac_version_id}, data_model=CONTROLLER_DATAMODEL)
... | The OEFActions class defines the actions of an agent towards the OEF. | OEFActions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OEFActions:
"""The OEFActions class defines the actions of an agent towards the OEF."""
def __init__(self, crypto: Crypto, liveness: Liveness, mailbox: MailBox, agent_name: str, tac_version_id: str) -> None:
"""Instantiate the OEFActions. :param crypto: the crypto module :param liven... | stack_v2_sparse_classes_75kplus_train_071764 | 3,132 | permissive | [
{
"docstring": "Instantiate the OEFActions. :param crypto: the crypto module :param liveness: the liveness module :param mailbox: the mailbox of the agent :param agent_name: the agent name :param tac_version: the tac version id :return: None",
"name": "__init__",
"signature": "def __init__(self, crypto:... | 2 | stack_v2_sparse_classes_30k_train_037701 | Implement the Python class `OEFActions` described below.
Class description:
The OEFActions class defines the actions of an agent towards the OEF.
Method signatures and docstrings:
- def __init__(self, crypto: Crypto, liveness: Liveness, mailbox: MailBox, agent_name: str, tac_version_id: str) -> None: Instantiate the ... | Implement the Python class `OEFActions` described below.
Class description:
The OEFActions class defines the actions of an agent towards the OEF.
Method signatures and docstrings:
- def __init__(self, crypto: Crypto, liveness: Liveness, mailbox: MailBox, agent_name: str, tac_version_id: str) -> None: Instantiate the ... | 33c4aa24ca8daf26f2c8f2d2fa38d7f4bf750cfa | <|skeleton|>
class OEFActions:
"""The OEFActions class defines the actions of an agent towards the OEF."""
def __init__(self, crypto: Crypto, liveness: Liveness, mailbox: MailBox, agent_name: str, tac_version_id: str) -> None:
"""Instantiate the OEFActions. :param crypto: the crypto module :param liven... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OEFActions:
"""The OEFActions class defines the actions of an agent towards the OEF."""
def __init__(self, crypto: Crypto, liveness: Liveness, mailbox: MailBox, agent_name: str, tac_version_id: str) -> None:
"""Instantiate the OEFActions. :param crypto: the crypto module :param liveness: the live... | the_stack_v2_python_sparse | tac/agents/controller/base/actions.py | fetchai/agents-tac | train | 30 |
fa7c75f9d21a1cf5935bb5648d69830a7d56e370 | [
"self.auth = auth\nself.auth_name = auth.__class__.__name__ if not auth_name else auth_name\nself.pool = Pool(auth)",
"assert isinstance(self.auth, AdministratorAuthenticator)\nother_config = self.pool.get_other_config()\nfield_name = f'vmemperor_quotas_{self.auth_name}'\nif field_name in other_config:\n try:\... | <|body_start_0|>
self.auth = auth
self.auth_name = auth.__class__.__name__ if not auth_name else auth_name
self.pool = Pool(auth)
<|end_body_0|>
<|body_start_1|>
assert isinstance(self.auth, AdministratorAuthenticator)
other_config = self.pool.get_other_config()
field_na... | Quota | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quota:
def __init__(self, auth, auth_name=None):
""":param auth: Any authenticator that represents one pool. It could be AdministratorAuthenticator or User's authenticator :param auth_name:"""
<|body_0|>
def set_storage_quota(self, user, bytes):
"""Set storage quota ... | stack_v2_sparse_classes_75kplus_train_071765 | 4,155 | permissive | [
{
"docstring": ":param auth: Any authenticator that represents one pool. It could be AdministratorAuthenticator or User's authenticator :param auth_name:",
"name": "__init__",
"signature": "def __init__(self, auth, auth_name=None)"
},
{
"docstring": "Set storage quota for user or group to bytes ... | 4 | null | Implement the Python class `Quota` described below.
Class description:
Implement the Quota class.
Method signatures and docstrings:
- def __init__(self, auth, auth_name=None): :param auth: Any authenticator that represents one pool. It could be AdministratorAuthenticator or User's authenticator :param auth_name:
- de... | Implement the Python class `Quota` described below.
Class description:
Implement the Quota class.
Method signatures and docstrings:
- def __init__(self, auth, auth_name=None): :param auth: Any authenticator that represents one pool. It could be AdministratorAuthenticator or User's authenticator :param auth_name:
- de... | a0b53f67d75cccbd8e1e6a0419d85babab7041f5 | <|skeleton|>
class Quota:
def __init__(self, auth, auth_name=None):
""":param auth: Any authenticator that represents one pool. It could be AdministratorAuthenticator or User's authenticator :param auth_name:"""
<|body_0|>
def set_storage_quota(self, user, bytes):
"""Set storage quota ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Quota:
def __init__(self, auth, auth_name=None):
""":param auth: Any authenticator that represents one pool. It could be AdministratorAuthenticator or User's authenticator :param auth_name:"""
self.auth = auth
self.auth_name = auth.__class__.__name__ if not auth_name else auth_name
... | the_stack_v2_python_sparse | quota.py | pashazz/vmemperor | train | 1 | |
64537b510102bd4700cb022b0d72d148c9c9ff1c | [
"super().__init__()\nself.x_dir = x_direction\nself.y_dir = y_direction\nself.z_dir = z_direction",
"if self.x_dir:\n self.grid.E[0, :, :, :] = self.grid.E[-1, :, :, :]\nif self.y_dir:\n self.grid.E[:, 0, :, :] = self.grid.E[:, -1, :, :]\nif self.z_dir:\n self.grid.E[:, :, 0, :] = self.grid.E[:, :, -1, :... | <|body_start_0|>
super().__init__()
self.x_dir = x_direction
self.y_dir = y_direction
self.z_dir = z_direction
<|end_body_0|>
<|body_start_1|>
if self.x_dir:
self.grid.E[0, :, :, :] = self.grid.E[-1, :, :, :]
if self.y_dir:
self.grid.E[:, 0, :, :]... | Implement a periodic boundary condition. | PeriodicBoundary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeriodicBoundary:
"""Implement a periodic boundary condition."""
def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False):
"""Initialize periodic boundary object."""
<|body_0|>
def update_E(self):
"""Update E field."""
... | stack_v2_sparse_classes_75kplus_train_071766 | 3,210 | permissive | [
{
"docstring": "Initialize periodic boundary object.",
"name": "__init__",
"signature": "def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False)"
},
{
"docstring": "Update E field.",
"name": "update_E",
"signature": "def update_E(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_031142 | Implement the Python class `PeriodicBoundary` described below.
Class description:
Implement a periodic boundary condition.
Method signatures and docstrings:
- def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False): Initialize periodic boundary object.
- def update_E(self): Updat... | Implement the Python class `PeriodicBoundary` described below.
Class description:
Implement a periodic boundary condition.
Method signatures and docstrings:
- def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False): Initialize periodic boundary object.
- def update_E(self): Updat... | f2134cb3e36eabca1639b8ff4e428d3a268953bd | <|skeleton|>
class PeriodicBoundary:
"""Implement a periodic boundary condition."""
def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False):
"""Initialize periodic boundary object."""
<|body_0|>
def update_E(self):
"""Update E field."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PeriodicBoundary:
"""Implement a periodic boundary condition."""
def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False):
"""Initialize periodic boundary object."""
super().__init__()
self.x_dir = x_direction
self.y_dir = y_direction
... | the_stack_v2_python_sparse | fdtd/boundaries.py | tiagovla/fdtd.py | train | 4 |
6820810f1c29717279f11ca1699ecbcdad1a8ffd | [
"name = self.parameter_value('name', kwargs)\nif name:\n return self.new_query(breed.Breed).get(name)",
"value = self.fetch_breed(kwargs)\nif not value:\n return self.set_status(404)\nLOGGER.warning('Deleting breed %s', value.id)\nself.database.delete(value)\nself.database.commit()\nself.set_status(204)",
... | <|body_start_0|>
name = self.parameter_value('name', kwargs)
if name:
return self.new_query(breed.Breed).get(name)
<|end_body_0|>
<|body_start_1|>
value = self.fetch_breed(kwargs)
if not value:
return self.set_status(404)
LOGGER.warning('Deleting breed %s... | API interface for managing breed data | Breed | [
"BSD-3-Clause",
"CC-BY-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Breed:
"""API interface for managing breed data"""
def fetch_breed(self, kwargs):
"""Get a single breed from the database. :param dict kwargs: Keyword arguments from the request :rtype: apiary.mappers.breed.Breed"""
<|body_0|>
def delete(self, *args, **kwargs):
"... | stack_v2_sparse_classes_75kplus_train_071767 | 2,846 | permissive | [
{
"docstring": "Get a single breed from the database. :param dict kwargs: Keyword arguments from the request :rtype: apiary.mappers.breed.Breed",
"name": "fetch_breed",
"signature": "def fetch_breed(self, kwargs)"
},
{
"docstring": "Delete a breed from the system. Accepts breed_id as a query par... | 4 | stack_v2_sparse_classes_30k_train_050972 | Implement the Python class `Breed` described below.
Class description:
API interface for managing breed data
Method signatures and docstrings:
- def fetch_breed(self, kwargs): Get a single breed from the database. :param dict kwargs: Keyword arguments from the request :rtype: apiary.mappers.breed.Breed
- def delete(s... | Implement the Python class `Breed` described below.
Class description:
API interface for managing breed data
Method signatures and docstrings:
- def fetch_breed(self, kwargs): Get a single breed from the database. :param dict kwargs: Keyword arguments from the request :rtype: apiary.mappers.breed.Breed
- def delete(s... | 0acd513b2bcbc9bb5f7c5a657b41ed6601fcd002 | <|skeleton|>
class Breed:
"""API interface for managing breed data"""
def fetch_breed(self, kwargs):
"""Get a single breed from the database. :param dict kwargs: Keyword arguments from the request :rtype: apiary.mappers.breed.Breed"""
<|body_0|>
def delete(self, *args, **kwargs):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Breed:
"""API interface for managing breed data"""
def fetch_breed(self, kwargs):
"""Get a single breed from the database. :param dict kwargs: Keyword arguments from the request :rtype: apiary.mappers.breed.Breed"""
name = self.parameter_value('name', kwargs)
if name:
... | the_stack_v2_python_sparse | apiary/api/breed.py | gmr/apiary | train | 0 |
684710d8b3e5fda9ec855ba73efbd6443531772d | [
"super(DelayCross, self).__init__()\nself.x, self.y = array_cross_check(x, y, 1)\nself.tau = None",
"self.tau = tau\nn = self.x.size\n_sum = 0\nfor i in range(n - self.tau):\n _sum += (self.x[i] - self.x.mean()) / self.x.std() * ((self.y[i + self.tau] - self.y.mean()) / self.y.std())\nself.statistics = _sum / ... | <|body_start_0|>
super(DelayCross, self).__init__()
self.x, self.y = array_cross_check(x, y, 1)
self.tau = None
<|end_body_0|>
<|body_start_1|>
self.tau = tau
n = self.x.size
_sum = 0
for i in range(n - self.tau):
_sum += (self.x[i] - self.x.mean()) /... | Two variable delay cross correlation. | DelayCross | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelayCross:
"""Two variable delay cross correlation."""
def __init__(self, x: array_like, y: array_like):
""":param x: array_like :param y: array_like"""
<|body_0|>
def __call__(self, tau: int):
"""Calculate delay cross correlation. :param tau: int delay length :... | stack_v2_sparse_classes_75kplus_train_071768 | 8,613 | no_license | [
{
"docstring": ":param x: array_like :param y: array_like",
"name": "__init__",
"signature": "def __init__(self, x: array_like, y: array_like)"
},
{
"docstring": "Calculate delay cross correlation. :param tau: int delay length :return: class self",
"name": "__call__",
"signature": "def _... | 3 | stack_v2_sparse_classes_30k_train_029400 | Implement the Python class `DelayCross` described below.
Class description:
Two variable delay cross correlation.
Method signatures and docstrings:
- def __init__(self, x: array_like, y: array_like): :param x: array_like :param y: array_like
- def __call__(self, tau: int): Calculate delay cross correlation. :param ta... | Implement the Python class `DelayCross` described below.
Class description:
Two variable delay cross correlation.
Method signatures and docstrings:
- def __init__(self, x: array_like, y: array_like): :param x: array_like :param y: array_like
- def __call__(self, tau: int): Calculate delay cross correlation. :param ta... | 1c8d5fbf3676dc81e9f143e93ee2564359519b11 | <|skeleton|>
class DelayCross:
"""Two variable delay cross correlation."""
def __init__(self, x: array_like, y: array_like):
""":param x: array_like :param y: array_like"""
<|body_0|>
def __call__(self, tau: int):
"""Calculate delay cross correlation. :param tau: int delay length :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DelayCross:
"""Two variable delay cross correlation."""
def __init__(self, x: array_like, y: array_like):
""":param x: array_like :param y: array_like"""
super(DelayCross, self).__init__()
self.x, self.y = array_cross_check(x, y, 1)
self.tau = None
def __call__(self, ... | the_stack_v2_python_sparse | statistics/correlation.py | qliu0/PythonInAirSeaScience | train | 0 |
b2f58b8890d4474f4ec55612673d0dd3e4cfd885 | [
"cleaned_data = super(RegistrationForm, self).clean()\npassword = cleaned_data.get('password')\npassword_confirmation = cleaned_data.get('password_confirmation')\nif password and password_confirmation:\n if password != password_confirmation:\n self.add_error('password_confirmation', 'Does not match passwo... | <|body_start_0|>
cleaned_data = super(RegistrationForm, self).clean()
password = cleaned_data.get('password')
password_confirmation = cleaned_data.get('password_confirmation')
if password and password_confirmation:
if password != password_confirmation:
self.ad... | Registration form class. | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Registration form class."""
def clean(self):
"""Clean data and add custom validation."""
<|body_0|>
def submit(self):
"""Create new user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cleaned_data = super(RegistrationForm,... | stack_v2_sparse_classes_75kplus_train_071769 | 1,850 | no_license | [
{
"docstring": "Clean data and add custom validation.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Create new user.",
"name": "submit",
"signature": "def submit(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013432 | Implement the Python class `RegistrationForm` described below.
Class description:
Registration form class.
Method signatures and docstrings:
- def clean(self): Clean data and add custom validation.
- def submit(self): Create new user. | Implement the Python class `RegistrationForm` described below.
Class description:
Registration form class.
Method signatures and docstrings:
- def clean(self): Clean data and add custom validation.
- def submit(self): Create new user.
<|skeleton|>
class RegistrationForm:
"""Registration form class."""
def c... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class RegistrationForm:
"""Registration form class."""
def clean(self):
"""Clean data and add custom validation."""
<|body_0|>
def submit(self):
"""Create new user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrationForm:
"""Registration form class."""
def clean(self):
"""Clean data and add custom validation."""
cleaned_data = super(RegistrationForm, self).clean()
password = cleaned_data.get('password')
password_confirmation = cleaned_data.get('password_confirmation')
... | the_stack_v2_python_sparse | app/authorization/forms/registration.py | vsokoltsov/Interview360Server | train | 2 |
af7701e084d96e61f35705798cf82747af601c85 | [
"n = len(nums) - 1\nleft, right = (1, n)\nwhile left < right:\n mid = left + (right - left) // 2\n count = 0\n for num in nums:\n if num <= mid:\n count += 1\n if count > mid:\n right = mid\n else:\n left = mid + 1\nreturn right",
"slow, fast = (nums[0], nums[nums[0]... | <|body_start_0|>
n = len(nums) - 1
left, right = (1, n)
while left < right:
mid = left + (right - left) // 2
count = 0
for num in nums:
if num <= mid:
count += 1
if count > mid:
right = mid
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate1(self, nums: List[int]) -> int:
"""一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。"""
<|body_0|>
def findDuplicate2(self, nums: List[int]) -> int:
"""快慢指针,比较难理解,参考142题解"""
... | stack_v2_sparse_classes_75kplus_train_071770 | 2,089 | no_license | [
{
"docstring": "一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。",
"name": "findDuplicate1",
"signature": "def findDuplicate1(self, nums: List[int]) -> int"
},
{
"docstring": "快慢指针,比较难理解,参考142题解",
"name": "findDuplicate2",
"... | 2 | stack_v2_sparse_classes_30k_test_001516 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate1(self, nums: List[int]) -> int: 一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。
- def findDupli... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate1(self, nums: List[int]) -> int: 一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。
- def findDupli... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def findDuplicate1(self, nums: List[int]) -> int:
"""一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。"""
<|body_0|>
def findDuplicate2(self, nums: List[int]) -> int:
"""快慢指针,比较难理解,参考142题解"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDuplicate1(self, nums: List[int]) -> int:
"""一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。"""
n = len(nums) - 1
left, right = (1, n)
while left < right:
mid = left + (right - left) ... | the_stack_v2_python_sparse | 287_find-the-duplicate-number.py | helloocc/algorithm | train | 1 | |
405bf38da00557f01944a124ac4c5ab04c3f26d9 | [
"if not api_key_id:\n api_keys = []\n for api_key in API_Key.objects.filter(user=request.user):\n api_keys.append({'id': api_key.id, 'title': api_key.title, 'read': api_key.read, 'write': api_key.write, 'restrict_to_secrets': api_key.restrict_to_secrets, 'allow_insecure_access': api_key.allow_insecure_... | <|body_start_0|>
if not api_key_id:
api_keys = []
for api_key in API_Key.objects.filter(user=request.user):
api_keys.append({'id': api_key.id, 'title': api_key.title, 'read': api_key.read, 'write': api_key.write, 'restrict_to_secrets': api_key.restrict_to_secrets, 'allow_... | Check the REST Token and returns a list of all api_keys or the specified api_keys details | APIKeyView | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIKeyView:
"""Check the REST Token and returns a list of all api_keys or the specified api_keys details"""
def get(self, request, api_key_id=None, *args, **kwargs):
"""Returns either a list of all api_keys with own access privileges or the members specified api_key :param request: :... | stack_v2_sparse_classes_75kplus_train_071771 | 7,116 | permissive | [
{
"docstring": "Returns either a list of all api_keys with own access privileges or the members specified api_key :param request: :type request: :param api_key_id: :type api_key_id: :param args: :type args: :param kwargs: :type kwargs: :return: 200 / 403 :rtype:",
"name": "get",
"signature": "def get(se... | 4 | stack_v2_sparse_classes_30k_train_047013 | Implement the Python class `APIKeyView` described below.
Class description:
Check the REST Token and returns a list of all api_keys or the specified api_keys details
Method signatures and docstrings:
- def get(self, request, api_key_id=None, *args, **kwargs): Returns either a list of all api_keys with own access priv... | Implement the Python class `APIKeyView` described below.
Class description:
Check the REST Token and returns a list of all api_keys or the specified api_keys details
Method signatures and docstrings:
- def get(self, request, api_key_id=None, *args, **kwargs): Returns either a list of all api_keys with own access priv... | 8936aa8ccdee8b9617ef7d894cb9a9a9f6f473cf | <|skeleton|>
class APIKeyView:
"""Check the REST Token and returns a list of all api_keys or the specified api_keys details"""
def get(self, request, api_key_id=None, *args, **kwargs):
"""Returns either a list of all api_keys with own access privileges or the members specified api_key :param request: :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class APIKeyView:
"""Check the REST Token and returns a list of all api_keys or the specified api_keys details"""
def get(self, request, api_key_id=None, *args, **kwargs):
"""Returns either a list of all api_keys with own access privileges or the members specified api_key :param request: :type request:... | the_stack_v2_python_sparse | psono/restapi/views/api_key.py | psono/psono-server | train | 76 |
f94b8702b2bdd4ff7731f6cd356025dd1625696e | [
"self.trade_days = trade_days\nself.trade_strategy = trade_strategy\nself.profit_array = []",
"for ind, day in enumerate(self.trade_days):\n '\\n 以时间驱动,完成交易回测\\n '\n if hasattr(self.trade_strategy, 'buy_strategy'):\n self.trade_strategy.buy_strategy(ind, day, self.trade_days)\n ... | <|body_start_0|>
self.trade_days = trade_days
self.trade_strategy = trade_strategy
self.profit_array = []
<|end_body_0|>
<|body_start_1|>
for ind, day in enumerate(self.trade_days):
'\n 以时间驱动,完成交易回测\n '
if hasattr(self.trade_strategy, 'buy_s... | 交易回测系统 | TradeLoopBack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TradeLoopBack:
"""交易回测系统"""
def __init__(self, trade_days, trade_strategy):
"""使用前面封装的StockTradeDays类和本节编写的交易策略类 TradeStrategyBase类初始化交易系统 :param trade_days: StockTradeDays交易数据序列 :param trade_strategy: TradeStrategyBase交易策略"""
<|body_0|>
def execute_trade(self):
... | stack_v2_sparse_classes_75kplus_train_071772 | 1,479 | no_license | [
{
"docstring": "使用前面封装的StockTradeDays类和本节编写的交易策略类 TradeStrategyBase类初始化交易系统 :param trade_days: StockTradeDays交易数据序列 :param trade_strategy: TradeStrategyBase交易策略",
"name": "__init__",
"signature": "def __init__(self, trade_days, trade_strategy)"
},
{
"docstring": "执行交易回测 :return:",
"name": "e... | 2 | stack_v2_sparse_classes_30k_train_004234 | Implement the Python class `TradeLoopBack` described below.
Class description:
交易回测系统
Method signatures and docstrings:
- def __init__(self, trade_days, trade_strategy): 使用前面封装的StockTradeDays类和本节编写的交易策略类 TradeStrategyBase类初始化交易系统 :param trade_days: StockTradeDays交易数据序列 :param trade_strategy: TradeStrategyBase交易策略
- d... | Implement the Python class `TradeLoopBack` described below.
Class description:
交易回测系统
Method signatures and docstrings:
- def __init__(self, trade_days, trade_strategy): 使用前面封装的StockTradeDays类和本节编写的交易策略类 TradeStrategyBase类初始化交易系统 :param trade_days: StockTradeDays交易数据序列 :param trade_strategy: TradeStrategyBase交易策略
- d... | 2294a4bbc38b3c5a0f978c4a6144d5aa4e5eefab | <|skeleton|>
class TradeLoopBack:
"""交易回测系统"""
def __init__(self, trade_days, trade_strategy):
"""使用前面封装的StockTradeDays类和本节编写的交易策略类 TradeStrategyBase类初始化交易系统 :param trade_days: StockTradeDays交易数据序列 :param trade_strategy: TradeStrategyBase交易策略"""
<|body_0|>
def execute_trade(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TradeLoopBack:
"""交易回测系统"""
def __init__(self, trade_days, trade_strategy):
"""使用前面封装的StockTradeDays类和本节编写的交易策略类 TradeStrategyBase类初始化交易系统 :param trade_days: StockTradeDays交易数据序列 :param trade_strategy: TradeStrategyBase交易策略"""
self.trade_days = trade_days
self.trade_strategy = tra... | the_stack_v2_python_sparse | trade/stock/trade_loop_back.py | 13936292023/trade | train | 0 |
9c6d534161bac49c6eb830b58ae72838bffdb12c | [
"self.barrier = Barrier(len(components))\nself.components = components\nfor component in components:\n component.boot()",
"logging.info(f'Printer executing command: {gcode}')\nfor component in self.components:\n component.assign_task(gcode, barrier=self.barrier)\nfor component in self.components:\n resul... | <|body_start_0|>
self.barrier = Barrier(len(components))
self.components = components
for component in components:
component.boot()
<|end_body_0|>
<|body_start_1|>
logging.info(f'Printer executing command: {gcode}')
for component in self.components:
compo... | Bundles absolutely all components necessary to control the 3D printer. | GPrinter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPrinter:
"""Bundles absolutely all components necessary to control the 3D printer."""
def __init__(self, *components: PrinterComponent):
"""Initializes the printer with a set of components. :param components: Usable list of printer components"""
<|body_0|>
def execute(s... | stack_v2_sparse_classes_75kplus_train_071773 | 3,181 | permissive | [
{
"docstring": "Initializes the printer with a set of components. :param components: Usable list of printer components",
"name": "__init__",
"signature": "def __init__(self, *components: PrinterComponent)"
},
{
"docstring": "Execute a G-code command on the printer. :param gcode: Command object",... | 4 | null | Implement the Python class `GPrinter` described below.
Class description:
Bundles absolutely all components necessary to control the 3D printer.
Method signatures and docstrings:
- def __init__(self, *components: PrinterComponent): Initializes the printer with a set of components. :param components: Usable list of pr... | Implement the Python class `GPrinter` described below.
Class description:
Bundles absolutely all components necessary to control the 3D printer.
Method signatures and docstrings:
- def __init__(self, *components: PrinterComponent): Initializes the printer with a set of components. :param components: Usable list of pr... | 4c35f7dc08f976c05d0b7f27902236132f19c024 | <|skeleton|>
class GPrinter:
"""Bundles absolutely all components necessary to control the 3D printer."""
def __init__(self, *components: PrinterComponent):
"""Initializes the printer with a set of components. :param components: Usable list of printer components"""
<|body_0|>
def execute(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GPrinter:
"""Bundles absolutely all components necessary to control the 3D printer."""
def __init__(self, *components: PrinterComponent):
"""Initializes the printer with a set of components. :param components: Usable list of printer components"""
self.barrier = Barrier(len(components))
... | the_stack_v2_python_sparse | src/printer_components/GPrinter.py | pat-bert/gcode | train | 0 |
2ab65d55a515b8ba56b061370da34fff4948d649 | [
"super(BaseRemapDataset, self).__init__(root=root, transform=transform)\nif map is not None:\n self.remap_classes(map=map)",
"if '*' in map:\n idx_to_class = {v: '*' for k, v in self.class_to_idx.items()}\nelse:\n idx_to_class = {v: k for k, v in self.class_to_idx.items()}\nself.targets = [map[idx_to_cla... | <|body_start_0|>
super(BaseRemapDataset, self).__init__(root=root, transform=transform)
if map is not None:
self.remap_classes(map=map)
<|end_body_0|>
<|body_start_1|>
if '*' in map:
idx_to_class = {v: '*' for k, v in self.class_to_idx.items()}
else:
... | BaseRemapDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseRemapDataset:
def __init__(self, root: str, transform: Optional[object]=None, map: Optional[object]=None):
"""Creates a dataset where classes name can be remaped. Useful when training with multiple dataset with similar classes but different classes names. Parameters ---------- root: ... | stack_v2_sparse_classes_75kplus_train_071774 | 3,843 | no_license | [
{
"docstring": "Creates a dataset where classes name can be remaped. Useful when training with multiple dataset with similar classes but different classes names. Parameters ---------- root: str Path to image folder. transform: callable, optional Transformation to apply on image.",
"name": "__init__",
"s... | 2 | stack_v2_sparse_classes_30k_train_026738 | Implement the Python class `BaseRemapDataset` described below.
Class description:
Implement the BaseRemapDataset class.
Method signatures and docstrings:
- def __init__(self, root: str, transform: Optional[object]=None, map: Optional[object]=None): Creates a dataset where classes name can be remaped. Useful when trai... | Implement the Python class `BaseRemapDataset` described below.
Class description:
Implement the BaseRemapDataset class.
Method signatures and docstrings:
- def __init__(self, root: str, transform: Optional[object]=None, map: Optional[object]=None): Creates a dataset where classes name can be remaped. Useful when trai... | 8cf6fc7092ecf13ee7155c31f7c4bf36b6b139b8 | <|skeleton|>
class BaseRemapDataset:
def __init__(self, root: str, transform: Optional[object]=None, map: Optional[object]=None):
"""Creates a dataset where classes name can be remaped. Useful when training with multiple dataset with similar classes but different classes names. Parameters ---------- root: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseRemapDataset:
def __init__(self, root: str, transform: Optional[object]=None, map: Optional[object]=None):
"""Creates a dataset where classes name can be remaped. Useful when training with multiple dataset with similar classes but different classes names. Parameters ---------- root: str Path to im... | the_stack_v2_python_sparse | dataset/base.py | arunadevikaruppasamy/SRA | train | 0 | |
996f21b645bfa78453a45c93c8e4ee3f512e5a68 | [
"super(lightUnetPlusPlus, self).__init__()\nself.name = 'light Unet++'\nself.upsampling = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\nbasis_filter = 32\nfilter_sizes = [basis_filter, basis_filter * 2, basis_filter * 4, basis_filter * 8, basis_filter * 16]\nself.layer0_0 = DoubleConvolutionLaye... | <|body_start_0|>
super(lightUnetPlusPlus, self).__init__()
self.name = 'light Unet++'
self.upsampling = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
basis_filter = 32
filter_sizes = [basis_filter, basis_filter * 2, basis_filter * 4, basis_filter * 8, basis_fil... | The class lightUnetPlusPlus extends torch Module. The main difference with the unetPlusPlus has fewer layers. | lightUnetPlusPlus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lightUnetPlusPlus:
"""The class lightUnetPlusPlus extends torch Module. The main difference with the unetPlusPlus has fewer layers."""
def __init__(self, n_channels, n_classes):
"""Initialises a lightUnetPlusPlus object. :param n_channels: number of channels in the input :param n_cla... | stack_v2_sparse_classes_75kplus_train_071775 | 3,914 | permissive | [
{
"docstring": "Initialises a lightUnetPlusPlus object. :param n_channels: number of channels in the input :param n_classes: number of classes to detect thus also the number of output feature maps",
"name": "__init__",
"signature": "def __init__(self, n_channels, n_classes)"
},
{
"docstring": "D... | 4 | null | Implement the Python class `lightUnetPlusPlus` described below.
Class description:
The class lightUnetPlusPlus extends torch Module. The main difference with the unetPlusPlus has fewer layers.
Method signatures and docstrings:
- def __init__(self, n_channels, n_classes): Initialises a lightUnetPlusPlus object. :param... | Implement the Python class `lightUnetPlusPlus` described below.
Class description:
The class lightUnetPlusPlus extends torch Module. The main difference with the unetPlusPlus has fewer layers.
Method signatures and docstrings:
- def __init__(self, n_channels, n_classes): Initialises a lightUnetPlusPlus object. :param... | 4ad97b04f98b10554c3c0de85645578df336df98 | <|skeleton|>
class lightUnetPlusPlus:
"""The class lightUnetPlusPlus extends torch Module. The main difference with the unetPlusPlus has fewer layers."""
def __init__(self, n_channels, n_classes):
"""Initialises a lightUnetPlusPlus object. :param n_channels: number of channels in the input :param n_cla... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class lightUnetPlusPlus:
"""The class lightUnetPlusPlus extends torch Module. The main difference with the unetPlusPlus has fewer layers."""
def __init__(self, n_channels, n_classes):
"""Initialises a lightUnetPlusPlus object. :param n_channels: number of channels in the input :param n_classes: number ... | the_stack_v2_python_sparse | Models/lightUnetPlusPlus.py | MinZHANG-WHU/LamboiseNet | train | 1 |
bc96f2961f10def0d793f018e623ea59cb1bfcf7 | [
"if hasattr(self, 'blockMeshDict'):\n convertToMeters = self.blockMeshDict.convertToMeters\nelse:\n convertToMeters = 1\nreturn loadOFMesh(self.polyMeshFolder, convertToMeters, innerMesh)",
"if hasattr(self, 'blockMeshDict'):\n convertToMeters = self.blockMeshDict.convertToMeters\nelse:\n convertToMet... | <|body_start_0|>
if hasattr(self, 'blockMeshDict'):
convertToMeters = self.blockMeshDict.convertToMeters
else:
convertToMeters = 1
return loadOFMesh(self.polyMeshFolder, convertToMeters, innerMesh)
<|end_body_0|>
<|body_start_1|>
if hasattr(self, 'blockMeshDict')... | Butterfly case for Dynamo. | Case | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Case:
"""Butterfly case for Dynamo."""
def loadMesh(self, innerMesh=True):
"""Return OpenFOAM mesh as a Rhino mesh."""
<|body_0|>
def loadPoints(self):
"""Return OpenFOAM mesh as a Rhino mesh."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if h... | stack_v2_sparse_classes_75kplus_train_071776 | 838 | no_license | [
{
"docstring": "Return OpenFOAM mesh as a Rhino mesh.",
"name": "loadMesh",
"signature": "def loadMesh(self, innerMesh=True)"
},
{
"docstring": "Return OpenFOAM mesh as a Rhino mesh.",
"name": "loadPoints",
"signature": "def loadPoints(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008130 | Implement the Python class `Case` described below.
Class description:
Butterfly case for Dynamo.
Method signatures and docstrings:
- def loadMesh(self, innerMesh=True): Return OpenFOAM mesh as a Rhino mesh.
- def loadPoints(self): Return OpenFOAM mesh as a Rhino mesh. | Implement the Python class `Case` described below.
Class description:
Butterfly case for Dynamo.
Method signatures and docstrings:
- def loadMesh(self, innerMesh=True): Return OpenFOAM mesh as a Rhino mesh.
- def loadPoints(self): Return OpenFOAM mesh as a Rhino mesh.
<|skeleton|>
class Case:
"""Butterfly case f... | 330e96867fc3df530ad21c11de01c54562745e65 | <|skeleton|>
class Case:
"""Butterfly case for Dynamo."""
def loadMesh(self, innerMesh=True):
"""Return OpenFOAM mesh as a Rhino mesh."""
<|body_0|>
def loadPoints(self):
"""Return OpenFOAM mesh as a Rhino mesh."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Case:
"""Butterfly case for Dynamo."""
def loadMesh(self, innerMesh=True):
"""Return OpenFOAM mesh as a Rhino mesh."""
if hasattr(self, 'blockMeshDict'):
convertToMeters = self.blockMeshDict.convertToMeters
else:
convertToMeters = 1
return loadOFMes... | the_stack_v2_python_sparse | samples/case.py | aKarm1905/PythonMSC | train | 0 |
96c474b23cda98e5d031bf4795b97e86b050e0ee | [
"group_number = int(self.ui.lineEdit_group_number.text())\nself.protocol.create_sequence(group_number)\nself.ui.tableWidget_tasks.setRowCount(len(self.protocol.trial_list))\nfor i in range(len(self.protocol.trial_list)):\n self.ui.tableWidget_tasks.setItem(i, 0, QTableWidgetItem(self.protocol.trial_list[i].name)... | <|body_start_0|>
group_number = int(self.ui.lineEdit_group_number.text())
self.protocol.create_sequence(group_number)
self.ui.tableWidget_tasks.setRowCount(len(self.protocol.trial_list))
for i in range(len(self.protocol.trial_list)):
self.ui.tableWidget_tasks.setItem(i, 0, QT... | SequenceManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceManager:
def onClicked_button_create_sequence(self):
"""Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number' times in the Task table"""
<|body_0|>
def onClicked_button_randomize(self):
"""Eve... | stack_v2_sparse_classes_75kplus_train_071777 | 2,026 | no_license | [
{
"docstring": "Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number' times in the Task table",
"name": "onClicked_button_create_sequence",
"signature": "def onClicked_button_create_sequence(self)"
},
{
"docstring": "Event listen... | 2 | stack_v2_sparse_classes_30k_train_019192 | Implement the Python class `SequenceManager` described below.
Class description:
Implement the SequenceManager class.
Method signatures and docstrings:
- def onClicked_button_create_sequence(self): Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number'... | Implement the Python class `SequenceManager` described below.
Class description:
Implement the SequenceManager class.
Method signatures and docstrings:
- def onClicked_button_create_sequence(self): Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number'... | 3fc47027ef2fcb69d54a95d4dec369e2221559a0 | <|skeleton|>
class SequenceManager:
def onClicked_button_create_sequence(self):
"""Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number' times in the Task table"""
<|body_0|>
def onClicked_button_randomize(self):
"""Eve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SequenceManager:
def onClicked_button_create_sequence(self):
"""Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number' times in the Task table"""
group_number = int(self.ui.lineEdit_group_number.text())
self.protocol.cre... | the_stack_v2_python_sparse | package/views/main_GUI/exp_protocol_design/sequence_manager.py | WILLSNIU186/EEG-Online-Experiment-GUI | train | 13 | |
7821c114132cad6bbbae204cb605867db2f677af | [
"PlotCanvas1D.__init__(self, parent, id, xlabel, ylabel, xscale, yscale)\nself.bank = FilterBank()\npub.subscribe(self.PostProcess, 'filter.change')\nself.Bind(wx.EVT_WINDOW_DESTROY, self.OnDelete)",
"PlotCanvas1D.OnDelete(self, event)\npub.unsubscribe(self.PostProcess, 'filter.change')\nevent.Skip()",
"event.S... | <|body_start_0|>
PlotCanvas1D.__init__(self, parent, id, xlabel, ylabel, xscale, yscale)
self.bank = FilterBank()
pub.subscribe(self.PostProcess, 'filter.change')
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDelete)
<|end_body_0|>
<|body_start_1|>
PlotCanvas1D.OnDelete(self, event)
... | Canvas class for 1D post-processed data plots Properties: is_data - False, canvas is not meant to display raw measurement data is_filter - True, canvas is meant to display post-processed data dim=1 - dimension of plots displayed on this canvas (int) name - name of canvas type (str) | PlotCanvasF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotCanvasF:
"""Canvas class for 1D post-processed data plots Properties: is_data - False, canvas is not meant to display raw measurement data is_filter - True, canvas is meant to display post-processed data dim=1 - dimension of plots displayed on this canvas (int) name - name of canvas type (str... | stack_v2_sparse_classes_75kplus_train_071778 | 5,257 | no_license | [
{
"docstring": "Initialization. Parameters: parent - parent window (wx.Window) id - id (int) xlabel - label and units of abscissa axis ([str,quantities]) ylabel - label and units of ordinate axis ([str,quantities]) xscale - abscissa scale type (linear or log) yscale - ordinate scale type (linear or log)",
"... | 6 | stack_v2_sparse_classes_30k_train_032841 | Implement the Python class `PlotCanvasF` described below.
Class description:
Canvas class for 1D post-processed data plots Properties: is_data - False, canvas is not meant to display raw measurement data is_filter - True, canvas is meant to display post-processed data dim=1 - dimension of plots displayed on this canva... | Implement the Python class `PlotCanvasF` described below.
Class description:
Canvas class for 1D post-processed data plots Properties: is_data - False, canvas is not meant to display raw measurement data is_filter - True, canvas is meant to display post-processed data dim=1 - dimension of plots displayed on this canva... | 712accd3534ca35ae4c5c7f1c9c33fc935552ca6 | <|skeleton|>
class PlotCanvasF:
"""Canvas class for 1D post-processed data plots Properties: is_data - False, canvas is not meant to display raw measurement data is_filter - True, canvas is meant to display post-processed data dim=1 - dimension of plots displayed on this canvas (int) name - name of canvas type (str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlotCanvasF:
"""Canvas class for 1D post-processed data plots Properties: is_data - False, canvas is not meant to display raw measurement data is_filter - True, canvas is meant to display post-processed data dim=1 - dimension of plots displayed on this canvas (int) name - name of canvas type (str)"""
def... | the_stack_v2_python_sparse | terapy_2/plot/canvasF.py | dawidgadziala/terapy | train | 0 |
6464a7edf66de13c179c81755ae48950d77441e0 | [
"self.wb = openpyxl.load_workbook(file_name)\nself.sheet = self.wb[sheet_name]\nself.list = list1",
"rows_data = list(self.sheet.rows)\ntitles = []\nfor title in rows_data[0]:\n titles.append(title.value)\ncases = []\nfor i in range(2, self.sheet.max_row + 1):\n data = []\n data.append(self.sheet.cell(ro... | <|body_start_0|>
self.wb = openpyxl.load_workbook(file_name)
self.sheet = self.wb[sheet_name]
self.list = list1
<|end_body_0|>
<|body_start_1|>
rows_data = list(self.sheet.rows)
titles = []
for title in rows_data[0]:
titles.append(title.value)
cases =... | 读取excel数据 | ReadExcel_dict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadExcel_dict:
"""读取excel数据"""
def __init__(self, file_name, sheet_name, list1):
"""这个是用例初始化读取对象的 :param file_name: 文件名字 --> str :param sheet_name: 表单名字 --> str :param list1: 指定列 --> list"""
<|body_0|>
def read_data(self):
"""按行读取数据 :return: 返回一个列表,列表中每个元素为一条用例"... | stack_v2_sparse_classes_75kplus_train_071779 | 3,739 | no_license | [
{
"docstring": "这个是用例初始化读取对象的 :param file_name: 文件名字 --> str :param sheet_name: 表单名字 --> str :param list1: 指定列 --> list",
"name": "__init__",
"signature": "def __init__(self, file_name, sheet_name, list1)"
},
{
"docstring": "按行读取数据 :return: 返回一个列表,列表中每个元素为一条用例",
"name": "read_data",
"sig... | 2 | stack_v2_sparse_classes_30k_train_037567 | Implement the Python class `ReadExcel_dict` described below.
Class description:
读取excel数据
Method signatures and docstrings:
- def __init__(self, file_name, sheet_name, list1): 这个是用例初始化读取对象的 :param file_name: 文件名字 --> str :param sheet_name: 表单名字 --> str :param list1: 指定列 --> list
- def read_data(self): 按行读取数据 :return:... | Implement the Python class `ReadExcel_dict` described below.
Class description:
读取excel数据
Method signatures and docstrings:
- def __init__(self, file_name, sheet_name, list1): 这个是用例初始化读取对象的 :param file_name: 文件名字 --> str :param sheet_name: 表单名字 --> str :param list1: 指定列 --> list
- def read_data(self): 按行读取数据 :return:... | f8a98389fa09f95e72914afa4935afc5c68eaccd | <|skeleton|>
class ReadExcel_dict:
"""读取excel数据"""
def __init__(self, file_name, sheet_name, list1):
"""这个是用例初始化读取对象的 :param file_name: 文件名字 --> str :param sheet_name: 表单名字 --> str :param list1: 指定列 --> list"""
<|body_0|>
def read_data(self):
"""按行读取数据 :return: 返回一个列表,列表中每个元素为一条用例"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReadExcel_dict:
"""读取excel数据"""
def __init__(self, file_name, sheet_name, list1):
"""这个是用例初始化读取对象的 :param file_name: 文件名字 --> str :param sheet_name: 表单名字 --> str :param list1: 指定列 --> list"""
self.wb = openpyxl.load_workbook(file_name)
self.sheet = self.wb[sheet_name]
self... | the_stack_v2_python_sparse | py_1816_ExcelClass/cankao.py | 2020668/python2019 | train | 0 |
bcd9349b766fdda15f514802c7a5703b1168ea98 | [
"super(ListMemberEvents, self).__init__(*args, **kwargs)\nself.endpoint = 'lists'\nself.list_id = None\nself.subscriber_hash = None",
"subscriber_hash = check_subscriber_hash(subscriber_hash)\nself.list_id = list_id\nself.subscriber_hash = subscriber_hash\nif 'name' not in data:\n raise KeyError('The list memb... | <|body_start_0|>
super(ListMemberEvents, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.list_id = None
self.subscriber_hash = None
<|end_body_0|>
<|body_start_1|>
subscriber_hash = check_subscriber_hash(subscriber_hash)
self.list_id = list_id
self.s... | Use the Events endpoint to collect website or in-app actions and trigger targeted automations. | ListMemberEvents | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListMemberEvents:
"""Use the Events endpoint to collect website or in-app actions and trigger targeted automations."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def create(self, list_id, subscriber_hash, data):
"""Add an event ... | stack_v2_sparse_classes_75kplus_train_071780 | 2,872 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Add an event for a list member. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The MD5 hash of the lowercase ver... | 3 | stack_v2_sparse_classes_30k_train_021094 | Implement the Python class `ListMemberEvents` described below.
Class description:
Use the Events endpoint to collect website or in-app actions and trigger targeted automations.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def create(self, list_id, subscriber_hash,... | Implement the Python class `ListMemberEvents` described below.
Class description:
Use the Events endpoint to collect website or in-app actions and trigger targeted automations.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def create(self, list_id, subscriber_hash,... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class ListMemberEvents:
"""Use the Events endpoint to collect website or in-app actions and trigger targeted automations."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def create(self, list_id, subscriber_hash, data):
"""Add an event ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListMemberEvents:
"""Use the Events endpoint to collect website or in-app actions and trigger targeted automations."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(ListMemberEvents, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.li... | the_stack_v2_python_sparse | mailchimp3/entities/listmemberevents.py | VingtCinq/python-mailchimp | train | 190 |
97dd115a64f90f415f15868879a592a9a349c4a2 | [
"self.dispatcher = dispatcher\nself.static_info = {'': DiscoInfoQuery()}\nself.static_items = {'': DiscoItemsQuery()}\nself.root_info = self.static_info['']\nself.root_items = self.static_items['']",
"self.dispatcher.registerHandler((self.DiscoInfoHandler, self))\nself.dispatcher.registerHandler((self.DiscoItemsH... | <|body_start_0|>
self.dispatcher = dispatcher
self.static_info = {'': DiscoInfoQuery()}
self.static_items = {'': DiscoItemsQuery()}
self.root_info = self.static_info['']
self.root_items = self.static_items['']
<|end_body_0|>
<|body_start_1|>
self.dispatcher.registerHandl... | Describe interaction dispatcher with service discovery. You can set your info or items using attributes static_info and static_items which are a dictionaries keys of which are nodes and values are instances of DiscoInfoQuery or DiscoItemsQuery appropriately For the root node you should use attributes root_info and root... | Disco | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Disco:
"""Describe interaction dispatcher with service discovery. You can set your info or items using attributes static_info and static_items which are a dictionaries keys of which are nodes and values are instances of DiscoInfoQuery or DiscoItemsQuery appropriately For the root node you should ... | stack_v2_sparse_classes_75kplus_train_071781 | 9,401 | no_license | [
{
"docstring": "Initialize class. Set dispatcher and base fields.",
"name": "__init__",
"signature": "def __init__(self, dispatcher)"
},
{
"docstring": "Initialize the service (Register all necessary handlers and add service discovery features as own. When called, the entity will be able to answ... | 5 | null | Implement the Python class `Disco` described below.
Class description:
Describe interaction dispatcher with service discovery. You can set your info or items using attributes static_info and static_items which are a dictionaries keys of which are nodes and values are instances of DiscoInfoQuery or DiscoItemsQuery appr... | Implement the Python class `Disco` described below.
Class description:
Describe interaction dispatcher with service discovery. You can set your info or items using attributes static_info and static_items which are a dictionaries keys of which are nodes and values are instances of DiscoInfoQuery or DiscoItemsQuery appr... | 2a53266ea9cf3989d4f3846cac627857c1cd7505 | <|skeleton|>
class Disco:
"""Describe interaction dispatcher with service discovery. You can set your info or items using attributes static_info and static_items which are a dictionaries keys of which are nodes and values are instances of DiscoInfoQuery or DiscoItemsQuery appropriately For the root node you should ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Disco:
"""Describe interaction dispatcher with service discovery. You can set your info or items using attributes static_info and static_items which are a dictionaries keys of which are nodes and values are instances of DiscoInfoQuery or DiscoItemsQuery appropriately For the root node you should use attribute... | the_stack_v2_python_sparse | twilix/disco.py | jbinary/twilix | train | 0 |
3b14eb9047cc2e89f5dfab481511f1759f9347bd | [
"res = []\n\ndef pre_order(root: TreeNode):\n if root:\n res.append(str(root.val))\n pre_order(root.left)\n pre_order(root.right)\npre_order(root)\nreturn ' '.join(res)",
"from collections import deque\nq = deque([int(d) for d in data.split()])\n\ndef build(minVal: int, maxVal: int) -> Tre... | <|body_start_0|>
res = []
def pre_order(root: TreeNode):
if root:
res.append(str(root.val))
pre_order(root.left)
pre_order(root.right)
pre_order(root)
return ' '.join(res)
<|end_body_0|>
<|body_start_1|>
from collectio... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
... | stack_v2_sparse_classes_75kplus_train_071782 | 1,506 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_026201 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | a390adeeb71e997b3c1a56c479825d4adda07ef9 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
res = []
def pre_order(root: TreeNode):
if root:
res.append(str(root.val))
pre_order(root.left)
pre_order(root.right)
pre_ord... | the_stack_v2_python_sparse | algorithms/python/serializeandDeserializeBST/serializeandDeserializeBST.py | MichelleZ/leetcode | train | 3 | |
a6d54e3d94d5674435b144b4f4f099c24316cbbe | [
"sub_list = re.findall('.{%s}' % self.word_len, substring)\nsub_dict = self.gen_dict(sub_list)\nif sub_dict == self.word_dic:\n return True\nreturn False",
"word_dic = dict.fromkeys(word_list, 0)\nfor w in word_list:\n word_dic[w] += 1\nreturn word_dic",
"if len(words) == 0:\n return []\nself.word_len ... | <|body_start_0|>
sub_list = re.findall('.{%s}' % self.word_len, substring)
sub_dict = self.gen_dict(sub_list)
if sub_dict == self.word_dic:
return True
return False
<|end_body_0|>
<|body_start_1|>
word_dic = dict.fromkeys(word_list, 0)
for w in word_list:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def check(self, substring):
""":type substring: str :rtype: bool"""
<|body_0|>
def gen_dict(word_list):
""":type word_list: List[str :rtype: dict"""
<|body_1|>
def findSubstring(self, s, words):
""":type s: str :type words: List[str] :r... | stack_v2_sparse_classes_75kplus_train_071783 | 2,182 | no_license | [
{
"docstring": ":type substring: str :rtype: bool",
"name": "check",
"signature": "def check(self, substring)"
},
{
"docstring": ":type word_list: List[str :rtype: dict",
"name": "gen_dict",
"signature": "def gen_dict(word_list)"
},
{
"docstring": ":type s: str :type words: List[... | 3 | stack_v2_sparse_classes_30k_train_007419 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def check(self, substring): :type substring: str :rtype: bool
- def gen_dict(word_list): :type word_list: List[str :rtype: dict
- def findSubstring(self, s, words): :type s: str ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def check(self, substring): :type substring: str :rtype: bool
- def gen_dict(word_list): :type word_list: List[str :rtype: dict
- def findSubstring(self, s, words): :type s: str ... | f8f3b0cdb47ee6bb4bf9bdc7c2a983f4a882d9dd | <|skeleton|>
class Solution:
def check(self, substring):
""":type substring: str :rtype: bool"""
<|body_0|>
def gen_dict(word_list):
""":type word_list: List[str :rtype: dict"""
<|body_1|>
def findSubstring(self, s, words):
""":type s: str :type words: List[str] :r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def check(self, substring):
""":type substring: str :rtype: bool"""
sub_list = re.findall('.{%s}' % self.word_len, substring)
sub_dict = self.gen_dict(sub_list)
if sub_dict == self.word_dic:
return True
return False
def gen_dict(word_list):
... | the_stack_v2_python_sparse | solutions/030-substring-with-concatenation-of-all-words/main.py | CallMeNP/leetcode | train | 0 | |
aee47da3a17df39128e1060c7d96903e985b32c5 | [
"self.track = segment.track\nself.samplerate = segment.track.samplerate\nself.comp_location = segment.comp_location\nself.duration = segment.duration\nself.volume_frames = volume_frames\nif self.duration != len(volume_frames):\n raise Exception('Duration must be same as volume frame length')",
"if channels == ... | <|body_start_0|>
self.track = segment.track
self.samplerate = segment.track.samplerate
self.comp_location = segment.comp_location
self.duration = segment.duration
self.volume_frames = volume_frames
if self.duration != len(volume_frames):
raise Exception('Durat... | Dynamic with manually-specified volume multiplier array | RawVolume | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawVolume:
"""Dynamic with manually-specified volume multiplier array"""
def __init__(self, segment, volume_frames):
"""Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to create dynamic :type segment: :py:class:`radiotool.compos... | stack_v2_sparse_classes_75kplus_train_071784 | 1,251 | permissive | [
{
"docstring": "Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to create dynamic :type segment: :py:class:`radiotool.composer.Segment` :param volume_frames: Raw volume multiplier frames :type volume_frames: numpy array",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_006955 | Implement the Python class `RawVolume` described below.
Class description:
Dynamic with manually-specified volume multiplier array
Method signatures and docstrings:
- def __init__(self, segment, volume_frames): Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to ... | Implement the Python class `RawVolume` described below.
Class description:
Dynamic with manually-specified volume multiplier array
Method signatures and docstrings:
- def __init__(self, segment, volume_frames): Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to ... | 7535a5aa02e45eab6355f4d37086690e4b254387 | <|skeleton|>
class RawVolume:
"""Dynamic with manually-specified volume multiplier array"""
def __init__(self, segment, volume_frames):
"""Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to create dynamic :type segment: :py:class:`radiotool.compos... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RawVolume:
"""Dynamic with manually-specified volume multiplier array"""
def __init__(self, segment, volume_frames):
"""Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to create dynamic :type segment: :py:class:`radiotool.composer.Segment` :... | the_stack_v2_python_sparse | radiotool/radiotool/composer/rawvolume.py | Morphinity/retarget_modified | train | 0 |
1657f5ba5f2d8f094993c3667a9bdc21375efe68 | [
"self.authdb = authdb\nself.fernet_secret = fernet_secret\nself.executor = executor",
"ipcheck = check_host(self.request.remote_ip)\nif not ipcheck:\n raise tornado.web.HTTPError(status_code=400)\npayload = decrypt_message(self.request.body, self.fernet_secret, 'debug-request')\nif not payload:\n raise torn... | <|body_start_0|>
self.authdb = authdb
self.fernet_secret = fernet_secret
self.executor = executor
<|end_body_0|>
<|body_start_1|>
ipcheck = check_host(self.request.remote_ip)
if not ipcheck:
raise tornado.web.HTTPError(status_code=400)
payload = decrypt_messa... | This just echoes back whatever we send. Useful to see if the encryption is working as intended. | EchoHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EchoHandler:
"""This just echoes back whatever we send. Useful to see if the encryption is working as intended."""
def initialize(self, authdb, fernet_secret, executor):
"""This sets up stuff."""
<|body_0|>
async def post(self):
"""Handles the incoming POST reque... | stack_v2_sparse_classes_75kplus_train_071785 | 3,889 | permissive | [
{
"docstring": "This sets up stuff.",
"name": "initialize",
"signature": "def initialize(self, authdb, fernet_secret, executor)"
},
{
"docstring": "Handles the incoming POST request.",
"name": "post",
"signature": "async def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019048 | Implement the Python class `EchoHandler` described below.
Class description:
This just echoes back whatever we send. Useful to see if the encryption is working as intended.
Method signatures and docstrings:
- def initialize(self, authdb, fernet_secret, executor): This sets up stuff.
- async def post(self): Handles th... | Implement the Python class `EchoHandler` described below.
Class description:
This just echoes back whatever we send. Useful to see if the encryption is working as intended.
Method signatures and docstrings:
- def initialize(self, authdb, fernet_secret, executor): This sets up stuff.
- async def post(self): Handles th... | 9a038e3734bb8f66115384a1e0917042a4bc4681 | <|skeleton|>
class EchoHandler:
"""This just echoes back whatever we send. Useful to see if the encryption is working as intended."""
def initialize(self, authdb, fernet_secret, executor):
"""This sets up stuff."""
<|body_0|>
async def post(self):
"""Handles the incoming POST reque... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EchoHandler:
"""This just echoes back whatever we send. Useful to see if the encryption is working as intended."""
def initialize(self, authdb, fernet_secret, executor):
"""This sets up stuff."""
self.authdb = authdb
self.fernet_secret = fernet_secret
self.executor = execu... | the_stack_v2_python_sparse | authnzerver/debughandler.py | waqasbhatti/authnzerver | train | 3 |
72dc28be21e84567063e62a7b57fe638d79ba093 | [
"networks = self.sf.query_all(format_soql('SELECT Id FROM Network WHERE Name = {network_name} LIMIT 1', network_name=network_name))\nif not networks['records']:\n raise SalesforceException(f'No Network record found with Name \"{network_name}\"')\nself.logger.info(f'Creating NetworkMemberGroup records for {networ... | <|body_start_0|>
networks = self.sf.query_all(format_soql('SELECT Id FROM Network WHERE Name = {network_name} LIMIT 1', network_name=network_name))
if not networks['records']:
raise SalesforceException(f'No Network record found with Name "{network_name}"')
self.logger.info(f'Creating... | Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_name - Profiles with Names in profile_names - Permission Sets with Names in permission_set_nam... | CreateNetworkMemberGroups | [
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateNetworkMemberGroups:
"""Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_name - Profiles with Names in profile_nam... | stack_v2_sparse_classes_75kplus_train_071786 | 6,853 | permissive | [
{
"docstring": "Returns Id of Network record with Name network_name. Raises a SalesforceException if no Network is found.",
"name": "_get_network_id",
"signature": "def _get_network_id(self, network_name: str) -> str"
},
{
"docstring": "Collect existing NetworkMemberGroup Parent IDs (associated ... | 6 | stack_v2_sparse_classes_30k_train_049921 | Implement the Python class `CreateNetworkMemberGroups` described below.
Class description:
Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_na... | Implement the Python class `CreateNetworkMemberGroups` described below.
Class description:
Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_na... | 9ccf3c9566f78c6e9102ac214db30470cef660c1 | <|skeleton|>
class CreateNetworkMemberGroups:
"""Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_name - Profiles with Names in profile_nam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateNetworkMemberGroups:
"""Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_name - Profiles with Names in profile_names - Permissi... | the_stack_v2_python_sparse | cumulusci/tasks/salesforce/network_member_group.py | SFDO-Tooling/CumulusCI | train | 226 |
38182815757a80e6ca3170965c74fd8dcd2d826c | [
"if approvers is None:\n approvers = []\nsuper(GRRFileCollector, self).__init__(hostname, reason, grr_server_url, grr_auth=grr_auth, approvers=approvers, verbose=verbose, keepalive=keepalive)\nself.files = files",
"self._client = self._GetClient(self._client_id, self.reason, self.approvers)\nfile_list = self.f... | <|body_start_0|>
if approvers is None:
approvers = []
super(GRRFileCollector, self).__init__(hostname, reason, grr_server_url, grr_auth=grr_auth, approvers=approvers, verbose=verbose, keepalive=keepalive)
self.files = files
<|end_body_0|>
<|body_start_1|>
self._client = self... | File collector for GRR flows. Attributes: files: list of file paths. reason: Justification for GRR access. approvers: list of GRR approval recipients. | GRRFileCollector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRRFileCollector:
"""File collector for GRR flows. Attributes: files: list of file paths. reason: Justification for GRR access. approvers: list of GRR approval recipients."""
def __init__(self, hostname, reason, grr_server_url, grr_auth, files=None, approvers=None, verbose=False, keepalive=F... | stack_v2_sparse_classes_75kplus_train_071787 | 36,928 | permissive | [
{
"docstring": "Initializes a GRR file collector. Args: hostname: hostname of machine. reason: justification for GRR access. grr_server_url: GRR server URL. grr_auth: Tuple containing a (username, password) combination. files: list of file paths. approvers: list of GRR approval recipients. verbose: toggle for v... | 2 | stack_v2_sparse_classes_30k_train_003312 | Implement the Python class `GRRFileCollector` described below.
Class description:
File collector for GRR flows. Attributes: files: list of file paths. reason: Justification for GRR access. approvers: list of GRR approval recipients.
Method signatures and docstrings:
- def __init__(self, hostname, reason, grr_server_u... | Implement the Python class `GRRFileCollector` described below.
Class description:
File collector for GRR flows. Attributes: files: list of file paths. reason: Justification for GRR access. approvers: list of GRR approval recipients.
Method signatures and docstrings:
- def __init__(self, hostname, reason, grr_server_u... | 0ef4bfe32fcda6acc9ea6e81d5186afb5c7d3275 | <|skeleton|>
class GRRFileCollector:
"""File collector for GRR flows. Attributes: files: list of file paths. reason: Justification for GRR access. approvers: list of GRR approval recipients."""
def __init__(self, hostname, reason, grr_server_url, grr_auth, files=None, approvers=None, verbose=False, keepalive=F... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GRRFileCollector:
"""File collector for GRR flows. Attributes: files: list of file paths. reason: Justification for GRR access. approvers: list of GRR approval recipients."""
def __init__(self, hostname, reason, grr_server_url, grr_auth, files=None, approvers=None, verbose=False, keepalive=False):
... | the_stack_v2_python_sparse | dftimewolf/lib/collectors/grr.py | berggren/dftimewolf | train | 0 |
506d7a651b513b3474ac3b5cc718e0a9e9331929 | [
"length = 0\nhead_0 = head\nwhile head_0 is not None:\n head_0 = head_0.next\n length += 1\nidx_n = length - n\nif idx_n == 0:\n head = head.next\n return head\nhead_0, cur, idx = (head, head_0, 0)\nwhile idx < idx_n:\n cur, head_0 = (head_0, head_0.next)\n idx += 1\nif head_0 is None:\n cur.ne... | <|body_start_0|>
length = 0
head_0 = head
while head_0 is not None:
head_0 = head_0.next
length += 1
idx_n = length - n
if idx_n == 0:
head = head.next
return head
head_0, cur, idx = (head, head_0, 0)
while idx < idx... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd1(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_071788 | 1,857 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd1",
"signature": "def removeNthFromEnd1(self, head, n)"
},
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(sel... | 2 | stack_v2_sparse_classes_30k_train_013955 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd1(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd1(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode... | 96e847591aa6ea7ea285dbcfc1c9bcfc32026de5 | <|skeleton|>
class Solution:
def removeNthFromEnd1(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeNthFromEnd1(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
length = 0
head_0 = head
while head_0 is not None:
head_0 = head_0.next
length += 1
idx_n = length - n
if idx_n == 0:
hea... | the_stack_v2_python_sparse | LinkList/L19_remove-nth-node-from-end-of-list.py | lihujun101/LeetCode | train | 0 | |
f68112ea98f56701e3febc702460dfc9d70db16f | [
"model_type = Path(model).name.rsplit('.', 1)[1]\nruntime_map = model_runtime_map[model_type]\nfor name, rt in runtime_map.items():\n print('Runtime {} <{}>: {}'.format(name, rt.__name__, 'available' if rt.is_available() else 'unavailable'))\nself.model = create_runtime_model(model, runtime)\nif model_type == 'p... | <|body_start_0|>
model_type = Path(model).name.rsplit('.', 1)[1]
runtime_map = model_runtime_map[model_type]
for name, rt in runtime_map.items():
print('Runtime {} <{}>: {}'.format(name, rt.__name__, 'available' if rt.is_available() else 'unavailable'))
self.model = create_ru... | Vortex Prediction Pipeline API for Vortex IR model | IRPredictionPipeline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IRPredictionPipeline:
"""Vortex Prediction Pipeline API for Vortex IR model"""
def __init__(self, model: Union[str, Path], runtime: str='cpu'):
"""Class initialization Args: model (Union[str,Path]): path to Vortex IR model, file with extension '.onnx' or '.pt' runtime (str, optional)... | stack_v2_sparse_classes_75kplus_train_071789 | 21,503 | no_license | [
{
"docstring": "Class initialization Args: model (Union[str,Path]): path to Vortex IR model, file with extension '.onnx' or '.pt' runtime (str, optional): backend runtime to be selected for model's computation. Defaults to 'cpu'. Example: ```python from vortex.development.core.pipelines import IRPredictionPipel... | 2 | null | Implement the Python class `IRPredictionPipeline` described below.
Class description:
Vortex Prediction Pipeline API for Vortex IR model
Method signatures and docstrings:
- def __init__(self, model: Union[str, Path], runtime: str='cpu'): Class initialization Args: model (Union[str,Path]): path to Vortex IR model, fil... | Implement the Python class `IRPredictionPipeline` described below.
Class description:
Vortex Prediction Pipeline API for Vortex IR model
Method signatures and docstrings:
- def __init__(self, model: Union[str, Path], runtime: str='cpu'): Class initialization Args: model (Union[str,Path]): path to Vortex IR model, fil... | 1532db8447d03e75d5ec26f93111270a4ccb7a7e | <|skeleton|>
class IRPredictionPipeline:
"""Vortex Prediction Pipeline API for Vortex IR model"""
def __init__(self, model: Union[str, Path], runtime: str='cpu'):
"""Class initialization Args: model (Union[str,Path]): path to Vortex IR model, file with extension '.onnx' or '.pt' runtime (str, optional)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IRPredictionPipeline:
"""Vortex Prediction Pipeline API for Vortex IR model"""
def __init__(self, model: Union[str, Path], runtime: str='cpu'):
"""Class initialization Args: model (Union[str,Path]): path to Vortex IR model, file with extension '.onnx' or '.pt' runtime (str, optional): backend run... | the_stack_v2_python_sparse | src/development/vortex/development/core/pipelines/prediction_pipeline.py | jesslynsepthiaa/vortex | train | 0 |
1b6ba4a0e8c4993d17518255b568cd541ba12ddc | [
"super(_ResponseCallbackManager, self).validate_callback(callback)\nif isinstance(callback, (type, types.ClassType)):\n if not issubclass(callback, ResponseCallback):\n raise ValueError('Type mismatch on callback argument')\nelif not issubclass(callback.__class__, ResponseCallback):\n raise ValueError(... | <|body_start_0|>
super(_ResponseCallbackManager, self).validate_callback(callback)
if isinstance(callback, (type, types.ClassType)):
if not issubclass(callback, ResponseCallback):
raise ValueError('Type mismatch on callback argument')
elif not issubclass(callback.__cl... | Manager for {@link ResponseCallback} message callbacks. | _ResponseCallbackManager | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ResponseCallbackManager:
"""Manager for {@link ResponseCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid ResponseCallback. :param callback: Callback to validate."""
<|body_0|>
def handle_fire(self, response_call... | stack_v2_sparse_classes_75kplus_train_071790 | 12,867 | permissive | [
{
"docstring": "Validates if `callback` is a valid ResponseCallback. :param callback: Callback to validate.",
"name": "validate_callback",
"signature": "def validate_callback(self, callback)"
},
{
"docstring": "Runs `response_callback` for `response`. :param response_callback: {@link dxlclient.c... | 2 | stack_v2_sparse_classes_30k_train_001673 | Implement the Python class `_ResponseCallbackManager` described below.
Class description:
Manager for {@link ResponseCallback} message callbacks.
Method signatures and docstrings:
- def validate_callback(self, callback): Validates if `callback` is a valid ResponseCallback. :param callback: Callback to validate.
- def... | Implement the Python class `_ResponseCallbackManager` described below.
Class description:
Manager for {@link ResponseCallback} message callbacks.
Method signatures and docstrings:
- def validate_callback(self, callback): Validates if `callback` is a valid ResponseCallback. :param callback: Callback to validate.
- def... | 7bbc003592022f5776006d467f591a214a119013 | <|skeleton|>
class _ResponseCallbackManager:
"""Manager for {@link ResponseCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid ResponseCallback. :param callback: Callback to validate."""
<|body_0|>
def handle_fire(self, response_call... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _ResponseCallbackManager:
"""Manager for {@link ResponseCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid ResponseCallback. :param callback: Callback to validate."""
super(_ResponseCallbackManager, self).validate_callback(callback... | the_stack_v2_python_sparse | src/main/resources/dxlclient/_callback_manager.py | att/OpenDXLJythonClient | train | 4 |
cd5c83b8e8f0d942542be6995e472c513cc880d1 | [
"book = BookInfo.objects.latest('id')\nserializer = BookInfoSerializer(book)\nreturn Response(serializer.data)",
"book = self.get_object()\nbook.bread = request.data.get('bread')\nbook.save()\nserializer = BookInfoSerializer(book)\nreturn Response(serializer.data)"
] | <|body_start_0|>
book = BookInfo.objects.latest('id')
serializer = BookInfoSerializer(book)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
book = self.get_object()
book.bread = request.data.get('bread')
book.save()
serializer = BookInfoSerialize... | BookViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookViewSet:
def latest(self, request):
"""获取倒序后的最新书籍数据"""
<|body_0|>
def update_bread(self, request, pk):
"""修改书籍阅读量"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
book = BookInfo.objects.latest('id')
serializer = BookInfoSerializer(book)
... | stack_v2_sparse_classes_75kplus_train_071791 | 6,830 | no_license | [
{
"docstring": "获取倒序后的最新书籍数据",
"name": "latest",
"signature": "def latest(self, request)"
},
{
"docstring": "修改书籍阅读量",
"name": "update_bread",
"signature": "def update_bread(self, request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000599 | Implement the Python class `BookViewSet` described below.
Class description:
Implement the BookViewSet class.
Method signatures and docstrings:
- def latest(self, request): 获取倒序后的最新书籍数据
- def update_bread(self, request, pk): 修改书籍阅读量 | Implement the Python class `BookViewSet` described below.
Class description:
Implement the BookViewSet class.
Method signatures and docstrings:
- def latest(self, request): 获取倒序后的最新书籍数据
- def update_bread(self, request, pk): 修改书籍阅读量
<|skeleton|>
class BookViewSet:
def latest(self, request):
"""获取倒序后的最新书... | ecccb7146c3fdc6a0a4d10127900e2b15e45ce73 | <|skeleton|>
class BookViewSet:
def latest(self, request):
"""获取倒序后的最新书籍数据"""
<|body_0|>
def update_bread(self, request, pk):
"""修改书籍阅读量"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookViewSet:
def latest(self, request):
"""获取倒序后的最新书籍数据"""
book = BookInfo.objects.latest('id')
serializer = BookInfoSerializer(book)
return Response(serializer.data)
def update_bread(self, request, pk):
"""修改书籍阅读量"""
book = self.get_object()
book.b... | the_stack_v2_python_sparse | booktest/views.py | ehananel-lirf23/demo | train | 0 | |
53f36807f85cb5c6de0e623b2795c303145f83d3 | [
"super(MultiLayerPerceptron, self).__init__()\nself.dims = [input_dim] + hidden_dims\nif isinstance(activation, str):\n self.activation = getattr(F, activation)\nelse:\n logger.info(f'Warning, activation passed {activation} is not string and ignored')\n self.activation = None\nif dropout > 0:\n self.dro... | <|body_start_0|>
super(MultiLayerPerceptron, self).__init__()
self.dims = [input_dim] + hidden_dims
if isinstance(activation, str):
self.activation = getattr(F, activation)
else:
logger.info(f'Warning, activation passed {activation} is not string and ignored')
... | Multi-layer Perceptron. Note there is no activation or dropout in the last layer. | MultiLayerPerceptron | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLayerPerceptron:
"""Multi-layer Perceptron. Note there is no activation or dropout in the last layer."""
def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None:
"""Initialize multi-layer perceptron. Args: input_dim: input dim... | stack_v2_sparse_classes_75kplus_train_071792 | 15,380 | permissive | [
{
"docstring": "Initialize multi-layer perceptron. Args: input_dim: input dimension hidden_dim: hidden dimensions activation: activation function dropout: dropout rate",
"name": "__init__",
"signature": "def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0)... | 2 | stack_v2_sparse_classes_30k_train_037477 | Implement the Python class `MultiLayerPerceptron` described below.
Class description:
Multi-layer Perceptron. Note there is no activation or dropout in the last layer.
Method signatures and docstrings:
- def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None: Init... | Implement the Python class `MultiLayerPerceptron` described below.
Class description:
Multi-layer Perceptron. Note there is no activation or dropout in the last layer.
Method signatures and docstrings:
- def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None: Init... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class MultiLayerPerceptron:
"""Multi-layer Perceptron. Note there is no activation or dropout in the last layer."""
def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None:
"""Initialize multi-layer perceptron. Args: input_dim: input dim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiLayerPerceptron:
"""Multi-layer Perceptron. Note there is no activation or dropout in the last layer."""
def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None:
"""Initialize multi-layer perceptron. Args: input_dim: input dimension hidden... | the_stack_v2_python_sparse | src/gt4sd/algorithms/generation/diffusion/geodiff/model/layers.py | GT4SD/gt4sd-core | train | 239 |
196dc6fc6c894390b640e46b4fee0c27ed71b6e9 | [
"super(dilnet, self).__init__()\nnbl = kwargs.get('layers', [3, 3, 3, 3])\ndilation_values_1 = torch.arange(2, 2 * nbl[1] + 1, 2).tolist()\npadding_values_1 = dilation_values_1.copy()\ndilation_values_2 = torch.arange(2, 2 * nbl[2] + 1, 2).tolist()\npadding_values_2 = dilation_values_2.copy()\ndropout_vals = [0.3, ... | <|body_start_0|>
super(dilnet, self).__init__()
nbl = kwargs.get('layers', [3, 3, 3, 3])
dilation_values_1 = torch.arange(2, 2 * nbl[1] + 1, 2).tolist()
padding_values_1 = dilation_values_1.copy()
dilation_values_2 = torch.arange(2, 2 * nbl[2] + 1, 2).tolist()
padding_val... | Builds a fully convolutional neural network model by utilizing a combination of regular and dilated convolutions Args: nb_classes: Number of classes in the ground truth nb_filters: Number of filters in first and last convolutional blocks (gets multiplied by 2 for the bottleneck layer) dropout: Add dropouts to the bottl... | dilnet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dilnet:
"""Builds a fully convolutional neural network model by utilizing a combination of regular and dilated convolutions Args: nb_classes: Number of classes in the ground truth nb_filters: Number of filters in first and last convolutional blocks (gets multiplied by 2 for the bottleneck layer) ... | stack_v2_sparse_classes_75kplus_train_071793 | 15,999 | permissive | [
{
"docstring": "Initializes model parameters",
"name": "__init__",
"signature": "def __init__(self, nb_classes: int=1, nb_filters: int=25, dropout: bool=False, batch_norm: bool=True, upsampling_mode: str='bilinear', **kwargs: List[int]) -> None"
},
{
"docstring": "Defines a forward pass",
"n... | 2 | null | Implement the Python class `dilnet` described below.
Class description:
Builds a fully convolutional neural network model by utilizing a combination of regular and dilated convolutions Args: nb_classes: Number of classes in the ground truth nb_filters: Number of filters in first and last convolutional blocks (gets mul... | Implement the Python class `dilnet` described below.
Class description:
Builds a fully convolutional neural network model by utilizing a combination of regular and dilated convolutions Args: nb_classes: Number of classes in the ground truth nb_filters: Number of filters in first and last convolutional blocks (gets mul... | 6d187296074143d017ca8fc60302364cd946b180 | <|skeleton|>
class dilnet:
"""Builds a fully convolutional neural network model by utilizing a combination of regular and dilated convolutions Args: nb_classes: Number of classes in the ground truth nb_filters: Number of filters in first and last convolutional blocks (gets multiplied by 2 for the bottleneck layer) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class dilnet:
"""Builds a fully convolutional neural network model by utilizing a combination of regular and dilated convolutions Args: nb_classes: Number of classes in the ground truth nb_filters: Number of filters in first and last convolutional blocks (gets multiplied by 2 for the bottleneck layer) dropout: Add ... | the_stack_v2_python_sparse | atomai/nets/fcnn.py | pycroscopy/atomai | train | 157 |
d834b47f3b09561143501689a65831fc73aaac19 | [
"decorator_name = ''.join(('@', MultiNode.__name__.lower()))\nself.decorator_name = decorator_name\nself.args = args\nself.kwargs = kwargs\nself.scope = CONTEXT.in_pycompss()\nself.core_element = None\nself.core_element_configured = False\nif self.scope:\n check_arguments(MANDATORY_ARGUMENTS, DEPRECATED_ARGUMENT... | <|body_start_0|>
decorator_name = ''.join(('@', MultiNode.__name__.lower()))
self.decorator_name = decorator_name
self.args = args
self.kwargs = kwargs
self.scope = CONTEXT.in_pycompss()
self.core_element = None
self.core_element_configured = False
if self... | MultiNode decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on MultiNode task creation. | MultiNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNode:
"""MultiNode decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on MultiNode task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorator. s... | stack_v2_sparse_classes_75kplus_train_071794 | 7,975 | permissive | [
{
"docstring": "Store arguments passed to the decorator. self = itself. args = not used. kwargs = dictionary with the given constraints. :param args: Arguments :param kwargs: Keyword arguments",
"name": "__init__",
"signature": "def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None"
},
... | 3 | stack_v2_sparse_classes_30k_train_054719 | Implement the Python class `MultiNode` described below.
Class description:
MultiNode decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on MultiNode task creation.
Method signatures and docstrings:
- def __init__(self, *args: typing.Any, **kwargs: typing... | Implement the Python class `MultiNode` described below.
Class description:
MultiNode decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on MultiNode task creation.
Method signatures and docstrings:
- def __init__(self, *args: typing.Any, **kwargs: typing... | 5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092 | <|skeleton|>
class MultiNode:
"""MultiNode decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on MultiNode task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorator. s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiNode:
"""MultiNode decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on MultiNode task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorator. self = itself.... | the_stack_v2_python_sparse | compss/programming_model/bindings/python/src/pycompss/api/multinode.py | bsc-wdc/compss | train | 39 |
6280d0f3a5cdc2278b20dba50ad5b3e0e1e7f873 | [
"if predictor is None:\n raise ValueError('PredictionHandler must have a predictor class passed to the init function.')\nself._predictor = predictor()\nself._predictor.load(artifacts_uri)",
"request_body = await request.body()\ncontent_type = handler_utils.get_content_type_from_headers(request.headers)\npredic... | <|body_start_0|>
if predictor is None:
raise ValueError('PredictionHandler must have a predictor class passed to the init function.')
self._predictor = predictor()
self._predictor.load(artifacts_uri)
<|end_body_0|>
<|body_start_1|>
request_body = await request.body()
... | Default prediction handler for the prediction requests sent to the application. | PredictionHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictionHandler:
"""Default prediction handler for the prediction requests sent to the application."""
def __init__(self, artifacts_uri: str, predictor: Optional[Type[Predictor]]=None):
"""Initializes a Handler instance. Args: artifacts_uri (str): Required. The value of the environ... | stack_v2_sparse_classes_75kplus_train_071795 | 4,584 | permissive | [
{
"docstring": "Initializes a Handler instance. Args: artifacts_uri (str): Required. The value of the environment variable AIP_STORAGE_URI. predictor (Type[Predictor]): Optional. The Predictor class this handler uses to initiate predictor instance if given. Raises: ValueError: If predictor is None.",
"name"... | 2 | null | Implement the Python class `PredictionHandler` described below.
Class description:
Default prediction handler for the prediction requests sent to the application.
Method signatures and docstrings:
- def __init__(self, artifacts_uri: str, predictor: Optional[Type[Predictor]]=None): Initializes a Handler instance. Args... | Implement the Python class `PredictionHandler` described below.
Class description:
Default prediction handler for the prediction requests sent to the application.
Method signatures and docstrings:
- def __init__(self, artifacts_uri: str, predictor: Optional[Type[Predictor]]=None): Initializes a Handler instance. Args... | 76b95b92c1d3b87c72d754d8c02b1bca652b9a27 | <|skeleton|>
class PredictionHandler:
"""Default prediction handler for the prediction requests sent to the application."""
def __init__(self, artifacts_uri: str, predictor: Optional[Type[Predictor]]=None):
"""Initializes a Handler instance. Args: artifacts_uri (str): Required. The value of the environ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PredictionHandler:
"""Default prediction handler for the prediction requests sent to the application."""
def __init__(self, artifacts_uri: str, predictor: Optional[Type[Predictor]]=None):
"""Initializes a Handler instance. Args: artifacts_uri (str): Required. The value of the environment variable... | the_stack_v2_python_sparse | google/cloud/aiplatform/prediction/handler.py | googleapis/python-aiplatform | train | 418 |
d6f49ba349e6f5ebe4536c845bad0af64518df0a | [
"if directory == None:\n directory = Settings.Settings().data_directory + '\\\\GlobalWarming'\nif not directory.endswith('\\\\'):\n directory += '\\\\'\nself.directory = directory\nraw_lines = self.__loadLines__('CodeTemplates.txt')\nlines = []\nself.codes_per_document = []\nfor l in raw_lines:\n ltrim = l... | <|body_start_0|>
if directory == None:
directory = Settings.Settings().data_directory + '\\GlobalWarming'
if not directory.endswith('\\'):
directory += '\\'
self.directory = directory
raw_lines = self.__loadLines__('CodeTemplates.txt')
lines = []
s... | Creates an object with .codes and .templates properties | GwCodeTemplates | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GwCodeTemplates:
"""Creates an object with .codes and .templates properties"""
def __init__(self, directory=None):
"""Constructor"""
<|body_0|>
def __loadLines__(self, fName):
"""Loads lines from a file and returns as a list file => []"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_071796 | 1,896 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, directory=None)"
},
{
"docstring": "Loads lines from a file and returns as a list file => []",
"name": "__loadLines__",
"signature": "def __loadLines__(self, fName)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046168 | Implement the Python class `GwCodeTemplates` described below.
Class description:
Creates an object with .codes and .templates properties
Method signatures and docstrings:
- def __init__(self, directory=None): Constructor
- def __loadLines__(self, fName): Loads lines from a file and returns as a list file => [] | Implement the Python class `GwCodeTemplates` described below.
Class description:
Creates an object with .codes and .templates properties
Method signatures and docstrings:
- def __init__(self, directory=None): Constructor
- def __loadLines__(self, fName): Loads lines from a file and returns as a list file => []
<|ske... | 2bc2914ce93fcef6dbd26f8097eec20b7d0e476d | <|skeleton|>
class GwCodeTemplates:
"""Creates an object with .codes and .templates properties"""
def __init__(self, directory=None):
"""Constructor"""
<|body_0|>
def __loadLines__(self, fName):
"""Loads lines from a file and returns as a list file => []"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GwCodeTemplates:
"""Creates an object with .codes and .templates properties"""
def __init__(self, directory=None):
"""Constructor"""
if directory == None:
directory = Settings.Settings().data_directory + '\\GlobalWarming'
if not directory.endswith('\\'):
di... | the_stack_v2_python_sparse | Data/GlobalWarming/GwCodeTemplates.py | simonhughes22/PythonNlpResearch | train | 17 |
b562544176835ff6c5e01f5bbf6eeaac59ff8634 | [
"self.primary = None\nself.secondary = None\nself.initialize(jconfig, kwargs)",
"cachesize = jconfig.get('cachesize', None)\nadminuser = jconfig.get('adminuser', None)\nif 'primary' in jconfig:\n self.primary = self.create_journal(jconfig['primary'], kwargs, cachesize, adminuser)\nif 'secondary' in jconfig:\n ... | <|body_start_0|>
self.primary = None
self.secondary = None
self.initialize(jconfig, kwargs)
<|end_body_0|>
<|body_start_1|>
cachesize = jconfig.get('cachesize', None)
adminuser = jconfig.get('adminuser', None)
if 'primary' in jconfig:
self.primary = self.crea... | Creates journal objects for primary and secondary | Journal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Journal:
"""Creates journal objects for primary and secondary"""
def __init__(self, jconfig, kwargs):
"""Constructor for journal"""
<|body_0|>
def initialize(self, jconfig, kwargs):
"""creates journal objects"""
<|body_1|>
def create_journal(self, jc... | stack_v2_sparse_classes_75kplus_train_071797 | 2,954 | permissive | [
{
"docstring": "Constructor for journal",
"name": "__init__",
"signature": "def __init__(self, jconfig, kwargs)"
},
{
"docstring": "creates journal objects",
"name": "initialize",
"signature": "def initialize(self, jconfig, kwargs)"
},
{
"docstring": "get the name and create obj"... | 5 | stack_v2_sparse_classes_30k_train_015126 | Implement the Python class `Journal` described below.
Class description:
Creates journal objects for primary and secondary
Method signatures and docstrings:
- def __init__(self, jconfig, kwargs): Constructor for journal
- def initialize(self, jconfig, kwargs): creates journal objects
- def create_journal(self, jconf,... | Implement the Python class `Journal` described below.
Class description:
Creates journal objects for primary and secondary
Method signatures and docstrings:
- def __init__(self, jconfig, kwargs): Constructor for journal
- def initialize(self, jconfig, kwargs): creates journal objects
- def create_journal(self, jconf,... | a233ad85b56ff43a81544386a0730bee590de8fc | <|skeleton|>
class Journal:
"""Creates journal objects for primary and secondary"""
def __init__(self, jconfig, kwargs):
"""Constructor for journal"""
<|body_0|>
def initialize(self, jconfig, kwargs):
"""creates journal objects"""
<|body_1|>
def create_journal(self, jc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Journal:
"""Creates journal objects for primary and secondary"""
def __init__(self, jconfig, kwargs):
"""Constructor for journal"""
self.primary = None
self.secondary = None
self.initialize(jconfig, kwargs)
def initialize(self, jconfig, kwargs):
"""creates jou... | the_stack_v2_python_sparse | lib/python/journal/mjournal.py | lisajoseph/journal | train | 0 |
e19a62a335ab1546c4220d5ac7355556d135c1c7 | [
"if isinstance(instance_or_queryset, Model):\n queryset = instance_or_queryset.__class__._default_manager.filter(pk=instance_or_queryset.pk)\nelif isinstance(instance_or_queryset, QuerySet):\n queryset = instance_or_queryset\nelse:\n raise ValueError('Only django model instances or QuerySets can be process... | <|body_start_0|>
if isinstance(instance_or_queryset, Model):
queryset = instance_or_queryset.__class__._default_manager.filter(pk=instance_or_queryset.pk)
elif isinstance(instance_or_queryset, QuerySet):
queryset = instance_or_queryset
else:
raise ValueError('... | A class for creating sets of images from a VersatileImageField | VersatileImageFieldWarmer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersatileImageFieldWarmer:
"""A class for creating sets of images from a VersatileImageField"""
def __init__(self, instance_or_queryset, rendition_key_set, image_attr, verbose=False):
"""Arguments: `instance_or_queryset`: A django model instance or QuerySet `rendition_key_set`: Eithe... | stack_v2_sparse_classes_75kplus_train_071798 | 5,664 | permissive | [
{
"docstring": "Arguments: `instance_or_queryset`: A django model instance or QuerySet `rendition_key_set`: Either a string that corresponds to a key on settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS or an iterable of 2-tuples, both strings: [0]: The 'name' of the image size. [1]: A VersatileImageField 'size_k... | 3 | stack_v2_sparse_classes_30k_train_042255 | Implement the Python class `VersatileImageFieldWarmer` described below.
Class description:
A class for creating sets of images from a VersatileImageField
Method signatures and docstrings:
- def __init__(self, instance_or_queryset, rendition_key_set, image_attr, verbose=False): Arguments: `instance_or_queryset`: A dja... | Implement the Python class `VersatileImageFieldWarmer` described below.
Class description:
A class for creating sets of images from a VersatileImageField
Method signatures and docstrings:
- def __init__(self, instance_or_queryset, rendition_key_set, image_attr, verbose=False): Arguments: `instance_or_queryset`: A dja... | f177150ace33db981aa5b8dee048b7ddd8508ef7 | <|skeleton|>
class VersatileImageFieldWarmer:
"""A class for creating sets of images from a VersatileImageField"""
def __init__(self, instance_or_queryset, rendition_key_set, image_attr, verbose=False):
"""Arguments: `instance_or_queryset`: A django model instance or QuerySet `rendition_key_set`: Eithe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VersatileImageFieldWarmer:
"""A class for creating sets of images from a VersatileImageField"""
def __init__(self, instance_or_queryset, rendition_key_set, image_attr, verbose=False):
"""Arguments: `instance_or_queryset`: A django model instance or QuerySet `rendition_key_set`: Either a string th... | the_stack_v2_python_sparse | versatileimagefield/image_warmer.py | respondcreate/django-versatileimagefield | train | 372 |
2e533441329ce3aff46516905ecb3c8230d49583 | [
"super().__init__()\nself.device = device\nself.rgb_dim = rgb_dim\nself.name_prefix = name_prefix\nself.channels = {'16': int(256 * dim_scale), '32': int(256 * dim_scale), '64': int(256 * dim_scale), '128': int(256 * dim_scale), '256': int(256 * dim_scale), '512': int(256 * dim_scale), '1024': int(256 * dim_scale)}... | <|body_start_0|>
super().__init__()
self.device = device
self.rgb_dim = rgb_dim
self.name_prefix = name_prefix
self.channels = {'16': int(256 * dim_scale), '32': int(256 * dim_scale), '64': int(256 * dim_scale), '128': int(256 * dim_scale), '256': int(256 * dim_scale), '512': int... | INRNetwork_Skip_Prog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class INRNetwork_Skip_Prog:
def __init__(self, input_dim, style_dim, dim_scale=1, rgb_dim=3, device=None, name_prefix='inr', **kwargs):
""":param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwargs:"""
<|body_0|>
def forward(self, input, style_dict, img_size, **... | stack_v2_sparse_classes_75kplus_train_071799 | 23,234 | permissive | [
{
"docstring": ":param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwargs:",
"name": "__init__",
"signature": "def __init__(self, input_dim, style_dim, dim_scale=1, rgb_dim=3, device=None, name_prefix='inr', **kwargs)"
},
{
"docstring": ":param input: points xyz, (b, num_poin... | 2 | null | Implement the Python class `INRNetwork_Skip_Prog` described below.
Class description:
Implement the INRNetwork_Skip_Prog class.
Method signatures and docstrings:
- def __init__(self, input_dim, style_dim, dim_scale=1, rgb_dim=3, device=None, name_prefix='inr', **kwargs): :param z_dim: :param hidden_dim: :param rgb_di... | Implement the Python class `INRNetwork_Skip_Prog` described below.
Class description:
Implement the INRNetwork_Skip_Prog class.
Method signatures and docstrings:
- def __init__(self, input_dim, style_dim, dim_scale=1, rgb_dim=3, device=None, name_prefix='inr', **kwargs): :param z_dim: :param hidden_dim: :param rgb_di... | 9244193048c73f55270d2df28fb160f42d5953ad | <|skeleton|>
class INRNetwork_Skip_Prog:
def __init__(self, input_dim, style_dim, dim_scale=1, rgb_dim=3, device=None, name_prefix='inr', **kwargs):
""":param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwargs:"""
<|body_0|>
def forward(self, input, style_dict, img_size, **... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class INRNetwork_Skip_Prog:
def __init__(self, input_dim, style_dim, dim_scale=1, rgb_dim=3, device=None, name_prefix='inr', **kwargs):
""":param z_dim: :param hidden_dim: :param rgb_dim: :param device: :param kwargs:"""
super().__init__()
self.device = device
self.rgb_dim = rgb_dim
... | the_stack_v2_python_sparse | exp/comm/models/inr_network.py | tonywork/CIPS-3D | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.