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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
95262f2ab4e171626936426643c895fbd331eeeb | [
"mapper = {}\nleft = max_len = 0\nfor right, char in enumerate(s):\n if char in mapper:\n left = max(left, mapper[char] + 1)\n max_len = max(max_len, right - left + 1)\n mapper[char] = right\nreturn max_len",
"mapper = {}\nleft = max_len = 0\nfor right, char in enumerate(s):\n if char in mapper... | <|body_start_0|>
mapper = {}
left = max_len = 0
for right, char in enumerate(s):
if char in mapper:
left = max(left, mapper[char] + 1)
max_len = max(max_len, right - left + 1)
mapper[char] = right
return max_len
<|end_body_0|>
<|body_s... | String | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class String:
def longest_substring_without_repetition_(self, s: str) -> int:
"""Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:"""
<|body_0|>
def longest_substring_without_repetition(self, s: str) -> int:
"""Approach:... | stack_v2_sparse_classes_75kplus_train_008300 | 3,182 | no_license | [
{
"docstring": "Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:",
"name": "longest_substring_without_repetition_",
"signature": "def longest_substring_without_repetition_(self, s: str) -> int"
},
{
"docstring": "Approach: Sliding Window Time... | 4 | stack_v2_sparse_classes_30k_test_000697 | Implement the Python class `String` described below.
Class description:
Implement the String class.
Method signatures and docstrings:
- def longest_substring_without_repetition_(self, s: str) -> int: Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:
- def longest_s... | Implement the Python class `String` described below.
Class description:
Implement the String class.
Method signatures and docstrings:
- def longest_substring_without_repetition_(self, s: str) -> int: Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:
- def longest_s... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class String:
def longest_substring_without_repetition_(self, s: str) -> int:
"""Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:"""
<|body_0|>
def longest_substring_without_repetition(self, s: str) -> int:
"""Approach:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class String:
def longest_substring_without_repetition_(self, s: str) -> int:
"""Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:"""
mapper = {}
left = max_len = 0
for right, char in enumerate(s):
if char in mapper:
... | the_stack_v2_python_sparse | revisited/math_and_strings/strings/longest_substring_without_repeating_chars.py | Shiv2157k/leet_code | train | 1 | |
e0e51d08ab022c7939580c37b0a1c132d5988a7f | [
"accepted_filter_labels_and_vals = {'active': 'False', 'deleted': 'True', 'all': 'All'}\naccepted_filters = []\nfor label, val in accepted_filter_labels_and_vals.items():\n args = {self.key: val}\n accepted_filters.append(GridColumnFilter(label, args))\nreturn accepted_filters",
"if column_filter == 'All':\... | <|body_start_0|>
accepted_filter_labels_and_vals = {'active': 'False', 'deleted': 'True', 'all': 'All'}
accepted_filters = []
for label, val in accepted_filter_labels_and_vals.items():
args = {self.key: val}
accepted_filters.append(GridColumnFilter(label, args))
r... | Column that tracks and filters for items with deleted attribute. | DeletedColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeletedColumn:
"""Column that tracks and filters for items with deleted attribute."""
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
<|body_0|>
def filter(self, trans, user, query, column_filter):
"""Modify query to filt... | stack_v2_sparse_classes_75kplus_train_008301 | 38,546 | permissive | [
{
"docstring": "Returns a list of accepted filters for this column.",
"name": "get_accepted_filters",
"signature": "def get_accepted_filters(self)"
},
{
"docstring": "Modify query to filter self.model_class by state.",
"name": "filter",
"signature": "def filter(self, trans, user, query, ... | 2 | stack_v2_sparse_classes_30k_train_033523 | Implement the Python class `DeletedColumn` described below.
Class description:
Column that tracks and filters for items with deleted attribute.
Method signatures and docstrings:
- def get_accepted_filters(self): Returns a list of accepted filters for this column.
- def filter(self, trans, user, query, column_filter):... | Implement the Python class `DeletedColumn` described below.
Class description:
Column that tracks and filters for items with deleted attribute.
Method signatures and docstrings:
- def get_accepted_filters(self): Returns a list of accepted filters for this column.
- def filter(self, trans, user, query, column_filter):... | e9edd90c95f0d12da19f45d4d11b374f87149550 | <|skeleton|>
class DeletedColumn:
"""Column that tracks and filters for items with deleted attribute."""
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
<|body_0|>
def filter(self, trans, user, query, column_filter):
"""Modify query to filt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeletedColumn:
"""Column that tracks and filters for items with deleted attribute."""
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
accepted_filter_labels_and_vals = {'active': 'False', 'deleted': 'True', 'all': 'All'}
accepted_filters =... | the_stack_v2_python_sparse | galaxy/coralsnp_reports/lib/galaxy/webapps/coralsnp_reports/framework/grids.py | gregvonkuster/galaxy_tools | train | 4 |
3fb68e5bab45328403123b8ef3eb3a3b1adc7fc0 | [
"item_links = response.xpath(\"//div[contains(@class,'product')]/div[contains(@class,'product-top')]/a[@class='product-link']/@href\").extract()\nyield from response.follow_all(item_links, self.parse_details)\nnext_page = response.xpath(\"//span[@class='next']/a/@href\").get()\nif next_page is not None:\n next_p... | <|body_start_0|>
item_links = response.xpath("//div[contains(@class,'product')]/div[contains(@class,'product-top')]/a[@class='product-link']/@href").extract()
yield from response.follow_all(item_links, self.parse_details)
next_page = response.xpath("//span[@class='next']/a/@href").get()
... | AmorusSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmorusSpider:
def parse(self, response, **kwargs):
"""This function should extract and loop item urls. @url https://www.amorususa.com/collections/all @request https://www.amorususa.com/collections/all?page=2 @returns items 0 @returns requests 1 41"""
<|body_0|>
def parse_det... | stack_v2_sparse_classes_75kplus_train_008302 | 3,093 | no_license | [
{
"docstring": "This function should extract and loop item urls. @url https://www.amorususa.com/collections/all @request https://www.amorususa.com/collections/all?page=2 @returns items 0 @returns requests 1 41",
"name": "parse",
"signature": "def parse(self, response, **kwargs)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_005321 | Implement the Python class `AmorusSpider` described below.
Class description:
Implement the AmorusSpider class.
Method signatures and docstrings:
- def parse(self, response, **kwargs): This function should extract and loop item urls. @url https://www.amorususa.com/collections/all @request https://www.amorususa.com/co... | Implement the Python class `AmorusSpider` described below.
Class description:
Implement the AmorusSpider class.
Method signatures and docstrings:
- def parse(self, response, **kwargs): This function should extract and loop item urls. @url https://www.amorususa.com/collections/all @request https://www.amorususa.com/co... | 025babe4a03553d720806828f89929c6e773d683 | <|skeleton|>
class AmorusSpider:
def parse(self, response, **kwargs):
"""This function should extract and loop item urls. @url https://www.amorususa.com/collections/all @request https://www.amorususa.com/collections/all?page=2 @returns items 0 @returns requests 1 41"""
<|body_0|>
def parse_det... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AmorusSpider:
def parse(self, response, **kwargs):
"""This function should extract and loop item urls. @url https://www.amorususa.com/collections/all @request https://www.amorususa.com/collections/all?page=2 @returns items 0 @returns requests 1 41"""
item_links = response.xpath("//div[contains... | the_stack_v2_python_sparse | data_scraping/gmd/spiders/amorus.py | panky2202/scrapy-dev | train | 1 | |
957fcec1fe0644a4513acab9ae70834d4813a480 | [
"super(BasicBlock, self).__init__()\nif norm_layer is None:\n norm_layer = nn.BatchNorm2d\nif groups != 1 or base_width != 64:\n raise ValueError('BasicBlock only supports groups=1 and base_width=64')\nself.conv1 = conv3x3(inplanes, planes, stride)\nself.bn1 = norm_layer(planes)\nself.relu = nn.ReLU(inplace=T... | <|body_start_0|>
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
self.conv1 = conv3x3(inplanes, planes, stride)
... | Basic neural network block for PyTorch | BasicBlock | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-protobuf",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock:
"""Basic neural network block for PyTorch"""
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, norm_layer=None):
"""Initializer Args: inplanes: planes: stride (int): stride for convolutional filters (Default=1) downsample: (Default=N... | stack_v2_sparse_classes_75kplus_train_008303 | 10,131 | permissive | [
{
"docstring": "Initializer Args: inplanes: planes: stride (int): stride for convolutional filters (Default=1) downsample: (Default=None) groups (int): (Default=1) base_width: (Default=64) norm_layer: (Default=None)",
"name": "__init__",
"signature": "def __init__(self, inplanes, planes, stride=1, downs... | 2 | stack_v2_sparse_classes_30k_train_017153 | Implement the Python class `BasicBlock` described below.
Class description:
Basic neural network block for PyTorch
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, norm_layer=None): Initializer Args: inplanes: planes: stride (int): stride for... | Implement the Python class `BasicBlock` described below.
Class description:
Basic neural network block for PyTorch
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, norm_layer=None): Initializer Args: inplanes: planes: stride (int): stride for... | d8e2d22dfccfb8488f70f1fb5593d4e6ee1eca1f | <|skeleton|>
class BasicBlock:
"""Basic neural network block for PyTorch"""
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, norm_layer=None):
"""Initializer Args: inplanes: planes: stride (int): stride for convolutional filters (Default=1) downsample: (Default=N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicBlock:
"""Basic neural network block for PyTorch"""
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, norm_layer=None):
"""Initializer Args: inplanes: planes: stride (int): stride for convolutional filters (Default=1) downsample: (Default=None) groups (... | the_stack_v2_python_sparse | openfl/models/pytorch/pt_resnet/pt_resnet.py | sbakas/OpenFederatedLearning-1 | train | 0 |
ce96580cfce1a0180c63e3cfb59613cddc72ed15 | [
"course = CourseFactory.create()\nexpected = '{title} ({uuid})'.format(title=course.title, uuid=course.uuid)\nassert str(course) == expected",
"module = ModuleFactory.create()\nexpected = '{title} ({uuid})'.format(title=module.title, uuid=module.uuid)\nassert str(module) == expected",
"instance = BackingInstanc... | <|body_start_0|>
course = CourseFactory.create()
expected = '{title} ({uuid})'.format(title=course.title, uuid=course.uuid)
assert str(course) == expected
<|end_body_0|>
<|body_start_1|>
module = ModuleFactory.create()
expected = '{title} ({uuid})'.format(title=module.title, uui... | Models tests | ModelsTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelsTests:
"""Models tests"""
def test_course_str(self):
"""Assert str(Course)"""
<|body_0|>
def test_module_str(self):
"""Assert str(Module)"""
<|body_1|>
def test_backinginstance_str(self):
"""Assert str(BackingInstance)"""
<|body... | stack_v2_sparse_classes_75kplus_train_008304 | 1,661 | no_license | [
{
"docstring": "Assert str(Course)",
"name": "test_course_str",
"signature": "def test_course_str(self)"
},
{
"docstring": "Assert str(Module)",
"name": "test_module_str",
"signature": "def test_module_str(self)"
},
{
"docstring": "Assert str(BackingInstance)",
"name": "test_... | 3 | stack_v2_sparse_classes_30k_train_042502 | Implement the Python class `ModelsTests` described below.
Class description:
Models tests
Method signatures and docstrings:
- def test_course_str(self): Assert str(Course)
- def test_module_str(self): Assert str(Module)
- def test_backinginstance_str(self): Assert str(BackingInstance) | Implement the Python class `ModelsTests` described below.
Class description:
Models tests
Method signatures and docstrings:
- def test_course_str(self): Assert str(Course)
- def test_module_str(self): Assert str(Module)
- def test_backinginstance_str(self): Assert str(BackingInstance)
<|skeleton|>
class ModelsTests:... | 5fd8fcf21c9bc5d7fbfcc29e72ee9ebea493b7fb | <|skeleton|>
class ModelsTests:
"""Models tests"""
def test_course_str(self):
"""Assert str(Course)"""
<|body_0|>
def test_module_str(self):
"""Assert str(Module)"""
<|body_1|>
def test_backinginstance_str(self):
"""Assert str(BackingInstance)"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelsTests:
"""Models tests"""
def test_course_str(self):
"""Assert str(Course)"""
course = CourseFactory.create()
expected = '{title} ({uuid})'.format(title=course.title, uuid=course.uuid)
assert str(course) == expected
def test_module_str(self):
"""Assert s... | the_stack_v2_python_sparse | portal/models_test.py | mitodl/teachersportal | train | 0 |
83cfa08bd310863b47ec6cca55da4ac6173ecaea | [
"size = len(prices)\nif size <= 0:\n return 0\nmaxPro = 0\nfor i in range(size):\n for j in range(i + 1, size):\n maxPro = max(maxPro, self.maxProfit(prices[j + 1:]) + prices[j] - prices[i])\nreturn maxPro",
"size = len(prices)\nif size <= 0:\n return 0\nminIdx = 0\nmaxPro = 0\nfor i in range(1, s... | <|body_start_0|>
size = len(prices)
if size <= 0:
return 0
maxPro = 0
for i in range(size):
for j in range(i + 1, size):
maxPro = max(maxPro, self.maxProfit(prices[j + 1:]) + prices[j] - prices[i])
return maxPro
<|end_body_0|>
<|body_start... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力思路:无效for...for嵌套转化为递归"""
<|body_0|>
def maxProfit1(self, prices: List[int]) -> int:
"""暴力优化:消除一层循环+备忘录"""
<|body_1|>
def maxProfit2(self, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录... | stack_v2_sparse_classes_75kplus_train_008305 | 6,235 | permissive | [
{
"docstring": "暴力思路:无效for...for嵌套转化为递归",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
},
{
"docstring": "暴力优化:消除一层循环+备忘录",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices: List[int]) -> int"
},
{
"docstring": "暴力优化2:消除一层循环+备忘录... | 6 | stack_v2_sparse_classes_30k_train_020467 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 暴力思路:无效for...for嵌套转化为递归
- def maxProfit1(self, prices: List[int]) -> int: 暴力优化:消除一层循环+备忘录
- def maxProfit2(self, prices: List[int])... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 暴力思路:无效for...for嵌套转化为递归
- def maxProfit1(self, prices: List[int]) -> int: 暴力优化:消除一层循环+备忘录
- def maxProfit2(self, prices: List[int])... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力思路:无效for...for嵌套转化为递归"""
<|body_0|>
def maxProfit1(self, prices: List[int]) -> int:
"""暴力优化:消除一层循环+备忘录"""
<|body_1|>
def maxProfit2(self, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力思路:无效for...for嵌套转化为递归"""
size = len(prices)
if size <= 0:
return 0
maxPro = 0
for i in range(size):
for j in range(i + 1, size):
maxPro = max(maxPro, self.maxProfit(pri... | the_stack_v2_python_sparse | 122-best-time-to-buy-and-sell-stock-ii.py | yuenliou/leetcode | train | 0 | |
7a3ca0fefc9589788e4009db8e975892f2892a3c | [
"obj.save()\nfrom celery_tasks.html.tasks import generate_static_list_search_html\ngenerate_static_list_search_html.delay()",
"obj.delete()\nfrom celery_tasks.html.tasks import generate_static_list_search_html\ngenerate_static_list_search_html.delay()"
] | <|body_start_0|>
obj.save()
from celery_tasks.html.tasks import generate_static_list_search_html
generate_static_list_search_html.delay()
<|end_body_0|>
<|body_start_1|>
obj.delete()
from celery_tasks.html.tasks import generate_static_list_search_html
generate_static_lis... | GoodsCategoryAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoodsCategoryAdmin:
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""admin后台删除了数据时调用"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj.save()
from celery_tasks.h... | stack_v2_sparse_classes_75kplus_train_008306 | 2,182 | permissive | [
{
"docstring": "admin后台新增或修改了数据时调用",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "admin后台删除了数据时调用",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003207 | Implement the Python class `GoodsCategoryAdmin` described below.
Class description:
Implement the GoodsCategoryAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): admin后台新增或修改了数据时调用
- def delete_model(self, request, obj): admin后台删除了数据时调用 | Implement the Python class `GoodsCategoryAdmin` described below.
Class description:
Implement the GoodsCategoryAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): admin后台新增或修改了数据时调用
- def delete_model(self, request, obj): admin后台删除了数据时调用
<|skeleton|>
class GoodsCategory... | 5fc4d9930b0cd1e115f8c6ebf51cd9e28922d263 | <|skeleton|>
class GoodsCategoryAdmin:
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""admin后台删除了数据时调用"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoodsCategoryAdmin:
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
obj.save()
from celery_tasks.html.tasks import generate_static_list_search_html
generate_static_list_search_html.delay()
def delete_model(self, request, obj):
"""admin后台删... | the_stack_v2_python_sparse | meiduo/meiduo_mall/meiduo_mall/apps/goods/admin.py | Highsir/Simplestore | train | 1 | |
74cf2663c72e62fd7acaea89e5afe5b93977d1ae | [
"try:\n return QueryPlansAcquired.objects.get(pk=pk)\nexcept QueryPlansAcquired.DoesNotExist:\n raise Http404",
"client = request.user.id\nquery_set = self.get_detail_plan(code, client)\ntry:\n serializer = PlanDetailSerializer(query_set)\n return Response(serializer.data)\nexcept Exception as e:\n ... | <|body_start_0|>
try:
return QueryPlansAcquired.objects.get(pk=pk)
except QueryPlansAcquired.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
client = request.user.id
query_set = self.get_detail_plan(code, client)
try:
serializer = ... | Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente | ActivationPlanView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivationPlanView:
"""Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente"""
def get_object(self, pk):
"""Buscar plan adquirido."""
<|body_0|>
def get(self, request, code):
"""Devuelve la in... | stack_v2_sparse_classes_75kplus_train_008307 | 44,248 | no_license | [
{
"docstring": "Buscar plan adquirido.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "Devuelve la informacion del plan segun el codigo pasado.",
"name": "get",
"signature": "def get(self, request, code)"
},
{
"docstring": "Activar producto, via... | 5 | stack_v2_sparse_classes_30k_train_006860 | Implement the Python class `ActivationPlanView` described below.
Class description:
Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente
Method signatures and docstrings:
- def get_object(self, pk): Buscar plan adquirido.
- def get(self, request, ... | Implement the Python class `ActivationPlanView` described below.
Class description:
Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente
Method signatures and docstrings:
- def get_object(self, pk): Buscar plan adquirido.
- def get(self, request, ... | 3135a4142c38f367a152e1fc79fee8af8fca4bcc | <|skeleton|>
class ActivationPlanView:
"""Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente"""
def get_object(self, pk):
"""Buscar plan adquirido."""
<|body_0|>
def get(self, request, code):
"""Devuelve la in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivationPlanView:
"""Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente"""
def get_object(self, pk):
"""Buscar plan adquirido."""
try:
return QueryPlansAcquired.objects.get(pk=pk)
except QueryPl... | the_stack_v2_python_sparse | api/views/plan.py | darwinv/api-chat-lnk | train | 0 |
a7b3dc23e04b973e6b81f53c3fc27abcfe54060c | [
"self.name = name\nself.required = required\nself.type = type\nself.units = units\nself.display_name = display_name\nself.description = description\nself.value_description = value_description",
"value_dict = {}\nreturn_dict = {}\nif self.required != None:\n return_dict[CommandDictKey.REQUIRED] = self.required\... | <|body_start_0|>
self.name = name
self.required = required
self.type = type
self.units = units
self.display_name = display_name
self.description = description
self.value_description = value_description
<|end_body_0|>
<|body_start_1|>
value_dict = {}
... | An object handling the description of the generally static description of one of the command's arguments | CommandArgument | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandArgument:
"""An object handling the description of the generally static description of one of the command's arguments"""
def __init__(self, name, required=False, display_name=None, description=None, type=None, units=None, value_description=None):
"""Create a command argument s... | stack_v2_sparse_classes_75kplus_train_008308 | 14,421 | permissive | [
{
"docstring": "Create a command argument structure @param name The command name. @param required A boolean indicating that the argument is required @param display_name The string to use for displaying the command or a prompt for the command use @param description The description of what the command is @param t... | 2 | null | Implement the Python class `CommandArgument` described below.
Class description:
An object handling the description of the generally static description of one of the command's arguments
Method signatures and docstrings:
- def __init__(self, name, required=False, display_name=None, description=None, type=None, units=N... | Implement the Python class `CommandArgument` described below.
Class description:
An object handling the description of the generally static description of one of the command's arguments
Method signatures and docstrings:
- def __init__(self, name, required=False, display_name=None, description=None, type=None, units=N... | bdbf01f5614e7188ce19596704794466e5683b30 | <|skeleton|>
class CommandArgument:
"""An object handling the description of the generally static description of one of the command's arguments"""
def __init__(self, name, required=False, display_name=None, description=None, type=None, units=None, value_description=None):
"""Create a command argument s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommandArgument:
"""An object handling the description of the generally static description of one of the command's arguments"""
def __init__(self, name, required=False, display_name=None, description=None, type=None, units=None, value_description=None):
"""Create a command argument structure @par... | the_stack_v2_python_sparse | mi/core/instrument/protocol_cmd_dict.py | oceanobservatories/mi-instrument | train | 1 |
9be5b4cff2d653ec53aa4fb994f953c190cd407b | [
"shortcut = data\nbm1 = BatchNormalization(axis=chanDim, epsilon=bnEps, momentum=bnMom)(data)\nact1 = Activation('relu')(bm1)\nconv1 = Conv2D(int(K * 0.25), (1, 1), use_bias=False, kernel_regularizer=l2(reg))(act1)\nbn2 = BatchNormalization(axis=chanDim, epsilon=bnEps, momentum=bnMom)(conv1)\nact2 = Activation('rel... | <|body_start_0|>
shortcut = data
bm1 = BatchNormalization(axis=chanDim, epsilon=bnEps, momentum=bnMom)(data)
act1 = Activation('relu')(bm1)
conv1 = Conv2D(int(K * 0.25), (1, 1), use_bias=False, kernel_regularizer=l2(reg))(act1)
bn2 = BatchNormalization(axis=chanDim, epsilon=bnEps... | ResNet | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet:
def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9):
"""Args: data: input K: number of output, aka filters stride: convolution stride chanDim: channel dimension red: sign whether this module response to reduce spatial dimension bnEps: bn l... | stack_v2_sparse_classes_75kplus_train_008309 | 3,786 | permissive | [
{
"docstring": "Args: data: input K: number of output, aka filters stride: convolution stride chanDim: channel dimension red: sign whether this module response to reduce spatial dimension bnEps: bn layer eps bnMon: bn layer momentum",
"name": "residual_module",
"signature": "def residual_module(data, K,... | 2 | stack_v2_sparse_classes_30k_train_006568 | Implement the Python class `ResNet` described below.
Class description:
Implement the ResNet class.
Method signatures and docstrings:
- def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9): Args: data: input K: number of output, aka filters stride: convolution stride chanDim: c... | Implement the Python class `ResNet` described below.
Class description:
Implement the ResNet class.
Method signatures and docstrings:
- def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9): Args: data: input K: number of output, aka filters stride: convolution stride chanDim: c... | 69727d76fd652390d9660e9ea4354ba5cc76dd5c | <|skeleton|>
class ResNet:
def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9):
"""Args: data: input K: number of output, aka filters stride: convolution stride chanDim: channel dimension red: sign whether this module response to reduce spatial dimension bnEps: bn l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResNet:
def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9):
"""Args: data: input K: number of output, aka filters stride: convolution stride chanDim: channel dimension red: sign whether this module response to reduce spatial dimension bnEps: bn layer eps bnMon... | the_stack_v2_python_sparse | books/dl-for-cv-with-python/network/pyimage/nn/conv/resnet.py | Bingwen-Hu/hackaway | train | 0 | |
94ba6f1b4f062ce9f899a3a0130cb63235d5f015 | [
"try:\n file = File.objects.get(pk=pk)\nexcept ObjectDoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\nif request.user.is_authenticated:\n serializer = FileSerializer(file)\n return Response(serializer.data)\nreturn Response(status=status.HTTP_401_UNAUTHORIZED)",
"try:\n file = Fil... | <|body_start_0|>
try:
file = File.objects.get(pk=pk)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.user.is_authenticated:
serializer = FileSerializer(file)
return Response(serializer.data)
return Re... | Retrieve or delete a File. | FileDetail | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileDetail:
"""Retrieve or delete a File."""
def get(self, request, pk):
"""Send the File corresponding to the given key."""
<|body_0|>
def delete(self, request, pk):
"""Delete the File corresponding to the given key."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_008310 | 3,371 | permissive | [
{
"docstring": "Send the File corresponding to the given key.",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "Delete the File corresponding to the given key.",
"name": "delete",
"signature": "def delete(self, request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050712 | Implement the Python class `FileDetail` described below.
Class description:
Retrieve or delete a File.
Method signatures and docstrings:
- def get(self, request, pk): Send the File corresponding to the given key.
- def delete(self, request, pk): Delete the File corresponding to the given key. | Implement the Python class `FileDetail` described below.
Class description:
Retrieve or delete a File.
Method signatures and docstrings:
- def get(self, request, pk): Send the File corresponding to the given key.
- def delete(self, request, pk): Delete the File corresponding to the given key.
<|skeleton|>
class File... | 56511ebac83a5dc1fb8768a98bc675e88530a447 | <|skeleton|>
class FileDetail:
"""Retrieve or delete a File."""
def get(self, request, pk):
"""Send the File corresponding to the given key."""
<|body_0|>
def delete(self, request, pk):
"""Delete the File corresponding to the given key."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileDetail:
"""Retrieve or delete a File."""
def get(self, request, pk):
"""Send the File corresponding to the given key."""
try:
file = File.objects.get(pk=pk)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.... | the_stack_v2_python_sparse | maintenancemanagement/views/views_file.py | Open-CMMS/openCMMS_backend | train | 4 |
659df4336699a99c4801fe23ed733bf7a7dd971c | [
"self.arr = vec2d\nself.row = 0\nself.col = 0",
"nextVar = self.arr[self.row][self.col]\nself.col += 1\nreturn nextVar",
"while self.row <= len(self.arr) - 1:\n if self.col <= len(self.arr[self.row]) - 1:\n return True\n self.col = 0\n self.row += 1\nreturn False"
] | <|body_start_0|>
self.arr = vec2d
self.row = 0
self.col = 0
<|end_body_0|>
<|body_start_1|>
nextVar = self.arr[self.row][self.col]
self.col += 1
return nextVar
<|end_body_1|>
<|body_start_2|>
while self.row <= len(self.arr) - 1:
if self.col <= len(se... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_008311 | 1,182 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_025464 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | d1666d44226274f13af25cf878cd63a24e1c5528 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.arr = vec2d
self.row = 0
self.col = 0
def next(self):
""":rtype: int"""
nextVar = self.arr[self.row][self.col]
self.col += 1
re... | the_stack_v2_python_sparse | Array+HashTable/LeetCode251_Flatten2DVector.py | rexhzhang/LeetCodeProbelms | train | 0 | |
06238577534bd1c9140f29531fa2a5332d875541 | [
"super().__init__()\nself.max_area_only = max_area_only\nself.use_rotated_box = use_rotated_box",
"mask_expand = mask.copy()\ncontours, _ = cv2.findContours(mask_expand, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\napprox_curve = []\nif self.max_area_only:\n contour_areas = [cv2.contourArea(contour) for contour ... | <|body_start_0|>
super().__init__()
self.max_area_only = max_area_only
self.use_rotated_box = use_rotated_box
<|end_body_0|>
<|body_start_1|>
mask_expand = mask.copy()
contours, _ = cv2.findContours(mask_expand, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
approx_curve = []... | Get the contour of the mask area and format output | PostMaskRCNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostMaskRCNN:
"""Get the contour of the mask area and format output"""
def __init__(self, max_area_only=True, use_rotated_box=False):
"""Args: max_area_only(boolean): whether to consider only one (maximum) region in each proposal regions. use_rotated_box(boolean): whether to use minA... | stack_v2_sparse_classes_75kplus_train_008312 | 4,302 | permissive | [
{
"docstring": "Args: max_area_only(boolean): whether to consider only one (maximum) region in each proposal regions. use_rotated_box(boolean): whether to use minAreaRect to represent text regions (or use contour polygon)",
"name": "__init__",
"signature": "def __init__(self, max_area_only=True, use_rot... | 3 | stack_v2_sparse_classes_30k_train_053377 | Implement the Python class `PostMaskRCNN` described below.
Class description:
Get the contour of the mask area and format output
Method signatures and docstrings:
- def __init__(self, max_area_only=True, use_rotated_box=False): Args: max_area_only(boolean): whether to consider only one (maximum) region in each propos... | Implement the Python class `PostMaskRCNN` described below.
Class description:
Get the contour of the mask area and format output
Method signatures and docstrings:
- def __init__(self, max_area_only=True, use_rotated_box=False): Args: max_area_only(boolean): whether to consider only one (maximum) region in each propos... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class PostMaskRCNN:
"""Get the contour of the mask area and format output"""
def __init__(self, max_area_only=True, use_rotated_box=False):
"""Args: max_area_only(boolean): whether to consider only one (maximum) region in each proposal regions. use_rotated_box(boolean): whether to use minA... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostMaskRCNN:
"""Get the contour of the mask area and format output"""
def __init__(self, max_area_only=True, use_rotated_box=False):
"""Args: max_area_only(boolean): whether to consider only one (maximum) region in each proposal regions. use_rotated_box(boolean): whether to use minAreaRect to re... | the_stack_v2_python_sparse | davarocr/davarocr/davar_det/core/post_processing/post_mask_rcnn.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
73418aad3190f1151b847d09a56011d724ec868b | [
"self.nctrsTMconn = False\nself.nctrsTMport = UTIL.SYS.s_configuration.NCTRS_TM_SERVER_PORT\nself.nctrsTCconn = False\nself.nctrsTCport = UTIL.SYS.s_configuration.NCTRS_TC_SERVER_PORT\nself.nctrsAdminConn = False\nself.nctrsAdminPort = UTIL.SYS.s_configuration.NCTRS_ADMIN_SERVER_PORT\nself.grndAck1 = ENABLE_ACK\nse... | <|body_start_0|>
self.nctrsTMconn = False
self.nctrsTMport = UTIL.SYS.s_configuration.NCTRS_TM_SERVER_PORT
self.nctrsTCconn = False
self.nctrsTCport = UTIL.SYS.s_configuration.NCTRS_TC_SERVER_PORT
self.nctrsAdminConn = False
self.nctrsAdminPort = UTIL.SYS.s_configuration.... | Server Configuration | Configuration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
"""Server Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the configuration attributes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_75kplus_train_008313 | 5,270 | permissive | [
{
"docstring": "Initialise the connection relevant informations",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Dumps the status of the configuration attributes",
"name": "dump",
"signature": "def dump(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034047 | Implement the Python class `Configuration` described below.
Class description:
Server Configuration
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the configuration attributes | Implement the Python class `Configuration` described below.
Class description:
Server Configuration
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the configuration attributes
<|skeleton|>
class Configuration:
"""Serve... | c94415e9d85519f345fc56938198ac2537c0c6d0 | <|skeleton|>
class Configuration:
"""Server Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the configuration attributes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Configuration:
"""Server Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
self.nctrsTMconn = False
self.nctrsTMport = UTIL.SYS.s_configuration.NCTRS_TM_SERVER_PORT
self.nctrsTCconn = False
self.nctrsTCport = UTIL.SYS.s_conf... | the_stack_v2_python_sparse | GRND/IF.py | khawatkom/SpacePyLibrary | train | 1 |
39e3829f7a19c9b559bbc89fec9d2da947ced615 | [
"if stones[1] != 1:\n return False\nstone_set, fail = (set(stones), set())\nstack = [(0, 0)]\nwhile stack:\n stone, jump = stack.pop()\n for jump_step in (jump - 1, jump, jump + 1):\n stone_next = stone + jump_step\n if jump_step > 0 and stone_next in stone_set and ((stone_next, jump_step) no... | <|body_start_0|>
if stones[1] != 1:
return False
stone_set, fail = (set(stones), set())
stack = [(0, 0)]
while stack:
stone, jump = stack.pop()
for jump_step in (jump - 1, jump, jump + 1):
stone_next = stone + jump_step
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCross(self, stones):
""":type stones: List[int] :rtype: bool beats 94.74%"""
<|body_0|>
def canCross1(self, stones):
""":type stones: List[int] :rtype: bool https://discuss.leetcode.com/topic/59570/python-documented-solution-that-is-easy-to-understan... | stack_v2_sparse_classes_75kplus_train_008314 | 2,969 | no_license | [
{
"docstring": ":type stones: List[int] :rtype: bool beats 94.74%",
"name": "canCross",
"signature": "def canCross(self, stones)"
},
{
"docstring": ":type stones: List[int] :rtype: bool https://discuss.leetcode.com/topic/59570/python-documented-solution-that-is-easy-to-understand beats 31.58%",
... | 3 | stack_v2_sparse_classes_30k_val_002416 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCross(self, stones): :type stones: List[int] :rtype: bool beats 94.74%
- def canCross1(self, stones): :type stones: List[int] :rtype: bool https://discuss.leetcode.com/top... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCross(self, stones): :type stones: List[int] :rtype: bool beats 94.74%
- def canCross1(self, stones): :type stones: List[int] :rtype: bool https://discuss.leetcode.com/top... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def canCross(self, stones):
""":type stones: List[int] :rtype: bool beats 94.74%"""
<|body_0|>
def canCross1(self, stones):
""":type stones: List[int] :rtype: bool https://discuss.leetcode.com/topic/59570/python-documented-solution-that-is-easy-to-understan... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canCross(self, stones):
""":type stones: List[int] :rtype: bool beats 94.74%"""
if stones[1] != 1:
return False
stone_set, fail = (set(stones), set())
stack = [(0, 0)]
while stack:
stone, jump = stack.pop()
for jump_step... | the_stack_v2_python_sparse | LeetCode/403_frog_jump.py | yao23/Machine_Learning_Playground | train | 12 | |
765f41b4953076d60696f39ed97239d2fe446025 | [
"input_tensor = tf.ones([1, 4, 4, 2])\noutput_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))\nself.assertAllEqual(output_tensor.shape, [1, 2, 2, 2])\nexpected = tf.constant([[[[-0.02436768, -0.27847868], [-0.0774256, -0.5111736]], [[0.50436425, -0.1713084], [0.2803106, -... | <|body_start_0|>
input_tensor = tf.ones([1, 4, 4, 2])
output_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))
self.assertAllEqual(output_tensor.shape, [1, 2, 2, 2])
expected = tf.constant([[[[-0.02436768, -0.27847868], [-0.0774256, -0.5111736]],... | CNNAutoencoderModelTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
<|body_0|>
def test_encoder_pool_list_values(self):
"""Tests encoder with default inputs."""
<|body_1|>
def test_encoder_batch_norm_all(self):
"""Te... | stack_v2_sparse_classes_75kplus_train_008315 | 4,774 | permissive | [
{
"docstring": "Tests encoder with default inputs.",
"name": "test_encoder_default",
"signature": "def test_encoder_default(self)"
},
{
"docstring": "Tests encoder with default inputs.",
"name": "test_encoder_pool_list_values",
"signature": "def test_encoder_pool_list_values(self)"
},
... | 5 | stack_v2_sparse_classes_30k_train_043066 | Implement the Python class `CNNAutoencoderModelTest` described below.
Class description:
Implement the CNNAutoencoderModelTest class.
Method signatures and docstrings:
- def test_encoder_default(self): Tests encoder with default inputs.
- def test_encoder_pool_list_values(self): Tests encoder with default inputs.
- d... | Implement the Python class `CNNAutoencoderModelTest` described below.
Class description:
Implement the CNNAutoencoderModelTest class.
Method signatures and docstrings:
- def test_encoder_default(self): Tests encoder with default inputs.
- def test_encoder_pool_list_values(self): Tests encoder with default inputs.
- d... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
<|body_0|>
def test_encoder_pool_list_values(self):
"""Tests encoder with default inputs."""
<|body_1|>
def test_encoder_batch_norm_all(self):
"""Te... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
input_tensor = tf.ones([1, 4, 4, 2])
output_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))
self.assertAllEqual(output_tensor.shape, [1,... | the_stack_v2_python_sparse | simulation_research/next_day_wildfire_spread/models/cnn_autoencoder_model_test.py | Jimmy-INL/google-research | train | 1 | |
99fdc297dd34011e0125e33d211d4dd6b954b38f | [
"super().__init__()\nself.layer_norm = nn.LayerNorm(hidden_dim)\nself.qkv_layer_norm = nn.LayerNorm(hidden_dim)\nself.attention = MultiHeadAttention(kv_dim=hidden_dim, q_dim=hidden_dim, qk_out_dim=qk_out_dim, v_out_dim=v_out_dim, output_dim=hidden_dim, num_heads=num_heads, dropout=attention_dropout)\nself.dropout =... | <|body_start_0|>
super().__init__()
self.layer_norm = nn.LayerNorm(hidden_dim)
self.qkv_layer_norm = nn.LayerNorm(hidden_dim)
self.attention = MultiHeadAttention(kv_dim=hidden_dim, q_dim=hidden_dim, qk_out_dim=qk_out_dim, v_out_dim=v_out_dim, output_dim=hidden_dim, num_heads=num_heads, d... | Self-attention module. | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Self-attention module."""
def __init__(self, *, hidden_dim: int, qk_out_dim: Optional[int]=None, v_out_dim: Optional[int]=None, widening_factor: int=4, num_heads: int=1, dropout: float=0.0, attention_dropout: float=0.0):
"""Constructor. Args: hidden_dim: Dimension o... | stack_v2_sparse_classes_75kplus_train_008316 | 21,096 | no_license | [
{
"docstring": "Constructor. Args: hidden_dim: Dimension of input tensor. qk_out_dim: Size of Query and Key matrices last dimension. Defaults to None. v_out_dim: Size of Value matrix last dimension. Defaults to None. widening_factor: Feed-forward network widening factor. Defaults to 4. num_heads: Number of atte... | 2 | null | Implement the Python class `SelfAttention` described below.
Class description:
Self-attention module.
Method signatures and docstrings:
- def __init__(self, *, hidden_dim: int, qk_out_dim: Optional[int]=None, v_out_dim: Optional[int]=None, widening_factor: int=4, num_heads: int=1, dropout: float=0.0, attention_dropou... | Implement the Python class `SelfAttention` described below.
Class description:
Self-attention module.
Method signatures and docstrings:
- def __init__(self, *, hidden_dim: int, qk_out_dim: Optional[int]=None, v_out_dim: Optional[int]=None, widening_factor: int=4, num_heads: int=1, dropout: float=0.0, attention_dropou... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SelfAttention:
"""Self-attention module."""
def __init__(self, *, hidden_dim: int, qk_out_dim: Optional[int]=None, v_out_dim: Optional[int]=None, widening_factor: int=4, num_heads: int=1, dropout: float=0.0, attention_dropout: float=0.0):
"""Constructor. Args: hidden_dim: Dimension o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfAttention:
"""Self-attention module."""
def __init__(self, *, hidden_dim: int, qk_out_dim: Optional[int]=None, v_out_dim: Optional[int]=None, widening_factor: int=4, num_heads: int=1, dropout: float=0.0, attention_dropout: float=0.0):
"""Constructor. Args: hidden_dim: Dimension of input tenso... | the_stack_v2_python_sparse | generated/test_esceptico_perceiver_io.py | jansel/pytorch-jit-paritybench | train | 35 |
acf02da5f3329d62da543069ba8a863c044a73e6 | [
"def preOrder(root):\n if root:\n vals.append(str(root.val))\n preOrder(root.left)\n preOrder(root.right)\nvals = []\npreOrder(root)\nreturn ''.join(vals)",
"vals = list(map(int, data.split()))\nvals.reverse()\n\ndef build(minVal, maxVal):\n if vals and minVal <= vals[-1] <= maxVal:\n ... | <|body_start_0|>
def preOrder(root):
if root:
vals.append(str(root.val))
preOrder(root.left)
preOrder(root.right)
vals = []
preOrder(root)
return ''.join(vals)
<|end_body_0|>
<|body_start_1|>
vals = list(map(int, data.s... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_008317 | 979 | 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_028887 | 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:... | 11c8fc663888b48b5417256aab1bf872190267ba | <|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"""
def preOrder(root):
if root:
vals.append(str(root.val))
preOrder(root.left)
preOrder(root.right)
vals = []
pre... | the_stack_v2_python_sparse | Serialize and Deserialize BST.py | lfdyf20/Leetcode | train | 1 | |
cec325bb82d1f6ded6943c8ad925184f6e410239 | [
"cursor = self.view.sel()\nself.original_position = cursor[0]\ncursor.clear()\ncursor.add(region)\nself.view.show(region)",
"last_edits = self.view.settings().get(LAST_EDITS_SETTING, {})\nlast_edit = last_edits.get(str(self.view.id()), None)\ncurrent_position = self.view.sel()[0]\nif last_edit is None:\n retur... | <|body_start_0|>
cursor = self.view.sel()
self.original_position = cursor[0]
cursor.clear()
cursor.add(region)
self.view.show(region)
<|end_body_0|>
<|body_start_1|>
last_edits = self.view.settings().get(LAST_EDITS_SETTING, {})
last_edit = last_edits.get(str(self... | GotoLastEdit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GotoLastEdit:
def move_cursor_to_region(self, region):
"""Clear the cursor's position and move it to `region`."""
<|body_0|>
def run(self, edit):
"""If there was a last edit recorded for the view, store the current position as self.original_position and move the curs... | stack_v2_sparse_classes_75kplus_train_008318 | 1,978 | no_license | [
{
"docstring": "Clear the cursor's position and move it to `region`.",
"name": "move_cursor_to_region",
"signature": "def move_cursor_to_region(self, region)"
},
{
"docstring": "If there was a last edit recorded for the view, store the current position as self.original_position and move the curs... | 2 | stack_v2_sparse_classes_30k_train_023643 | Implement the Python class `GotoLastEdit` described below.
Class description:
Implement the GotoLastEdit class.
Method signatures and docstrings:
- def move_cursor_to_region(self, region): Clear the cursor's position and move it to `region`.
- def run(self, edit): If there was a last edit recorded for the view, store... | Implement the Python class `GotoLastEdit` described below.
Class description:
Implement the GotoLastEdit class.
Method signatures and docstrings:
- def move_cursor_to_region(self, region): Clear the cursor's position and move it to `region`.
- def run(self, edit): If there was a last edit recorded for the view, store... | 8390a0139137574ab237b3ff5fe8ea61e8a0b76b | <|skeleton|>
class GotoLastEdit:
def move_cursor_to_region(self, region):
"""Clear the cursor's position and move it to `region`."""
<|body_0|>
def run(self, edit):
"""If there was a last edit recorded for the view, store the current position as self.original_position and move the curs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GotoLastEdit:
def move_cursor_to_region(self, region):
"""Clear the cursor's position and move it to `region`."""
cursor = self.view.sel()
self.original_position = cursor[0]
cursor.clear()
cursor.add(region)
self.view.show(region)
def run(self, edit):
... | the_stack_v2_python_sparse | data/input/abrookins/GotoLastEdit/goto_last_edit.py | bopopescu/pythonanalyzer | train | 0 | |
646d8b468b6646117d08b8bc81eae2e7936ff9e3 | [
"result = {}\noutput = []\nfor i in nums:\n result[i] = result.get(i, 0) + 1\nfor k, v in result.items():\n if v == 1:\n output.append(k)\nreturn output",
"res1, res2 = (0, 0)\nfor num in nums:\n res1 ^= num\nfor num in nums[::-1]:\n res2 ^= num\nreturn [res1, res2]"
] | <|body_start_0|>
result = {}
output = []
for i in nums:
result[i] = result.get(i, 0) + 1
for k, v in result.items():
if v == 1:
output.append(k)
return output
<|end_body_0|>
<|body_start_1|>
res1, res2 = (0, 0)
for num in n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber_2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = {}
output = []
... | stack_v2_sparse_classes_75kplus_train_008319 | 672 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber_1",
"signature": "def singleNumber_1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber_2",
"signature": "def singleNumber_2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042849 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber_1(self, nums): :type nums: List[int] :rtype: int
- def singleNumber_2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber_1(self, nums): :type nums: List[int] :rtype: int
- def singleNumber_2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def singl... | 8a62b397a5fa107c70efc8ea65d0edfb74f8baa7 | <|skeleton|>
class Solution:
def singleNumber_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber_2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def singleNumber_1(self, nums):
""":type nums: List[int] :rtype: int"""
result = {}
output = []
for i in nums:
result[i] = result.get(i, 0) + 1
for k, v in result.items():
if v == 1:
output.append(k)
return outpu... | the_stack_v2_python_sparse | LeetCode-Solution/Algorithms/Single-Number-III.py | LFYG/leetcode-acm-euler-other | train | 0 | |
0b4e70cd72a130822d9dae9ef9d13eaffb401c63 | [
"def helper(tree, lower=float('-inf'), upper=float('inf')):\n if not tree:\n return True\n val = tree.val\n if val <= lower or val >= upper:\n return False\n return helper(tree.left, lower, val) and helper(tree.right, val, upper)\nreturn helper(root)",
"if not root:\n return True\nsta... | <|body_start_0|>
def helper(tree, lower=float('-inf'), upper=float('inf')):
if not tree:
return True
val = tree.val
if val <= lower or val >= upper:
return False
return helper(tree.left, lower, val) and helper(tree.right, val, upper... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root):
"""DFS (recursive)"""
<|body_0|>
def isValidBST2(self, root):
"""DFS (Iteration)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def helper(tree, lower=float('-inf'), upper=float('inf')):
if not tree... | stack_v2_sparse_classes_75kplus_train_008320 | 1,730 | permissive | [
{
"docstring": "DFS (recursive)",
"name": "isValidBST",
"signature": "def isValidBST(self, root)"
},
{
"docstring": "DFS (Iteration)",
"name": "isValidBST2",
"signature": "def isValidBST2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014977 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): DFS (recursive)
- def isValidBST2(self, root): DFS (Iteration) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): DFS (recursive)
- def isValidBST2(self, root): DFS (Iteration)
<|skeleton|>
class Solution:
def isValidBST(self, root):
"""DFS (recursiv... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def isValidBST(self, root):
"""DFS (recursive)"""
<|body_0|>
def isValidBST2(self, root):
"""DFS (Iteration)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValidBST(self, root):
"""DFS (recursive)"""
def helper(tree, lower=float('-inf'), upper=float('inf')):
if not tree:
return True
val = tree.val
if val <= lower or val >= upper:
return False
return he... | the_stack_v2_python_sparse | leetcode/0098_validate_binary_search_tree.py | chaosWsF/Python-Practice | train | 1 | |
872f76f0e297e4dfffb49d9f6b3caa49c4321b05 | [
"self.nums = nums\n\ndef buildHelper(nums, start, end):\n if start > end:\n return None\n root = self.SegmentTreeNode(start, end, 0)\n if start == end:\n root.sum = nums[start]\n return root\n root.left = buildHelper(nums, start, (start + end) / 2)\n root.right = buildHelper(nums... | <|body_start_0|>
self.nums = nums
def buildHelper(nums, start, end):
if start > end:
return None
root = self.SegmentTreeNode(start, end, 0)
if start == end:
root.sum = nums[start]
return root
root.left = bui... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_008321 | 2,247 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_025007 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 16ad99a6511543f0286559c483206c43ed655ddd | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
def buildHelper(nums, start, end):
if start > end:
return None
root = self.SegmentTreeNode(start, end, 0)
if start == end:
root.sum = nu... | the_stack_v2_python_sparse | range-sum-query-mutable.py | stella-shen/Leetcode | train | 0 | |
30f126b48c2c2c1b925fdb0453832f01e9b22b0a | [
"cls.endpoint = '/api/courseentry/'\ncls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)\ncls.student = StudentFactory(user__username='student', user__first_name='Name', user__last_name='Surname', about='About student')\ncls.superuser = User.objects.cre... | <|body_start_0|>
cls.endpoint = '/api/courseentry/'
cls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)
cls.student = StudentFactory(user__username='student', user__first_name='Name', user__last_name='Surname', about='About student')... | Тесты записей на курс | CourseEntryTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
<|body_0|>
def test_course_entry_list(self):
"""Список записей на курс"""
<|body_1|>
def test_get_course_entry(self):
"""Получение записи на к... | stack_v2_sparse_classes_75kplus_train_008322 | 33,302 | no_license | [
{
"docstring": "Данные для тесткейса",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Список записей на курс",
"name": "test_course_entry_list",
"signature": "def test_course_entry_list(self)"
},
{
"docstring": "Получение записи на курс",
"n... | 5 | stack_v2_sparse_classes_30k_val_000996 | Implement the Python class `CourseEntryTestCase` described below.
Class description:
Тесты записей на курс
Method signatures and docstrings:
- def setUpTestData(cls): Данные для тесткейса
- def test_course_entry_list(self): Список записей на курс
- def test_get_course_entry(self): Получение записи на курс
- def test_... | Implement the Python class `CourseEntryTestCase` described below.
Class description:
Тесты записей на курс
Method signatures and docstrings:
- def setUpTestData(cls): Данные для тесткейса
- def test_course_entry_list(self): Список записей на курс
- def test_get_course_entry(self): Получение записи на курс
- def test_... | 3de0f8eeb4dbf9ec37b17ece0dde51c9e0f381ac | <|skeleton|>
class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
<|body_0|>
def test_course_entry_list(self):
"""Список записей на курс"""
<|body_1|>
def test_get_course_entry(self):
"""Получение записи на к... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
cls.endpoint = '/api/courseentry/'
cls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)
cls.student = StudentFa... | the_stack_v2_python_sparse | education_django/education_app/test_api.py | ilyaignatyev/python-web-otus-ru | train | 0 |
2c9ef78662ec0b05a092d3da18ec6ae627a784da | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IPv6Range()",
"from .ip_range import IpRange\nfrom .ip_range import IpRange\nfields: Dict[str, Callable[[Any], None]] = {'lowerAddress': lambda n: setattr(self, 'lower_address', n.get_str_value()), 'upperAddress': lambda n: setattr(sel... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IPv6Range()
<|end_body_0|>
<|body_start_1|>
from .ip_range import IpRange
from .ip_range import IpRange
fields: Dict[str, Callable[[Any], None]] = {'lowerAddress': lambda n: seta... | IPv6 Range definition. | IPv6Range | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPv6Range:
"""IPv6 Range definition."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IPv6Range:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and ... | stack_v2_sparse_classes_75kplus_train_008323 | 2,237 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: IPv6Range",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(par... | 3 | stack_v2_sparse_classes_30k_train_033878 | Implement the Python class `IPv6Range` described below.
Class description:
IPv6 Range definition.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IPv6Range: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: T... | Implement the Python class `IPv6Range` described below.
Class description:
IPv6 Range definition.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IPv6Range: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: T... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IPv6Range:
"""IPv6 Range definition."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IPv6Range:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPv6Range:
"""IPv6 Range definition."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IPv6Range:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | the_stack_v2_python_sparse | msgraph/generated/models/i_pv6_range.py | microsoftgraph/msgraph-sdk-python | train | 135 |
cbd97486cbc6f45110ffd16fff54e917ac270b9e | [
"try:\n t = DateUtil.nowTimestamp(True)\n img = Image.open(src)\n img.save(dst)\n LogUtil.d('convert {} to {} time: {}ms'.format(src, dst, DateUtil.nowTimestamp(True) - t))\n return True\nexcept Exception as err:\n LogUtil.e('convert 错误信息:', err)\n return False",
"img = Image.open(srcFp)\nif ... | <|body_start_0|>
try:
t = DateUtil.nowTimestamp(True)
img = Image.open(src)
img.save(dst)
LogUtil.d('convert {} to {} time: {}ms'.format(src, dst, DateUtil.nowTimestamp(True) - t))
return True
except Exception as err:
LogUtil.e('con... | ImageUtil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageUtil:
def convert(src, dst):
"""转换图片格式 :param src: 待转换的源图片文件名 :param dst: 转换后的目标文件名 :return: True 转换成功"""
<|body_0|>
def isAllBackPic(srcFp, mode=2):
"""判断是否全黑图片 :param srcFp: 图片路径 :param mode: 检查方式 :return: True 全黑图片"""
<|body_1|>
def isAllWhitePic... | stack_v2_sparse_classes_75kplus_train_008324 | 2,269 | permissive | [
{
"docstring": "转换图片格式 :param src: 待转换的源图片文件名 :param dst: 转换后的目标文件名 :return: True 转换成功",
"name": "convert",
"signature": "def convert(src, dst)"
},
{
"docstring": "判断是否全黑图片 :param srcFp: 图片路径 :param mode: 检查方式 :return: True 全黑图片",
"name": "isAllBackPic",
"signature": "def isAllBackPic(sr... | 4 | stack_v2_sparse_classes_30k_train_000480 | Implement the Python class `ImageUtil` described below.
Class description:
Implement the ImageUtil class.
Method signatures and docstrings:
- def convert(src, dst): 转换图片格式 :param src: 待转换的源图片文件名 :param dst: 转换后的目标文件名 :return: True 转换成功
- def isAllBackPic(srcFp, mode=2): 判断是否全黑图片 :param srcFp: 图片路径 :param mode: 检查方式 :... | Implement the Python class `ImageUtil` described below.
Class description:
Implement the ImageUtil class.
Method signatures and docstrings:
- def convert(src, dst): 转换图片格式 :param src: 待转换的源图片文件名 :param dst: 转换后的目标文件名 :return: True 转换成功
- def isAllBackPic(srcFp, mode=2): 判断是否全黑图片 :param srcFp: 图片路径 :param mode: 检查方式 :... | 24cca5e9aaa56392200da48a1692201e2dfa25c8 | <|skeleton|>
class ImageUtil:
def convert(src, dst):
"""转换图片格式 :param src: 待转换的源图片文件名 :param dst: 转换后的目标文件名 :return: True 转换成功"""
<|body_0|>
def isAllBackPic(srcFp, mode=2):
"""判断是否全黑图片 :param srcFp: 图片路径 :param mode: 检查方式 :return: True 全黑图片"""
<|body_1|>
def isAllWhitePic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageUtil:
def convert(src, dst):
"""转换图片格式 :param src: 待转换的源图片文件名 :param dst: 转换后的目标文件名 :return: True 转换成功"""
try:
t = DateUtil.nowTimestamp(True)
img = Image.open(src)
img.save(dst)
LogUtil.d('convert {} to {} time: {}ms'.format(src, dst, DateU... | the_stack_v2_python_sparse | util/ImageUtil.py | lkl22/CommonTools | train | 2 | |
fac494d833405f87273e1127a7a7637cdfa31235 | [
"train_set = []\nfor tagged_sent in train_sents:\n untagged_sent = nltk.tag.untag(tagged_sent)\n history = []\n for i, (word, tag) in enumerate(tagged_sent):\n featureset = pos_features(untagged_sent, i, history)\n train_set.append((featureset, tag))\n history.append(tag)\nself.classif... | <|body_start_0|>
train_set = []
for tagged_sent in train_sents:
untagged_sent = nltk.tag.untag(tagged_sent)
history = []
for i, (word, tag) in enumerate(tagged_sent):
featureset = pos_features(untagged_sent, i, history)
train_set.append... | Tags parts of speech based upon the previous word's tag. It uses a naive bayes classifier. | ConsecutivePosTagger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsecutivePosTagger:
"""Tags parts of speech based upon the previous word's tag. It uses a naive bayes classifier."""
def __init__(self, train_sents):
"""For the tagged [[(word, pos)]] sentences in the training set, determine the parts of speech features for the each word in the sen... | stack_v2_sparse_classes_75kplus_train_008325 | 3,814 | no_license | [
{
"docstring": "For the tagged [[(word, pos)]] sentences in the training set, determine the parts of speech features for the each word in the sentence. Relate a feature set to a tag and record the sequential position of that parts of speech tag. Run this through a NaiveBayesClassifier",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_000288 | Implement the Python class `ConsecutivePosTagger` described below.
Class description:
Tags parts of speech based upon the previous word's tag. It uses a naive bayes classifier.
Method signatures and docstrings:
- def __init__(self, train_sents): For the tagged [[(word, pos)]] sentences in the training set, determine ... | Implement the Python class `ConsecutivePosTagger` described below.
Class description:
Tags parts of speech based upon the previous word's tag. It uses a naive bayes classifier.
Method signatures and docstrings:
- def __init__(self, train_sents): For the tagged [[(word, pos)]] sentences in the training set, determine ... | 12aceac5752180aebb7b5fab8d2860ab7afadc90 | <|skeleton|>
class ConsecutivePosTagger:
"""Tags parts of speech based upon the previous word's tag. It uses a naive bayes classifier."""
def __init__(self, train_sents):
"""For the tagged [[(word, pos)]] sentences in the training set, determine the parts of speech features for the each word in the sen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsecutivePosTagger:
"""Tags parts of speech based upon the previous word's tag. It uses a naive bayes classifier."""
def __init__(self, train_sents):
"""For the tagged [[(word, pos)]] sentences in the training set, determine the parts of speech features for the each word in the sentence. Relate... | the_stack_v2_python_sparse | python/rdt/nlp/pos.py | juchiyama/bigdata_fall2015 | train | 0 |
bba310e00c1afdffef382cfdc4ce467497ec007c | [
"assert isinstance(X0, numpy.ndarray), 'X0 must be numpy array'\nassert X0.shape == (1, 3), 'X0 must be numpy (3,) array'\nsuper(CirclingParkController, self).__init__(self._circle, self._circle_accel, L, is_ned)\nself._X0 = X0\nself._R = R\nself._direction = numpy.sign(direction)",
"if self._is_ned:\n dx = se... | <|body_start_0|>
assert isinstance(X0, numpy.ndarray), 'X0 must be numpy array'
assert X0.shape == (1, 3), 'X0 must be numpy (3,) array'
super(CirclingParkController, self).__init__(self._circle, self._circle_accel, L, is_ned)
self._X0 = X0
self._R = R
self._direction = n... | A parameterized path controller that is pre-built to do circles | CirclingParkController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CirclingParkController:
"""A parameterized path controller that is pre-built to do circles"""
def __init__(self, X0, R, L, direction=1, is_ned=True):
"""Constructor Arguments: X0: the circle center point numpy (1,3) array (lla or ned depending on the argument is_ned) R: the circle ra... | stack_v2_sparse_classes_75kplus_train_008326 | 19,298 | permissive | [
{
"docstring": "Constructor Arguments: X0: the circle center point numpy (1,3) array (lla or ned depending on the argument is_ned) R: the circle radius (m) L: the lookahead distance on the path. (m) direction: optional, turn direction, sign of the yaw rate. defaults to positive turn rate is_ned: optional flag i... | 3 | stack_v2_sparse_classes_30k_train_046045 | Implement the Python class `CirclingParkController` described below.
Class description:
A parameterized path controller that is pre-built to do circles
Method signatures and docstrings:
- def __init__(self, X0, R, L, direction=1, is_ned=True): Constructor Arguments: X0: the circle center point numpy (1,3) array (lla ... | Implement the Python class `CirclingParkController` described below.
Class description:
A parameterized path controller that is pre-built to do circles
Method signatures and docstrings:
- def __init__(self, X0, R, L, direction=1, is_ned=True): Constructor Arguments: X0: the circle center point numpy (1,3) array (lla ... | 6827886916e36432ce1d806f0a78edef6c9270d9 | <|skeleton|>
class CirclingParkController:
"""A parameterized path controller that is pre-built to do circles"""
def __init__(self, X0, R, L, direction=1, is_ned=True):
"""Constructor Arguments: X0: the circle center point numpy (1,3) array (lla or ned depending on the argument is_ned) R: the circle ra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CirclingParkController:
"""A parameterized path controller that is pre-built to do circles"""
def __init__(self, X0, R, L, direction=1, is_ned=True):
"""Constructor Arguments: X0: the circle center point numpy (1,3) array (lla or ned depending on the argument is_ned) R: the circle radius (m) L: t... | the_stack_v2_python_sparse | pybots/src/robot_control/path_following.py | aivian/robots | train | 0 |
5ff2810bcf32cd45a084ed94fe7dc94340993a4d | [
"if not current_user.is_anonymous and current_user.acl.is_moderator() and (not current_user.acl.is_client_rw(client, server)):\n self.abort(403, \"You don't have rights on this server\")\nargs = self.parser_post.parse_args()\ntemplate = args.get('template', False)\nstatictemplate = args.get('statictemplate', Fal... | <|body_start_0|>
if not current_user.is_anonymous and current_user.acl.is_moderator() and (not current_user.acl.is_client_rw(client, server)):
self.abort(403, "You don't have rights on this server")
args = self.parser_post.parse_args()
template = args.get('template', False)
s... | ClientSettings | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientSettings:
def post(self, server=None, client=None, conf=None):
"""Saves a given client configuration"""
<|body_0|>
def get(self, server=None, client=None, conf=None):
"""Reads a given client configuration"""
<|body_1|>
def delete(self, server=None,... | stack_v2_sparse_classes_75kplus_train_008327 | 35,800 | permissive | [
{
"docstring": "Saves a given client configuration",
"name": "post",
"signature": "def post(self, server=None, client=None, conf=None)"
},
{
"docstring": "Reads a given client configuration",
"name": "get",
"signature": "def get(self, server=None, client=None, conf=None)"
},
{
"d... | 4 | null | Implement the Python class `ClientSettings` described below.
Class description:
Implement the ClientSettings class.
Method signatures and docstrings:
- def post(self, server=None, client=None, conf=None): Saves a given client configuration
- def get(self, server=None, client=None, conf=None): Reads a given client con... | Implement the Python class `ClientSettings` described below.
Class description:
Implement the ClientSettings class.
Method signatures and docstrings:
- def post(self, server=None, client=None, conf=None): Saves a given client configuration
- def get(self, server=None, client=None, conf=None): Reads a given client con... | 2b8c6e09a4174f2ae3545fa048f59c55c4ae7dba | <|skeleton|>
class ClientSettings:
def post(self, server=None, client=None, conf=None):
"""Saves a given client configuration"""
<|body_0|>
def get(self, server=None, client=None, conf=None):
"""Reads a given client configuration"""
<|body_1|>
def delete(self, server=None,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClientSettings:
def post(self, server=None, client=None, conf=None):
"""Saves a given client configuration"""
if not current_user.is_anonymous and current_user.acl.is_moderator() and (not current_user.acl.is_client_rw(client, server)):
self.abort(403, "You don't have rights on this... | the_stack_v2_python_sparse | burpui/api/settings.py | ziirish/burp-ui | train | 98 | |
94bca1698cb0999e911343a71874afa9ae7d63ae | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nself.mate = dict(((node, None) for node in self.graph.iternodes()))\nself.cardinality = 0\nself._pq = PriorityQueue()",
"for edge in self.graph.iteredges():\n self._pq.put((edge.weight, edge))\nwhile not self._pq.empty... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
self.mate = dict(((node, None) for node in self.graph.iternodes()))
self.cardinality = 0
self._pq = PriorityQueue()
<|end_body_0|>
<|body_start_1|>
for edge ... | Find a minimum weight matching using a greedy method. Attributes ---------- graph : input undirected graph mate : dict with nodes (values are edges or None) cardinality : number | MinimumWeightMatchingWithEdges | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinimumWeightMatchingWithEdges:
"""Find a minimum weight matching using a greedy method. Attributes ---------- graph : input undirected graph mate : dict with nodes (values are edges or None) cardinality : number"""
def __init__(self, graph):
"""The algorithm initialization."""
... | stack_v2_sparse_classes_75kplus_train_008328 | 3,502 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024333 | Implement the Python class `MinimumWeightMatchingWithEdges` described below.
Class description:
Find a minimum weight matching using a greedy method. Attributes ---------- graph : input undirected graph mate : dict with nodes (values are edges or None) cardinality : number
Method signatures and docstrings:
- def __in... | Implement the Python class `MinimumWeightMatchingWithEdges` described below.
Class description:
Find a minimum weight matching using a greedy method. Attributes ---------- graph : input undirected graph mate : dict with nodes (values are edges or None) cardinality : number
Method signatures and docstrings:
- def __in... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class MinimumWeightMatchingWithEdges:
"""Find a minimum weight matching using a greedy method. Attributes ---------- graph : input undirected graph mate : dict with nodes (values are edges or None) cardinality : number"""
def __init__(self, graph):
"""The algorithm initialization."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinimumWeightMatchingWithEdges:
"""Find a minimum weight matching using a greedy method. Attributes ---------- graph : input undirected graph mate : dict with nodes (values are edges or None) cardinality : number"""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.i... | the_stack_v2_python_sparse | graphtheory/algorithms/matching.py | kgashok/graphs-dict | train | 0 |
983143aa0915f882aeaee564716774482ff8c522 | [
"self.url = cmds.url\nresponse = requests.get(f'{self.url}').text\nself.htmlcontent = BeautifulSoup(response, 'html.parser')",
"dwnload = cmds.download\nanchors = self.htmlcontent.find_all('img')\nfiltered_list = list(set(anchors))\nfor images in filtered_list:\n print(self.url + images['src'])\n'If --download... | <|body_start_0|>
self.url = cmds.url
response = requests.get(f'{self.url}').text
self.htmlcontent = BeautifulSoup(response, 'html.parser')
<|end_body_0|>
<|body_start_1|>
dwnload = cmds.download
anchors = self.htmlcontent.find_all('img')
filtered_list = list(set(anchors)... | Fetch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fetch:
def __init__(self):
"""Requests passed urls and Store Response for Further use"""
<|body_0|>
def pull_images(self):
"""Scrapes all Images links found in img tage"""
<|body_1|>
def get_all_links(self):
"""Get Scrapes All links found in anch... | stack_v2_sparse_classes_75kplus_train_008329 | 2,996 | permissive | [
{
"docstring": "Requests passed urls and Store Response for Further use",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Scrapes all Images links found in img tage",
"name": "pull_images",
"signature": "def pull_images(self)"
},
{
"docstring": "Get Scrap... | 3 | stack_v2_sparse_classes_30k_test_000783 | Implement the Python class `Fetch` described below.
Class description:
Implement the Fetch class.
Method signatures and docstrings:
- def __init__(self): Requests passed urls and Store Response for Further use
- def pull_images(self): Scrapes all Images links found in img tage
- def get_all_links(self): Get Scrapes A... | Implement the Python class `Fetch` described below.
Class description:
Implement the Fetch class.
Method signatures and docstrings:
- def __init__(self): Requests passed urls and Store Response for Further use
- def pull_images(self): Scrapes all Images links found in img tage
- def get_all_links(self): Get Scrapes A... | 70a3d5d798e2987d37e7562d2e556f364627a59c | <|skeleton|>
class Fetch:
def __init__(self):
"""Requests passed urls and Store Response for Further use"""
<|body_0|>
def pull_images(self):
"""Scrapes all Images links found in img tage"""
<|body_1|>
def get_all_links(self):
"""Get Scrapes All links found in anch... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fetch:
def __init__(self):
"""Requests passed urls and Store Response for Further use"""
self.url = cmds.url
response = requests.get(f'{self.url}').text
self.htmlcontent = BeautifulSoup(response, 'html.parser')
def pull_images(self):
"""Scrapes all Images links fou... | the_stack_v2_python_sparse | Python-Programs/webpage-link-image-scraper/webpage-link-image-scraper/fetch.py | MMVonnSeek/Hacktoberfest-2021 | train | 5 | |
f4f8d64980e522e9acfab0ba35e5d3102c01490d | [
"self.username = username\nself.new_email = new_email\nself.new_password = new_password\nself.confirm_password = confirm_password\nself.credit_type = credit_type",
"if dictionary is None:\n return None\nusername = dictionary.get('username')\nnew_email = dictionary.get('new_email')\nnew_password = dictionary.ge... | <|body_start_0|>
self.username = username
self.new_email = new_email
self.new_password = new_password
self.confirm_password = confirm_password
self.credit_type = credit_type
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
username =... | Implementation of the 'Updatesubaccount' model. UpdateSubaccount modal Attributes: username (string): The username for the subaccount new_email (string): The new email address to be registered with the subaccount new_password (string): The new password of the subaccount confirm_password (string): reconfirm the new pass... | Updatesubaccount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Updatesubaccount:
"""Implementation of the 'Updatesubaccount' model. UpdateSubaccount modal Attributes: username (string): The username for the subaccount new_email (string): The new email address to be registered with the subaccount new_password (string): The new password of the subaccount confi... | stack_v2_sparse_classes_75kplus_train_008330 | 2,670 | permissive | [
{
"docstring": "Constructor for the Updatesubaccount class",
"name": "__init__",
"signature": "def __init__(self, username=None, new_email=None, new_password=None, confirm_password=None, credit_type=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (d... | 2 | stack_v2_sparse_classes_30k_train_041448 | Implement the Python class `Updatesubaccount` described below.
Class description:
Implementation of the 'Updatesubaccount' model. UpdateSubaccount modal Attributes: username (string): The username for the subaccount new_email (string): The new email address to be registered with the subaccount new_password (string): T... | Implement the Python class `Updatesubaccount` described below.
Class description:
Implementation of the 'Updatesubaccount' model. UpdateSubaccount modal Attributes: username (string): The username for the subaccount new_email (string): The new email address to be registered with the subaccount new_password (string): T... | 6e3ac051c5156ea9f9ee46209436675bf78e72ae | <|skeleton|>
class Updatesubaccount:
"""Implementation of the 'Updatesubaccount' model. UpdateSubaccount modal Attributes: username (string): The username for the subaccount new_email (string): The new email address to be registered with the subaccount new_password (string): The new password of the subaccount confi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Updatesubaccount:
"""Implementation of the 'Updatesubaccount' model. UpdateSubaccount modal Attributes: username (string): The username for the subaccount new_email (string): The new email address to be registered with the subaccount new_password (string): The new password of the subaccount confirm_password (... | the_stack_v2_python_sparse | pepipost/models/updatesubaccount.py | pepipost/pepipost-sdk-python | train | 7 |
7131d2bf1e1edca2fafb6106719316580e9a814b | [
"user_name = 'user'\nif user_name in kwargs.keys():\n kwargs.__setitem__('owner', kwargs.get(user_name))\n del kwargs[user_name]\nreturn self.filter(name__icontains=q, **kwargs)",
"level = CategoryLevel.objects.get_root_level()\nfrom cashapp_models.models.CategoryModel import Category\ncategory = Category(n... | <|body_start_0|>
user_name = 'user'
if user_name in kwargs.keys():
kwargs.__setitem__('owner', kwargs.get(user_name))
del kwargs[user_name]
return self.filter(name__icontains=q, **kwargs)
<|end_body_0|>
<|body_start_1|>
level = CategoryLevel.objects.get_root_leve... | Category model manager | CategoryManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryManager:
"""Category model manager"""
def search(self, q, *args, **kwargs):
"""Implementation search method :param q: :param args: :param kwargs: :return:"""
<|body_0|>
def create_root(self, name):
"""Creates unsaved root level category :param name: categ... | stack_v2_sparse_classes_75kplus_train_008331 | 1,855 | no_license | [
{
"docstring": "Implementation search method :param q: :param args: :param kwargs: :return:",
"name": "search",
"signature": "def search(self, q, *args, **kwargs)"
},
{
"docstring": "Creates unsaved root level category :param name: category name :return: {CategoryModel} instance",
"name": "c... | 4 | stack_v2_sparse_classes_30k_train_033740 | Implement the Python class `CategoryManager` described below.
Class description:
Category model manager
Method signatures and docstrings:
- def search(self, q, *args, **kwargs): Implementation search method :param q: :param args: :param kwargs: :return:
- def create_root(self, name): Creates unsaved root level catego... | Implement the Python class `CategoryManager` described below.
Class description:
Category model manager
Method signatures and docstrings:
- def search(self, q, *args, **kwargs): Implementation search method :param q: :param args: :param kwargs: :return:
- def create_root(self, name): Creates unsaved root level catego... | a93e0eee39e1f45fa73de84514ca254e235a17bd | <|skeleton|>
class CategoryManager:
"""Category model manager"""
def search(self, q, *args, **kwargs):
"""Implementation search method :param q: :param args: :param kwargs: :return:"""
<|body_0|>
def create_root(self, name):
"""Creates unsaved root level category :param name: categ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoryManager:
"""Category model manager"""
def search(self, q, *args, **kwargs):
"""Implementation search method :param q: :param args: :param kwargs: :return:"""
user_name = 'user'
if user_name in kwargs.keys():
kwargs.__setitem__('owner', kwargs.get(user_name))
... | the_stack_v2_python_sparse | cashapp_models/managers/CategoryManager.py | dmitryshepelev/cashapp | train | 0 |
e3d81a88d2beae1934c4d4bd3cc410487944496d | [
"self.is_entire_drive_required = is_entire_drive_required\nself.restore_drive_id = restore_drive_id\nself.restore_drive_name = restore_drive_name\nself.restore_path_vec = restore_path_vec",
"if dictionary is None:\n return None\nis_entire_drive_required = dictionary.get('isEntireDriveRequired')\nrestore_drive_... | <|body_start_0|>
self.is_entire_drive_required = is_entire_drive_required
self.restore_drive_id = restore_drive_id
self.restore_drive_name = restore_drive_name
self.restore_path_vec = restore_path_vec
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None... | Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id (string): Id of the drive whose items are being restored. re... | RestoreSiteParams_SiteOwner_Drive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreSiteParams_SiteOwner_Drive:
"""Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id... | stack_v2_sparse_classes_75kplus_train_008332 | 3,026 | permissive | [
{
"docstring": "Constructor for the RestoreSiteParams_SiteOwner_Drive class",
"name": "__init__",
"signature": "def __init__(self, is_entire_drive_required=None, restore_drive_id=None, restore_drive_name=None, restore_path_vec=None)"
},
{
"docstring": "Creates an instance of this model from a di... | 2 | stack_v2_sparse_classes_30k_train_016226 | Implement the Python class `RestoreSiteParams_SiteOwner_Drive` described below.
Class description:
Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if rest... | Implement the Python class `RestoreSiteParams_SiteOwner_Drive` described below.
Class description:
Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if rest... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreSiteParams_SiteOwner_Drive:
"""Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestoreSiteParams_SiteOwner_Drive:
"""Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id (string): Id... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_site_params_site_owner_drive.py | cohesity/management-sdk-python | train | 24 |
0d01091335ff4ddb5f3bb0ef4bf27eecaf5ed676 | [
"self.intercept_params = intercept_params\nself.linear_params = linear_params\nself.intercept_term = np.random.normal(self.intercept_params[0], self.intercept_params[1])\nself.linear_term = np.random.normal(self.linear_params[0], self.linear_params[1])\nsuper().__init__(dataset, noise_sd)",
"new = LinearColumn(da... | <|body_start_0|>
self.intercept_params = intercept_params
self.linear_params = linear_params
self.intercept_term = np.random.normal(self.intercept_params[0], self.intercept_params[1])
self.linear_term = np.random.normal(self.linear_params[0], self.linear_params[1])
super().__init... | A column with linear drift in the RT | LinearColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearColumn:
"""A column with linear drift in the RT"""
def __init__(self, dataset, noise_sd, intercept_params, linear_params):
"""Create a linear drift column Args: dataset: the set of Chemicals that passes through this column noise_sd: noise standard deviation intercept_params: in... | stack_v2_sparse_classes_75kplus_train_008333 | 7,467 | permissive | [
{
"docstring": "Create a linear drift column Args: dataset: the set of Chemicals that passes through this column noise_sd: noise standard deviation intercept_params: intercept parameters linear_params: linear parameters",
"name": "__init__",
"signature": "def __init__(self, dataset, noise_sd, intercept_... | 4 | null | Implement the Python class `LinearColumn` described below.
Class description:
A column with linear drift in the RT
Method signatures and docstrings:
- def __init__(self, dataset, noise_sd, intercept_params, linear_params): Create a linear drift column Args: dataset: the set of Chemicals that passes through this colum... | Implement the Python class `LinearColumn` described below.
Class description:
A column with linear drift in the RT
Method signatures and docstrings:
- def __init__(self, dataset, noise_sd, intercept_params, linear_params): Create a linear drift column Args: dataset: the set of Chemicals that passes through this colum... | e5d97ae4ff42d613fc55db51443e1e733999b908 | <|skeleton|>
class LinearColumn:
"""A column with linear drift in the RT"""
def __init__(self, dataset, noise_sd, intercept_params, linear_params):
"""Create a linear drift column Args: dataset: the set of Chemicals that passes through this column noise_sd: noise standard deviation intercept_params: in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearColumn:
"""A column with linear drift in the RT"""
def __init__(self, dataset, noise_sd, intercept_params, linear_params):
"""Create a linear drift column Args: dataset: the set of Chemicals that passes through this column noise_sd: noise standard deviation intercept_params: intercept param... | the_stack_v2_python_sparse | vimms/Column.py | glasgowcompbio/vimms | train | 22 |
7cfcaa264270376d26b5636d418894e47728364c | [
"super(QCILRenderWindowInteractor, self).__init__(parent, **kw)\nself.__saveModifiers = self._QVTKRenderWindowInteractor__saveModifiers\nself.__saveX = self._QVTKRenderWindowInteractor__saveX\nself.__saveY = self._QVTKRenderWindowInteractor__saveY\nself.__saveButtons = self._QVTKRenderWindowInteractor__saveButtons\... | <|body_start_0|>
super(QCILRenderWindowInteractor, self).__init__(parent, **kw)
self.__saveModifiers = self._QVTKRenderWindowInteractor__saveModifiers
self.__saveX = self._QVTKRenderWindowInteractor__saveX
self.__saveY = self._QVTKRenderWindowInteractor__saveY
self.__saveButtons ... | Extends the QVTKRenderWindowInteractor to accept also ALT modifier | QCILRenderWindowInteractor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCILRenderWindowInteractor:
"""Extends the QVTKRenderWindowInteractor to accept also ALT modifier"""
def __init__(self, parent=None, **kw):
"""Constructor"""
<|body_0|>
def _GetCtrlShiftAlt(self, ev):
"""Get CTRL SHIFT ALT key modifiers"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008334 | 3,441 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent=None, **kw)"
},
{
"docstring": "Get CTRL SHIFT ALT key modifiers",
"name": "_GetCtrlShiftAlt",
"signature": "def _GetCtrlShiftAlt(self, ev)"
},
{
"docstring": "Overload of enterEvent from ba... | 6 | stack_v2_sparse_classes_30k_test_001262 | Implement the Python class `QCILRenderWindowInteractor` described below.
Class description:
Extends the QVTKRenderWindowInteractor to accept also ALT modifier
Method signatures and docstrings:
- def __init__(self, parent=None, **kw): Constructor
- def _GetCtrlShiftAlt(self, ev): Get CTRL SHIFT ALT key modifiers
- def... | Implement the Python class `QCILRenderWindowInteractor` described below.
Class description:
Extends the QVTKRenderWindowInteractor to accept also ALT modifier
Method signatures and docstrings:
- def __init__(self, parent=None, **kw): Constructor
- def _GetCtrlShiftAlt(self, ev): Get CTRL SHIFT ALT key modifiers
- def... | 8c7caca5a78d0f83658a25409abf8291f4a802b7 | <|skeleton|>
class QCILRenderWindowInteractor:
"""Extends the QVTKRenderWindowInteractor to accept also ALT modifier"""
def __init__(self, parent=None, **kw):
"""Constructor"""
<|body_0|>
def _GetCtrlShiftAlt(self, ev):
"""Get CTRL SHIFT ALT key modifiers"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QCILRenderWindowInteractor:
"""Extends the QVTKRenderWindowInteractor to accept also ALT modifier"""
def __init__(self, parent=None, **kw):
"""Constructor"""
super(QCILRenderWindowInteractor, self).__init__(parent, **kw)
self.__saveModifiers = self._QVTKRenderWindowInteractor__sav... | the_stack_v2_python_sparse | Wrappers/Python/ccpi/viewer/QCILRenderWindowInteractor.py | vais-ral/CILViewer | train | 9 |
f773d38eff37d8ef57aaf18ad035fbdb55822427 | [
"UserProfile.objects.create(id=1, password='pbkdf2_sha256$36000$4cg1SAMlOhxd$ONEWDCYTR/kbWBuwpMIo1GUJvMsC+cHZgFUl9YF6KC0=', is_superuser=1, username='cheertt', first_name='cheertt', last_name='油炸皮卡丘', email='1913278504@qq.com', is_staff=1, is_active=1, date_joined='2019-03-01 14:56:48.298648', name='python1234', mo... | <|body_start_0|>
UserProfile.objects.create(id=1, password='pbkdf2_sha256$36000$4cg1SAMlOhxd$ONEWDCYTR/kbWBuwpMIo1GUJvMsC+cHZgFUl9YF6KC0=', is_superuser=1, username='cheertt', first_name='cheertt', last_name='油炸皮卡丘', email='1913278504@qq.com', is_staff=1, is_active=1, date_joined='2019-03-01 14:56:48.298648', n... | UserViewTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserViewTest:
def setUp(self):
"""创建一条用户信息数据 :return: None"""
<|body_0|>
def test_MemberView_get(self):
"""会员管理首页,显示会员列表页面 :return:"""
<|body_1|>
def test_MemberListView_get(self):
"""点击会员管理之后商品列表显示的单元测试 若返回200状态码,表示可以登陆页面可以正常显示 否则,系统BUG,需要检查修复 :... | stack_v2_sparse_classes_75kplus_train_008335 | 5,302 | no_license | [
{
"docstring": "创建一条用户信息数据 :return: None",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "会员管理首页,显示会员列表页面 :return:",
"name": "test_MemberView_get",
"signature": "def test_MemberView_get(self)"
},
{
"docstring": "点击会员管理之后商品列表显示的单元测试 若返回200状态码,表示可以登陆页面可以正常显示 否则,... | 6 | null | Implement the Python class `UserViewTest` described below.
Class description:
Implement the UserViewTest class.
Method signatures and docstrings:
- def setUp(self): 创建一条用户信息数据 :return: None
- def test_MemberView_get(self): 会员管理首页,显示会员列表页面 :return:
- def test_MemberListView_get(self): 点击会员管理之后商品列表显示的单元测试 若返回200状态码,表示可... | Implement the Python class `UserViewTest` described below.
Class description:
Implement the UserViewTest class.
Method signatures and docstrings:
- def setUp(self): 创建一条用户信息数据 :return: None
- def test_MemberView_get(self): 会员管理首页,显示会员列表页面 :return:
- def test_MemberListView_get(self): 点击会员管理之后商品列表显示的单元测试 若返回200状态码,表示可... | e83b94a44e6188b0c745b61512845c3da5cc9643 | <|skeleton|>
class UserViewTest:
def setUp(self):
"""创建一条用户信息数据 :return: None"""
<|body_0|>
def test_MemberView_get(self):
"""会员管理首页,显示会员列表页面 :return:"""
<|body_1|>
def test_MemberListView_get(self):
"""点击会员管理之后商品列表显示的单元测试 若返回200状态码,表示可以登陆页面可以正常显示 否则,系统BUG,需要检查修复 :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserViewTest:
def setUp(self):
"""创建一条用户信息数据 :return: None"""
UserProfile.objects.create(id=1, password='pbkdf2_sha256$36000$4cg1SAMlOhxd$ONEWDCYTR/kbWBuwpMIo1GUJvMsC+cHZgFUl9YF6KC0=', is_superuser=1, username='cheertt', first_name='cheertt', last_name='油炸皮卡丘', email='1913278504@qq.com', is_st... | the_stack_v2_python_sparse | apps/member/tests.py | TTWen/REProject-RED | train | 1 | |
a3e6cc3ade0443014c3434b377cac0177a5ecc51 | [
"if obj.author is None:\n obj.author = request.user\nsuper(AutoAuthoredModelAdmin, self).save_model(request, obj, form, change)",
"if hasattr(formset.model, 'author'):\n instances = formset.save(commit=False)\n for instance in instances:\n if instance.author is None:\n instance.author =... | <|body_start_0|>
if obj.author is None:
obj.author = request.user
super(AutoAuthoredModelAdmin, self).save_model(request, obj, form, change)
<|end_body_0|>
<|body_start_1|>
if hasattr(formset.model, 'author'):
instances = formset.save(commit=False)
for instan... | Mixin d'admin pour appliquer automatiquement un auteur en cas d'absence | AutoAuthoredModelAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoAuthoredModelAdmin:
"""Mixin d'admin pour appliquer automatiquement un auteur en cas d'absence"""
def save_model(self, request, obj, form, change):
"""Enregistrer l'objet en base de données"""
<|body_0|>
def save_formset(self, request, form, formset, change):
... | stack_v2_sparse_classes_75kplus_train_008336 | 5,211 | no_license | [
{
"docstring": "Enregistrer l'objet en base de données",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "Sauvegarder le formset",
"name": "save_formset",
"signature": "def save_formset(self, request, form, formset, change)"
},
... | 4 | stack_v2_sparse_classes_30k_train_043549 | Implement the Python class `AutoAuthoredModelAdmin` described below.
Class description:
Mixin d'admin pour appliquer automatiquement un auteur en cas d'absence
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): Enregistrer l'objet en base de données
- def save_formset(self, request,... | Implement the Python class `AutoAuthoredModelAdmin` described below.
Class description:
Mixin d'admin pour appliquer automatiquement un auteur en cas d'absence
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): Enregistrer l'objet en base de données
- def save_formset(self, request,... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class AutoAuthoredModelAdmin:
"""Mixin d'admin pour appliquer automatiquement un auteur en cas d'absence"""
def save_model(self, request, obj, form, change):
"""Enregistrer l'objet en base de données"""
<|body_0|>
def save_formset(self, request, form, formset, change):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoAuthoredModelAdmin:
"""Mixin d'admin pour appliquer automatiquement un auteur en cas d'absence"""
def save_model(self, request, obj, form, change):
"""Enregistrer l'objet en base de données"""
if obj.author is None:
obj.author = request.user
super(AutoAuthoredModel... | the_stack_v2_python_sparse | scoop/core/abstract/user/authored.py | artscoop/scoop | train | 0 |
a0dfb5a67fa80589aa1f3d741b5232a13827a4ee | [
"con_mysql_connect = con_mysql.connection()\ncursor = con_mysql_connect.cursor()\ncursor.execute('SELECT modeName, modeId FROM mode_list')\ndata = cursor.fetchall()\ncursor.close()\ncon_mysql_connect.close()\nmode_list = list()\nfor mode in data:\n mode_list.append({'modeName': mode[0], 'modeId': mode[1]})\nretu... | <|body_start_0|>
con_mysql_connect = con_mysql.connection()
cursor = con_mysql_connect.cursor()
cursor.execute('SELECT modeName, modeId FROM mode_list')
data = cursor.fetchall()
cursor.close()
con_mysql_connect.close()
mode_list = list()
for mode in data:
... | 新增医院 | AddHospitalData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddHospitalData:
"""新增医院"""
def get(self, request):
"""get请求 返回套餐名称 :param request: :return:"""
<|body_0|>
def post(self, request):
"""该接口完善 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
con_mysql_connect = con_mysql.c... | stack_v2_sparse_classes_75kplus_train_008337 | 18,260 | no_license | [
{
"docstring": "get请求 返回套餐名称 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "该接口完善 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `AddHospitalData` described below.
Class description:
新增医院
Method signatures and docstrings:
- def get(self, request): get请求 返回套餐名称 :param request: :return:
- def post(self, request): 该接口完善 :param request: :return: | Implement the Python class `AddHospitalData` described below.
Class description:
新增医院
Method signatures and docstrings:
- def get(self, request): get请求 返回套餐名称 :param request: :return:
- def post(self, request): 该接口完善 :param request: :return:
<|skeleton|>
class AddHospitalData:
"""新增医院"""
def get(self, reque... | 37b0bbff8818e73fd4897871956cfef446589e2f | <|skeleton|>
class AddHospitalData:
"""新增医院"""
def get(self, request):
"""get请求 返回套餐名称 :param request: :return:"""
<|body_0|>
def post(self, request):
"""该接口完善 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddHospitalData:
"""新增医院"""
def get(self, request):
"""get请求 返回套餐名称 :param request: :return:"""
con_mysql_connect = con_mysql.connection()
cursor = con_mysql_connect.cursor()
cursor.execute('SELECT modeName, modeId FROM mode_list')
data = cursor.fetchall()
... | the_stack_v2_python_sparse | applet_background/participate_hospital_management/hospital_join_views.py | xieboxiebo/escortbed | train | 0 |
474df53acf571da7437fefbb1eda4df859fd377e | [
"super().__init__(product, style_cfg, defer_multi_date=defer_multi_date, stand_alone=stand_alone, user_defined=user_defined)\nstyle_cfg = cast(CFG_DICT, self._raw_cfg)\nself.component_ratio = float(cast(Union[float, str], style_cfg['component_ratio']))\nif self.component_ratio < 0.0 or self.component_ratio > 1.0:\n... | <|body_start_0|>
super().__init__(product, style_cfg, defer_multi_date=defer_multi_date, stand_alone=stand_alone, user_defined=user_defined)
style_cfg = cast(CFG_DICT, self._raw_cfg)
self.component_ratio = float(cast(Union[float, str], style_cfg['component_ratio']))
if self.component_rat... | Hybrid component/colour ramp style type. Returns a linear blend of a component image and colour ramp image | HybridStyleDef | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HybridStyleDef:
"""Hybrid component/colour ramp style type. Returns a linear blend of a component image and colour ramp image"""
def __init__(self, product: 'datacube_ows.ows_configuration.OWSNamedLayer', style_cfg: CFG_DICT, defer_multi_date: bool=False, stand_alone: bool=False, user_define... | stack_v2_sparse_classes_75kplus_train_008338 | 3,676 | permissive | [
{
"docstring": "See StyleBaseDef",
"name": "__init__",
"signature": "def __init__(self, product: 'datacube_ows.ows_configuration.OWSNamedLayer', style_cfg: CFG_DICT, defer_multi_date: bool=False, stand_alone: bool=False, user_defined: bool=False) -> None"
},
{
"docstring": "Apply style to raw da... | 2 | stack_v2_sparse_classes_30k_test_002693 | Implement the Python class `HybridStyleDef` described below.
Class description:
Hybrid component/colour ramp style type. Returns a linear blend of a component image and colour ramp image
Method signatures and docstrings:
- def __init__(self, product: 'datacube_ows.ows_configuration.OWSNamedLayer', style_cfg: CFG_DICT... | Implement the Python class `HybridStyleDef` described below.
Class description:
Hybrid component/colour ramp style type. Returns a linear blend of a component image and colour ramp image
Method signatures and docstrings:
- def __init__(self, product: 'datacube_ows.ows_configuration.OWSNamedLayer', style_cfg: CFG_DICT... | 0ed9b0a39c443cdb1ba54c56eb1ad5caf153ea99 | <|skeleton|>
class HybridStyleDef:
"""Hybrid component/colour ramp style type. Returns a linear blend of a component image and colour ramp image"""
def __init__(self, product: 'datacube_ows.ows_configuration.OWSNamedLayer', style_cfg: CFG_DICT, defer_multi_date: bool=False, stand_alone: bool=False, user_define... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HybridStyleDef:
"""Hybrid component/colour ramp style type. Returns a linear blend of a component image and colour ramp image"""
def __init__(self, product: 'datacube_ows.ows_configuration.OWSNamedLayer', style_cfg: CFG_DICT, defer_multi_date: bool=False, stand_alone: bool=False, user_defined: bool=False... | the_stack_v2_python_sparse | datacube_ows/styles/hybrid.py | ArpitKubadia/datacube-ows | train | 0 |
db7d49b80bbfbd282f0c6467cb4fe8850640ca0b | [
"ofst = _fst.LatticeVectorFst()\nsuccess = self._get_raw_lattice(ofst, use_final_probs)\nif not success:\n raise RuntimeError('Decoding failed. No tokens survived.')\nreturn ofst",
"ofst = _fst.CompactLatticeVectorFst()\nsuccess = self._get_lattice(ofst, use_final_probs)\nif not success:\n raise RuntimeErro... | <|body_start_0|>
ofst = _fst.LatticeVectorFst()
success = self._get_raw_lattice(ofst, use_final_probs)
if not success:
raise RuntimeError('Decoding failed. No tokens survived.')
return ofst
<|end_body_0|>
<|body_start_1|>
ofst = _fst.CompactLatticeVectorFst()
... | Base class defining the Python API for lattice generating decoders. | _LatticeDecoderBase | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LatticeDecoderBase:
"""Base class defining the Python API for lattice generating decoders."""
def get_raw_lattice(self, use_final_probs=True):
"""Gets raw state-level lattice. The output raw lattice will be topologically sorted. Args: use_final_probs (bool): If ``True`` and a final ... | stack_v2_sparse_classes_75kplus_train_008339 | 10,445 | permissive | [
{
"docstring": "Gets raw state-level lattice. The output raw lattice will be topologically sorted. Args: use_final_probs (bool): If ``True`` and a final state of the graph is reached, then the output will include final probabilities given by the graph. Otherwise all final probabilities are treated as one. Retur... | 2 | stack_v2_sparse_classes_30k_train_030198 | Implement the Python class `_LatticeDecoderBase` described below.
Class description:
Base class defining the Python API for lattice generating decoders.
Method signatures and docstrings:
- def get_raw_lattice(self, use_final_probs=True): Gets raw state-level lattice. The output raw lattice will be topologically sorte... | Implement the Python class `_LatticeDecoderBase` described below.
Class description:
Base class defining the Python API for lattice generating decoders.
Method signatures and docstrings:
- def get_raw_lattice(self, use_final_probs=True): Gets raw state-level lattice. The output raw lattice will be topologically sorte... | b482f79a334383a16a3805d658aa221ca3d23c6d | <|skeleton|>
class _LatticeDecoderBase:
"""Base class defining the Python API for lattice generating decoders."""
def get_raw_lattice(self, use_final_probs=True):
"""Gets raw state-level lattice. The output raw lattice will be topologically sorted. Args: use_final_probs (bool): If ``True`` and a final ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _LatticeDecoderBase:
"""Base class defining the Python API for lattice generating decoders."""
def get_raw_lattice(self, use_final_probs=True):
"""Gets raw state-level lattice. The output raw lattice will be topologically sorted. Args: use_final_probs (bool): If ``True`` and a final state of the ... | the_stack_v2_python_sparse | kaldi/decoder/_decoder.py | pykaldi/pykaldi | train | 1,019 |
1c362f3bb9fd45986f7a19bc6cf65905f25b78a5 | [
"self._shape = shape\nself._field = field\nself._comp = comp\nself._bounds = bounds\nself._data = numpy.zeros(self._shape, dtype='double')",
"if self._comp == 0:\n self._data -= Grid.C / Grid.Z0 * (other[0]._data[:, 1:] - other[0]._data[:, :-1])\nelif self._comp == 1:\n self._data += Grid.C / Grid.Z0 * (oth... | <|body_start_0|>
self._shape = shape
self._field = field
self._comp = comp
self._bounds = bounds
self._data = numpy.zeros(self._shape, dtype='double')
<|end_body_0|>
<|body_start_1|>
if self._comp == 0:
self._data -= Grid.C / Grid.Z0 * (other[0]._data[:, 1:] ... | Class that represents a single field component over the whole grid or a subset of it # TODO next clean up :) | Field | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Field:
"""Class that represents a single field component over the whole grid or a subset of it # TODO next clean up :)"""
def __init__(self, shape, field, comp, bounds=None):
"""Create an object representing a field component over the grid or a subset of the grid :param shape: tuple ... | stack_v2_sparse_classes_75kplus_train_008340 | 6,532 | permissive | [
{
"docstring": "Create an object representing a field component over the grid or a subset of the grid :param shape: tuple representing the number of points along x and y :param field: electric or magnetic field :param comp: x, y, or z component :param bounds: dictionary of boundaries on the four edges",
"na... | 2 | null | Implement the Python class `Field` described below.
Class description:
Class that represents a single field component over the whole grid or a subset of it # TODO next clean up :)
Method signatures and docstrings:
- def __init__(self, shape, field, comp, bounds=None): Create an object representing a field component o... | Implement the Python class `Field` described below.
Class description:
Class that represents a single field component over the whole grid or a subset of it # TODO next clean up :)
Method signatures and docstrings:
- def __init__(self, shape, field, comp, bounds=None): Create an object representing a field component o... | 9311c754046c6d5ab4638d4ea23d5119d434cbdc | <|skeleton|>
class Field:
"""Class that represents a single field component over the whole grid or a subset of it # TODO next clean up :)"""
def __init__(self, shape, field, comp, bounds=None):
"""Create an object representing a field component over the grid or a subset of the grid :param shape: tuple ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Field:
"""Class that represents a single field component over the whole grid or a subset of it # TODO next clean up :)"""
def __init__(self, shape, field, comp, bounds=None):
"""Create an object representing a field component over the grid or a subset of the grid :param shape: tuple representing ... | the_stack_v2_python_sparse | engine/solver.py | joelberk/FDTD-PoC | train | 0 |
d7e08d9fe74455f70df4be5b7c4ca61f6214f580 | [
"if name is None:\n name = 'simple_conv_net_{}'.format(network_type)\nsuper(SimpleConvNet, self).__init__(name=name)\nself._conv_spec = conv_spec\nself._use_bias = use_bias\nself._initializers = initializers\nself._initializers_no_bias = initializers_no_bias\nself._regularizers = regularizers\nself._regularizers... | <|body_start_0|>
if name is None:
name = 'simple_conv_net_{}'.format(network_type)
super(SimpleConvNet, self).__init__(name=name)
self._conv_spec = conv_spec
self._use_bias = use_bias
self._initializers = initializers
self._initializers_no_bias = initializers_... | A simple convolutional network. | SimpleConvNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleConvNet:
"""A simple convolutional network."""
def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_bias=None, regularizers=None, regularizers_no_bias=None, name=None):... | stack_v2_sparse_classes_75kplus_train_008341 | 31,363 | no_license | [
{
"docstring": "Constructs a SimpleConvNet. Args: conv_spec: A tuple specifying the parameters of the network. Each entry is a NamedTuple, with the values of the corresponding layer. network_type: Determines whether the network is an 'encoder' or 'decoder'. The former can specify pooling layers, while the latte... | 2 | stack_v2_sparse_classes_30k_train_005845 | Implement the Python class `SimpleConvNet` described below.
Class description:
A simple convolutional network.
Method signatures and docstrings:
- def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_... | Implement the Python class `SimpleConvNet` described below.
Class description:
A simple convolutional network.
Method signatures and docstrings:
- def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_... | 358a09d491aab0794df9cc7f3f8064430a78fbc3 | <|skeleton|>
class SimpleConvNet:
"""A simple convolutional network."""
def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_bias=None, regularizers=None, regularizers_no_bias=None, name=None):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleConvNet:
"""A simple convolutional network."""
def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_bias=None, regularizers=None, regularizers_no_bias=None, name=None):
"""C... | the_stack_v2_python_sparse | architectures/conv_architectures.py | zwbgood6/temporal-hierarchy | train | 0 |
3849b66c415823cc707222ffe324f2aebd91a93a | [
"super(Decoder, self).__init__()\nself.layers = clones(layer, N)\nself.norm = LayerNorm(layer.size)",
"for layer in self.layers:\n x = layer(x, memory, src_mask, tgt_mask)\nreturn self.norm(x)"
] | <|body_start_0|>
super(Decoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
<|end_body_0|>
<|body_start_1|>
for layer in self.layers:
x = layer(x, memory, src_mask, tgt_mask)
return self.norm(x)
<|end_body_1|>
| Generic N layer decoder with masking. | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Generic N layer decoder with masking."""
def __init__(self, layer, N):
""":param layer: :param N:"""
<|body_0|>
def forward(self, x, memory, src_mask, tgt_mask):
""":param x: :param memory: :param src_mask: :param tgt_mask: :return:"""
<|body_... | stack_v2_sparse_classes_75kplus_train_008342 | 767 | no_license | [
{
"docstring": ":param layer: :param N:",
"name": "__init__",
"signature": "def __init__(self, layer, N)"
},
{
"docstring": ":param x: :param memory: :param src_mask: :param tgt_mask: :return:",
"name": "forward",
"signature": "def forward(self, x, memory, src_mask, tgt_mask)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018768 | Implement the Python class `Decoder` described below.
Class description:
Generic N layer decoder with masking.
Method signatures and docstrings:
- def __init__(self, layer, N): :param layer: :param N:
- def forward(self, x, memory, src_mask, tgt_mask): :param x: :param memory: :param src_mask: :param tgt_mask: :retur... | Implement the Python class `Decoder` described below.
Class description:
Generic N layer decoder with masking.
Method signatures and docstrings:
- def __init__(self, layer, N): :param layer: :param N:
- def forward(self, x, memory, src_mask, tgt_mask): :param x: :param memory: :param src_mask: :param tgt_mask: :retur... | a56a7bed796987d8c012b9c568a2aaefbc072119 | <|skeleton|>
class Decoder:
"""Generic N layer decoder with masking."""
def __init__(self, layer, N):
""":param layer: :param N:"""
<|body_0|>
def forward(self, x, memory, src_mask, tgt_mask):
""":param x: :param memory: :param src_mask: :param tgt_mask: :return:"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
"""Generic N layer decoder with masking."""
def __init__(self, layer, N):
""":param layer: :param N:"""
super(Decoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, memory, src_mask, tgt_mask):
... | the_stack_v2_python_sparse | transformer_package/decoder.py | allenmien/Learn_Scripts_3 | train | 0 |
b9581b26684bd902214d637d1c26db16f0d36a40 | [
"self.base_url = 'https://data.lacity.org/resource/'\nself.base_url_and_endpoint = self.base_url + endpoint + '.csv?'\nself.parameters = parameters\nself.label = label\nself.app_token = app_token\nself.pandas_kwargs = pandas_kwargs\nif '$$app_token' in parameters:\n raise RuntimeError('Use app_token option in co... | <|body_start_0|>
self.base_url = 'https://data.lacity.org/resource/'
self.base_url_and_endpoint = self.base_url + endpoint + '.csv?'
self.parameters = parameters
self.label = label
self.app_token = app_token
self.pandas_kwargs = pandas_kwargs
if '$$app_token' in p... | Class for handling data requests to data.lacity.org | DataFetcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFetcher:
"""Class for handling data requests to data.lacity.org"""
def __init__(self, endpoint, parameters, label, verbose=False, app_token=None, **pandas_kwargs):
"""Initialize Data Fetcher for accessing data.lacity.org @param endpoint: Data endpoint string @param parameters: Pa... | stack_v2_sparse_classes_75kplus_train_008343 | 3,472 | permissive | [
{
"docstring": "Initialize Data Fetcher for accessing data.lacity.org @param endpoint: Data endpoint string @param parameters: Parameters to use when retrieving dta @param label: Label of pandas dataframe @param verbose: Print out extra information @param app_token: Application token to use to avoid throttling ... | 2 | stack_v2_sparse_classes_30k_train_035694 | Implement the Python class `DataFetcher` described below.
Class description:
Class for handling data requests to data.lacity.org
Method signatures and docstrings:
- def __init__(self, endpoint, parameters, label, verbose=False, app_token=None, **pandas_kwargs): Initialize Data Fetcher for accessing data.lacity.org @p... | Implement the Python class `DataFetcher` described below.
Class description:
Class for handling data requests to data.lacity.org
Method signatures and docstrings:
- def __init__(self, endpoint, parameters, label, verbose=False, app_token=None, **pandas_kwargs): Initialize Data Fetcher for accessing data.lacity.org @p... | 935bfd54149abd9542fe38e77b7eabab48b1c3a1 | <|skeleton|>
class DataFetcher:
"""Class for handling data requests to data.lacity.org"""
def __init__(self, endpoint, parameters, label, verbose=False, app_token=None, **pandas_kwargs):
"""Initialize Data Fetcher for accessing data.lacity.org @param endpoint: Data endpoint string @param parameters: Pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataFetcher:
"""Class for handling data requests to data.lacity.org"""
def __init__(self, endpoint, parameters, label, verbose=False, app_token=None, **pandas_kwargs):
"""Initialize Data Fetcher for accessing data.lacity.org @param endpoint: Data endpoint string @param parameters: Parameters to u... | the_stack_v2_python_sparse | skdaccess/engineering/la/generic/stream.py | MITHaystack/scikit-dataaccess | train | 41 |
19b9893a324a8f723380c068fb7a85bbf7ef22f7 | [
"username = claims.get(os.environ.get('CLAIMS_ENDPOINT') + 'username')\nif not username:\n return HttpResponse('No username provided, contact support.')\ntry:\n user = User.objects.filter(username=username)\n return user\nexcept User.DoesNotExist:\n return self.UserModel.objects.none()",
"user = super... | <|body_start_0|>
username = claims.get(os.environ.get('CLAIMS_ENDPOINT') + 'username')
if not username:
return HttpResponse('No username provided, contact support.')
try:
user = User.objects.filter(username=username)
return user
except User.DoesNotExis... | MyOIDCAB | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyOIDCAB:
def filter_users_by_claims(self, claims):
"""Checks to see if user exists and create user if not Linux foundation does not allow users to change their username, so chose to match users based on their username. If this changes we will need to match users based on some other crit... | stack_v2_sparse_classes_75kplus_train_008344 | 8,249 | permissive | [
{
"docstring": "Checks to see if user exists and create user if not Linux foundation does not allow users to change their username, so chose to match users based on their username. If this changes we will need to match users based on some other criterea.",
"name": "filter_users_by_claims",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_020977 | Implement the Python class `MyOIDCAB` described below.
Class description:
Implement the MyOIDCAB class.
Method signatures and docstrings:
- def filter_users_by_claims(self, claims): Checks to see if user exists and create user if not Linux foundation does not allow users to change their username, so chose to match us... | Implement the Python class `MyOIDCAB` described below.
Class description:
Implement the MyOIDCAB class.
Method signatures and docstrings:
- def filter_users_by_claims(self, claims): Checks to see if user exists and create user if not Linux foundation does not allow users to change their username, so chose to match us... | 886a644432ff53f97babccbae4eee555338caec1 | <|skeleton|>
class MyOIDCAB:
def filter_users_by_claims(self, claims):
"""Checks to see if user exists and create user if not Linux foundation does not allow users to change their username, so chose to match users based on their username. If this changes we will need to match users based on some other crit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyOIDCAB:
def filter_users_by_claims(self, claims):
"""Checks to see if user exists and create user if not Linux foundation does not allow users to change their username, so chose to match users based on their username. If this changes we will need to match users based on some other criterea."""
... | the_stack_v2_python_sparse | src/account/views.py | opnfv/laas | train | 3 | |
f7b0d716b3202ae85f8593e8e999a52f1a143b04 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = IOSDatausageEventData()\nevent_data.bundle_identifier = self._GetRowValue(query_hash, row, 'ZBUNDLENAME')\neven... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = IOSDatausageEventData()
... | SQLite parser plugin for iOS DataUsage database. | IOSDatausagePlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOSDatausagePlugin:
"""SQLite parser plugin for iOS DataUsage database."""
def _GetTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. ro... | stack_v2_sparse_classes_75kplus_train_008345 | 4,379 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.CocoaTime: date and time value or None if not available.",
"name... | 2 | stack_v2_sparse_classes_30k_train_003126 | Implement the Python class `IOSDatausagePlugin` described below.
Class description:
SQLite parser plugin for iOS DataUsage database.
Method signatures and docstrings:
- def _GetTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, tha... | Implement the Python class `IOSDatausagePlugin` described below.
Class description:
SQLite parser plugin for iOS DataUsage database.
Method signatures and docstrings:
- def _GetTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, tha... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class IOSDatausagePlugin:
"""SQLite parser plugin for iOS DataUsage database."""
def _GetTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. ro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IOSDatausagePlugin:
"""SQLite parser plugin for iOS DataUsage database."""
def _GetTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Ro... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/ios_datausage.py | log2timeline/plaso | train | 1,506 |
1a349d7d58bf852ae911793403c4e5977fc6c1ec | [
"self.new_category(name.encode())\nfor column in columns:\n self.new_column(column.encode())",
"self.new_row()\nself.rewind_column()\nfor item in data:\n try:\n self.set_value(item.encode())\n except AttributeError:\n self.set_value(item)\n if item == '.':\n self.set_typeofvalue(b... | <|body_start_0|>
self.new_category(name.encode())
for column in columns:
self.new_column(column.encode())
<|end_body_0|>
<|body_start_1|>
self.new_row()
self.rewind_column()
for item in data:
try:
self.set_value(item.encode())
... | Wrapper class that provides convenience functions for working with cbflib | cbf_wrapper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cbf_wrapper:
"""Wrapper class that provides convenience functions for working with cbflib"""
def add_category(self, name, columns):
"""Create a new category and populate it with column names"""
<|body_0|>
def add_row(self, data):
"""Add a row to the current categ... | stack_v2_sparse_classes_75kplus_train_008346 | 7,825 | permissive | [
{
"docstring": "Create a new category and populate it with column names",
"name": "add_category",
"signature": "def add_category(self, name, columns)"
},
{
"docstring": "Add a row to the current category. If data contains more entries than there are columns in this category, then the remainder i... | 3 | stack_v2_sparse_classes_30k_train_043692 | Implement the Python class `cbf_wrapper` described below.
Class description:
Wrapper class that provides convenience functions for working with cbflib
Method signatures and docstrings:
- def add_category(self, name, columns): Create a new category and populate it with column names
- def add_row(self, data): Add a row... | Implement the Python class `cbf_wrapper` described below.
Class description:
Wrapper class that provides convenience functions for working with cbflib
Method signatures and docstrings:
- def add_category(self, name, columns): Create a new category and populate it with column names
- def add_row(self, data): Add a row... | 2fc8ffadbf67d0611e2d7affcf50d0f23abfc16f | <|skeleton|>
class cbf_wrapper:
"""Wrapper class that provides convenience functions for working with cbflib"""
def add_category(self, name, columns):
"""Create a new category and populate it with column names"""
<|body_0|>
def add_row(self, data):
"""Add a row to the current categ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class cbf_wrapper:
"""Wrapper class that provides convenience functions for working with cbflib"""
def add_category(self, name, columns):
"""Create a new category and populate it with column names"""
self.new_category(name.encode())
for column in columns:
self.new_column(col... | the_stack_v2_python_sparse | src/dxtbx/format/FormatCBFMultiTile.py | cctbx/dxtbx | train | 2 |
ce20f94ac8a6b5ea5cebc5a581fe60168cbd28a3 | [
"unconfirmed_orders = self.filtered(lambda so: so.state not in ['sale', 'done'])\nunconfirmed_orders.invoice_status = 'no'\nconfirmed_orders = self - unconfirmed_orders\nif not confirmed_orders:\n return\nline_invoice_status_all = [(d['order_id'][0], d['invoice_status']) for d in self.env['sale.order.line'].read... | <|body_start_0|>
unconfirmed_orders = self.filtered(lambda so: so.state not in ['sale', 'done'])
unconfirmed_orders.invoice_status = 'no'
confirmed_orders = self - unconfirmed_orders
if not confirmed_orders:
return
line_invoice_status_all = [(d['order_id'][0], d['invo... | SaleOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleOrder:
def _get_invoice_status(self):
"""Compute the invoice status of a SO. Possible statuses: - no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to invoice. This is also the default value if the conditions of no other status is met. - to invoice: i... | stack_v2_sparse_classes_75kplus_train_008347 | 4,886 | no_license | [
{
"docstring": "Compute the invoice status of a SO. Possible statuses: - no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to invoice. This is also the default value if the conditions of no other status is met. - to invoice: if any SO line is 'to invoice', the whole SO is 'to in... | 2 | stack_v2_sparse_classes_30k_train_017879 | Implement the Python class `SaleOrder` described below.
Class description:
Implement the SaleOrder class.
Method signatures and docstrings:
- def _get_invoice_status(self): Compute the invoice status of a SO. Possible statuses: - no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to in... | Implement the Python class `SaleOrder` described below.
Class description:
Implement the SaleOrder class.
Method signatures and docstrings:
- def _get_invoice_status(self): Compute the invoice status of a SO. Possible statuses: - no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to in... | 527ca57ace3d10f4f76ef0fd8a46f9f4a0581cc9 | <|skeleton|>
class SaleOrder:
def _get_invoice_status(self):
"""Compute the invoice status of a SO. Possible statuses: - no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to invoice. This is also the default value if the conditions of no other status is met. - to invoice: i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaleOrder:
def _get_invoice_status(self):
"""Compute the invoice status of a SO. Possible statuses: - no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to invoice. This is also the default value if the conditions of no other status is met. - to invoice: if any SO line ... | the_stack_v2_python_sparse | custom_modules/sale_report_custom/models/sale_invoice_status_custom.py | westlyou/foodsfortomorrow | train | 0 | |
b4b0807c17bea4045f9541a0c7bf9468d585908c | [
"if isinstance(cls.config, FinestrinoConfigParser):\n return False\ntry:\n logging_config = cls.config['logging']\nexcept (TypeError, KeyError, NoSectionError):\n return False\nlogging.config.dictConfig(logging_config)\nreturn True",
"logger = logging.getLogger('finestrino')\nif cls._configured:\n log... | <|body_start_0|>
if isinstance(cls.config, FinestrinoConfigParser):
return False
try:
logging_config = cls.config['logging']
except (TypeError, KeyError, NoSectionError):
return False
logging.config.dictConfig(logging_config)
return True
<|end_... | BaseLogging | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseLogging:
def _section(cls, opts):
"""Get logging settings from config file "logging"."""
<|body_0|>
def setup(cls, opts=type('opts', (), {'background': None, 'logdir': None, 'logging_conf_file': None, 'log_level': 'DEBUG'})):
"""Setup logging via CLI params and c... | stack_v2_sparse_classes_75kplus_train_008348 | 5,132 | no_license | [
{
"docstring": "Get logging settings from config file \"logging\".",
"name": "_section",
"signature": "def _section(cls, opts)"
},
{
"docstring": "Setup logging via CLI params and config.",
"name": "setup",
"signature": "def setup(cls, opts=type('opts', (), {'background': None, 'logdir':... | 2 | stack_v2_sparse_classes_30k_train_023076 | Implement the Python class `BaseLogging` described below.
Class description:
Implement the BaseLogging class.
Method signatures and docstrings:
- def _section(cls, opts): Get logging settings from config file "logging".
- def setup(cls, opts=type('opts', (), {'background': None, 'logdir': None, 'logging_conf_file': N... | Implement the Python class `BaseLogging` described below.
Class description:
Implement the BaseLogging class.
Method signatures and docstrings:
- def _section(cls, opts): Get logging settings from config file "logging".
- def setup(cls, opts=type('opts', (), {'background': None, 'logdir': None, 'logging_conf_file': N... | a9bb052608b47f8cd515c4983cfa178a0af96a0b | <|skeleton|>
class BaseLogging:
def _section(cls, opts):
"""Get logging settings from config file "logging"."""
<|body_0|>
def setup(cls, opts=type('opts', (), {'background': None, 'logdir': None, 'logging_conf_file': None, 'log_level': 'DEBUG'})):
"""Setup logging via CLI params and c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseLogging:
def _section(cls, opts):
"""Get logging settings from config file "logging"."""
if isinstance(cls.config, FinestrinoConfigParser):
return False
try:
logging_config = cls.config['logging']
except (TypeError, KeyError, NoSectionError):
... | the_stack_v2_python_sparse | vibm/finestrino/finestrino/setup_logging.py | mvimplis2013/port_scanner | train | 0 | |
3f1cc7a524db9dd65f30dd029ec638665f3b0b41 | [
"bloc_names2country_codes = {b.name: [c.code for c in b.countries.all()] for b in Bloc.objects.prefetch_related('countries')}\nall_country_codes = set(Country.objects.values_list('code', flat=True))\ndecomposer = SetDecomposer(bloc_names2country_codes, all_country_codes)\nreturn lambda countries: decomposer.decompo... | <|body_start_0|>
bloc_names2country_codes = {b.name: [c.code for c in b.countries.all()] for b in Bloc.objects.prefetch_related('countries')}
all_country_codes = set(Country.objects.values_list('code', flat=True))
decomposer = SetDecomposer(bloc_names2country_codes, all_country_codes)
re... | BlocManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlocManager:
def make_get_description_from_countries(self) -> 'Callable[[Iterable[Country]], str]':
"""Return a function taking as input an iterable of countries and returning a string describing the set of countries in terms of blocs."""
<|body_0|>
def get_country_id2contai... | stack_v2_sparse_classes_75kplus_train_008349 | 1,851 | no_license | [
{
"docstring": "Return a function taking as input an iterable of countries and returning a string describing the set of countries in terms of blocs.",
"name": "make_get_description_from_countries",
"signature": "def make_get_description_from_countries(self) -> 'Callable[[Iterable[Country]], str]'"
},
... | 2 | stack_v2_sparse_classes_30k_train_027910 | Implement the Python class `BlocManager` described below.
Class description:
Implement the BlocManager class.
Method signatures and docstrings:
- def make_get_description_from_countries(self) -> 'Callable[[Iterable[Country]], str]': Return a function taking as input an iterable of countries and returning a string des... | Implement the Python class `BlocManager` described below.
Class description:
Implement the BlocManager class.
Method signatures and docstrings:
- def make_get_description_from_countries(self) -> 'Callable[[Iterable[Country]], str]': Return a function taking as input an iterable of countries and returning a string des... | 196e849cb70de44523132e67659f8344f8d5cc0a | <|skeleton|>
class BlocManager:
def make_get_description_from_countries(self) -> 'Callable[[Iterable[Country]], str]':
"""Return a function taking as input an iterable of countries and returning a string describing the set of countries in terms of blocs."""
<|body_0|>
def get_country_id2contai... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlocManager:
def make_get_description_from_countries(self) -> 'Callable[[Iterable[Country]], str]':
"""Return a function taking as input an iterable of countries and returning a string describing the set of countries in terms of blocs."""
bloc_names2country_codes = {b.name: [c.code for c in b.... | the_stack_v2_python_sparse | backend/app/models/bloc.py | dandavison/_owldock | train | 0 | |
b756604d267a19ea6b386f7d8b889b9a131ef5d2 | [
"user = request.user\ntry:\n product = Product.objects.get(pk=product_pk)\n wishlist, _ = WishList.objects.get_or_create(owner=user)\n wishlist.add(product)\n return Response(err_result(SUCCESS_CODE, u'关注成功').msg)\nexcept Exception as e:\n logging.exception(e)\n return Response(err_result(SYSTEM_E... | <|body_start_0|>
user = request.user
try:
product = Product.objects.get(pk=product_pk)
wishlist, _ = WishList.objects.get_or_create(owner=user)
wishlist.add(product)
return Response(err_result(SUCCESS_CODE, u'关注成功').msg)
except Exception as e:
... | AppMyFavProduct | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppMyFavProduct:
def post(self, request, product_pk, *args, **kwargs):
"""添加商品到我的关注 :param request: :param product_pk: 商品id :param args: :param kwargs: :return:"""
<|body_0|>
def delete(self, request, product_pk, format=None):
"""从我的关注里删除关注商品 :param request: :param p... | stack_v2_sparse_classes_75kplus_train_008350 | 4,827 | no_license | [
{
"docstring": "添加商品到我的关注 :param request: :param product_pk: 商品id :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, request, product_pk, *args, **kwargs)"
},
{
"docstring": "从我的关注里删除关注商品 :param request: :param product_pk:商品id :param format: :return: SUCCESS_CODE... | 2 | stack_v2_sparse_classes_30k_test_003008 | Implement the Python class `AppMyFavProduct` described below.
Class description:
Implement the AppMyFavProduct class.
Method signatures and docstrings:
- def post(self, request, product_pk, *args, **kwargs): 添加商品到我的关注 :param request: :param product_pk: 商品id :param args: :param kwargs: :return:
- def delete(self, requ... | Implement the Python class `AppMyFavProduct` described below.
Class description:
Implement the AppMyFavProduct class.
Method signatures and docstrings:
- def post(self, request, product_pk, *args, **kwargs): 添加商品到我的关注 :param request: :param product_pk: 商品id :param args: :param kwargs: :return:
- def delete(self, requ... | 3d6198c2a1abc97fa9286408f52c1f5153883b7a | <|skeleton|>
class AppMyFavProduct:
def post(self, request, product_pk, *args, **kwargs):
"""添加商品到我的关注 :param request: :param product_pk: 商品id :param args: :param kwargs: :return:"""
<|body_0|>
def delete(self, request, product_pk, format=None):
"""从我的关注里删除关注商品 :param request: :param p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppMyFavProduct:
def post(self, request, product_pk, *args, **kwargs):
"""添加商品到我的关注 :param request: :param product_pk: 商品id :param args: :param kwargs: :return:"""
user = request.user
try:
product = Product.objects.get(pk=product_pk)
wishlist, _ = WishList.objec... | the_stack_v2_python_sparse | stars/apps/api/wishlists/views.py | lisongwei15931/stars | train | 0 | |
89e6ec5aec2e3f68ea95f4451449ea9adcff015a | [
"super().construct_global_ctx()\ngtx = self.gtx\nrc = self.rc\ngtx['month_and_year'] = month_and_year\ngtx['latex_safe'] = latex_safe\ngtx['people'] = sorted(all_docs_from_collection(rc.client, 'people'), key=position_key, reverse=True)\ngtx['all_docs_from_collection'] = all_docs_from_collection",
"rc = self.rc\n... | <|body_start_0|>
super().construct_global_ctx()
gtx = self.gtx
rc = self.rc
gtx['month_and_year'] = month_and_year
gtx['latex_safe'] = latex_safe
gtx['people'] = sorted(all_docs_from_collection(rc.client, 'people'), key=position_key, reverse=True)
gtx['all_docs_fr... | Build resume from database entries | ResumeBuilder | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResumeBuilder:
"""Build resume from database entries"""
def construct_global_ctx(self):
"""Constructs the global context"""
<|body_0|>
def latex(self):
"""Render latex template"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().construct_gl... | stack_v2_sparse_classes_75kplus_train_008351 | 3,071 | permissive | [
{
"docstring": "Constructs the global context",
"name": "construct_global_ctx",
"signature": "def construct_global_ctx(self)"
},
{
"docstring": "Render latex template",
"name": "latex",
"signature": "def latex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041165 | Implement the Python class `ResumeBuilder` described below.
Class description:
Build resume from database entries
Method signatures and docstrings:
- def construct_global_ctx(self): Constructs the global context
- def latex(self): Render latex template | Implement the Python class `ResumeBuilder` described below.
Class description:
Build resume from database entries
Method signatures and docstrings:
- def construct_global_ctx(self): Constructs the global context
- def latex(self): Render latex template
<|skeleton|>
class ResumeBuilder:
"""Build resume from datab... | a0ebf84971c50a6cc444c040e1f2c50c52289a41 | <|skeleton|>
class ResumeBuilder:
"""Build resume from database entries"""
def construct_global_ctx(self):
"""Constructs the global context"""
<|body_0|>
def latex(self):
"""Render latex template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResumeBuilder:
"""Build resume from database entries"""
def construct_global_ctx(self):
"""Constructs the global context"""
super().construct_global_ctx()
gtx = self.gtx
rc = self.rc
gtx['month_and_year'] = month_and_year
gtx['latex_safe'] = latex_safe
... | the_stack_v2_python_sparse | regolith/builders/resumebuilder.py | sbillinge/regolith | train | 1 |
bdcf768f75c74f4900f61438a4ee56b1ff924fec | [
"cached_state = None\nif self.cli_state is self.SHELL:\n cached_state = self.SHELL\nif self.cli_state is not self.CONFIG:\n self._drive_cli_state(self.cli_state, self.CONFIG)\nerr_cmd, status = (None, True)\nerr_msg = None\ncmd_list = self._va_list_of_cmds(cmd)\nfor each_cmd in cmd_list:\n output, status =... | <|body_start_0|>
cached_state = None
if self.cli_state is self.SHELL:
cached_state = self.SHELL
if self.cli_state is not self.CONFIG:
self._drive_cli_state(self.cli_state, self.CONFIG)
err_cmd, status = (None, True)
err_msg = None
cmd_list = self._... | Access implements methods that translate to executing cli commands remotely on the director. | VaAccess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaAccess:
"""Access implements methods that translate to executing cli commands remotely on the director."""
def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs):
"""method calls the _va_exec_cli_cmd method of the access layer. kwargs: :cmd (str|list): a single... | stack_v2_sparse_classes_75kplus_train_008352 | 5,550 | no_license | [
{
"docstring": "method calls the _va_exec_cli_cmd method of the access layer. kwargs: :cmd (str|list): a single string command or a list of string commands :timeout (int): timeout for each command in the list :commit (bool-True): if the config requires a commit :exit (bool-True): exit config mode and go back to... | 5 | stack_v2_sparse_classes_30k_train_018848 | Implement the Python class `VaAccess` described below.
Class description:
Access implements methods that translate to executing cli commands remotely on the director.
Method signatures and docstrings:
- def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs): method calls the _va_exec_cli_cmd meth... | Implement the Python class `VaAccess` described below.
Class description:
Access implements methods that translate to executing cli commands remotely on the director.
Method signatures and docstrings:
- def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs): method calls the _va_exec_cli_cmd meth... | cb02979e233ce772bd5fe88ecdc31caf8764d306 | <|skeleton|>
class VaAccess:
"""Access implements methods that translate to executing cli commands remotely on the director."""
def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs):
"""method calls the _va_exec_cli_cmd method of the access layer. kwargs: :cmd (str|list): a single... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VaAccess:
"""Access implements methods that translate to executing cli commands remotely on the director."""
def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs):
"""method calls the _va_exec_cli_cmd method of the access layer. kwargs: :cmd (str|list): a single string comma... | the_stack_v2_python_sparse | feature/director/accesslib/director_3_1.py | 18782967131/test | train | 1 |
b82c03c738eb7d4f347a2ac7bc89d0b8045cd819 | [
"if args.eid == '':\n self._eid = 'no_eid'\nelse:\n self._eid = args.eid",
"mgr = self.manager\nif algo == 'al' or algo == 'apprenticeship_learning':\n bal = BAL(pi_init=mgr._pi_init, D=mgr._D, action_list=mgr._action_list, p=mgr._p, q=mgr._q, gamma=mgr._gamma, irl_precision=mgr._irl_precision, lstd_eps=... | <|body_start_0|>
if args.eid == '':
self._eid = 'no_eid'
else:
self._eid = args.eid
<|end_body_0|>
<|body_start_1|>
mgr = self.manager
if algo == 'al' or algo == 'apprenticeship_learning':
bal = BAL(pi_init=mgr._pi_init, D=mgr._D, action_list=mgr._act... | Docstring for Experiment. | Experiment | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Experiment:
"""Docstring for Experiment."""
def __init__(self, args):
"""TODO: to be defined1. Parameters ---------- pi_init : TODO eid : TODO"""
<|body_0|>
def run(self, algo):
"""TODO: Docstring for run. Parameters ---------- algo : TODO Returns ------- TODO"""... | stack_v2_sparse_classes_75kplus_train_008353 | 2,914 | permissive | [
{
"docstring": "TODO: to be defined1. Parameters ---------- pi_init : TODO eid : TODO",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "TODO: Docstring for run. Parameters ---------- algo : TODO Returns ------- TODO",
"name": "run",
"signature": "def run(se... | 2 | null | Implement the Python class `Experiment` described below.
Class description:
Docstring for Experiment.
Method signatures and docstrings:
- def __init__(self, args): TODO: to be defined1. Parameters ---------- pi_init : TODO eid : TODO
- def run(self, algo): TODO: Docstring for run. Parameters ---------- algo : TODO Re... | Implement the Python class `Experiment` described below.
Class description:
Docstring for Experiment.
Method signatures and docstrings:
- def __init__(self, args): TODO: to be defined1. Parameters ---------- pi_init : TODO eid : TODO
- def run(self, algo): TODO: Docstring for run. Parameters ---------- algo : TODO Re... | 6af26b3ebc322a9a38af37790e313cf4f409f48c | <|skeleton|>
class Experiment:
"""Docstring for Experiment."""
def __init__(self, args):
"""TODO: to be defined1. Parameters ---------- pi_init : TODO eid : TODO"""
<|body_0|>
def run(self, algo):
"""TODO: Docstring for run. Parameters ---------- algo : TODO Returns ------- TODO"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Experiment:
"""Docstring for Experiment."""
def __init__(self, args):
"""TODO: to be defined1. Parameters ---------- pi_init : TODO eid : TODO"""
if args.eid == '':
self._eid = 'no_eid'
else:
self._eid = args.eid
def run(self, algo):
"""TODO: D... | the_stack_v2_python_sparse | src/runner/experiment.py | dtak/batch-apprenticeship-learning | train | 4 |
0f779bbc3f0463e921d9d45cc32872e2dfda0761 | [
"self.file_name = file_name\nself.buffer_size = buffer_size\nself.buffer = []\nself.file = None",
"if data is None or len(data) == 0:\n data = (' ',)\nif self.buffer_size > 1:\n if len(self.buffer) < self.buffer_size - 1:\n self.buffer.append(data)\n return\nif self.file is None:\n self.fil... | <|body_start_0|>
self.file_name = file_name
self.buffer_size = buffer_size
self.buffer = []
self.file = None
<|end_body_0|>
<|body_start_1|>
if data is None or len(data) == 0:
data = (' ',)
if self.buffer_size > 1:
if len(self.buffer) < self.buffe... | Log each sensor data sample on a new line separated by commas with a line terminator. If any element of the data contains a comma that element is enclosed in quotes. | CSVLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVLog:
"""Log each sensor data sample on a new line separated by commas with a line terminator. If any element of the data contains a comma that element is enclosed in quotes."""
def __init__(self, file_name, buffer_size):
"""Save properties for creating log file when first data is ... | stack_v2_sparse_classes_75kplus_train_008354 | 2,844 | no_license | [
{
"docstring": "Save properties for creating log file when first data is received. file_name must not already exist on the file system or an exception will be thrown. Buffer size is how many samples to buffer before writing (and flushing) to file. buffer_size = 0 or 1 flush every sample to file right when it's ... | 4 | stack_v2_sparse_classes_30k_train_050489 | Implement the Python class `CSVLog` described below.
Class description:
Log each sensor data sample on a new line separated by commas with a line terminator. If any element of the data contains a comma that element is enclosed in quotes.
Method signatures and docstrings:
- def __init__(self, file_name, buffer_size): ... | Implement the Python class `CSVLog` described below.
Class description:
Log each sensor data sample on a new line separated by commas with a line terminator. If any element of the data contains a comma that element is enclosed in quotes.
Method signatures and docstrings:
- def __init__(self, file_name, buffer_size): ... | a894b7381b2ff731859e3959c3b3b5188866b3d2 | <|skeleton|>
class CSVLog:
"""Log each sensor data sample on a new line separated by commas with a line terminator. If any element of the data contains a comma that element is enclosed in quotes."""
def __init__(self, file_name, buffer_size):
"""Save properties for creating log file when first data is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSVLog:
"""Log each sensor data sample on a new line separated by commas with a line terminator. If any element of the data contains a comma that element is enclosed in quotes."""
def __init__(self, file_name, buffer_size):
"""Save properties for creating log file when first data is received. fil... | the_stack_v2_python_sparse | pisc/data_handlers/csv_log.py | Phenomics-KSU/pisc | train | 0 |
42504b3dfcadf004be9bda4e03eff0d8b7c73dbc | [
"eve_entity_id = int(eve_entity_id)\ntry:\n obj = self.get(id=eve_entity_id)\n created = False\nexcept self.model.DoesNotExist:\n obj, created = self.update_or_create_esi(eve_entity_id)\nreturn (obj, created)",
"eve_entity_id = int(eve_entity_id)\nlog_prefix = make_log_prefix(self, eve_entity_id)\ntry:\n... | <|body_start_0|>
eve_entity_id = int(eve_entity_id)
try:
obj = self.get(id=eve_entity_id)
created = False
except self.model.DoesNotExist:
obj, created = self.update_or_create_esi(eve_entity_id)
return (obj, created)
<|end_body_0|>
<|body_start_1|>
... | EveEntityManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EveEntityManager:
def get_or_create_esi(self, eve_entity_id: int) -> tuple:
"""gets or creates EveEntity obj with data fetched from ESI if needed eve_id: Eve Online ID of object Returns: object, created"""
<|body_0|>
def update_or_create_esi(self, eve_entity_id: int) -> tupl... | stack_v2_sparse_classes_75kplus_train_008355 | 20,116 | permissive | [
{
"docstring": "gets or creates EveEntity obj with data fetched from ESI if needed eve_id: Eve Online ID of object Returns: object, created",
"name": "get_or_create_esi",
"signature": "def get_or_create_esi(self, eve_entity_id: int) -> tuple"
},
{
"docstring": "updates or creates EveEntity objec... | 2 | stack_v2_sparse_classes_30k_train_034633 | Implement the Python class `EveEntityManager` described below.
Class description:
Implement the EveEntityManager class.
Method signatures and docstrings:
- def get_or_create_esi(self, eve_entity_id: int) -> tuple: gets or creates EveEntity obj with data fetched from ESI if needed eve_id: Eve Online ID of object Retur... | Implement the Python class `EveEntityManager` described below.
Class description:
Implement the EveEntityManager class.
Method signatures and docstrings:
- def get_or_create_esi(self, eve_entity_id: int) -> tuple: gets or creates EveEntity obj with data fetched from ESI if needed eve_id: Eve Online ID of object Retur... | 3d8d1e126cea8584cd9cd11aed6ae0c0dbef4d5f | <|skeleton|>
class EveEntityManager:
def get_or_create_esi(self, eve_entity_id: int) -> tuple:
"""gets or creates EveEntity obj with data fetched from ESI if needed eve_id: Eve Online ID of object Returns: object, created"""
<|body_0|>
def update_or_create_esi(self, eve_entity_id: int) -> tupl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EveEntityManager:
def get_or_create_esi(self, eve_entity_id: int) -> tuple:
"""gets or creates EveEntity obj with data fetched from ESI if needed eve_id: Eve Online ID of object Returns: object, created"""
eve_entity_id = int(eve_entity_id)
try:
obj = self.get(id=eve_entity... | the_stack_v2_python_sparse | structures/managers.py | staropera/aa-structures | train | 0 | |
0d8d92882f5ae73c5e0331d4909fc18495c4e7eb | [
"res = []\ncur = []\nnum_of_letters = 0\nfor w in words:\n if num_of_letters + len(w) + len(cur) > maxWidth:\n for i in range(maxWidth - num_of_letters):\n cur[i % (len(cur) - 1 or 1)] += ' '\n res.append(''.join(cur))\n cur = []\n num_of_letters = 0\n cur += [w]\n nu... | <|body_start_0|>
res = []
cur = []
num_of_letters = 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - num_of_letters):
cur[i % (len(cur) - 1 or 1)] += ' '
res.append(''.join(cur))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fullJustify(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_0|>
def rewrite(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_75kplus_train_008356 | 3,757 | no_license | [
{
"docstring": ":type words: List[str] :type maxWidth: int :rtype: List[str]",
"name": "fullJustify",
"signature": "def fullJustify(self, words, maxWidth)"
},
{
"docstring": ":type words: List[str] :type maxWidth: int :rtype: List[str]",
"name": "rewrite",
"signature": "def rewrite(self,... | 2 | stack_v2_sparse_classes_30k_train_000406 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fullJustify(self, words, maxWidth): :type words: List[str] :type maxWidth: int :rtype: List[str]
- def rewrite(self, words, maxWidth): :type words: List[str] :type maxWidth: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fullJustify(self, words, maxWidth): :type words: List[str] :type maxWidth: int :rtype: List[str]
- def rewrite(self, words, maxWidth): :type words: List[str] :type maxWidth: ... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def fullJustify(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_0|>
def rewrite(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def fullJustify(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
res = []
cur = []
num_of_letters = 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidt... | the_stack_v2_python_sparse | co_linkedin/68_Text_Justification.py | vsdrun/lc_public | train | 6 | |
67fb52c73f53c1b819b5fc5284d3798fa7732628 | [
"messages = list(AdminMessage.query.options(joinedload('user')))\nif not messages:\n return self.respond(None)\nif len(messages) > 1:\n logging.warning('Multiple messages found')\nreturn self.respond(messages[0])",
"args = self.post_parser.parse_args()\nmessage, _ = create_or_update(AdminMessage, where={}, ... | <|body_start_0|>
messages = list(AdminMessage.query.options(joinedload('user')))
if not messages:
return self.respond(None)
if len(messages) > 1:
logging.warning('Multiple messages found')
return self.respond(messages[0])
<|end_body_0|>
<|body_start_1|>
a... | CRUD API for the AdminMessage model. AdminMessages are system-level messages that should be displayed to users. This API is intended for use by the Changes UI for displaying information about outages, upcoming down-time or new features. These messages can be fetched by anyone, but are intended to be set only by admins.... | AdminMessageIndexAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminMessageIndexAPIView:
"""CRUD API for the AdminMessage model. AdminMessages are system-level messages that should be displayed to users. This API is intended for use by the Changes UI for displaying information about outages, upcoming down-time or new features. These messages can be fetched b... | stack_v2_sparse_classes_75kplus_train_008357 | 2,479 | permissive | [
{
"docstring": "HTTP GET response to read AdminMessages. Returns: str: None if no messages are found; others JSON representation of the AdminMessage in the system. If the message is empty, treat that as no message.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "HTTP POST to cre... | 2 | stack_v2_sparse_classes_30k_train_051700 | Implement the Python class `AdminMessageIndexAPIView` described below.
Class description:
CRUD API for the AdminMessage model. AdminMessages are system-level messages that should be displayed to users. This API is intended for use by the Changes UI for displaying information about outages, upcoming down-time or new fe... | Implement the Python class `AdminMessageIndexAPIView` described below.
Class description:
CRUD API for the AdminMessage model. AdminMessages are system-level messages that should be displayed to users. This API is intended for use by the Changes UI for displaying information about outages, upcoming down-time or new fe... | ae5159498f239a48184accf811cf36be2eab1e96 | <|skeleton|>
class AdminMessageIndexAPIView:
"""CRUD API for the AdminMessage model. AdminMessages are system-level messages that should be displayed to users. This API is intended for use by the Changes UI for displaying information about outages, upcoming down-time or new features. These messages can be fetched b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdminMessageIndexAPIView:
"""CRUD API for the AdminMessage model. AdminMessages are system-level messages that should be displayed to users. This API is intended for use by the Changes UI for displaying information about outages, upcoming down-time or new features. These messages can be fetched by anyone, but... | the_stack_v2_python_sparse | changes/api/adminmessage_index.py | getsentry/changes | train | 6 |
84b3312c8f555f26119986091fe2ce41c6fa87d6 | [
"try:\n import elasticsearch\nexcept ImportError:\n raise ValueError('Could not import elasticsearch python package. Please install it with `pip install elasticsearch`.')\nself.embedding = embedding\nself.index_name = index_name\ntry:\n es_client = elasticsearch.Elasticsearch(elasticsearch_url)\nexcept Val... | <|body_start_0|>
try:
import elasticsearch
except ImportError:
raise ValueError('Could not import elasticsearch python package. Please install it with `pip install elasticsearch`.')
self.embedding = embedding
self.index_name = index_name
try:
e... | Wrapper around Elasticsearch as a vector database. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Example: .. code-block:: python from langchain import ElasticVectorSearch from langchain.embed... | ElasticVectorSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticVectorSearch:
"""Wrapper around Elasticsearch as a vector database. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Example: .. code-block:: python from langchain ... | stack_v2_sparse_classes_75kplus_train_008358 | 10,618 | no_license | [
{
"docstring": "Initialize with necessary components.",
"name": "__init__",
"signature": "def __init__(self, elasticsearch_url: str, index_name: str, embedding: Embeddings)"
},
{
"docstring": "Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to a... | 4 | stack_v2_sparse_classes_30k_train_036465 | Implement the Python class `ElasticVectorSearch` described below.
Class description:
Wrapper around Elasticsearch as a vector database. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Example:... | Implement the Python class `ElasticVectorSearch` described below.
Class description:
Wrapper around Elasticsearch as a vector database. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Example:... | b7aaa920a52613e3f1f04fa5cd7568ad37302d11 | <|skeleton|>
class ElasticVectorSearch:
"""Wrapper around Elasticsearch as a vector database. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Example: .. code-block:: python from langchain ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElasticVectorSearch:
"""Wrapper around Elasticsearch as a vector database. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Example: .. code-block:: python from langchain import Elasti... | the_stack_v2_python_sparse | openai/venv/lib64/python3.10/site-packages/langchain/vectorstores/elastic_vector_search.py | henrymendez/garage | train | 0 |
6c521f53ee011b2eed03b83d1b7031f36ec31102 | [
"APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant)\n\ndef dbfn(storeConnection):\n a = GetPerson(appObj, personGUID, storeConnection)\n if a is None:\n raise NotFound('Person Not Found')\n return a.getJSONRepresenation()\nreturn appObj.objectStore.executeInsideConnectionContext(db... | <|body_start_0|>
APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant)
def dbfn(storeConnection):
a = GetPerson(appObj, personGUID, storeConnection)
if a is None:
raise NotFound('Person Not Found')
return a.getJSONRepresenation()
... | Admin | personInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class personInfo:
"""Admin"""
def get(self, tenant, personGUID):
"""Get Person information"""
<|body_0|>
def put(self, tenant, personGUID):
"""Update Person"""
<|body_1|>
def delete(self, tenant, personGUID):
"""Delete Person"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_008359 | 35,114 | permissive | [
{
"docstring": "Get Person information",
"name": "get",
"signature": "def get(self, tenant, personGUID)"
},
{
"docstring": "Update Person",
"name": "put",
"signature": "def put(self, tenant, personGUID)"
},
{
"docstring": "Delete Person",
"name": "delete",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_015534 | Implement the Python class `personInfo` described below.
Class description:
Admin
Method signatures and docstrings:
- def get(self, tenant, personGUID): Get Person information
- def put(self, tenant, personGUID): Update Person
- def delete(self, tenant, personGUID): Delete Person | Implement the Python class `personInfo` described below.
Class description:
Admin
Method signatures and docstrings:
- def get(self, tenant, personGUID): Get Person information
- def put(self, tenant, personGUID): Update Person
- def delete(self, tenant, personGUID): Delete Person
<|skeleton|>
class personInfo:
"... | d3908c46614fb1b638553282cd72ba3634277495 | <|skeleton|>
class personInfo:
"""Admin"""
def get(self, tenant, personGUID):
"""Get Person information"""
<|body_0|>
def put(self, tenant, personGUID):
"""Update Person"""
<|body_1|>
def delete(self, tenant, personGUID):
"""Delete Person"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class personInfo:
"""Admin"""
def get(self, tenant, personGUID):
"""Get Person information"""
APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant)
def dbfn(storeConnection):
a = GetPerson(appObj, personGUID, storeConnection)
if a is None:
... | the_stack_v2_python_sparse | services/src/APIadmin_Legacy.py | rmetcalf9/saas_user_management_system | train | 1 |
b09ef5f895336b13a6127ac47e50bd0c02d2c576 | [
"query = query or {}\nobject_id = mongo.ObjectId(asset_id)\nquery['$or'] = [{'_id': object_id, 'versions.mediatype': mediatype}, {'versions': {'$elemMatch': {'version_id': object_id, 'mediatype': mediatype}}}]\nasset = (yield self.one(query))\nif asset.pk == object_id:\n version = asset.get_version(mediatype=med... | <|body_start_0|>
query = query or {}
object_id = mongo.ObjectId(asset_id)
query['$or'] = [{'_id': object_id, 'versions.mediatype': mediatype}, {'versions': {'$elemMatch': {'version_id': object_id, 'mediatype': mediatype}}}]
asset = (yield self.one(query))
if asset.pk == object_id... | Custom manager to work on asset instances. | AssetsManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssetsManager:
"""Custom manager to work on asset instances."""
def find_type(self, asset_id, mediatype, query=None):
"""Finds an asset given its ID or the ID of one of its versions for the given mediatype."""
<|body_0|>
def find_version(self, version_id, query=None):
... | stack_v2_sparse_classes_75kplus_train_008360 | 4,758 | no_license | [
{
"docstring": "Finds an asset given its ID or the ID of one of its versions for the given mediatype.",
"name": "find_type",
"signature": "def find_type(self, asset_id, mediatype, query=None)"
},
{
"docstring": "Finds an asset given the ID of one of its versions, optionally restrained by the giv... | 2 | null | Implement the Python class `AssetsManager` described below.
Class description:
Custom manager to work on asset instances.
Method signatures and docstrings:
- def find_type(self, asset_id, mediatype, query=None): Finds an asset given its ID or the ID of one of its versions for the given mediatype.
- def find_version(s... | Implement the Python class `AssetsManager` described below.
Class description:
Custom manager to work on asset instances.
Method signatures and docstrings:
- def find_type(self, asset_id, mediatype, query=None): Finds an asset given its ID or the ID of one of its versions for the given mediatype.
- def find_version(s... | 9590878d964c01e396ef4597782eb83cd1c69fa4 | <|skeleton|>
class AssetsManager:
"""Custom manager to work on asset instances."""
def find_type(self, asset_id, mediatype, query=None):
"""Finds an asset given its ID or the ID of one of its versions for the given mediatype."""
<|body_0|>
def find_version(self, version_id, query=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssetsManager:
"""Custom manager to work on asset instances."""
def find_type(self, asset_id, mediatype, query=None):
"""Finds an asset given its ID or the ID of one of its versions for the given mediatype."""
query = query or {}
object_id = mongo.ObjectId(asset_id)
query[... | the_stack_v2_python_sparse | smaclib/models/assets.py | SMAC/smaclib | train | 0 |
9417421a197f42c7eaa61ce0532b242f63cca8b8 | [
"assert isinstance(disease, str)\nassert disease.lower() in ['ebola', 'sars', 'polio']\nself.disease = disease.lower()\nif self.disease == 'ebola':\n self.fname = 'ebola.xlsx'\nelif self.disease == 'sars':\n self.fname = 'sars.csv'\nelif self.disease == 'polio':\n self.fname = 'polio.xls'\nelse:\n raise... | <|body_start_0|>
assert isinstance(disease, str)
assert disease.lower() in ['ebola', 'sars', 'polio']
self.disease = disease.lower()
if self.disease == 'ebola':
self.fname = 'ebola.xlsx'
elif self.disease == 'sars':
self.fname = 'sars.csv'
elif sel... | : Draw animations for the datasets('ebola.xlsx','sars.csv','polio.xls') : which are located in 'data' folder | Animation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Animation:
""": Draw animations for the datasets('ebola.xlsx','sars.csv','polio.xls') : which are located in 'data' folder"""
def __init__(self, disease=None, countries=None, Indicator=None, output=None):
""":"""
<|body_0|>
def plot(self, countries=None, Indicator=None, ... | stack_v2_sparse_classes_75kplus_train_008361 | 1,736 | no_license | [
{
"docstring": ":",
"name": "__init__",
"signature": "def __init__(self, disease=None, countries=None, Indicator=None, output=None)"
},
{
"docstring": ": Plots the animations for \"ebola.xlsx\" in the data",
"name": "plot",
"signature": "def plot(self, countries=None, Indicator=None, out... | 2 | stack_v2_sparse_classes_30k_train_034263 | Implement the Python class `Animation` described below.
Class description:
: Draw animations for the datasets('ebola.xlsx','sars.csv','polio.xls') : which are located in 'data' folder
Method signatures and docstrings:
- def __init__(self, disease=None, countries=None, Indicator=None, output=None): :
- def plot(self, ... | Implement the Python class `Animation` described below.
Class description:
: Draw animations for the datasets('ebola.xlsx','sars.csv','polio.xls') : which are located in 'data' folder
Method signatures and docstrings:
- def __init__(self, disease=None, countries=None, Indicator=None, output=None): :
- def plot(self, ... | 89158be5192361ed9a1c7927aa4115d47b0fb38e | <|skeleton|>
class Animation:
""": Draw animations for the datasets('ebola.xlsx','sars.csv','polio.xls') : which are located in 'data' folder"""
def __init__(self, disease=None, countries=None, Indicator=None, output=None):
""":"""
<|body_0|>
def plot(self, countries=None, Indicator=None, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Animation:
""": Draw animations for the datasets('ebola.xlsx','sars.csv','polio.xls') : which are located in 'data' folder"""
def __init__(self, disease=None, countries=None, Indicator=None, output=None):
""":"""
assert isinstance(disease, str)
assert disease.lower() in ['ebola', ... | the_stack_v2_python_sparse | scripts/animations.py | ShikaZzz/disease-outbreak | train | 0 |
09884443f2dfd8b0cd53d0d719f9ec426a3059f0 | [
"nums = [float('-inf')] + nums + [float('-inf')]\nfor i in range(1, len(nums)):\n if nums[i + 1] < nums[i] > nums[i - 1]:\n return int(i - 1)",
"if len(nums) == 1:\n return 0\nif len(nums) == 2:\n return int(nums[0] < nums[1])\nmid = int(len(nums) / 2)\nif nums[mid - 1] > nums[mid]:\n return se... | <|body_start_0|>
nums = [float('-inf')] + nums + [float('-inf')]
for i in range(1, len(nums)):
if nums[i + 1] < nums[i] > nums[i - 1]:
return int(i - 1)
<|end_body_0|>
<|body_start_1|>
if len(nums) == 1:
return 0
if len(nums) == 2:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums = [float('-inf')] + nums + [flo... | stack_v2_sparse_classes_75kplus_train_008362 | 1,299 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement",
"signature": "def findPeakElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement2",
"signature": "def findPeakElement2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038963 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def fi... | 391328c7c601b5c77ff250ad173600d4d1dd7f57 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
nums = [float('-inf')] + nums + [float('-inf')]
for i in range(1, len(nums)):
if nums[i + 1] < nums[i] > nums[i - 1]:
return int(i - 1)
def findPeakElement2(self, nums):
... | the_stack_v2_python_sparse | leetcode/algo/162. Find Peak Element.py | wduncan21/Challenges | train | 0 | |
e38ac1555e6368c5013ba8e44c7063a0bc4e51d5 | [
"BoxBase.__init__(self)\nNoteType.__init__(self, box_corner, exclude)\nself.doc = doc\nself.boxstr = boxstr",
"liloffset = canvas.report_opts.littleoffset\nif self.value == NoteType.BOTTOMLEFT or self.value == NoteType.TOPLEFT:\n self.x_cm = liloffset\nelse:\n self.x_cm = self.doc.get_usable_width() - self.... | <|body_start_0|>
BoxBase.__init__(self)
NoteType.__init__(self, box_corner, exclude)
self.doc = doc
self.boxstr = boxstr
<|end_body_0|>
<|body_start_1|>
liloffset = canvas.report_opts.littleoffset
if self.value == NoteType.BOTTOMLEFT or self.value == NoteType.TOPLEFT:
... | Box that will hold the note to display on the page | NoteBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoteBox:
"""Box that will hold the note to display on the page"""
def __init__(self, doc, boxstr, box_corner, exclude=None):
"""initialize the NoteBox"""
<|body_0|>
def set_on_page(self, canvas):
"""set the x_cm and y_cm given self.doc, leloffset, and title_heigh... | stack_v2_sparse_classes_75kplus_train_008363 | 35,846 | no_license | [
{
"docstring": "initialize the NoteBox",
"name": "__init__",
"signature": "def __init__(self, doc, boxstr, box_corner, exclude=None)"
},
{
"docstring": "set the x_cm and y_cm given self.doc, leloffset, and title_height",
"name": "set_on_page",
"signature": "def set_on_page(self, canvas)"... | 3 | stack_v2_sparse_classes_30k_train_030989 | Implement the Python class `NoteBox` described below.
Class description:
Box that will hold the note to display on the page
Method signatures and docstrings:
- def __init__(self, doc, boxstr, box_corner, exclude=None): initialize the NoteBox
- def set_on_page(self, canvas): set the x_cm and y_cm given self.doc, lelof... | Implement the Python class `NoteBox` described below.
Class description:
Box that will hold the note to display on the page
Method signatures and docstrings:
- def __init__(self, doc, boxstr, box_corner, exclude=None): initialize the NoteBox
- def set_on_page(self, canvas): set the x_cm and y_cm given self.doc, lelof... | 0c79561bed7ff42c88714edbc85197fa9235e188 | <|skeleton|>
class NoteBox:
"""Box that will hold the note to display on the page"""
def __init__(self, doc, boxstr, box_corner, exclude=None):
"""initialize the NoteBox"""
<|body_0|>
def set_on_page(self, canvas):
"""set the x_cm and y_cm given self.doc, leloffset, and title_heigh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoteBox:
"""Box that will hold the note to display on the page"""
def __init__(self, doc, boxstr, box_corner, exclude=None):
"""initialize the NoteBox"""
BoxBase.__init__(self)
NoteType.__init__(self, box_corner, exclude)
self.doc = doc
self.boxstr = boxstr
de... | the_stack_v2_python_sparse | plugins/lib/libtreebase.py | balrok/gramps_addon | train | 2 |
d7f99fe0d1a3e47d41ac68d85f3a9e83c618859a | [
"self.check_parameters(params)\ncos = np.cos(params[0])\nsin = -1j * np.sin(params[0])\nphi = np.exp(-1j * params[1])\nreturn UnitaryMatrix([[1, 0, 0, 0], [0, cos, sin, 0], [0, sin, cos, 0], [0, 0, 0, phi]])",
"self.check_parameters(params)\ndcos = -np.sin(params[0])\ndsin = -1j * np.cos(params[0])\ndphi = -1j * ... | <|body_start_0|>
self.check_parameters(params)
cos = np.cos(params[0])
sin = -1j * np.sin(params[0])
phi = np.exp(-1j * params[1])
return UnitaryMatrix([[1, 0, 0, 0], [0, cos, sin, 0], [0, sin, cos, 0], [0, 0, 0, phi]])
<|end_body_0|>
<|body_start_1|>
self.check_paramete... | Google's FSIM Gate. Contains all two qubit interactions that preserve excitations, up to single-qubit rotations and global phase. It is given by the following parameterized unitary: .. math:: $ \\begin{pmatrix} 1 & 0 & 0 & 0 \\\\ 0 & \\cos{\\theta} & -i\\sin{\\theta} & 0 \\\\ 0 & -i\\sin{\\theta} & \\cos{\\theta} & 0 \... | FSIMGate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FSIMGate:
"""Google's FSIM Gate. Contains all two qubit interactions that preserve excitations, up to single-qubit rotations and global phase. It is given by the following parameterized unitary: .. math:: $ \\begin{pmatrix} 1 & 0 & 0 & 0 \\\\ 0 & \\cos{\\theta} & -i\\sin{\\theta} & 0 \\\\ 0 & -i\... | stack_v2_sparse_classes_75kplus_train_008364 | 2,444 | permissive | [
{
"docstring": "Return the unitary for this gate, see :class:`Unitary` for more.",
"name": "get_unitary",
"signature": "def get_unitary(self, params: RealVector=[]) -> UnitaryMatrix"
},
{
"docstring": "Return the gradient for this gate. See :class:`DifferentiableUnitary` for more info.",
"na... | 2 | null | Implement the Python class `FSIMGate` described below.
Class description:
Google's FSIM Gate. Contains all two qubit interactions that preserve excitations, up to single-qubit rotations and global phase. It is given by the following parameterized unitary: .. math:: $ \\begin{pmatrix} 1 & 0 & 0 & 0 \\\\ 0 & \\cos{\\the... | Implement the Python class `FSIMGate` described below.
Class description:
Google's FSIM Gate. Contains all two qubit interactions that preserve excitations, up to single-qubit rotations and global phase. It is given by the following parameterized unitary: .. math:: $ \\begin{pmatrix} 1 & 0 & 0 & 0 \\\\ 0 & \\cos{\\the... | c89112d15072e8ffffb68cf1757b184e2aeb3dc8 | <|skeleton|>
class FSIMGate:
"""Google's FSIM Gate. Contains all two qubit interactions that preserve excitations, up to single-qubit rotations and global phase. It is given by the following parameterized unitary: .. math:: $ \\begin{pmatrix} 1 & 0 & 0 & 0 \\\\ 0 & \\cos{\\theta} & -i\\sin{\\theta} & 0 \\\\ 0 & -i\... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FSIMGate:
"""Google's FSIM Gate. Contains all two qubit interactions that preserve excitations, up to single-qubit rotations and global phase. It is given by the following parameterized unitary: .. math:: $ \\begin{pmatrix} 1 & 0 & 0 & 0 \\\\ 0 & \\cos{\\theta} & -i\\sin{\\theta} & 0 \\\\ 0 & -i\\sin{\\theta}... | the_stack_v2_python_sparse | bqskit/ir/gates/parameterized/fsim.py | BQSKit/bqskit | train | 54 |
656622f471827d17677296e50835769e5d77a62f | [
"if field == 'current_password':\n if current_user.password != value and obj.password != value:\n abort(code=HTTPStatus.FORBIDDEN, message='Wrong password')\n else:\n state['current_password'] = value\n return True\nreturn PatchJSONParameters.test(obj, field, value, state)",
"log.debug(... | <|body_start_0|>
if field == 'current_password':
if current_user.password != value and obj.password != value:
abort(code=HTTPStatus.FORBIDDEN, message='Wrong password')
else:
state['current_password'] = value
return True
return Patc... | User details updating parameters following PATCH JSON RFC. | PatchUserDetailsParameters | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatchUserDetailsParameters:
"""User details updating parameters following PATCH JSON RFC."""
def test(cls, obj, field, value, state):
"""Additional check for 'current_password' as User hasn't field 'current_password'"""
<|body_0|>
def replace(cls, obj, field, value, stat... | stack_v2_sparse_classes_75kplus_train_008365 | 6,997 | permissive | [
{
"docstring": "Additional check for 'current_password' as User hasn't field 'current_password'",
"name": "test",
"signature": "def test(cls, obj, field, value, state)"
},
{
"docstring": "Some fields require extra permissions to be changed. Changing `is_active` and `is_staff` properties, current... | 2 | stack_v2_sparse_classes_30k_train_052852 | Implement the Python class `PatchUserDetailsParameters` described below.
Class description:
User details updating parameters following PATCH JSON RFC.
Method signatures and docstrings:
- def test(cls, obj, field, value, state): Additional check for 'current_password' as User hasn't field 'current_password'
- def repl... | Implement the Python class `PatchUserDetailsParameters` described below.
Class description:
User details updating parameters following PATCH JSON RFC.
Method signatures and docstrings:
- def test(cls, obj, field, value, state): Additional check for 'current_password' as User hasn't field 'current_password'
- def repl... | 821c9cae985751a129b3be1ad08b8ad295d0a3d8 | <|skeleton|>
class PatchUserDetailsParameters:
"""User details updating parameters following PATCH JSON RFC."""
def test(cls, obj, field, value, state):
"""Additional check for 'current_password' as User hasn't field 'current_password'"""
<|body_0|>
def replace(cls, obj, field, value, stat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PatchUserDetailsParameters:
"""User details updating parameters following PATCH JSON RFC."""
def test(cls, obj, field, value, state):
"""Additional check for 'current_password' as User hasn't field 'current_password'"""
if field == 'current_password':
if current_user.password ... | the_stack_v2_python_sparse | app/modules/users/parameters.py | Emily-Ke/houston | train | 0 |
1068d2f4d8383c3aa6a1a9c5e0f7ea6c5bd14c99 | [
"super().__init__(context)\nself._beam_pipeline_args = []\nself._make_beam_pipeline_fn = None\nif context:\n if isinstance(context, BaseBeamExecutor.Context):\n self._beam_pipeline_args = context.beam_pipeline_args or []\n self._make_beam_pipeline_fn = context.make_beam_pipeline_fn\n else:\n ... | <|body_start_0|>
super().__init__(context)
self._beam_pipeline_args = []
self._make_beam_pipeline_fn = None
if context:
if isinstance(context, BaseBeamExecutor.Context):
self._beam_pipeline_args = context.beam_pipeline_args or []
self._make_bea... | Abstract TFX executor class for Beam powered components. | BaseBeamExecutor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseBeamExecutor:
"""Abstract TFX executor class for Beam powered components."""
def __init__(self, context: Optional[Context]=None):
"""Constructs a beam based executor."""
<|body_0|>
def _make_beam_pipeline(self) -> _BeamPipeline:
"""Makes beam pipeline."""
... | stack_v2_sparse_classes_75kplus_train_008366 | 5,166 | permissive | [
{
"docstring": "Constructs a beam based executor.",
"name": "__init__",
"signature": "def __init__(self, context: Optional[Context]=None)"
},
{
"docstring": "Makes beam pipeline.",
"name": "_make_beam_pipeline",
"signature": "def _make_beam_pipeline(self) -> _BeamPipeline"
}
] | 2 | stack_v2_sparse_classes_30k_train_050758 | Implement the Python class `BaseBeamExecutor` described below.
Class description:
Abstract TFX executor class for Beam powered components.
Method signatures and docstrings:
- def __init__(self, context: Optional[Context]=None): Constructs a beam based executor.
- def _make_beam_pipeline(self) -> _BeamPipeline: Makes ... | Implement the Python class `BaseBeamExecutor` described below.
Class description:
Abstract TFX executor class for Beam powered components.
Method signatures and docstrings:
- def __init__(self, context: Optional[Context]=None): Constructs a beam based executor.
- def _make_beam_pipeline(self) -> _BeamPipeline: Makes ... | 1b328504fa08a70388691e4072df76f143631325 | <|skeleton|>
class BaseBeamExecutor:
"""Abstract TFX executor class for Beam powered components."""
def __init__(self, context: Optional[Context]=None):
"""Constructs a beam based executor."""
<|body_0|>
def _make_beam_pipeline(self) -> _BeamPipeline:
"""Makes beam pipeline."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseBeamExecutor:
"""Abstract TFX executor class for Beam powered components."""
def __init__(self, context: Optional[Context]=None):
"""Constructs a beam based executor."""
super().__init__(context)
self._beam_pipeline_args = []
self._make_beam_pipeline_fn = None
... | the_stack_v2_python_sparse | tfx/dsl/components/base/base_beam_executor.py | tensorflow/tfx | train | 2,116 |
565c42408320e7de368e2e1ebdb25709255f99c0 | [
"self.user32 = user32\nself.kernel32 = kernel32\nself.is_hooked = None",
"self.is_hooked = self.user32.SetWindowsHookExA(WH_KEYBOARD_LL, ptr, kernel32.GetModuleHandleW(None), 0)\nif not self.is_hooked:\n return False\nreturn True",
"if self.is_hooked is None:\n return\nself.user32.UnhookWindowsHookEx(self... | <|body_start_0|>
self.user32 = user32
self.kernel32 = kernel32
self.is_hooked = None
<|end_body_0|>
<|body_start_1|>
self.is_hooked = self.user32.SetWindowsHookExA(WH_KEYBOARD_LL, ptr, kernel32.GetModuleHandleW(None), 0)
if not self.is_hooked:
return False
re... | Class for installing/uninstalling a hook | hook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class hook:
"""Class for installing/uninstalling a hook"""
def __init__(self):
"""Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll."""
<|body_0|>
def install_hook(self, ptr):
"""Method for installing ho... | stack_v2_sparse_classes_75kplus_train_008367 | 2,947 | no_license | [
{
"docstring": "Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method for installing hook. Arguments ptr: pointer to the HOOKPROC callback function",
... | 3 | stack_v2_sparse_classes_30k_test_002773 | Implement the Python class `hook` described below.
Class description:
Class for installing/uninstalling a hook
Method signatures and docstrings:
- def __init__(self): Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll.
- def install_hook(self, ptr): Met... | Implement the Python class `hook` described below.
Class description:
Class for installing/uninstalling a hook
Method signatures and docstrings:
- def __init__(self): Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll.
- def install_hook(self, ptr): Met... | 0e965cdc4a23c1d02f7052bc8da473b7f57ffa04 | <|skeleton|>
class hook:
"""Class for installing/uninstalling a hook"""
def __init__(self):
"""Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll."""
<|body_0|>
def install_hook(self, ptr):
"""Method for installing ho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class hook:
"""Class for installing/uninstalling a hook"""
def __init__(self):
"""Constructor for the hook class. Responsible for allowing methods to call functions from user32.dll and kernel32.dll."""
self.user32 = user32
self.kernel32 = kernel32
self.is_hooked = None
def ... | the_stack_v2_python_sparse | misc/keylogger_test.py | minhkhoi1026/remote-monitor | train | 0 |
687263f3499598702d961e0a24393906505f282f | [
"self.key_1, self.key_2 = keys\nself.text = text\nself.cyphertext = cyphertext\nsuper().__init__(text=text, cyphertext=cyphertext)",
"positions_in_alphabet = super().encode()\nbins = []\nfor position in positions_in_alphabet:\n if ord('a') + position >= ord('j'):\n position -= 1\n if ord('a') + posit... | <|body_start_0|>
self.key_1, self.key_2 = keys
self.text = text
self.cyphertext = cyphertext
super().__init__(text=text, cyphertext=cyphertext)
<|end_body_0|>
<|body_start_1|>
positions_in_alphabet = super().encode()
bins = []
for position in positions_in_alphabe... | responsible for handling the encoding and decoding to and from bacon cypher. eg. Hello, World -> AABBB AABAA ABABA ABABA ABBAB BABAA ABBAB BAAAA ABABA AAABB | BaconCypher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaconCypher:
"""responsible for handling the encoding and decoding to and from bacon cypher. eg. Hello, World -> AABBB AABAA ABABA ABABA ABBAB BABAA ABBAB BAAAA ABABA AAABB"""
def __init__(self, keys, text='', cyphertext=''):
"""upon initialisation, create the decoder and encoder sub... | stack_v2_sparse_classes_75kplus_train_008368 | 4,248 | no_license | [
{
"docstring": "upon initialisation, create the decoder and encoder subclasses to help with substitution :keys (tuple of characters) -> choose what letters to decrypt the message in :text (str) -> unencrypted message",
"name": "__init__",
"signature": "def __init__(self, keys, text='', cyphertext='')"
... | 3 | null | Implement the Python class `BaconCypher` described below.
Class description:
responsible for handling the encoding and decoding to and from bacon cypher. eg. Hello, World -> AABBB AABAA ABABA ABABA ABBAB BABAA ABBAB BAAAA ABABA AAABB
Method signatures and docstrings:
- def __init__(self, keys, text='', cyphertext='')... | Implement the Python class `BaconCypher` described below.
Class description:
responsible for handling the encoding and decoding to and from bacon cypher. eg. Hello, World -> AABBB AABAA ABABA ABABA ABBAB BABAA ABBAB BAAAA ABABA AAABB
Method signatures and docstrings:
- def __init__(self, keys, text='', cyphertext='')... | 6b10296dcb187024df75d7620b01a1d848313c95 | <|skeleton|>
class BaconCypher:
"""responsible for handling the encoding and decoding to and from bacon cypher. eg. Hello, World -> AABBB AABAA ABABA ABABA ABBAB BABAA ABBAB BAAAA ABABA AAABB"""
def __init__(self, keys, text='', cyphertext=''):
"""upon initialisation, create the decoder and encoder sub... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaconCypher:
"""responsible for handling the encoding and decoding to and from bacon cypher. eg. Hello, World -> AABBB AABAA ABABA ABABA ABBAB BABAA ABBAB BAAAA ABABA AAABB"""
def __init__(self, keys, text='', cyphertext=''):
"""upon initialisation, create the decoder and encoder subclasses to he... | the_stack_v2_python_sparse | week-6/bacon_cypher.py | joeyabouharb/term2-challenges | train | 0 |
30810befe4a038edc338c224305b3989be4a0a30 | [
"max_so_far = 0\narea = 0\nfor i, j in product(range(len(height)), range(len(height))):\n if height[i] == height[j]:\n area = (i - j) * height[i]\n if area >= max_so_far:\n max_so_far = area\nreturn area",
"max_so_far = 0\ni, j = (0, len(height) - 1)\nwhile i < j:\n area = min(heigh... | <|body_start_0|>
max_so_far = 0
area = 0
for i, j in product(range(len(height)), range(len(height))):
if height[i] == height[j]:
area = (i - j) * height[i]
if area >= max_so_far:
max_so_far = area
return area
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea_ineff(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_so_far = 0
area = 0
... | stack_v2_sparse_classes_75kplus_train_008369 | 1,445 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea_ineff",
"signature": "def maxArea_ineff(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039027 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_ineff(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_ineff(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxAr... | 032aa1cf59e177f8c35e1cf4b51dc5d12c880fee | <|skeleton|>
class Solution:
def maxArea_ineff(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxArea_ineff(self, height):
""":type height: List[int] :rtype: int"""
max_so_far = 0
area = 0
for i, j in product(range(len(height)), range(len(height))):
if height[i] == height[j]:
area = (i - j) * height[i]
if area >=... | the_stack_v2_python_sparse | leetcode/container_most_water.py | dkarapetyan-zz/interview_prep | train | 0 | |
06a0fc1c4b5f5f8f03e5529b23a91637741bbf24 | [
"super(CachedImageDataSource, self).__init__(root_location=root_location, file_prefix=file_prefix, file_suffix=file_suffix, file_ext=file_ext, id_dict_preprocessing=id_dict_preprocessing, set_identity_spacing=set_identity_spacing, set_zero_origin=set_zero_origin, set_identity_direction=set_identity_direction, round... | <|body_start_0|>
super(CachedImageDataSource, self).__init__(root_location=root_location, file_prefix=file_prefix, file_suffix=file_suffix, file_ext=file_ext, id_dict_preprocessing=id_dict_preprocessing, set_identity_spacing=set_identity_spacing, set_zero_origin=set_zero_origin, set_identity_direction=set_ident... | DataSource used for loading sitk images. Uses id_dict['image_id'] as image path and returns the sitk_image at the given path. Supports caching for holding the images in memory. Preprocesses the path as follows: file_path_to_load = os.path.join(root_location, file_prefix + id_dict['image_id'] + file_suffix + file_ext) F... | CachedImageDataSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedImageDataSource:
"""DataSource used for loading sitk images. Uses id_dict['image_id'] as image path and returns the sitk_image at the given path. Supports caching for holding the images in memory. Preprocesses the path as follows: file_path_to_load = os.path.join(root_location, file_prefix ... | stack_v2_sparse_classes_75kplus_train_008370 | 5,393 | no_license | [
{
"docstring": "Initializer. :param root_location: Root path, where the images will be loaded from. :param file_prefix: Prefix of the file path. :param file_suffix: Suffix of the file path. :param file_ext: Extension of the file path. :param id_dict_preprocessing: Function that will be called for preprocessing ... | 3 | stack_v2_sparse_classes_30k_train_007549 | Implement the Python class `CachedImageDataSource` described below.
Class description:
DataSource used for loading sitk images. Uses id_dict['image_id'] as image path and returns the sitk_image at the given path. Supports caching for holding the images in memory. Preprocesses the path as follows: file_path_to_load = o... | Implement the Python class `CachedImageDataSource` described below.
Class description:
DataSource used for loading sitk images. Uses id_dict['image_id'] as image path and returns the sitk_image at the given path. Supports caching for holding the images in memory. Preprocesses the path as follows: file_path_to_load = o... | ef6cee91264ba1fe6b40d9823a07647b95bcc2c4 | <|skeleton|>
class CachedImageDataSource:
"""DataSource used for loading sitk images. Uses id_dict['image_id'] as image path and returns the sitk_image at the given path. Supports caching for holding the images in memory. Preprocesses the path as follows: file_path_to_load = os.path.join(root_location, file_prefix ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CachedImageDataSource:
"""DataSource used for loading sitk images. Uses id_dict['image_id'] as image path and returns the sitk_image at the given path. Supports caching for holding the images in memory. Preprocesses the path as follows: file_path_to_load = os.path.join(root_location, file_prefix + id_dict['im... | the_stack_v2_python_sparse | datasources/cached_image_datasource.py | XiaoweiXu/MedicalDataAugmentationTool | train | 1 |
9481c50268e1d8e996d07bd0f7415f29761d861c | [
"self.entity_description = description\nself.pushbullet = pb\nself._attr_name = f'Pushbullet {description.key}'",
"try:\n self._attr_native_value = self.pushbullet.data[self.entity_description.key]\n self._attr_extra_state_attributes = self.pushbullet.data\nexcept (KeyError, TypeError):\n pass"
] | <|body_start_0|>
self.entity_description = description
self.pushbullet = pb
self._attr_name = f'Pushbullet {description.key}'
<|end_body_0|>
<|body_start_1|>
try:
self._attr_native_value = self.pushbullet.data[self.entity_description.key]
self._attr_extra_state_a... | Representation of a Pushbullet Sensor. | PushBulletNotificationSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PushBulletNotificationSensor:
"""Representation of a Pushbullet Sensor."""
def __init__(self, pb, description: SensorEntityDescription):
"""Initialize the Pushbullet sensor."""
<|body_0|>
def update(self):
"""Fetch the latest data from the sensor. This will fetch... | stack_v2_sparse_classes_75kplus_train_008371 | 4,378 | permissive | [
{
"docstring": "Initialize the Pushbullet sensor.",
"name": "__init__",
"signature": "def __init__(self, pb, description: SensorEntityDescription)"
},
{
"docstring": "Fetch the latest data from the sensor. This will fetch the 'sensor reading' into self._state but also all attributes into self._s... | 2 | stack_v2_sparse_classes_30k_train_046661 | Implement the Python class `PushBulletNotificationSensor` described below.
Class description:
Representation of a Pushbullet Sensor.
Method signatures and docstrings:
- def __init__(self, pb, description: SensorEntityDescription): Initialize the Pushbullet sensor.
- def update(self): Fetch the latest data from the se... | Implement the Python class `PushBulletNotificationSensor` described below.
Class description:
Representation of a Pushbullet Sensor.
Method signatures and docstrings:
- def __init__(self, pb, description: SensorEntityDescription): Initialize the Pushbullet sensor.
- def update(self): Fetch the latest data from the se... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class PushBulletNotificationSensor:
"""Representation of a Pushbullet Sensor."""
def __init__(self, pb, description: SensorEntityDescription):
"""Initialize the Pushbullet sensor."""
<|body_0|>
def update(self):
"""Fetch the latest data from the sensor. This will fetch... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PushBulletNotificationSensor:
"""Representation of a Pushbullet Sensor."""
def __init__(self, pb, description: SensorEntityDescription):
"""Initialize the Pushbullet sensor."""
self.entity_description = description
self.pushbullet = pb
self._attr_name = f'Pushbullet {descr... | the_stack_v2_python_sparse | homeassistant/components/pushbullet/sensor.py | AlexxIT/home-assistant | train | 9 |
fe265303576890ab4bfbbe45914ac848e6d02de3 | [
"from dials.util.options import ArgumentParser\nusage = 'usage: %s tag=tagname' % libtbx.env.dispatcher_name\nself.parser = ArgumentParser(usage=usage, sort_options=True, phil=phil_scope, epilog=help_message)",
"params, options = self.parser.parse_args(show_diff_phil=True)\nself.params = params\nif params.tag is ... | <|body_start_0|>
from dials.util.options import ArgumentParser
usage = 'usage: %s tag=tagname' % libtbx.env.dispatcher_name
self.parser = ArgumentParser(usage=usage, sort_options=True, phil=phil_scope, epilog=help_message)
<|end_body_0|>
<|body_start_1|>
params, options = self.parser.pa... | Class to parse the command line options. | Script | [
"BSD-3-Clause-LBNL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Script:
"""Class to parse the command line options."""
def __init__(self):
"""Set the expected options."""
<|body_0|>
def run(self):
"""Parse the options."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from dials.util.options import ArgumentPar... | stack_v2_sparse_classes_75kplus_train_008372 | 2,549 | permissive | [
{
"docstring": "Set the expected options.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parse the options.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `Script` described below.
Class description:
Class to parse the command line options.
Method signatures and docstrings:
- def __init__(self): Set the expected options.
- def run(self): Parse the options. | Implement the Python class `Script` described below.
Class description:
Class to parse the command line options.
Method signatures and docstrings:
- def __init__(self): Set the expected options.
- def run(self): Parse the options.
<|skeleton|>
class Script:
"""Class to parse the command line options."""
def... | 7f4dfb6c873fd560920f697cbfd8a5ff6eed82fa | <|skeleton|>
class Script:
"""Class to parse the command line options."""
def __init__(self):
"""Set the expected options."""
<|body_0|>
def run(self):
"""Parse the options."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Script:
"""Class to parse the command line options."""
def __init__(self):
"""Set the expected options."""
from dials.util.options import ArgumentParser
usage = 'usage: %s tag=tagname' % libtbx.env.dispatcher_name
self.parser = ArgumentParser(usage=usage, sort_options=True... | the_stack_v2_python_sparse | xfel/command_line/cspad_detector_statistics.py | cctbx/cctbx_project | train | 206 |
f64a5622cc3b851ecb05970c165ed9bb04173376 | [
"queryset = BookInfo.objects.all()\nbook_list = []\nfor book in queryset:\n book_list.append({'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_data, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else ''})\nreturn JsonResponse(book_list, safe=False)",
"json_by... | <|body_start_0|>
queryset = BookInfo.objects.all()
book_list = []
for book in queryset:
book_list.append({'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_data, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else ''})
return ... | 查询所有图书、增加图书 | BooksAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BooksAPIView:
"""查询所有图书、增加图书"""
def get(self, request):
"""查询所有图书,路由:GET /books/"""
<|body_0|>
def post(self, request):
"""新增图书,路由:POST /books/"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queryset = BookInfo.objects.all()
book_list =... | stack_v2_sparse_classes_75kplus_train_008373 | 8,903 | no_license | [
{
"docstring": "查询所有图书,路由:GET /books/",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新增图书,路由:POST /books/",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000847 | Implement the Python class `BooksAPIView` described below.
Class description:
查询所有图书、增加图书
Method signatures and docstrings:
- def get(self, request): 查询所有图书,路由:GET /books/
- def post(self, request): 新增图书,路由:POST /books/ | Implement the Python class `BooksAPIView` described below.
Class description:
查询所有图书、增加图书
Method signatures and docstrings:
- def get(self, request): 查询所有图书,路由:GET /books/
- def post(self, request): 新增图书,路由:POST /books/
<|skeleton|>
class BooksAPIView:
"""查询所有图书、增加图书"""
def get(self, request):
"""查询... | e4bfa900b95764880e2ca2fcfb0389113f570147 | <|skeleton|>
class BooksAPIView:
"""查询所有图书、增加图书"""
def get(self, request):
"""查询所有图书,路由:GET /books/"""
<|body_0|>
def post(self, request):
"""新增图书,路由:POST /books/"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BooksAPIView:
"""查询所有图书、增加图书"""
def get(self, request):
"""查询所有图书,路由:GET /books/"""
queryset = BookInfo.objects.all()
book_list = []
for book in queryset:
book_list.append({'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_data, 'bread': book.bread, ... | the_stack_v2_python_sparse | H_django/demo/Users/views.py | Jhon-Chen/Code_Practice | train | 0 |
9c62a47a8fbb331afcccecbaad161ea36c3f815f | [
"specs = super(ExpectedImprovement, cls).getInputSpecification()\nspecs.description = \"If this node is present within the acquisition node,\\n the expected improvement acqusition function is utilized.\\n This function is derived by applying Bayesian optimal decision ma... | <|body_start_0|>
specs = super(ExpectedImprovement, cls).getInputSpecification()
specs.description = "If this node is present within the acquisition node,\n the expected improvement acqusition function is utilized.\n This function is derived by applying Baye... | Provides class for the Expected Improvement (EI) acquisition function | ExpectedImprovement | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for sp... | stack_v2_sparse_classes_75kplus_train_008374 | 5,235 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signature": "def getInputSpecification(cls)"
},
{
"docstring": "Evalu... | 3 | stack_v2_sparse_classes_30k_train_052516 | Implement the Python class `ExpectedImprovement` described below.
Class description:
Provides class for the Expected Improvement (EI) acquisition function
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class cls. @ In, None @ ... | Implement the Python class `ExpectedImprovement` described below.
Class description:
Provides class for the Expected Improvement (EI) acquisition function
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class cls. @ In, None @ ... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for sp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying inpu... | the_stack_v2_python_sparse | ravenframework/Optimizers/acquisitionFunctions/ExpectedImprovement.py | idaholab/raven | train | 201 |
f52957f572073650cf122021c25752587457ff7c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn FilterOperatorSchema()",
"from .attribute_type import AttributeType\nfrom .entity import Entity\nfrom .scope_operator_multi_valued_comparison_type import ScopeOperatorMultiValuedComparisonType\nfrom .scope_operator_type import ScopeOpe... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return FilterOperatorSchema()
<|end_body_0|>
<|body_start_1|>
from .attribute_type import AttributeType
from .entity import Entity
from .scope_operator_multi_valued_comparison_type impo... | FilterOperatorSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_75kplus_train_008375 | 3,425 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: FilterOperatorSchema",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | stack_v2_sparse_classes_30k_train_009253 | Implement the Python class `FilterOperatorSchema` described below.
Class description:
Implement the FilterOperatorSchema class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema: Creates a new instance of the appropriate class based o... | Implement the Python class `FilterOperatorSchema` described below.
Class description:
Implement the FilterOperatorSchema class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | the_stack_v2_python_sparse | msgraph/generated/models/filter_operator_schema.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
c7a17213a818bf2743d5548d99ac1f3265a2d2b4 | [
"if alert_rate > 1 or alert_rate < 0:\n raise ValueError('Alert rate is outside of valid range [0,1]')\nself.alert_rate = alert_rate",
"ypred_proba = self._standardize_input_type(ypred_proba)\nif len(ypred_proba.unique()) == 1:\n logger.debug(f'All predicted probabilities have the same value: {ypred_proba.u... | <|body_start_0|>
if alert_rate > 1 or alert_rate < 0:
raise ValueError('Alert rate is outside of valid range [0,1]')
self.alert_rate = alert_rate
<|end_body_0|>
<|body_start_1|>
ypred_proba = self._standardize_input_type(ypred_proba)
if len(ypred_proba.unique()) == 1:
... | SensitivityLowAlert | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensitivityLowAlert:
def __init__(self, alert_rate=0.01):
"""Create instance of SensitivityLowAlert Arguments: alert_rate (float): percentage of top scores to classify as high risk"""
<|body_0|>
def decision_function(self, ypred_proba, **kwargs):
"""Determine if an o... | stack_v2_sparse_classes_75kplus_train_008376 | 2,359 | permissive | [
{
"docstring": "Create instance of SensitivityLowAlert Arguments: alert_rate (float): percentage of top scores to classify as high risk",
"name": "__init__",
"signature": "def __init__(self, alert_rate=0.01)"
},
{
"docstring": "Determine if an observation is high risk given an alert rate Argumen... | 3 | stack_v2_sparse_classes_30k_train_035277 | Implement the Python class `SensitivityLowAlert` described below.
Class description:
Implement the SensitivityLowAlert class.
Method signatures and docstrings:
- def __init__(self, alert_rate=0.01): Create instance of SensitivityLowAlert Arguments: alert_rate (float): percentage of top scores to classify as high risk... | Implement the Python class `SensitivityLowAlert` described below.
Class description:
Implement the SensitivityLowAlert class.
Method signatures and docstrings:
- def __init__(self, alert_rate=0.01): Create instance of SensitivityLowAlert Arguments: alert_rate (float): percentage of top scores to classify as high risk... | 3b5bf62b08a5a5bc6485ba5387a08c32e1857473 | <|skeleton|>
class SensitivityLowAlert:
def __init__(self, alert_rate=0.01):
"""Create instance of SensitivityLowAlert Arguments: alert_rate (float): percentage of top scores to classify as high risk"""
<|body_0|>
def decision_function(self, ypred_proba, **kwargs):
"""Determine if an o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SensitivityLowAlert:
def __init__(self, alert_rate=0.01):
"""Create instance of SensitivityLowAlert Arguments: alert_rate (float): percentage of top scores to classify as high risk"""
if alert_rate > 1 or alert_rate < 0:
raise ValueError('Alert rate is outside of valid range [0,1]'... | the_stack_v2_python_sparse | evalml/objectives/sensitivity_low_alert.py | ObinnaObeleagu/evalml | train | 1 | |
a9478436c73bee86644e0abac6295cec93d5f3cb | [
"self.ansible_host = kwargs['data']['ansible_host']\nself.inventory = kwargs['data']['inventory']\nself.all_resources = kwargs['data']['all_resources']\nself.resource_type = kwargs['data']['resource_type']\nself.resource_config = kwargs['data']['resource_config']\nself.logger = logging.getLogger(__name__)",
"look... | <|body_start_0|>
self.ansible_host = kwargs['data']['ansible_host']
self.inventory = kwargs['data']['inventory']
self.all_resources = kwargs['data']['all_resources']
self.resource_type = kwargs['data']['resource_type']
self.resource_config = kwargs['data']['resource_config']
... | Main VMware Class. | VMware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VMware:
"""Main VMware Class."""
def __init__(self, **kwargs):
"""Init a thing."""
<|body_0|>
def parse(self):
"""Parse VMware resources to generate Ansible inventory."""
<|body_1|>
def datacenter(self):
"""Parse vSphere datacenter resources.... | stack_v2_sparse_classes_75kplus_train_008377 | 4,631 | permissive | [
{
"docstring": "Init a thing.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Parse VMware resources to generate Ansible inventory.",
"name": "parse",
"signature": "def parse(self)"
},
{
"docstring": "Parse vSphere datacenter resources.",
... | 6 | stack_v2_sparse_classes_30k_train_017672 | Implement the Python class `VMware` described below.
Class description:
Main VMware Class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Init a thing.
- def parse(self): Parse VMware resources to generate Ansible inventory.
- def datacenter(self): Parse vSphere datacenter resources.
- def tag(self... | Implement the Python class `VMware` described below.
Class description:
Main VMware Class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Init a thing.
- def parse(self): Parse VMware resources to generate Ansible inventory.
- def datacenter(self): Parse vSphere datacenter resources.
- def tag(self... | d3c0f7449f44c620567c8b9ea520c3a31806be3c | <|skeleton|>
class VMware:
"""Main VMware Class."""
def __init__(self, **kwargs):
"""Init a thing."""
<|body_0|>
def parse(self):
"""Parse VMware resources to generate Ansible inventory."""
<|body_1|>
def datacenter(self):
"""Parse vSphere datacenter resources.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VMware:
"""Main VMware Class."""
def __init__(self, **kwargs):
"""Init a thing."""
self.ansible_host = kwargs['data']['ansible_host']
self.inventory = kwargs['data']['inventory']
self.all_resources = kwargs['data']['all_resources']
self.resource_type = kwargs['data... | the_stack_v2_python_sparse | terraform_to_ansible/generators/vmware.py | mrlesmithjr/terraform-to-ansible | train | 19 |
4022a86d614484bafe7548750f4e12f6a51dd300 | [
"try:\n self.key = RSA.import_key(private_key)\n self.cipher = PKCS1_OAEP.new(self.key)\n self.signer = pkcs1_15.new(self.key)\nexcept (ValueError, TypeError):\n print('导入私钥出错: %s' % private_key)",
"signature = None\ntry:\n result = self.cipher.decrypt(msg)\nexcept (ValueError, TypeError):\n res... | <|body_start_0|>
try:
self.key = RSA.import_key(private_key)
self.cipher = PKCS1_OAEP.new(self.key)
self.signer = pkcs1_15.new(self.key)
except (ValueError, TypeError):
print('导入私钥出错: %s' % private_key)
<|end_body_0|>
<|body_start_1|>
signature = ... | 这个类包含对应的私钥创建的cipher,包含用私钥对信息进行解密和用私钥对信息进行签名的功能。 一般来讲,这部分应该是在服务器端处调用,用私钥解密收到的信息和对返回的信息进行签名。 | PrivateCipher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrivateCipher:
"""这个类包含对应的私钥创建的cipher,包含用私钥对信息进行解密和用私钥对信息进行签名的功能。 一般来讲,这部分应该是在服务器端处调用,用私钥解密收到的信息和对返回的信息进行签名。"""
def __init__(self, private_key: bytes):
"""根据提供的private_key初始化PrivateCipher. @param private_key: 私钥输入。"""
<|body_0|>
def decrypt_sign_message(self, msg: bytes)... | stack_v2_sparse_classes_75kplus_train_008378 | 3,452 | no_license | [
{
"docstring": "根据提供的private_key初始化PrivateCipher. @param private_key: 私钥输入。",
"name": "__init__",
"signature": "def __init__(self, private_key: bytes)"
},
{
"docstring": "对收到的msg用私钥进行解密,同时用私钥对解密后的信息进行数字签名。 @param msg: 需要解密的信息。 @returns: (解密后的信息,数字签名信息)",
"name": "decrypt_sign_message",
"... | 2 | stack_v2_sparse_classes_30k_train_031449 | Implement the Python class `PrivateCipher` described below.
Class description:
这个类包含对应的私钥创建的cipher,包含用私钥对信息进行解密和用私钥对信息进行签名的功能。 一般来讲,这部分应该是在服务器端处调用,用私钥解密收到的信息和对返回的信息进行签名。
Method signatures and docstrings:
- def __init__(self, private_key: bytes): 根据提供的private_key初始化PrivateCipher. @param private_key: 私钥输入。
- def decryp... | Implement the Python class `PrivateCipher` described below.
Class description:
这个类包含对应的私钥创建的cipher,包含用私钥对信息进行解密和用私钥对信息进行签名的功能。 一般来讲,这部分应该是在服务器端处调用,用私钥解密收到的信息和对返回的信息进行签名。
Method signatures and docstrings:
- def __init__(self, private_key: bytes): 根据提供的private_key初始化PrivateCipher. @param private_key: 私钥输入。
- def decryp... | 8e012855cce61fb53437758021416e5f6deb02ea | <|skeleton|>
class PrivateCipher:
"""这个类包含对应的私钥创建的cipher,包含用私钥对信息进行解密和用私钥对信息进行签名的功能。 一般来讲,这部分应该是在服务器端处调用,用私钥解密收到的信息和对返回的信息进行签名。"""
def __init__(self, private_key: bytes):
"""根据提供的private_key初始化PrivateCipher. @param private_key: 私钥输入。"""
<|body_0|>
def decrypt_sign_message(self, msg: bytes)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrivateCipher:
"""这个类包含对应的私钥创建的cipher,包含用私钥对信息进行解密和用私钥对信息进行签名的功能。 一般来讲,这部分应该是在服务器端处调用,用私钥解密收到的信息和对返回的信息进行签名。"""
def __init__(self, private_key: bytes):
"""根据提供的private_key初始化PrivateCipher. @param private_key: 私钥输入。"""
try:
self.key = RSA.import_key(private_key)
sel... | the_stack_v2_python_sparse | DEMO/auth_server/authantication/cipher.py | hanhiver/PythonBasic | train | 0 |
15a52e613ca529ef39b8b96e2ad9ef34659bd067 | [
"self.cluster_dir = cluster_dir\nself.year_id = year_id\nself.input_me = input_me\nself.output_me = output_me\nself.conn_def = 'cod'\nself.gbd_round = 4",
"query = 'SELECT location_id, most_detailed FROM shared.location_hierarchy_history WHERE location_set_version_id=(SELECT location_set_version_id FROM {DATABASE... | <|body_start_0|>
self.cluster_dir = cluster_dir
self.year_id = year_id
self.input_me = input_me
self.output_me = output_me
self.conn_def = 'cod'
self.gbd_round = 4
<|end_body_0|>
<|body_start_1|>
query = 'SELECT location_id, most_detailed FROM shared.location_hie... | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
def __init__(self, cluster_dir, year_id, input_me, output_me):
"""This class incorporates all the functions that all the specific causes use, but all in different sequence"""
<|body_0|>
def get_locations(self, location_set_id):
"""Pulls the location hierarchy u... | stack_v2_sparse_classes_75kplus_train_008379 | 4,519 | no_license | [
{
"docstring": "This class incorporates all the functions that all the specific causes use, but all in different sequence",
"name": "__init__",
"signature": "def __init__(self, cluster_dir, year_id, input_me, output_me)"
},
{
"docstring": "Pulls the location hierarchy upon which this code is to ... | 6 | stack_v2_sparse_classes_30k_train_053532 | Implement the Python class `Base` described below.
Class description:
Implement the Base class.
Method signatures and docstrings:
- def __init__(self, cluster_dir, year_id, input_me, output_me): This class incorporates all the functions that all the specific causes use, but all in different sequence
- def get_locatio... | Implement the Python class `Base` described below.
Class description:
Implement the Base class.
Method signatures and docstrings:
- def __init__(self, cluster_dir, year_id, input_me, output_me): This class incorporates all the functions that all the specific causes use, but all in different sequence
- def get_locatio... | 746ea5fb76a9c049c37a8c15aa089c041a90a6d5 | <|skeleton|>
class Base:
def __init__(self, cluster_dir, year_id, input_me, output_me):
"""This class incorporates all the functions that all the specific causes use, but all in different sequence"""
<|body_0|>
def get_locations(self, location_set_id):
"""Pulls the location hierarchy u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
def __init__(self, cluster_dir, year_id, input_me, output_me):
"""This class incorporates all the functions that all the specific causes use, but all in different sequence"""
self.cluster_dir = cluster_dir
self.year_id = year_id
self.input_me = input_me
self.outpu... | the_stack_v2_python_sparse | nonfatal_code/obstetric_fistula/fistula_zero_out_locations_GATHER.py | Nermin-Ghith/ihme-modeling | train | 0 | |
f070749868f5ba2b7c0382cc2c8c12088889f72d | [
"super().__init__(model=acq_function.model)\nself.acq_func = acq_function\nself.prior_module = prior_module\nself._log = log\nself._prior_exponent = prior_exponent\nself._is_sample_reducing_af = isinstance(acq_function, SampleReducingMCAcquisitionFunction)\nself.set_X_pending(X_pending=X_pending)",
"prior = self.... | <|body_start_0|>
super().__init__(model=acq_function.model)
self.acq_func = acq_function
self.prior_module = prior_module
self._log = log
self._prior_exponent = prior_exponent
self._is_sample_reducing_af = isinstance(acq_function, SampleReducingMCAcquisitionFunction)
... | Class for weighting acquisition functions by a prior distribution. Supports MC and batch acquisition functions via SampleReducingAcquisitionFunction. See [Hvarfner2022]_ for details. | PriorGuidedAcquisitionFunction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriorGuidedAcquisitionFunction:
"""Class for weighting acquisition functions by a prior distribution. Supports MC and batch acquisition functions via SampleReducingAcquisitionFunction. See [Hvarfner2022]_ for details."""
def __init__(self, acq_function: AcquisitionFunction, prior_module: Mod... | stack_v2_sparse_classes_75kplus_train_008380 | 3,750 | permissive | [
{
"docstring": "Initialize the prior-guided acquisition function. Args: acq_function: The base acquisition function. prior_module: A Module that computes the probability (or log probability) for the provided inputs. `prior_module.forward` should take a `batch_shape x q`-dim tensor of inputs and return a `batch_... | 2 | stack_v2_sparse_classes_30k_train_008173 | Implement the Python class `PriorGuidedAcquisitionFunction` described below.
Class description:
Class for weighting acquisition functions by a prior distribution. Supports MC and batch acquisition functions via SampleReducingAcquisitionFunction. See [Hvarfner2022]_ for details.
Method signatures and docstrings:
- def... | Implement the Python class `PriorGuidedAcquisitionFunction` described below.
Class description:
Class for weighting acquisition functions by a prior distribution. Supports MC and batch acquisition functions via SampleReducingAcquisitionFunction. See [Hvarfner2022]_ for details.
Method signatures and docstrings:
- def... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class PriorGuidedAcquisitionFunction:
"""Class for weighting acquisition functions by a prior distribution. Supports MC and batch acquisition functions via SampleReducingAcquisitionFunction. See [Hvarfner2022]_ for details."""
def __init__(self, acq_function: AcquisitionFunction, prior_module: Mod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PriorGuidedAcquisitionFunction:
"""Class for weighting acquisition functions by a prior distribution. Supports MC and batch acquisition functions via SampleReducingAcquisitionFunction. See [Hvarfner2022]_ for details."""
def __init__(self, acq_function: AcquisitionFunction, prior_module: Module, log: boo... | the_stack_v2_python_sparse | botorch/acquisition/prior_guided.py | pytorch/botorch | train | 2,891 |
f3a5c03e6d9ede1809948635880e291274f897ab | [
"self.state_size = state_size\nself.action_size = action_size\nself.name = name\nself.build_model()",
"states = Input(shape=self.state_size)\nactions = Input(shape=self.action_size)\nnet_states = Conv2D(8, (3, 3), strides=(1, 1), activation='relu', padding='same', kernel_initializer='glorot_uniform')(states)\nnet... | <|body_start_0|>
self.state_size = state_size
self.action_size = action_size
self.name = name
self.build_model()
<|end_body_0|>
<|body_start_1|>
states = Input(shape=self.state_size)
actions = Input(shape=self.action_size)
net_states = Conv2D(8, (3, 3), strides=(... | Critic (Value) Model. | Critic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""Critic (Value) Model."""
def __init__(self, state_size, action_size, name='Critic'):
"""Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action fc1_units (int): Dimensions of 1st hidden laye... | stack_v2_sparse_classes_75kplus_train_008381 | 4,330 | no_license | [
{
"docstring": "Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action fc1_units (int): Dimensions of 1st hidden layer fc2_units (int): Dimensions of 2nd hidden layer name (string): Name of the model",
"name": "__init__",
... | 2 | null | Implement the Python class `Critic` described below.
Class description:
Critic (Value) Model.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, name='Critic'): Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of e... | Implement the Python class `Critic` described below.
Class description:
Critic (Value) Model.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, name='Critic'): Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of e... | d84886319f3598c7dc6ba3c07587a968fed0735e | <|skeleton|>
class Critic:
"""Critic (Value) Model."""
def __init__(self, state_size, action_size, name='Critic'):
"""Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action fc1_units (int): Dimensions of 1st hidden laye... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Critic:
"""Critic (Value) Model."""
def __init__(self, state_size, action_size, name='Critic'):
"""Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action fc1_units (int): Dimensions of 1st hidden layer fc2_units (... | the_stack_v2_python_sparse | models/model.py | VikramRadhakrishnan/DeepContrast | train | 1 |
bf99336bd2c29ad714006bdfb35a6ce2bc7dcc2e | [
"self.license_key = license_key\nself.signed_by_user = signed_by_user\nself.signed_time = signed_time\nself.signed_version = signed_version",
"if dictionary is None:\n return None\nlicense_key = dictionary.get('licenseKey')\nsigned_by_user = dictionary.get('signedByUser')\nsigned_time = dictionary.get('signedT... | <|body_start_0|>
self.license_key = license_key
self.signed_by_user = signed_by_user
self.signed_time = signed_time
self.signed_version = signed_version
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
license_key = dictionary.get('licenseKe... | Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the Cohesity user who accepted the End User License Agreement. signed_time (long... | EulaConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EulaConfig:
"""Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the Cohesity user who accepted the End Use... | stack_v2_sparse_classes_75kplus_train_008382 | 2,344 | permissive | [
{
"docstring": "Constructor for the EulaConfig class",
"name": "__init__",
"signature": "def __init__(self, license_key=None, signed_by_user=None, signed_time=None, signed_version=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dicti... | 2 | stack_v2_sparse_classes_30k_train_039114 | Implement the Python class `EulaConfig` described below.
Class description:
Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the... | Implement the Python class `EulaConfig` described below.
Class description:
Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class EulaConfig:
"""Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the Cohesity user who accepted the End Use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EulaConfig:
"""Implementation of the 'EulaConfig' model. Specifies the End User License Agreement acceptance information. Attributes: license_key (string, required): Specifies the license key. signed_by_user (string): Specifies the login account name for the Cohesity user who accepted the End User License Agr... | the_stack_v2_python_sparse | cohesity_management_sdk/models/eula_config.py | cohesity/management-sdk-python | train | 24 |
f0170b4edea4c1052efd999f392aea95534debd0 | [
"nums.sort()\nans = []\nfor i in range(len(nums) - 1):\n if i == 0 or nums[i] > nums[i - 1]:\n for j in self.threeSum(nums[i + 1:], target - nums[i]):\n tem = j.copy()\n tem.append(nums[i])\n if tem not in ans:\n ans.append(tem)\nreturn ans",
"if len(nums)... | <|body_start_0|>
nums.sort()
ans = []
for i in range(len(nums) - 1):
if i == 0 or nums[i] > nums[i - 1]:
for j in self.threeSum(nums[i + 1:], target - nums[i]):
tem = j.copy()
tem.append(nums[i])
if tem not i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums, target):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_008383 | 1,630 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums, target)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def threeSum(self, nums, target): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def threeSum(self, nums, target): :type nums: List[int] :rtype: List[List[int]]... | bf243269810869d28c7484667f46fb1cc0464005 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums, target):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
nums.sort()
ans = []
for i in range(len(nums) - 1):
if i == 0 or nums[i] > nums[i - 1]:
for j in self.threeSum(nums[i + 1:], target - num... | the_stack_v2_python_sparse | 18. 4Sum.py | hemxzp/leetcode | train | 0 | |
823bc1e89d231d64d9d94568134e5d365a373315 | [
"list_of_links = response.xpath('//*/a[@class=\"exhibitorName\"]/@href').extract()\nfor link in list_of_links:\n yield scrapy.Request(response.urljoin(link), callback=self.parse_data)",
"url = 'https://retailx.a2zinc.net/RetailX2020/Public/Exhibitors.aspx?ID=23735'\nitem = RetailXItem()\nitem['url'] = url\nnam... | <|body_start_0|>
list_of_links = response.xpath('//*/a[@class="exhibitorName"]/@href').extract()
for link in list_of_links:
yield scrapy.Request(response.urljoin(link), callback=self.parse_data)
<|end_body_0|>
<|body_start_1|>
url = 'https://retailx.a2zinc.net/RetailX2020/Public/Exh... | Spider to get the data from the online.marketing | RetailX | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetailX:
"""Spider to get the data from the online.marketing"""
def parse(self, response):
"""Method checks for the shops :param response: the fully downloaded webpagage :return:"""
<|body_0|>
def parse_data(self, response):
"""Method get the the data of the tool... | stack_v2_sparse_classes_75kplus_train_008384 | 2,112 | no_license | [
{
"docstring": "Method checks for the shops :param response: the fully downloaded webpagage :return:",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Method get the the data of the tools :param response: :return:",
"name": "parse_data",
"signature": "def par... | 2 | stack_v2_sparse_classes_30k_train_002216 | Implement the Python class `RetailX` described below.
Class description:
Spider to get the data from the online.marketing
Method signatures and docstrings:
- def parse(self, response): Method checks for the shops :param response: the fully downloaded webpagage :return:
- def parse_data(self, response): Method get the... | Implement the Python class `RetailX` described below.
Class description:
Spider to get the data from the online.marketing
Method signatures and docstrings:
- def parse(self, response): Method checks for the shops :param response: the fully downloaded webpagage :return:
- def parse_data(self, response): Method get the... | 64a7ec204166532fc653f7001f288179e45d1046 | <|skeleton|>
class RetailX:
"""Spider to get the data from the online.marketing"""
def parse(self, response):
"""Method checks for the shops :param response: the fully downloaded webpagage :return:"""
<|body_0|>
def parse_data(self, response):
"""Method get the the data of the tool... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RetailX:
"""Spider to get the data from the online.marketing"""
def parse(self, response):
"""Method checks for the shops :param response: the fully downloaded webpagage :return:"""
list_of_links = response.xpath('//*/a[@class="exhibitorName"]/@href').extract()
for link in list_of... | the_stack_v2_python_sparse | AutoScrapy/spiders/retailx.py | SpaceZZ/AutoScrapyProject2 | train | 0 |
60abc9cbd5f2a3ab903e0e970f21f64a21e8ff37 | [
"headers = {'tenant-id': tenant_id, 'user-auth-token': token, 'user-login-type': AgentApp.agent_login_type, 'device-uuid': AgentApp.device_uuid, 'user-id': user_id, 'agent-app': AgentApp.agent_app, 'Api-version': AgentApp.Api_Version}\nparams = {}\nparams.update(kwargs)\nurl = AgentApp.fws + '/appapi/v4/bkges/bkges... | <|body_start_0|>
headers = {'tenant-id': tenant_id, 'user-auth-token': token, 'user-login-type': AgentApp.agent_login_type, 'device-uuid': AgentApp.device_uuid, 'user-id': user_id, 'agent-app': AgentApp.agent_app, 'Api-version': AgentApp.Api_Version}
params = {}
params.update(kwargs)
url... | Bkges | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bkges:
def get_bkge_indexs(self, token, user_id, tenant_id, **kwargs):
"""佣金统计页面"""
<|body_0|>
def get_channel_bkge_list(self, token, user_id, tenant_id, **kwargs):
"""通道佣金列表创"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
headers = {'tenant-id': t... | stack_v2_sparse_classes_75kplus_train_008385 | 1,428 | no_license | [
{
"docstring": "佣金统计页面",
"name": "get_bkge_indexs",
"signature": "def get_bkge_indexs(self, token, user_id, tenant_id, **kwargs)"
},
{
"docstring": "通道佣金列表创",
"name": "get_channel_bkge_list",
"signature": "def get_channel_bkge_list(self, token, user_id, tenant_id, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000899 | Implement the Python class `Bkges` described below.
Class description:
Implement the Bkges class.
Method signatures and docstrings:
- def get_bkge_indexs(self, token, user_id, tenant_id, **kwargs): 佣金统计页面
- def get_channel_bkge_list(self, token, user_id, tenant_id, **kwargs): 通道佣金列表创 | Implement the Python class `Bkges` described below.
Class description:
Implement the Bkges class.
Method signatures and docstrings:
- def get_bkge_indexs(self, token, user_id, tenant_id, **kwargs): 佣金统计页面
- def get_channel_bkge_list(self, token, user_id, tenant_id, **kwargs): 通道佣金列表创
<|skeleton|>
class Bkges:
d... | 2278222cf86887bf16f88cde0ebcce5b5ec98b8f | <|skeleton|>
class Bkges:
def get_bkge_indexs(self, token, user_id, tenant_id, **kwargs):
"""佣金统计页面"""
<|body_0|>
def get_channel_bkge_list(self, token, user_id, tenant_id, **kwargs):
"""通道佣金列表创"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bkges:
def get_bkge_indexs(self, token, user_id, tenant_id, **kwargs):
"""佣金统计页面"""
headers = {'tenant-id': tenant_id, 'user-auth-token': token, 'user-login-type': AgentApp.agent_login_type, 'device-uuid': AgentApp.device_uuid, 'user-id': user_id, 'agent-app': AgentApp.agent_app, 'Api-version'... | the_stack_v2_python_sparse | api/bkges.py | Tiffanyfei/agent_app_api | train | 0 | |
2ee8755a1635d3b0281516dc883a5a44a4f6963c | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)\nself.reqparser.add_argument('attribute_id', required=False, type=str, store_missing=False)\nself.reqparser.add_argument('widget_id', required=False, type=int, store_missing=False)",
"... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)
self.reqparser.add_argument('attribute_id', required=False, type=str, store_missing=False)
self.reqparser.add_argument('widget_id', required=Fa... | Get alerts by user id and/or attribute id. | GetAlerts | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetAlerts:
"""Get alerts by user id and/or attribute id."""
def __init__(self) -> None:
"""Instantiate Reqparse."""
<|body_0|>
def get(self) -> (dict, HTTPStatus):
"""Get alerts by user id and/or attribute id. :return: An HTTP Response with a JSON body content co... | stack_v2_sparse_classes_75kplus_train_008386 | 1,395 | permissive | [
{
"docstring": "Instantiate Reqparse.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Get alerts by user id and/or attribute id. :return: An HTTP Response with a JSON body content containing a list of alerts matching the parsed POST request arguments on success... | 2 | stack_v2_sparse_classes_30k_train_038106 | Implement the Python class `GetAlerts` described below.
Class description:
Get alerts by user id and/or attribute id.
Method signatures and docstrings:
- def __init__(self) -> None: Instantiate Reqparse.
- def get(self) -> (dict, HTTPStatus): Get alerts by user id and/or attribute id. :return: An HTTP Response with a... | Implement the Python class `GetAlerts` described below.
Class description:
Get alerts by user id and/or attribute id.
Method signatures and docstrings:
- def __init__(self) -> None: Instantiate Reqparse.
- def get(self) -> (dict, HTTPStatus): Get alerts by user id and/or attribute id. :return: An HTTP Response with a... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class GetAlerts:
"""Get alerts by user id and/or attribute id."""
def __init__(self) -> None:
"""Instantiate Reqparse."""
<|body_0|>
def get(self) -> (dict, HTTPStatus):
"""Get alerts by user id and/or attribute id. :return: An HTTP Response with a JSON body content co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetAlerts:
"""Get alerts by user id and/or attribute id."""
def __init__(self) -> None:
"""Instantiate Reqparse."""
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)
self.reqparser.add_argument('... | the_stack_v2_python_sparse | Analytics/resources/alerts/get_alerts.py | thanosbnt/SharingCitiesDashboard | train | 0 |
f17c40136b77f3afe30538cbd2c0d44ed8ddef81 | [
"self.feature_headers = feature_headers\nself.feature_types = feature_types\nself.features_attribute = features_attribute\nself.probability_index = probability_index\nself.probability_attribute = probability_attribute\nself.label_index = label_index\nself.label_attribute = label_attribute\nself.label_headers = labe... | <|body_start_0|>
self.feature_headers = feature_headers
self.feature_types = feature_types
self.features_attribute = features_attribute
self.probability_index = probability_index
self.probability_attribute = probability_attribute
self.label_index = label_index
sel... | The inference configuration parameter for the model container. | ClarifyInferenceConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClarifyInferenceConfig:
"""The inference configuration parameter for the model container."""
def __init__(self, feature_headers: Optional[List[str]]=None, feature_types: Optional[List[str]]=None, features_attribute: Optional[str]=None, probability_index: Optional[int]=None, probability_attri... | stack_v2_sparse_classes_75kplus_train_008387 | 17,006 | permissive | [
{
"docstring": "Initialize a config object for model container. Args: feature_headers (list[str]): Optional. The names of the features. If provided, these are included in the endpoint response payload to help readability of the ``InvokeEndpoint`` output. feature_types (list[str]): Optional. A list of data types... | 2 | null | Implement the Python class `ClarifyInferenceConfig` described below.
Class description:
The inference configuration parameter for the model container.
Method signatures and docstrings:
- def __init__(self, feature_headers: Optional[List[str]]=None, feature_types: Optional[List[str]]=None, features_attribute: Optional... | Implement the Python class `ClarifyInferenceConfig` described below.
Class description:
The inference configuration parameter for the model container.
Method signatures and docstrings:
- def __init__(self, feature_headers: Optional[List[str]]=None, feature_types: Optional[List[str]]=None, features_attribute: Optional... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class ClarifyInferenceConfig:
"""The inference configuration parameter for the model container."""
def __init__(self, feature_headers: Optional[List[str]]=None, feature_types: Optional[List[str]]=None, features_attribute: Optional[str]=None, probability_index: Optional[int]=None, probability_attri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClarifyInferenceConfig:
"""The inference configuration parameter for the model container."""
def __init__(self, feature_headers: Optional[List[str]]=None, feature_types: Optional[List[str]]=None, features_attribute: Optional[str]=None, probability_index: Optional[int]=None, probability_attribute: Optiona... | the_stack_v2_python_sparse | src/sagemaker/explainer/clarify_explainer_config.py | aws/sagemaker-python-sdk | train | 2,050 |
ed6f6866ffbf9b036a82bc82d1ffc47ca6a03fb1 | [
"li = []\nfor index in range(len(s)):\n ch = s[index]\n t = -1\n for i in range(len(li)):\n if li[i][0] == ch:\n t = i\n break\n if t != -1:\n li[t][1].append(index)\n else:\n li.append([ch, [index]])\nfor el in li:\n if len(el[1]) == 1:\n return e... | <|body_start_0|>
li = []
for index in range(len(s)):
ch = s[index]
t = -1
for i in range(len(li)):
if li[i][0] == ch:
t = i
break
if t != -1:
li[t][1].append(index)
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
li = []
for index in range(len(s)):
ch = s[i... | stack_v2_sparse_classes_75kplus_train_008388 | 1,033 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar1",
"signature": "def firstUniqChar1(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037621 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar1(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar1(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def firstUniqChar1(self, s):
... | 478bb4019ed38d489171428dced8cbc6f9b3eb52 | <|skeleton|>
class Solution:
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
li = []
for index in range(len(s)):
ch = s[index]
t = -1
for i in range(len(li)):
if li[i][0] == ch:
t = i
break
... | the_stack_v2_python_sparse | First Unique Character in a String.py | harshittiwari/LeetCode | train | 0 | |
412323f1f44e149d44f493f8a4fd5f185762c326 | [
"threadTraces = []\nfor trace in traces:\n threadTraces.append(ThreadSelection.a0Single(trace))\nreturn threadTraces",
"l = 0\nlongestTt = None\nfor tt in trace:\n if len(tt) > l:\n l = len(tt)\n longestTt = tt\nreturn longestTt"
] | <|body_start_0|>
threadTraces = []
for trace in traces:
threadTraces.append(ThreadSelection.a0Single(trace))
return threadTraces
<|end_body_0|>
<|body_start_1|>
l = 0
longestTt = None
for tt in trace:
if len(tt) > l:
l = len(tt)
... | ThreadSelection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadSelection:
def a0(traces):
"""Just selects the longest thread-trace for each trace."""
<|body_0|>
def a0Single(trace):
"""Selects the longest thread-trace."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
threadTraces = []
for trace in ... | stack_v2_sparse_classes_75kplus_train_008389 | 17,901 | no_license | [
{
"docstring": "Just selects the longest thread-trace for each trace.",
"name": "a0",
"signature": "def a0(traces)"
},
{
"docstring": "Selects the longest thread-trace.",
"name": "a0Single",
"signature": "def a0Single(trace)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002779 | Implement the Python class `ThreadSelection` described below.
Class description:
Implement the ThreadSelection class.
Method signatures and docstrings:
- def a0(traces): Just selects the longest thread-trace for each trace.
- def a0Single(trace): Selects the longest thread-trace. | Implement the Python class `ThreadSelection` described below.
Class description:
Implement the ThreadSelection class.
Method signatures and docstrings:
- def a0(traces): Just selects the longest thread-trace for each trace.
- def a0Single(trace): Selects the longest thread-trace.
<|skeleton|>
class ThreadSelection:
... | 4517d12441b9890f8563990975eafa1e3393d3c4 | <|skeleton|>
class ThreadSelection:
def a0(traces):
"""Just selects the longest thread-trace for each trace."""
<|body_0|>
def a0Single(trace):
"""Selects the longest thread-trace."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreadSelection:
def a0(traces):
"""Just selects the longest thread-trace for each trace."""
threadTraces = []
for trace in traces:
threadTraces.append(ThreadSelection.a0Single(trace))
return threadTraces
def a0Single(trace):
"""Selects the longest thre... | the_stack_v2_python_sparse | analysis/algorithms.py | chubbymaggie/weasel | train | 0 | |
1ba10d0548594f961d4719016b0314fa1e237a3e | [
"super().__init__(env)\nself.lives = 0\nself.done = True",
"if self.done:\n state = self.env.reset(**kwargs)\nelse:\n state, _, _, _ = self.env.step(0)\nself.lives = self.env.unwrapped.ale.lives()\nreturn state",
"state, reward, done, info = self.env.step(action)\nself.done = done\nlives = self.env.unwrap... | <|body_start_0|>
super().__init__(env)
self.lives = 0
self.done = True
<|end_body_0|>
<|body_start_1|>
if self.done:
state = self.env.reset(**kwargs)
else:
state, _, _, _ = self.env.step(0)
self.lives = self.env.unwrapped.ale.lives()
retur... | EpisodicLifeEnv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpisodicLifeEnv:
def __init__(self, env: gym.Wrapper):
"""Signals end of episode on loss of life to improve value estimation. Slightly modified from OpenAI baselines AtariWrappers. As detailed in Mnih et al. (2015) -- aka Nature paper. :param env: the inner environment"""
<|body_... | stack_v2_sparse_classes_75kplus_train_008390 | 1,408 | permissive | [
{
"docstring": "Signals end of episode on loss of life to improve value estimation. Slightly modified from OpenAI baselines AtariWrappers. As detailed in Mnih et al. (2015) -- aka Nature paper. :param env: the inner environment",
"name": "__init__",
"signature": "def __init__(self, env: gym.Wrapper)"
... | 3 | stack_v2_sparse_classes_30k_train_009183 | Implement the Python class `EpisodicLifeEnv` described below.
Class description:
Implement the EpisodicLifeEnv class.
Method signatures and docstrings:
- def __init__(self, env: gym.Wrapper): Signals end of episode on loss of life to improve value estimation. Slightly modified from OpenAI baselines AtariWrappers. As ... | Implement the Python class `EpisodicLifeEnv` described below.
Class description:
Implement the EpisodicLifeEnv class.
Method signatures and docstrings:
- def __init__(self, env: gym.Wrapper): Signals end of episode on loss of life to improve value estimation. Slightly modified from OpenAI baselines AtariWrappers. As ... | b3fb6bdb466056cf84115ca7b0af21d2b48185ae | <|skeleton|>
class EpisodicLifeEnv:
def __init__(self, env: gym.Wrapper):
"""Signals end of episode on loss of life to improve value estimation. Slightly modified from OpenAI baselines AtariWrappers. As detailed in Mnih et al. (2015) -- aka Nature paper. :param env: the inner environment"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EpisodicLifeEnv:
def __init__(self, env: gym.Wrapper):
"""Signals end of episode on loss of life to improve value estimation. Slightly modified from OpenAI baselines AtariWrappers. As detailed in Mnih et al. (2015) -- aka Nature paper. :param env: the inner environment"""
super().__init__(env)... | the_stack_v2_python_sparse | source/environment/atari/episodic_life.py | Aethiles/ppo-pytorch | train | 0 | |
ea9deb272d5ca1636b099675c39c47086e2dd3fa | [
"data = request.json\nif data is None:\n return self.json_message('No data received.', HTTP_BAD_REQUEST)\ntry:\n host = data['host']\n api_password = data['api_password']\nexcept KeyError:\n return self.json_message('No host or api_password received.', HTTP_BAD_REQUEST)\ntry:\n port = int(data['port'... | <|body_start_0|>
data = request.json
if data is None:
return self.json_message('No data received.', HTTP_BAD_REQUEST)
try:
host = data['host']
api_password = data['api_password']
except KeyError:
return self.json_message('No host or api_pas... | View to handle EventForwarding requests. | APIEventForwardingView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIEventForwardingView:
"""View to handle EventForwarding requests."""
def post(self, request):
"""Setup an event forwarder."""
<|body_0|>
def delete(self, request):
"""Remove event forwarer."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data ... | stack_v2_sparse_classes_75kplus_train_008391 | 12,334 | permissive | [
{
"docstring": "Setup an event forwarder.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Remove event forwarer.",
"name": "delete",
"signature": "def delete(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052382 | Implement the Python class `APIEventForwardingView` described below.
Class description:
View to handle EventForwarding requests.
Method signatures and docstrings:
- def post(self, request): Setup an event forwarder.
- def delete(self, request): Remove event forwarer. | Implement the Python class `APIEventForwardingView` described below.
Class description:
View to handle EventForwarding requests.
Method signatures and docstrings:
- def post(self, request): Setup an event forwarder.
- def delete(self, request): Remove event forwarer.
<|skeleton|>
class APIEventForwardingView:
""... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class APIEventForwardingView:
"""View to handle EventForwarding requests."""
def post(self, request):
"""Setup an event forwarder."""
<|body_0|>
def delete(self, request):
"""Remove event forwarer."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class APIEventForwardingView:
"""View to handle EventForwarding requests."""
def post(self, request):
"""Setup an event forwarder."""
data = request.json
if data is None:
return self.json_message('No data received.', HTTP_BAD_REQUEST)
try:
host = data['ho... | the_stack_v2_python_sparse | homeassistant/components/api.py | Smart-Torvy/torvy-home-assistant | train | 2 |
6626040044ee42877b3d16195d6c7ea599c688d1 | [
"res = []\nfor k, v in json.loads(signup_form.errors.as_json()).items():\n res.append(v[0]['message'])\nreturn ' '.join(res)",
"request_username = login_form.cleaned_data['username']\nif not User.objects.filter(username=request_username).exists():\n return JsonResponse({'message': 'User not found'})\nuser =... | <|body_start_0|>
res = []
for k, v in json.loads(signup_form.errors.as_json()).items():
res.append(v[0]['message'])
return ' '.join(res)
<|end_body_0|>
<|body_start_1|>
request_username = login_form.cleaned_data['username']
if not User.objects.filter(username=request... | Class responsible for regulating authentication processes. | AuthenticationHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticationHandler:
"""Class responsible for regulating authentication processes."""
def form_erors(signup_form: object) -> str:
"""Method that shows form errors."""
<|body_0|>
def login_handler(request: object, login_form: object) -> object:
"""Account login ... | stack_v2_sparse_classes_75kplus_train_008392 | 3,770 | permissive | [
{
"docstring": "Method that shows form errors.",
"name": "form_erors",
"signature": "def form_erors(signup_form: object) -> str"
},
{
"docstring": "Account login processing method.",
"name": "login_handler",
"signature": "def login_handler(request: object, login_form: object) -> object"
... | 5 | stack_v2_sparse_classes_30k_train_045699 | Implement the Python class `AuthenticationHandler` described below.
Class description:
Class responsible for regulating authentication processes.
Method signatures and docstrings:
- def form_erors(signup_form: object) -> str: Method that shows form errors.
- def login_handler(request: object, login_form: object) -> o... | Implement the Python class `AuthenticationHandler` described below.
Class description:
Class responsible for regulating authentication processes.
Method signatures and docstrings:
- def form_erors(signup_form: object) -> str: Method that shows form errors.
- def login_handler(request: object, login_form: object) -> o... | 7423235ca55cb09761e79d44b50363397585bcb5 | <|skeleton|>
class AuthenticationHandler:
"""Class responsible for regulating authentication processes."""
def form_erors(signup_form: object) -> str:
"""Method that shows form errors."""
<|body_0|>
def login_handler(request: object, login_form: object) -> object:
"""Account login ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthenticationHandler:
"""Class responsible for regulating authentication processes."""
def form_erors(signup_form: object) -> str:
"""Method that shows form errors."""
res = []
for k, v in json.loads(signup_form.errors.as_json()).items():
res.append(v[0]['message'])
... | the_stack_v2_python_sparse | account/services/authentication.py | spanickroon/Market-Place | train | 1 |
1ea156fe30c9b93415dd21f0bacf7a1e197c8205 | [
"super(DMSelfAttention, self).__init__(name=name)\nself._normalizer = gn.modules._unsorted_segment_softmax\nself._kq_dim_division = kq_dim_division\nself._kq_dim = kq_dim",
"sender_keys = gn.blocks.broadcast_sender_nodes_to_edges(attention_graph.replace(nodes=node_keys))\nsender_values = gn.blocks.broadcast_sende... | <|body_start_0|>
super(DMSelfAttention, self).__init__(name=name)
self._normalizer = gn.modules._unsorted_segment_softmax
self._kq_dim_division = kq_dim_division
self._kq_dim = kq_dim
<|end_body_0|>
<|body_start_1|>
sender_keys = gn.blocks.broadcast_sender_nodes_to_edges(attenti... | Multi-head self-attention module. The module is based on the following three papers: * A simple neural network module for relational reasoning (RNs): https://arxiv.org/abs/1706.01427 * Non-local Neural Networks: https://arxiv.org/abs/1711.07971. * Attention Is All You Need (AIAYN): https://arxiv.org/abs/1706.03762. The... | DMSelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DMSelfAttention:
"""Multi-head self-attention module. The module is based on the following three papers: * A simple neural network module for relational reasoning (RNs): https://arxiv.org/abs/1706.01427 * Non-local Neural Networks: https://arxiv.org/abs/1711.07971. * Attention Is All You Need (AI... | stack_v2_sparse_classes_75kplus_train_008393 | 43,752 | no_license | [
{
"docstring": "Inits the module. Args: name: The module name.",
"name": "__init__",
"signature": "def __init__(self, kq_dim_division, kq_dim, name='dm_self_attention')"
},
{
"docstring": "Connects the multi-head self-attention module. The self-attention is only computed according to the connect... | 2 | stack_v2_sparse_classes_30k_train_038189 | Implement the Python class `DMSelfAttention` described below.
Class description:
Multi-head self-attention module. The module is based on the following three papers: * A simple neural network module for relational reasoning (RNs): https://arxiv.org/abs/1706.01427 * Non-local Neural Networks: https://arxiv.org/abs/1711... | Implement the Python class `DMSelfAttention` described below.
Class description:
Multi-head self-attention module. The module is based on the following three papers: * A simple neural network module for relational reasoning (RNs): https://arxiv.org/abs/1706.01427 * Non-local Neural Networks: https://arxiv.org/abs/1711... | 212b45a74db63cbf371478d72ed467e372803a47 | <|skeleton|>
class DMSelfAttention:
"""Multi-head self-attention module. The module is based on the following three papers: * A simple neural network module for relational reasoning (RNs): https://arxiv.org/abs/1706.01427 * Non-local Neural Networks: https://arxiv.org/abs/1711.07971. * Attention Is All You Need (AI... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DMSelfAttention:
"""Multi-head self-attention module. The module is based on the following three papers: * A simple neural network module for relational reasoning (RNs): https://arxiv.org/abs/1706.01427 * Non-local Neural Networks: https://arxiv.org/abs/1711.07971. * Attention Is All You Need (AIAYN): https:/... | the_stack_v2_python_sparse | gnn.py | xju2/graph-normalizing-flows | train | 1 |
7688c7441fd85991175349e513291209940e3b0f | [
"@lru_cache(None)\ndef gen_surrounded(n):\n if n == 0:\n return ['']\n return [f'({s})' for s in gen_all(n - 1)]\n\n@lru_cache(None)\ndef gen_all(n):\n if n == 0:\n return ['']\n ret = []\n for i in range(1, n + 1):\n for pre in gen_surrounded(i):\n for post in gen_all... | <|body_start_0|>
@lru_cache(None)
def gen_surrounded(n):
if n == 0:
return ['']
return [f'({s})' for s in gen_all(n - 1)]
@lru_cache(None)
def gen_all(n):
if n == 0:
return ['']
ret = []
for i in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""Time complexity: O(n^3) Space complexity: O(n^3)"""
<|body_0|>
def generateParenthesis(self, n: int) -> List[str]:
"""Time complexity: O(n^3) Space complexity: O(n^3)"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_008394 | 1,989 | no_license | [
{
"docstring": "Time complexity: O(n^3) Space complexity: O(n^3)",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n: int) -> List[str]"
},
{
"docstring": "Time complexity: O(n^3) Space complexity: O(n^3)",
"name": "generateParenthesis",
"signature": "def gener... | 2 | stack_v2_sparse_classes_30k_train_048708 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: Time complexity: O(n^3) Space complexity: O(n^3)
- def generateParenthesis(self, n: int) -> List[str]: Time complexity: O(n^3)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: Time complexity: O(n^3) Space complexity: O(n^3)
- def generateParenthesis(self, n: int) -> List[str]: Time complexity: O(n^3)... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""Time complexity: O(n^3) Space complexity: O(n^3)"""
<|body_0|>
def generateParenthesis(self, n: int) -> List[str]:
"""Time complexity: O(n^3) Space complexity: O(n^3)"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""Time complexity: O(n^3) Space complexity: O(n^3)"""
@lru_cache(None)
def gen_surrounded(n):
if n == 0:
return ['']
return [f'({s})' for s in gen_all(n - 1)]
@lru_cache(None... | the_stack_v2_python_sparse | leetcode/solved/22_Generate_Parentheses/solution.py | sungminoh/algorithms | train | 0 | |
c652428851eb81eab8ea3fa740d3fb1f52b51bfc | [
"K = len(probs)\nself.q = torch.zeros(K).cuda()\nself.J = torch.LongTensor([0] * K).cuda()\nsmaller = []\nlarger = []\nfor kk, prob in enumerate(probs):\n self.q[kk] = K * prob\n if self.q[kk] < 1.0:\n smaller.append(kk)\n else:\n larger.append(kk)\nwhile len(smaller) > 0 and len(larger) > 0:... | <|body_start_0|>
K = len(probs)
self.q = torch.zeros(K).cuda()
self.J = torch.LongTensor([0] * K).cuda()
smaller = []
larger = []
for kk, prob in enumerate(probs):
self.q[kk] = K * prob
if self.q[kk] < 1.0:
smaller.append(kk)
... | Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/ | AliasMultinomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AliasMultinomial:
"""Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/"""
def __init__(self, probs):
"""probs: a float tensor with shape [K]. It represents probabilities of dif... | stack_v2_sparse_classes_75kplus_train_008395 | 29,814 | no_license | [
{
"docstring": "probs: a float tensor with shape [K]. It represents probabilities of different outcomes. There are K outcomes. Probabilities sum to one.",
"name": "__init__",
"signature": "def __init__(self, probs)"
},
{
"docstring": "Draw N samples from the distribution.",
"name": "draw",
... | 2 | stack_v2_sparse_classes_30k_train_001663 | Implement the Python class `AliasMultinomial` described below.
Class description:
Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
Method signatures and docstrings:
- def __init__(self, probs): probs: a float ... | Implement the Python class `AliasMultinomial` described below.
Class description:
Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
Method signatures and docstrings:
- def __init__(self, probs): probs: a float ... | 82d3e9808073f2145b039ccf464c526cb85274e3 | <|skeleton|>
class AliasMultinomial:
"""Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/"""
def __init__(self, probs):
"""probs: a float tensor with shape [K]. It represents probabilities of dif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AliasMultinomial:
"""Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/"""
def __init__(self, probs):
"""probs: a float tensor with shape [K]. It represents probabilities of different outcom... | the_stack_v2_python_sparse | business/p201908/3507_750/lda2vec_model.py | Alvin2580du/alvin_py | train | 12 |
63ee579c1d48742aaa58fa2e37118e2c26670be3 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('janellc_rstiffel', 'janellc_rstiffel')\nurl = 'https://chronicdata.cdc.gov/resource/mxg7-989n.json?locationdesc=Massachusetts&$limit=1000'\nresponse = urllib.request.urlopen(url).read().decode('utf-8')\n... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('janellc_rstiffel', 'janellc_rstiffel')
url = 'https://chronicdata.cdc.gov/resource/mxg7-989n.json?locationdesc=Massachusetts&$limit=1000'
response... | getObesityData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getObesityData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythin... | stack_v2_sparse_classes_75kplus_train_008396 | 3,620 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_009363 | Implement the Python class `getObesityData` described below.
Class description:
Implement the getObesityData class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None,... | Implement the Python class `getObesityData` described below.
Class description:
Implement the getObesityData class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None,... | b5ccaad97f6e35f9580e645ca764f36eb3406f43 | <|skeleton|>
class getObesityData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class getObesityData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('janellc_rstiffel', 'janellc_rstiffel... | the_stack_v2_python_sparse | janellc_rstiffel/getObesityData.py | dwang1995/course-2018-spr-proj | train | 1 | |
4113edc266483296716b543ba8cc85585910ef39 | [
"outfile = open(outputDir / self.name + '.txt', 'wt')\noutfile.write(self.render(prevPage, nextPage, pages))\noutfile.close()",
"html = u'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n'\nhtml += u'<title>'\nhtml += escape(self.node.titleLong)\nhtml += u'</title>\\n'\nbody = ''\nfor idevice in self.node.idevices:\n... | <|body_start_0|>
outfile = open(outputDir / self.name + '.txt', 'wt')
outfile.write(self.render(prevPage, nextPage, pages))
outfile.close()
<|end_body_0|>
<|body_start_1|>
html = u'<?xml version="1.0" encoding="UTF-8"?>\n'
html += u'<title>'
html += escape(self.node.titl... | This class transforms an eXe node into an iPod Note page | IpodPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IpodPage:
"""This class transforms an eXe node into an iPod Note page"""
def save(self, outputDir, prevPage, nextPage, pages):
"""This is the main function. It will render the page and save it to a file. 'outputDir' is the directory where the filenames will be saved (a 'path' instanc... | stack_v2_sparse_classes_75kplus_train_008397 | 2,796 | no_license | [
{
"docstring": "This is the main function. It will render the page and save it to a file. 'outputDir' is the directory where the filenames will be saved (a 'path' instance)",
"name": "save",
"signature": "def save(self, outputDir, prevPage, nextPage, pages)"
},
{
"docstring": "Returns an XHTML s... | 3 | stack_v2_sparse_classes_30k_train_023977 | Implement the Python class `IpodPage` described below.
Class description:
This class transforms an eXe node into an iPod Note page
Method signatures and docstrings:
- def save(self, outputDir, prevPage, nextPage, pages): This is the main function. It will render the page and save it to a file. 'outputDir' is the dire... | Implement the Python class `IpodPage` described below.
Class description:
This class transforms an eXe node into an iPod Note page
Method signatures and docstrings:
- def save(self, outputDir, prevPage, nextPage, pages): This is the main function. It will render the page and save it to a file. 'outputDir' is the dire... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class IpodPage:
"""This class transforms an eXe node into an iPod Note page"""
def save(self, outputDir, prevPage, nextPage, pages):
"""This is the main function. It will render the page and save it to a file. 'outputDir' is the directory where the filenames will be saved (a 'path' instanc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IpodPage:
"""This class transforms an eXe node into an iPod Note page"""
def save(self, outputDir, prevPage, nextPage, pages):
"""This is the main function. It will render the page and save it to a file. 'outputDir' is the directory where the filenames will be saved (a 'path' instance)"""
... | the_stack_v2_python_sparse | eXe/rev2735-2828/right-branch-2828/exe/export/ipodpage.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
788870a4181be993f9ead321217801caec97fcf7 | [
"portfolio = Portfolio.objects.filter(user=request.user)\nportfolio_serializer = PortfolioSerializer(portfolio, many=True)\nfor portfolio in portfolio_serializer.data:\n portfolio['balance'] = decimal.Decimal(portfolio['balance'])\n portfolio['holdings'] = fetch_holdings(portfolio)\n portfolio['balance_his... | <|body_start_0|>
portfolio = Portfolio.objects.filter(user=request.user)
portfolio_serializer = PortfolioSerializer(portfolio, many=True)
for portfolio in portfolio_serializer.data:
portfolio['balance'] = decimal.Decimal(portfolio['balance'])
portfolio['holdings'] = fetch... | List all accounts, or add a new one Attributes: permission_classes (list): A list of the accepted permissions for this view | PortfolioList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PortfolioList:
"""List all accounts, or add a new one Attributes: permission_classes (list): A list of the accepted permissions for this view"""
def get(self, request):
"""Get the list of accounts Arguments: request (HttpRequest): The request object from an HTTP request Returns: Resp... | stack_v2_sparse_classes_75kplus_train_008398 | 12,376 | no_license | [
{
"docstring": "Get the list of accounts Arguments: request (HttpRequest): The request object from an HTTP request Returns: Response: list of account in JSON format",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Add a new account Arguments: request (HttpRequest): The r... | 2 | stack_v2_sparse_classes_30k_train_011557 | Implement the Python class `PortfolioList` described below.
Class description:
List all accounts, or add a new one Attributes: permission_classes (list): A list of the accepted permissions for this view
Method signatures and docstrings:
- def get(self, request): Get the list of accounts Arguments: request (HttpReques... | Implement the Python class `PortfolioList` described below.
Class description:
List all accounts, or add a new one Attributes: permission_classes (list): A list of the accepted permissions for this view
Method signatures and docstrings:
- def get(self, request): Get the list of accounts Arguments: request (HttpReques... | d30666ff678e38513d83245ab6dfa8657baa09c5 | <|skeleton|>
class PortfolioList:
"""List all accounts, or add a new one Attributes: permission_classes (list): A list of the accepted permissions for this view"""
def get(self, request):
"""Get the list of accounts Arguments: request (HttpRequest): The request object from an HTTP request Returns: Resp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PortfolioList:
"""List all accounts, or add a new one Attributes: permission_classes (list): A list of the accepted permissions for this view"""
def get(self, request):
"""Get the list of accounts Arguments: request (HttpRequest): The request object from an HTTP request Returns: Response: list of... | the_stack_v2_python_sparse | fiscal/planning_tool/views.py | CIS-Projects-in-CS-S21/pro-fiscal | train | 0 |
69ec434f96503c0302f7f2df946ad3670374e88f | [
"query = DBSession.query(GroupPermAssignment)\nquery = query.join(Group, GroupPermAssignment.group_id == Group.group_id)\nquery = query.filter(Group.group_name == group_name)\nreturn query.all()",
"query = DBSession.query(GroupPermAssignment)\nquery = query.join(Group, GroupPermAssignment.group_id == Group.group_... | <|body_start_0|>
query = DBSession.query(GroupPermAssignment)
query = query.join(Group, GroupPermAssignment.group_id == Group.group_id)
query = query.filter(Group.group_name == group_name)
return query.all()
<|end_body_0|>
<|body_start_1|>
query = DBSession.query(GroupPermAssign... | Arsenal GroupPermAssignment object. | GroupPermAssignment | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupPermAssignment:
"""Arsenal GroupPermAssignment object."""
def get_assignments_by_group(self, group_name):
"""Return a list of permission assignments by group name."""
<|body_0|>
def get_assignments_by_perm(self, perm_name):
"""Return a list of permission ass... | stack_v2_sparse_classes_75kplus_train_008399 | 14,777 | permissive | [
{
"docstring": "Return a list of permission assignments by group name.",
"name": "get_assignments_by_group",
"signature": "def get_assignments_by_group(self, group_name)"
},
{
"docstring": "Return a list of permission assignments by permission name.",
"name": "get_assignments_by_perm",
"... | 2 | stack_v2_sparse_classes_30k_train_000250 | Implement the Python class `GroupPermAssignment` described below.
Class description:
Arsenal GroupPermAssignment object.
Method signatures and docstrings:
- def get_assignments_by_group(self, group_name): Return a list of permission assignments by group name.
- def get_assignments_by_perm(self, perm_name): Return a l... | Implement the Python class `GroupPermAssignment` described below.
Class description:
Arsenal GroupPermAssignment object.
Method signatures and docstrings:
- def get_assignments_by_group(self, group_name): Return a list of permission assignments by group name.
- def get_assignments_by_perm(self, perm_name): Return a l... | 5e8584b5805bb5d1603bb251ed8faeceaed31f59 | <|skeleton|>
class GroupPermAssignment:
"""Arsenal GroupPermAssignment object."""
def get_assignments_by_group(self, group_name):
"""Return a list of permission assignments by group name."""
<|body_0|>
def get_assignments_by_perm(self, perm_name):
"""Return a list of permission ass... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupPermAssignment:
"""Arsenal GroupPermAssignment object."""
def get_assignments_by_group(self, group_name):
"""Return a list of permission assignments by group name."""
query = DBSession.query(GroupPermAssignment)
query = query.join(Group, GroupPermAssignment.group_id == Group.... | the_stack_v2_python_sparse | server/arsenalweb/models/common.py | UnblockedByOps/arsenal | train | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.