blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
8320a062b4c705f6f2f90053ca66ed686da534b5
[ "if not root:\n return 0\nlDepth = self.minDepth(root.left)\nrDepth = self.minDepth(root.right)\nif 0 in [lDepth, rDepth]:\n return lDepth + rDepth + 1\nreturn min(lDepth, rDepth) + 1", "if not root:\n return 0\nq = Queue()\nq.put(root)\nlevel = 1\nwhile not q.empty():\n level += 1\n n = q.qsize()\...
<|body_start_0|> if not root: return 0 lDepth = self.minDepth(root.left) rDepth = self.minDepth(root.right) if 0 in [lDepth, rDepth]: return lDepth + rDepth + 1 return min(lDepth, rDepth) + 1 <|end_body_0|> <|body_start_1|> if not root: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minDepth(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def minDepthIter(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: return 0 lDepth ...
stack_v2_sparse_classes_36k_train_011600
1,284
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "minDepth", "signature": "def minDepth(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "minDepthIter", "signature": "def minDepthIter(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minDepth(self, root): :type root: TreeNode :rtype: int - def minDepthIter(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minDepth(self, root): :type root: TreeNode :rtype: int - def minDepthIter(self, root): :type root: TreeNode :rtype: int <|skeleton|> class Solution: def minDepth(self, ...
2d06ab566c8adc6d864c5565310b56008d2d4b31
<|skeleton|> class Solution: def minDepth(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def minDepthIter(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minDepth(self, root): """:type root: TreeNode :rtype: int""" if not root: return 0 lDepth = self.minDepth(root.left) rDepth = self.minDepth(root.right) if 0 in [lDepth, rDepth]: return lDepth + rDepth + 1 return min(lDepth, ...
the_stack_v2_python_sparse
leetcode/Done/111_MinDepthBinaryTree.py
humachine/AlgoLearning
train
1
b5ed78144468806fc1cfd6fb5bd1b63a7afad66e
[ "ban = [0 for i in range(len(senate))]\ndn = 0\ncrt = ''\nflag = True\nwhile flag:\n i = 0\n flag = False\n while i < len(senate):\n if not ban[i]:\n if dn == 0:\n crt = senate[i]\n dn += 1\n elif crt == senate[i]:\n dn += 1\n ...
<|body_start_0|> ban = [0 for i in range(len(senate))] dn = 0 crt = '' flag = True while flag: i = 0 flag = False while i < len(senate): if not ban[i]: if dn == 0: crt = senate[i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def predictPartyVictory(self, senate): """:type senate: str :rtype: str""" <|body_0|> def predictPartyVictory2(self, senate): """:type senate: str :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> ban = [0 for i in range(len(sena...
stack_v2_sparse_classes_36k_train_011601
4,412
no_license
[ { "docstring": ":type senate: str :rtype: str", "name": "predictPartyVictory", "signature": "def predictPartyVictory(self, senate)" }, { "docstring": ":type senate: str :rtype: str", "name": "predictPartyVictory2", "signature": "def predictPartyVictory2(self, senate)" } ]
2
stack_v2_sparse_classes_30k_train_004799
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def predictPartyVictory(self, senate): :type senate: str :rtype: str - def predictPartyVictory2(self, senate): :type senate: str :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def predictPartyVictory(self, senate): :type senate: str :rtype: str - def predictPartyVictory2(self, senate): :type senate: str :rtype: str <|skeleton|> class Solution: de...
416fed6e441612e1ad82467d07ee1b5570386a94
<|skeleton|> class Solution: def predictPartyVictory(self, senate): """:type senate: str :rtype: str""" <|body_0|> def predictPartyVictory2(self, senate): """:type senate: str :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def predictPartyVictory(self, senate): """:type senate: str :rtype: str""" ban = [0 for i in range(len(senate))] dn = 0 crt = '' flag = True while flag: i = 0 flag = False while i < len(senate): if no...
the_stack_v2_python_sparse
src/python/greedy_algorithm/dota2_senate.py
liadbiz/Leetcode-Solutions
train
1
14b9e6a14811ffbb36dc88818c38256c5156f1ab
[ "calificacion = Calificacion.obtener_calificacion(id_cancion, id_usuario)\nif calificacion is not None:\n error = {'error': 'calificacion_registrada', 'mensaje': 'Ya existe una calificacion registrada'}\n return error", "calificacion = Calificacion.obtener_calificacion(id_cancion, id_usuario)\nif calificaci...
<|body_start_0|> calificacion = Calificacion.obtener_calificacion(id_cancion, id_usuario) if calificacion is not None: error = {'error': 'calificacion_registrada', 'mensaje': 'Ya existe una calificacion registrada'} return error <|end_body_0|> <|body_start_1|> calificaci...
ValidacionCalificacion
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidacionCalificacion: def validar_existe_calificacion(id_usuario, id_cancion): """Valida si existe una Calificacion con el id_usuario y el id_cancion :param id_usuario: El id del usuario que realizo la calificacion :param id_cancion: El id de la cancion calificada :return: Un diccionar...
stack_v2_sparse_classes_36k_train_011602
3,691
no_license
[ { "docstring": "Valida si existe una Calificacion con el id_usuario y el id_cancion :param id_usuario: El id del usuario que realizo la calificacion :param id_cancion: El id de la cancion calificada :return: Un diccionario indicando que existe una calificacion registrada o None si no", "name": "validar_exis...
5
stack_v2_sparse_classes_30k_train_016513
Implement the Python class `ValidacionCalificacion` described below. Class description: Implement the ValidacionCalificacion class. Method signatures and docstrings: - def validar_existe_calificacion(id_usuario, id_cancion): Valida si existe una Calificacion con el id_usuario y el id_cancion :param id_usuario: El id ...
Implement the Python class `ValidacionCalificacion` described below. Class description: Implement the ValidacionCalificacion class. Method signatures and docstrings: - def validar_existe_calificacion(id_usuario, id_cancion): Valida si existe una Calificacion con el id_usuario y el id_cancion :param id_usuario: El id ...
49bbaaf0bd4d1bec2d81eb35882e5f073b1c149f
<|skeleton|> class ValidacionCalificacion: def validar_existe_calificacion(id_usuario, id_cancion): """Valida si existe una Calificacion con el id_usuario y el id_cancion :param id_usuario: El id del usuario que realizo la calificacion :param id_cancion: El id de la cancion calificada :return: Un diccionar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidacionCalificacion: def validar_existe_calificacion(id_usuario, id_cancion): """Valida si existe una Calificacion con el id_usuario y el id_cancion :param id_usuario: El id del usuario que realizo la calificacion :param id_cancion: El id de la cancion calificada :return: Un diccionario indicando q...
the_stack_v2_python_sparse
app/util/validaciones/modelos/ValidacionCalificacion.py
codeChinoUV/EspotifeiAPI
train
0
e6376670bb76ef8b963e4188aa5075c3afb4535d
[ "found_categories = []\nprevious_categories = filter(lambda x: page in x.pages, Category.query.all())\npattern = re.compile('\\\\[\\\\[Category:[a-zA-Z0-9 _]+\\\\]\\\\]')\nmatches = re.findall(pattern, content)\nfor match in matches:\n category_name = match[11:-2].strip()\n is_new, category = CategoryAPI.get_...
<|body_start_0|> found_categories = [] previous_categories = filter(lambda x: page in x.pages, Category.query.all()) pattern = re.compile('\\[\\[Category:[a-zA-Z0-9 _]+\\]\\]') matches = re.findall(pattern, content) for match in matches: category_name = match[11:-2].s...
CategoryAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CategoryAPI: def update_categories_from_content(content, page): """Parse the string content for categories. The found categories in the content are processed as followed: * Existing categories are updated to save the path. * Unknown categories are created and save the path. Categories wh...
stack_v2_sparse_classes_36k_train_011603
3,400
permissive
[ { "docstring": "Parse the string content for categories. The found categories in the content are processed as followed: * Existing categories are updated to save the path. * Unknown categories are created and save the path. Categories which had this page, but are not found in the content are updated if the cate...
2
stack_v2_sparse_classes_30k_train_001750
Implement the Python class `CategoryAPI` described below. Class description: Implement the CategoryAPI class. Method signatures and docstrings: - def update_categories_from_content(content, page): Parse the string content for categories. The found categories in the content are processed as followed: * Existing catego...
Implement the Python class `CategoryAPI` described below. Class description: Implement the CategoryAPI class. Method signatures and docstrings: - def update_categories_from_content(content, page): Parse the string content for categories. The found categories in the content are processed as followed: * Existing catego...
1faec7e123c3fae7e8dbe1a354ad27b68f2a8cef
<|skeleton|> class CategoryAPI: def update_categories_from_content(content, page): """Parse the string content for categories. The found categories in the content are processed as followed: * Existing categories are updated to save the path. * Unknown categories are created and save the path. Categories wh...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CategoryAPI: def update_categories_from_content(content, page): """Parse the string content for categories. The found categories in the content are processed as followed: * Existing categories are updated to save the path. * Unknown categories are created and save the path. Categories which had this p...
the_stack_v2_python_sparse
app/utils/category.py
viaict/viaduct
train
11
adb19d7e105462a4841a136cb62fd3fe105c6b5f
[ "super().__init__(*args, **kwargs)\nsource_projects = DataRequestProject.objects.filter(approved=True).exclude(returned_data_description='')\nself.fields['requested_sources'].choices = [(p.id, p.name) for p in source_projects]\nself.fields['requested_sources'].widget = forms.CheckboxSelectMultiple()\nself.fields['r...
<|body_start_0|> super().__init__(*args, **kwargs) source_projects = DataRequestProject.objects.filter(approved=True).exclude(returned_data_description='') self.fields['requested_sources'].choices = [(p.id, p.name) for p in source_projects] self.fields['requested_sources'].widget = forms...
The base for all DataRequestProject forms
DataRequestProjectForm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataRequestProjectForm: """The base for all DataRequestProject forms""" def __init__(self, *args, **kwargs): """Add custom handling for requested_sources and override some widgets.""" <|body_0|> def clean(self): """Logic to for conditional required elements in ou...
stack_v2_sparse_classes_36k_train_011604
16,550
permissive
[ { "docstring": "Add custom handling for requested_sources and override some widgets.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Logic to for conditional required elements in our form.", "name": "clean", "signature": "def clean(self)" } ]
2
null
Implement the Python class `DataRequestProjectForm` described below. Class description: The base for all DataRequestProject forms Method signatures and docstrings: - def __init__(self, *args, **kwargs): Add custom handling for requested_sources and override some widgets. - def clean(self): Logic to for conditional re...
Implement the Python class `DataRequestProjectForm` described below. Class description: The base for all DataRequestProject forms Method signatures and docstrings: - def __init__(self, *args, **kwargs): Add custom handling for requested_sources and override some widgets. - def clean(self): Logic to for conditional re...
a2e3bf3b95d7fcfb2cdffe3a42f86cb6e09674e4
<|skeleton|> class DataRequestProjectForm: """The base for all DataRequestProject forms""" def __init__(self, *args, **kwargs): """Add custom handling for requested_sources and override some widgets.""" <|body_0|> def clean(self): """Logic to for conditional required elements in ou...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataRequestProjectForm: """The base for all DataRequestProject forms""" def __init__(self, *args, **kwargs): """Add custom handling for requested_sources and override some widgets.""" super().__init__(*args, **kwargs) source_projects = DataRequestProject.objects.filter(approved=Tr...
the_stack_v2_python_sparse
private_sharing/forms.py
madprime/open-humans
train
2
9b567739910ae0a144a739f736d3bd34d00f2581
[ "self.name = name\nself.base_energy = base_energy\nself.goals = goals", "if time % 9 == 0:\n return self.base_energy - self.energy_expended * self.goals - self.energy_expended * 0.1\nelse:\n return self.base_energy - self.energy_expended * self.goals" ]
<|body_start_0|> self.name = name self.base_energy = base_energy self.goals = goals <|end_body_0|> <|body_start_1|> if time % 9 == 0: return self.base_energy - self.energy_expended * self.goals - self.energy_expended * 0.1 else: return self.base_energy - ...
Chaser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Chaser: def __init__(self, name, base_energy, goals): """Chasers have a name, score goals, and begin with base_energy.""" <|body_0|> def energy(self, time): """Returns the amount of energy left after playing for time minutes. For every goal they score, they use energ...
stack_v2_sparse_classes_36k_train_011605
9,033
permissive
[ { "docstring": "Chasers have a name, score goals, and begin with base_energy.", "name": "__init__", "signature": "def __init__(self, name, base_energy, goals)" }, { "docstring": "Returns the amount of energy left after playing for time minutes. For every goal they score, they use energy_expended...
2
stack_v2_sparse_classes_30k_train_018766
Implement the Python class `Chaser` described below. Class description: Implement the Chaser class. Method signatures and docstrings: - def __init__(self, name, base_energy, goals): Chasers have a name, score goals, and begin with base_energy. - def energy(self, time): Returns the amount of energy left after playing ...
Implement the Python class `Chaser` described below. Class description: Implement the Chaser class. Method signatures and docstrings: - def __init__(self, name, base_energy, goals): Chasers have a name, score goals, and begin with base_energy. - def energy(self, time): Returns the amount of energy left after playing ...
6d0da2c1468b9a571c742a62ab0b8cf625688591
<|skeleton|> class Chaser: def __init__(self, name, base_energy, goals): """Chasers have a name, score goals, and begin with base_energy.""" <|body_0|> def energy(self, time): """Returns the amount of energy left after playing for time minutes. For every goal they score, they use energ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Chaser: def __init__(self, name, base_energy, goals): """Chasers have a name, score goals, and begin with base_energy.""" self.name = name self.base_energy = base_energy self.goals = goals def energy(self, time): """Returns the amount of energy left after playing f...
the_stack_v2_python_sparse
lab/lab10/lab10.py
tingjunwong/cs88-python-data-analysis
train
0
b774ced2c55b630d7de8d6fd1cfb5b376cb36c53
[ "ans = []\nnums1 = set(nums1)\nnums2 = set(nums2)\nif len(nums1) >= len(nums2):\n nums1 = list(nums1)\n for i in range(len(nums1)):\n if nums1[i] in nums2:\n ans.append(nums1[i])\nelse:\n nums2 = list(nums2)\n for i in range(len(nums2)):\n if nums2[i] in nums1:\n ans....
<|body_start_0|> ans = [] nums1 = set(nums1) nums2 = set(nums2) if len(nums1) >= len(nums2): nums1 = list(nums1) for i in range(len(nums1)): if nums1[i] in nums2: ans.append(nums1[i]) else: nums2 = list(nums2...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def intersection(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" <|body_0|> def intersection(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" <|body_1|> def in...
stack_v2_sparse_classes_36k_train_011606
2,170
no_license
[ { "docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]", "name": "intersection", "signature": "def intersection(self, nums1, nums2)" }, { "docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]", "name": "intersection", "signature": "def int...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def intersection(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int] - def intersection(self, nums1, nums2): :type nums1: List[int] :type nums2: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def intersection(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int] - def intersection(self, nums1, nums2): :type nums1: List[int] :type nums2: ...
b925bb22d1daa4a56c5a238a5758a926905559b4
<|skeleton|> class Solution: def intersection(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" <|body_0|> def intersection(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" <|body_1|> def in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def intersection(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" ans = [] nums1 = set(nums1) nums2 = set(nums2) if len(nums1) >= len(nums2): nums1 = list(nums1) for i in range(len(nums1)): ...
the_stack_v2_python_sparse
Arrays/349. Intersection of Two Arrays.py
beninghton/notGivenUpToG
train
0
5a3dc80453bda0bfa9f74dbb92afebbec31fb5f7
[ "if lang is not None and (not isinstance(lang, AlgorandLanguages)):\n raise TypeError('Language is not an enumerative of AlgorandLanguages')\nsuper().__init__(lang.value if lang is not None else lang, Bip39WordsListFinder, Bip39WordsListGetter)", "mnemonic_obj = AlgorandMnemonic.FromString(mnemonic) if isinsta...
<|body_start_0|> if lang is not None and (not isinstance(lang, AlgorandLanguages)): raise TypeError('Language is not an enumerative of AlgorandLanguages') super().__init__(lang.value if lang is not None else lang, Bip39WordsListFinder, Bip39WordsListGetter) <|end_body_0|> <|body_start_1|> ...
Algorand mnemonic decoder class. It decodes a mnemonic phrase to bytes.
AlgorandMnemonicDecoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlgorandMnemonicDecoder: """Algorand mnemonic decoder class. It decodes a mnemonic phrase to bytes.""" def __init__(self, lang: Optional[AlgorandLanguages]=AlgorandLanguages.ENGLISH) -> None: """Construct class. Language is set to English by default because Algorand mnemonic only sup...
stack_v2_sparse_classes_36k_train_011607
5,112
permissive
[ { "docstring": "Construct class. Language is set to English by default because Algorand mnemonic only support one language, so it's useless (and slower) to automatically detect the language. Args: lang (AlgorandLanguages, optional): Language, None for automatic detection Raises: TypeError: If the language is no...
3
stack_v2_sparse_classes_30k_train_015955
Implement the Python class `AlgorandMnemonicDecoder` described below. Class description: Algorand mnemonic decoder class. It decodes a mnemonic phrase to bytes. Method signatures and docstrings: - def __init__(self, lang: Optional[AlgorandLanguages]=AlgorandLanguages.ENGLISH) -> None: Construct class. Language is set...
Implement the Python class `AlgorandMnemonicDecoder` described below. Class description: Algorand mnemonic decoder class. It decodes a mnemonic phrase to bytes. Method signatures and docstrings: - def __init__(self, lang: Optional[AlgorandLanguages]=AlgorandLanguages.ENGLISH) -> None: Construct class. Language is set...
d15c75ddd74e4838c396a0d036ef6faf11b06a4b
<|skeleton|> class AlgorandMnemonicDecoder: """Algorand mnemonic decoder class. It decodes a mnemonic phrase to bytes.""" def __init__(self, lang: Optional[AlgorandLanguages]=AlgorandLanguages.ENGLISH) -> None: """Construct class. Language is set to English by default because Algorand mnemonic only sup...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AlgorandMnemonicDecoder: """Algorand mnemonic decoder class. It decodes a mnemonic phrase to bytes.""" def __init__(self, lang: Optional[AlgorandLanguages]=AlgorandLanguages.ENGLISH) -> None: """Construct class. Language is set to English by default because Algorand mnemonic only support one lang...
the_stack_v2_python_sparse
bip_utils/algorand/mnemonic/algorand_mnemonic_decoder.py
ebellocchia/bip_utils
train
244
5a96c15aba770dd768ce1a2343c71c1dc6d79302
[ "self.enable_worm_on_external_target = enable_worm_on_external_target\nself.policy_type = policy_type\nself.retention_secs = retention_secs\nself.version = version", "if dictionary is None:\n return None\nenable_worm_on_external_target = dictionary.get('enableWormOnExternalTarget')\npolicy_type = dictionary.ge...
<|body_start_0|> self.enable_worm_on_external_target = enable_worm_on_external_target self.policy_type = policy_type self.retention_secs = retention_secs self.version = version <|end_body_0|> <|body_start_1|> if dictionary is None: return None enable_worm_on_...
Implementation of the 'WormRetentionProto' model. Message that specifies the WORM attributes. WORM attributes can be associated with any of the following: 1. backup policy: compliance or administrative policy with worm retention. 2. backup runs: worm retention inherited from policy at successful backup run completion.....
WormRetentionProto
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WormRetentionProto: """Implementation of the 'WormRetentionProto' model. Message that specifies the WORM attributes. WORM attributes can be associated with any of the following: 1. backup policy: compliance or administrative policy with worm retention. 2. backup runs: worm retention inherited fro...
stack_v2_sparse_classes_36k_train_011608
3,033
permissive
[ { "docstring": "Constructor for the WormRetentionProto class", "name": "__init__", "signature": "def __init__(self, enable_worm_on_external_target=None, policy_type=None, retention_secs=None, version=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (...
2
stack_v2_sparse_classes_30k_val_000359
Implement the Python class `WormRetentionProto` described below. Class description: Implementation of the 'WormRetentionProto' model. Message that specifies the WORM attributes. WORM attributes can be associated with any of the following: 1. backup policy: compliance or administrative policy with worm retention. 2. ba...
Implement the Python class `WormRetentionProto` described below. Class description: Implementation of the 'WormRetentionProto' model. Message that specifies the WORM attributes. WORM attributes can be associated with any of the following: 1. backup policy: compliance or administrative policy with worm retention. 2. ba...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class WormRetentionProto: """Implementation of the 'WormRetentionProto' model. Message that specifies the WORM attributes. WORM attributes can be associated with any of the following: 1. backup policy: compliance or administrative policy with worm retention. 2. backup runs: worm retention inherited fro...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WormRetentionProto: """Implementation of the 'WormRetentionProto' model. Message that specifies the WORM attributes. WORM attributes can be associated with any of the following: 1. backup policy: compliance or administrative policy with worm retention. 2. backup runs: worm retention inherited from policy at s...
the_stack_v2_python_sparse
cohesity_management_sdk/models/worm_retention_proto.py
cohesity/management-sdk-python
train
24
8266cc0b5f9919a245912d493cf2904d2b34d6a9
[ "self.ld = ld\nself.parmsh = {}\nself.parmsh['file'] = True\nself.filename = filename\nself.cdf = []\nfor d in self.ld:\n try:\n self.save = d['save']\n except:\n self.save = True\n bound = d['bound']\n values = d['values']\n Nv = len(values)\n cdf = np.array([])\n for k in bound:...
<|body_start_0|> self.ld = ld self.parmsh = {} self.parmsh['file'] = True self.filename = filename self.cdf = [] for d in self.ld: try: self.save = d['save'] except: self.save = True bound = d['bound'] ...
CDF
[ "MIT", "GPL-3.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CDF: def __init__(self, ld, filename='cdf'): """cdf = CDF(ld) ld is a list of dictionnary d0 = ld[0] d0['bound'] : bornes en abscisses de la cdf 0 d0['values'] : valeurs d0['xlabel'] : d0['ylabel'] : d0['legend'] : legend d0['title] : title d0['filename] : filename d0['linewidth'] : line...
stack_v2_sparse_classes_36k_train_011609
3,799
permissive
[ { "docstring": "cdf = CDF(ld) ld is a list of dictionnary d0 = ld[0] d0['bound'] : bornes en abscisses de la cdf 0 d0['values'] : valeurs d0['xlabel'] : d0['ylabel'] : d0['legend'] : legend d0['title] : title d0['filename] : filename d0['linewidth'] : linewidth", "name": "__init__", "signature": "def __...
2
stack_v2_sparse_classes_30k_train_005625
Implement the Python class `CDF` described below. Class description: Implement the CDF class. Method signatures and docstrings: - def __init__(self, ld, filename='cdf'): cdf = CDF(ld) ld is a list of dictionnary d0 = ld[0] d0['bound'] : bornes en abscisses de la cdf 0 d0['values'] : valeurs d0['xlabel'] : d0['ylabel'...
Implement the Python class `CDF` described below. Class description: Implement the CDF class. Method signatures and docstrings: - def __init__(self, ld, filename='cdf'): cdf = CDF(ld) ld is a list of dictionnary d0 = ld[0] d0['bound'] : bornes en abscisses de la cdf 0 d0['values'] : valeurs d0['xlabel'] : d0['ylabel'...
84bdc924ae8055313b9ec833f0509000b0a30f45
<|skeleton|> class CDF: def __init__(self, ld, filename='cdf'): """cdf = CDF(ld) ld is a list of dictionnary d0 = ld[0] d0['bound'] : bornes en abscisses de la cdf 0 d0['values'] : valeurs d0['xlabel'] : d0['ylabel'] : d0['legend'] : legend d0['title] : title d0['filename] : filename d0['linewidth'] : line...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CDF: def __init__(self, ld, filename='cdf'): """cdf = CDF(ld) ld is a list of dictionnary d0 = ld[0] d0['bound'] : bornes en abscisses de la cdf 0 d0['values'] : valeurs d0['xlabel'] : d0['ylabel'] : d0['legend'] : legend d0['title] : title d0['filename] : filename d0['linewidth'] : linewidth""" ...
the_stack_v2_python_sparse
pylayers/location/geometric/util/cdf2.py
tom2rd/pylayers
train
0
3d317fbd1b08326fd870ca9d738ca97b660df64d
[ "self.text = ''\nself.keywords = None\nself.seg = Segmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags, delimiters=delimiters)\nself.sentences = None\nself.words_no_filter = None\nself.words_no_stop_words = None\nself.words_all_filters = None", "self.text = text\nself.word_index = {}\...
<|body_start_0|> self.text = '' self.keywords = None self.seg = Segmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags, delimiters=delimiters) self.sentences = None self.words_no_filter = None self.words_no_stop_words = None self.words_a...
TextRankKeyword
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextRankKeyword: def __init__(self, stop_words_file='./stopwords.txt', allow_speech_tags=util.allow_speech_tags, delimiters=util.sentence_delimiters): """Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: w...
stack_v2_sparse_classes_36k_train_011610
8,424
no_license
[ { "docstring": "Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 words_no_stop_words -- 去掉words_no_filter中的停止词而得到的两级列表。 words_all_filters -- 保留words_no_stop_words中指定词性的单词而得到的两级列表。", ...
4
stack_v2_sparse_classes_30k_train_010320
Implement the Python class `TextRankKeyword` described below. Class description: Implement the TextRankKeyword class. Method signatures and docstrings: - def __init__(self, stop_words_file='./stopwords.txt', allow_speech_tags=util.allow_speech_tags, delimiters=util.sentence_delimiters): Keyword arguments: stop_words_...
Implement the Python class `TextRankKeyword` described below. Class description: Implement the TextRankKeyword class. Method signatures and docstrings: - def __init__(self, stop_words_file='./stopwords.txt', allow_speech_tags=util.allow_speech_tags, delimiters=util.sentence_delimiters): Keyword arguments: stop_words_...
7f7c4e56a8a66618feeb245b5394c0fc7d4f529a
<|skeleton|> class TextRankKeyword: def __init__(self, stop_words_file='./stopwords.txt', allow_speech_tags=util.allow_speech_tags, delimiters=util.sentence_delimiters): """Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: w...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextRankKeyword: def __init__(self, stop_words_file='./stopwords.txt', allow_speech_tags=util.allow_speech_tags, delimiters=util.sentence_delimiters): """Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: words_no_filter...
the_stack_v2_python_sparse
KwordExtr/TextRank/TextRankKeyword.py
primingrx/NLP
train
0
50f8d7442322b239010632cd6c34d6a7a11f4d31
[ "mocker.patch.object(client, 'get_detections', return_value=detections)\ncmd_res = get_detections_cmd(client, first_timestamp='')\nif detections:\n assert len(cmd_res.outputs) == len(detections.get('results'))\nelse:\n assert 'No detections found' in cmd_res.readable_output", "mocker.patch.object(client, 'g...
<|body_start_0|> mocker.patch.object(client, 'get_detections', return_value=detections) cmd_res = get_detections_cmd(client, first_timestamp='') if detections: assert len(cmd_res.outputs) == len(detections.get('results')) else: assert 'No detections found' in cmd_...
TestCommands
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCommands: def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]): """Test `vectra-get-events` method detections part.""" <|body_0|> def test_get_audits_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audi...
stack_v2_sparse_classes_36k_train_011611
12,115
permissive
[ { "docstring": "Test `vectra-get-events` method detections part.", "name": "test_get_detections_cmd", "signature": "def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any])" }, { "docstring": "Test `vectra-get-events` method audits part.", ...
5
stack_v2_sparse_classes_30k_train_008503
Implement the Python class `TestCommands` described below. Class description: Implement the TestCommands class. Method signatures and docstrings: - def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]): Test `vectra-get-events` method detections part. - def test_...
Implement the Python class `TestCommands` described below. Class description: Implement the TestCommands class. Method signatures and docstrings: - def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]): Test `vectra-get-events` method detections part. - def test_...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestCommands: def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]): """Test `vectra-get-events` method detections part.""" <|body_0|> def test_get_audits_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCommands: def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]): """Test `vectra-get-events` method detections part.""" mocker.patch.object(client, 'get_detections', return_value=detections) cmd_res = get_detections_cmd(client,...
the_stack_v2_python_sparse
Packs/Vectra_AI/Integrations/VectraAIEventCollector/VectraAIEventCollector_test.py
demisto/content
train
1,023
c459a5bfb6427bb215a67ce6c74b2e6f2cab813f
[ "self.size = len(words)\nself.word_pos = collections.defaultdict(list)\nfor i, word in enumerate(words):\n self.word_pos[word].append(i)", "pos_list1 = self.word_pos[word1]\npos_list2 = self.word_pos[word2]\nshortest = self.size\nfor i in pos_list1:\n for j in pos_list2:\n if shortest > abs(i - j):\n...
<|body_start_0|> self.size = len(words) self.word_pos = collections.defaultdict(list) for i, word in enumerate(words): self.word_pos[word].append(i) <|end_body_0|> <|body_start_1|> pos_list1 = self.word_pos[word1] pos_list2 = self.word_pos[word2] shortest = s...
WordDistance
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDistance: def __init__(self, words): """Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many time...
stack_v2_sparse_classes_36k_train_011612
1,603
no_license
[ { "docstring": "Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters. Example: Assume that wo...
2
stack_v2_sparse_classes_30k_train_007509
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the s...
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the s...
08c6d27498e35f636045fed05a6f94b760ab69ca
<|skeleton|> class WordDistance: def __init__(self, words): """Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many time...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordDistance: def __init__(self, words): """Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with differe...
the_stack_v2_python_sparse
solutions/hashtable/244.Shortest.Word.Distance.II.py
ljia2/leetcode.py
train
0
3ef678a1342741e610ad44441e2cd5f629f57173
[ "self.__dataset_path = dataset_path\nself.__trainX = None\nself.__trainY = None\nself.__testX = None\nself.__testY = None\nself.__valX = None\nself.__valY = None\nself.__lb = LabelBinarizer()\nself.__data = []\nself.__labels = []", "self.__loading_Images()\nself.__scale_Pixels()\nself.__divide_data()\nreturn (sel...
<|body_start_0|> self.__dataset_path = dataset_path self.__trainX = None self.__trainY = None self.__testX = None self.__testY = None self.__valX = None self.__valY = None self.__lb = LabelBinarizer() self.__data = [] self.__labels = [] <|e...
LoadData
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadData: def __init__(self, dataset_path): """Create the HandleData class object. :param dataset_path: string :return: None""" <|body_0|> def handle_dataset(self): """this function manage the HandleData class :param: None :return self.__trainX: array :return self.__...
stack_v2_sparse_classes_36k_train_011613
5,531
no_license
[ { "docstring": "Create the HandleData class object. :param dataset_path: string :return: None", "name": "__init__", "signature": "def __init__(self, dataset_path)" }, { "docstring": "this function manage the HandleData class :param: None :return self.__trainX: array :return self.__trainY: array ...
5
stack_v2_sparse_classes_30k_train_013865
Implement the Python class `LoadData` described below. Class description: Implement the LoadData class. Method signatures and docstrings: - def __init__(self, dataset_path): Create the HandleData class object. :param dataset_path: string :return: None - def handle_dataset(self): this function manage the HandleData cl...
Implement the Python class `LoadData` described below. Class description: Implement the LoadData class. Method signatures and docstrings: - def __init__(self, dataset_path): Create the HandleData class object. :param dataset_path: string :return: None - def handle_dataset(self): this function manage the HandleData cl...
9b7f035dca04e9ac4d20d4d9fa9e687ce583603b
<|skeleton|> class LoadData: def __init__(self, dataset_path): """Create the HandleData class object. :param dataset_path: string :return: None""" <|body_0|> def handle_dataset(self): """this function manage the HandleData class :param: None :return self.__trainX: array :return self.__...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoadData: def __init__(self, dataset_path): """Create the HandleData class object. :param dataset_path: string :return: None""" self.__dataset_path = dataset_path self.__trainX = None self.__trainY = None self.__testX = None self.__testY = None self.__va...
the_stack_v2_python_sparse
python files/load_data.py
maayan121/project_python_letters-DL
train
0
2c0a83fe0542a074b7d2100d503da6c6bba6a5e1
[ "self.T_myClass = 0\nself.T_otherClass = 0\nself.F_myClass = 0\nself.F_otherClass = 0", "if my_class and is_correct:\n self.T_myClass += 1\nelif is_correct:\n self.T_otherClass += 1\nelif my_class:\n self.F_myClass += 1\nelse:\n self.F_otherClass += 1" ]
<|body_start_0|> self.T_myClass = 0 self.T_otherClass = 0 self.F_myClass = 0 self.F_otherClass = 0 <|end_body_0|> <|body_start_1|> if my_class and is_correct: self.T_myClass += 1 elif is_correct: self.T_otherClass += 1 elif my_class: ...
ClassAccuracy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassAccuracy: def __init__(self): """Initialize the accuracy calculation for a single class""" <|body_0|> def updateAccuracy(self, my_class, is_correct): """Increment the appropriate cell of the confusion matrix""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_011614
840
no_license
[ { "docstring": "Initialize the accuracy calculation for a single class", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Increment the appropriate cell of the confusion matrix", "name": "updateAccuracy", "signature": "def updateAccuracy(self, my_class, is_correct...
2
stack_v2_sparse_classes_30k_train_015106
Implement the Python class `ClassAccuracy` described below. Class description: Implement the ClassAccuracy class. Method signatures and docstrings: - def __init__(self): Initialize the accuracy calculation for a single class - def updateAccuracy(self, my_class, is_correct): Increment the appropriate cell of the confu...
Implement the Python class `ClassAccuracy` described below. Class description: Implement the ClassAccuracy class. Method signatures and docstrings: - def __init__(self): Initialize the accuracy calculation for a single class - def updateAccuracy(self, my_class, is_correct): Increment the appropriate cell of the confu...
bec4ebeee6bf800addc5a6d1fb434ac92855aff2
<|skeleton|> class ClassAccuracy: def __init__(self): """Initialize the accuracy calculation for a single class""" <|body_0|> def updateAccuracy(self, my_class, is_correct): """Increment the appropriate cell of the confusion matrix""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClassAccuracy: def __init__(self): """Initialize the accuracy calculation for a single class""" self.T_myClass = 0 self.T_otherClass = 0 self.F_myClass = 0 self.F_otherClass = 0 def updateAccuracy(self, my_class, is_correct): """Increment the appropriate ce...
the_stack_v2_python_sparse
XCS/XCS_ClassAccuracy.py
VasilyShcherbinin/LCS-Suite
train
3
14f58c051bd45199cc2f55a79f4e9885f8a9c5e8
[ "gate_id = gate.key.integer_id()\nearliest_response = datetime.datetime.max\napprovers = approval_defs.get_approvers(gate.gate_type)\nactivities = Activity.get_activities(gate.feature_id, gate_id=gate_id, comments_only=True)\nfor a in activities:\n if gate.requested_on < a.created < earliest_response:\n i...
<|body_start_0|> gate_id = gate.key.integer_id() earliest_response = datetime.datetime.max approvers = approval_defs.get_approvers(gate.gate_type) activities = Activity.get_activities(gate.feature_id, gate_id=gate_id, comments_only=True) for a in activities: if gate.r...
BackfillRespondedOn
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BackfillRespondedOn: def update_responded_on(self, gate): """Update gate.responded_on and return True if an update was needed.""" <|body_0|> def get_template_data(self, **kwargs): """Backfill responded_on dates for existing gates.""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_011615
7,549
permissive
[ { "docstring": "Update gate.responded_on and return True if an update was needed.", "name": "update_responded_on", "signature": "def update_responded_on(self, gate)" }, { "docstring": "Backfill responded_on dates for existing gates.", "name": "get_template_data", "signature": "def get_te...
2
stack_v2_sparse_classes_30k_train_007570
Implement the Python class `BackfillRespondedOn` described below. Class description: Implement the BackfillRespondedOn class. Method signatures and docstrings: - def update_responded_on(self, gate): Update gate.responded_on and return True if an update was needed. - def get_template_data(self, **kwargs): Backfill res...
Implement the Python class `BackfillRespondedOn` described below. Class description: Implement the BackfillRespondedOn class. Method signatures and docstrings: - def update_responded_on(self, gate): Update gate.responded_on and return True if an update was needed. - def get_template_data(self, **kwargs): Backfill res...
17f9886d064da5bda84006d5866077727646fff2
<|skeleton|> class BackfillRespondedOn: def update_responded_on(self, gate): """Update gate.responded_on and return True if an update was needed.""" <|body_0|> def get_template_data(self, **kwargs): """Backfill responded_on dates for existing gates.""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BackfillRespondedOn: def update_responded_on(self, gate): """Update gate.responded_on and return True if an update was needed.""" gate_id = gate.key.integer_id() earliest_response = datetime.datetime.max approvers = approval_defs.get_approvers(gate.gate_type) activities...
the_stack_v2_python_sparse
internals/maintenance_scripts.py
GoogleChrome/chromium-dashboard
train
574
6e278751b2349560d1adc8299bde7d08ab4bc9ef
[ "syntax_options: SyntaxOptions = assert_not_none(self.config.syntax)\nspacy_model = spacy.load(syntax_options.spacy_model)\nutterances = batch[self.config.columns.text_input]\nrecords: List[TaggingResponse] = []\nfor utterance in utterances:\n tag: Dict[Tag, bool] = {smart_tag: False for family in [SmartTagFamil...
<|body_start_0|> syntax_options: SyntaxOptions = assert_not_none(self.config.syntax) spacy_model = spacy.load(syntax_options.spacy_model) utterances = batch[self.config.columns.text_input] records: List[TaggingResponse] = [] for utterance in utterances: tag: Dict[Tag,...
Calculate smart tags related to syntax.
SyntaxTaggingModule
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SyntaxTaggingModule: """Calculate smart tags related to syntax.""" def compute(self, batch: Dataset) -> List[TaggingResponse]: """Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the smart tags. Returns: tags: Newly calculated tags.""" ...
stack_v2_sparse_classes_36k_train_011616
3,923
permissive
[ { "docstring": "Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the smart tags. Returns: tags: Newly calculated tags.", "name": "compute", "signature": "def compute(self, batch: Dataset) -> List[TaggingResponse]" }, { "docstring": "Save tags in a Dataset...
2
stack_v2_sparse_classes_30k_train_006733
Implement the Python class `SyntaxTaggingModule` described below. Class description: Calculate smart tags related to syntax. Method signatures and docstrings: - def compute(self, batch: Dataset) -> List[TaggingResponse]: Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the sma...
Implement the Python class `SyntaxTaggingModule` described below. Class description: Calculate smart tags related to syntax. Method signatures and docstrings: - def compute(self, batch: Dataset) -> List[TaggingResponse]: Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the sma...
34081048a4de3900ca29ac0d37bce7026113382c
<|skeleton|> class SyntaxTaggingModule: """Calculate smart tags related to syntax.""" def compute(self, batch: Dataset) -> List[TaggingResponse]: """Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the smart tags. Returns: tags: Newly calculated tags.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SyntaxTaggingModule: """Calculate smart tags related to syntax.""" def compute(self, batch: Dataset) -> List[TaggingResponse]: """Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the smart tags. Returns: tags: Newly calculated tags.""" syntax_optio...
the_stack_v2_python_sparse
azimuth/modules/dataset_analysis/syntax_tagging.py
ServiceNow/azimuth
train
172
213e81d94c8249b283a002b2bdf368023db0a6d9
[ "self.v = x\nself.c = None\nreturn None", "if not a or not isinstance(a, list):\n return ListNode(None)\no = ListNode(None)\np = o\nn = len(a)\nfor i in range(n):\n p.c = ListNode(a[i])\n p = p.c\nreturn o.c", "if not o or not isinstance(o, ListNode):\n return list()\na = list()\np = o\nwhile p:\n ...
<|body_start_0|> self.v = x self.c = None return None <|end_body_0|> <|body_start_1|> if not a or not isinstance(a, list): return ListNode(None) o = ListNode(None) p = o n = len(a) for i in range(n): p.c = ListNode(a[i]) ...
Manage ListNode objects for linked lists.
ListNode
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListNode: """Manage ListNode objects for linked lists.""" def __init__(self, x=None): """Constructor for ListNode objects. :param (int or None) x: integer value for node :param ListNode c: pointer to child ListNode :return: None :rtype: None""" <|body_0|> def convert(sel...
stack_v2_sparse_classes_36k_train_011617
1,738
permissive
[ { "docstring": "Constructor for ListNode objects. :param (int or None) x: integer value for node :param ListNode c: pointer to child ListNode :return: None :rtype: None", "name": "__init__", "signature": "def __init__(self, x=None)" }, { "docstring": "Transforms array to linked list representati...
3
stack_v2_sparse_classes_30k_train_015511
Implement the Python class `ListNode` described below. Class description: Manage ListNode objects for linked lists. Method signatures and docstrings: - def __init__(self, x=None): Constructor for ListNode objects. :param (int or None) x: integer value for node :param ListNode c: pointer to child ListNode :return: Non...
Implement the Python class `ListNode` described below. Class description: Manage ListNode objects for linked lists. Method signatures and docstrings: - def __init__(self, x=None): Constructor for ListNode objects. :param (int or None) x: integer value for node :param ListNode c: pointer to child ListNode :return: Non...
69f90877c5466927e8b081c4268cbcda074813ec
<|skeleton|> class ListNode: """Manage ListNode objects for linked lists.""" def __init__(self, x=None): """Constructor for ListNode objects. :param (int or None) x: integer value for node :param ListNode c: pointer to child ListNode :return: None :rtype: None""" <|body_0|> def convert(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ListNode: """Manage ListNode objects for linked lists.""" def __init__(self, x=None): """Constructor for ListNode objects. :param (int or None) x: integer value for node :param ListNode c: pointer to child ListNode :return: None :rtype: None""" self.v = x self.c = None ret...
the_stack_v2_python_sparse
0002_add_two_numbers/python_util.py
arthurdysart/LeetCode
train
0
f3730fe39d468d47f60f130d5f5964e532b61f1f
[ "shareList = Share.objects.filter(delete_flag=0).order_by('team', 'shareperson')\nserializer = Shareserializers(shareList, many=True)\nreturn Response({'status': True, 'message': '成功', 'data': serializer.data})", "if request.data['sharetitle'] == '':\n return Response({'status': True, 'message': '不新建分享', 'data...
<|body_start_0|> shareList = Share.objects.filter(delete_flag=0).order_by('team', 'shareperson') serializer = Shareserializers(shareList, many=True) return Response({'status': True, 'message': '成功', 'data': serializer.data}) <|end_body_0|> <|body_start_1|> if request.data['sharetitle'] ...
分享
Shares
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Shares: """分享""" def get(self, request): """获取分享列表""" <|body_0|> def post(self, request): """新建分享列表""" <|body_1|> def put(self, request): """修改分享列表""" <|body_2|> def delete(self, request): """删除分享""" <|body_3|> <...
stack_v2_sparse_classes_36k_train_011618
2,709
no_license
[ { "docstring": "获取分享列表", "name": "get", "signature": "def get(self, request)" }, { "docstring": "新建分享列表", "name": "post", "signature": "def post(self, request)" }, { "docstring": "修改分享列表", "name": "put", "signature": "def put(self, request)" }, { "docstring": "删除分...
4
stack_v2_sparse_classes_30k_train_016934
Implement the Python class `Shares` described below. Class description: 分享 Method signatures and docstrings: - def get(self, request): 获取分享列表 - def post(self, request): 新建分享列表 - def put(self, request): 修改分享列表 - def delete(self, request): 删除分享
Implement the Python class `Shares` described below. Class description: 分享 Method signatures and docstrings: - def get(self, request): 获取分享列表 - def post(self, request): 新建分享列表 - def put(self, request): 修改分享列表 - def delete(self, request): 删除分享 <|skeleton|> class Shares: """分享""" def get(self, request): ...
9ccebcc6820af3f950c28fc2a4dee4f41a3157f1
<|skeleton|> class Shares: """分享""" def get(self, request): """获取分享列表""" <|body_0|> def post(self, request): """新建分享列表""" <|body_1|> def put(self, request): """修改分享列表""" <|body_2|> def delete(self, request): """删除分享""" <|body_3|> <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Shares: """分享""" def get(self, request): """获取分享列表""" shareList = Share.objects.filter(delete_flag=0).order_by('team', 'shareperson') serializer = Shareserializers(shareList, many=True) return Response({'status': True, 'message': '成功', 'data': serializer.data}) def po...
the_stack_v2_python_sparse
moon/share/views.py
xiaominwanglast/python
train
0
807120c87a2fe923d9dd8c299b624d979c85f8dd
[ "py_typecheck.check_type(symbols, dict)\nfor k, v in symbols.items():\n py_typecheck.check_type(k, str)\n py_typecheck.check_type(v, LambdaExecutorValue)\nif parent is not None:\n py_typecheck.check_type(parent, LambdaExecutorScope)\nself._parent = parent\nself._symbols = {k: v for k, v in symbols.items()}...
<|body_start_0|> py_typecheck.check_type(symbols, dict) for k, v in symbols.items(): py_typecheck.check_type(k, str) py_typecheck.check_type(v, LambdaExecutorValue) if parent is not None: py_typecheck.check_type(parent, LambdaExecutorScope) self._paren...
Represents a naming scope for computations in the lambda executor.
LambdaExecutorScope
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LambdaExecutorScope: """Represents a naming scope for computations in the lambda executor.""" def __init__(self, symbols, parent=None): """Constructs a new scope. Args: symbols: A dict of symbols available in this scope, with keys being strings, and values being instances of `LambdaE...
stack_v2_sparse_classes_36k_train_011619
18,827
permissive
[ { "docstring": "Constructs a new scope. Args: symbols: A dict of symbols available in this scope, with keys being strings, and values being instances of `LambdaExecutorValue`. parent: The parent scope, or `None` if this is the root.", "name": "__init__", "signature": "def __init__(self, symbols, parent=...
2
stack_v2_sparse_classes_30k_val_000607
Implement the Python class `LambdaExecutorScope` described below. Class description: Represents a naming scope for computations in the lambda executor. Method signatures and docstrings: - def __init__(self, symbols, parent=None): Constructs a new scope. Args: symbols: A dict of symbols available in this scope, with k...
Implement the Python class `LambdaExecutorScope` described below. Class description: Represents a naming scope for computations in the lambda executor. Method signatures and docstrings: - def __init__(self, symbols, parent=None): Constructs a new scope. Args: symbols: A dict of symbols available in this scope, with k...
91be7e99906112c008f04ef8534eb6ea87a7053d
<|skeleton|> class LambdaExecutorScope: """Represents a naming scope for computations in the lambda executor.""" def __init__(self, symbols, parent=None): """Constructs a new scope. Args: symbols: A dict of symbols available in this scope, with keys being strings, and values being instances of `LambdaE...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LambdaExecutorScope: """Represents a naming scope for computations in the lambda executor.""" def __init__(self, symbols, parent=None): """Constructs a new scope. Args: symbols: A dict of symbols available in this scope, with keys being strings, and values being instances of `LambdaExecutorValue`...
the_stack_v2_python_sparse
tensorflow_federated/python/core/impl/lambda_executor.py
igabriel85/federated
train
2
450016e1acacda541140e9f73bbff8a8dcd5145a
[ "params = dict(workspace_name='harfangletest_corp')\nform = WorkspaceCreateForm(params)\nself.assertTrue(form.is_valid())\nself.assertEquals(form.cleaned_data['workspace_name'], 'harfangletest_corp')", "params = dict(workspace_name='全角テスト株式会社')\nform = WorkspaceCreateForm(params)\nself.assertTrue(form.is_valid())...
<|body_start_0|> params = dict(workspace_name='harfangletest_corp') form = WorkspaceCreateForm(params) self.assertTrue(form.is_valid()) self.assertEquals(form.cleaned_data['workspace_name'], 'harfangletest_corp') <|end_body_0|> <|body_start_1|> params = dict(workspace_name='全角テス...
WorkspaceCreateFormTests
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkspaceCreateFormTests: def test_workspace_create_forms_normal_1(self): """顧客情報登録フォーム 正常系 1""" <|body_0|> def test_workspace_create_forms_normal_2(self): """顧客情報登録フォーム 正常系 2""" <|body_1|> def test_workspace_create_forms_normal_3(self): """顧客情報登...
stack_v2_sparse_classes_36k_train_011620
4,355
permissive
[ { "docstring": "顧客情報登録フォーム 正常系 1", "name": "test_workspace_create_forms_normal_1", "signature": "def test_workspace_create_forms_normal_1(self)" }, { "docstring": "顧客情報登録フォーム 正常系 2", "name": "test_workspace_create_forms_normal_2", "signature": "def test_workspace_create_forms_normal_2(se...
5
stack_v2_sparse_classes_30k_train_015158
Implement the Python class `WorkspaceCreateFormTests` described below. Class description: Implement the WorkspaceCreateFormTests class. Method signatures and docstrings: - def test_workspace_create_forms_normal_1(self): 顧客情報登録フォーム 正常系 1 - def test_workspace_create_forms_normal_2(self): 顧客情報登録フォーム 正常系 2 - def test_wor...
Implement the Python class `WorkspaceCreateFormTests` described below. Class description: Implement the WorkspaceCreateFormTests class. Method signatures and docstrings: - def test_workspace_create_forms_normal_1(self): 顧客情報登録フォーム 正常系 1 - def test_workspace_create_forms_normal_2(self): 顧客情報登録フォーム 正常系 2 - def test_wor...
049058a37b9ee45b58be5f4393a0b3191362043c
<|skeleton|> class WorkspaceCreateFormTests: def test_workspace_create_forms_normal_1(self): """顧客情報登録フォーム 正常系 1""" <|body_0|> def test_workspace_create_forms_normal_2(self): """顧客情報登録フォーム 正常系 2""" <|body_1|> def test_workspace_create_forms_normal_3(self): """顧客情報登...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WorkspaceCreateFormTests: def test_workspace_create_forms_normal_1(self): """顧客情報登録フォーム 正常系 1""" params = dict(workspace_name='harfangletest_corp') form = WorkspaceCreateForm(params) self.assertTrue(form.is_valid()) self.assertEquals(form.cleaned_data['workspace_name'],...
the_stack_v2_python_sparse
register/tests_forms.py
yashiki-takajin/sfa-next
train
0
cd81149eb09663da0f05505c52c051ed7981f3aa
[ "super().__init__(parent=parent)\nself.plotWidget: Optional['PlotWidget'] = None\nself.data: Optional[DataDictBase] = None\nlayout: QtWidgets.QVBoxLayout = QtWidgets.QVBoxLayout(self)\nlayout.setContentsMargins(0, 0, 0, 0)\nself.setLayout(layout)", "if widget is self.plotWidget:\n return\nif self.plotWidget is...
<|body_start_0|> super().__init__(parent=parent) self.plotWidget: Optional['PlotWidget'] = None self.data: Optional[DataDictBase] = None layout: QtWidgets.QVBoxLayout = QtWidgets.QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) <|end_body_0|>...
This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :class:`PlotWidget` as base for implementing widgets that can be added to this container.
PlotWidgetContainer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlotWidgetContainer: """This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :class:`PlotWidget` as base for implementi...
stack_v2_sparse_classes_36k_train_011621
23,346
permissive
[ { "docstring": "Constructor for :class:`PlotWidgetContainer`.", "name": "__init__", "signature": "def __init__(self, parent: Optional[QtWidgets.QWidget]=None)" }, { "docstring": "Set the plot widget. Makes sure that the added widget receives new data. :param widget: plot widget", "name": "se...
3
stack_v2_sparse_classes_30k_train_003170
Implement the Python class `PlotWidgetContainer` described below. Class description: This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :cl...
Implement the Python class `PlotWidgetContainer` described below. Class description: This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :cl...
0ccdeb76d44fcc57e5b986c8b75cb0696fbff03b
<|skeleton|> class PlotWidgetContainer: """This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :class:`PlotWidget` as base for implementi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PlotWidgetContainer: """This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :class:`PlotWidget` as base for implementing widgets th...
the_stack_v2_python_sparse
plottr/plot/base.py
labist/plottr
train
0
7aaee75a4f1b6a275c1cef8d344f4f92051525bb
[ "super(PermissionForm, self).__init__(*args, **kwargs)\nself.current_user = current_user\nself.user_id.choices = [(-1, _('--- Select User ---'))] + [(user.id, user.email) for user in User.query.order_by('email').filter_by(is_deleted=False)]\nself.collection_id.choices = [(-1, _('--- Select Collection ---'))]\nif cu...
<|body_start_0|> super(PermissionForm, self).__init__(*args, **kwargs) self.current_user = current_user self.user_id.choices = [(-1, _('--- Select User ---'))] + [(user.id, user.email) for user in User.query.order_by('email').filter_by(is_deleted=False)] self.collection_id.choices = [(-1...
Permission form.
PermissionForm
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PermissionForm: """Permission form.""" def __init__(self, current_user, *args, **kwargs): """Create instance.""" <|body_0|> def validate_user_id(self, field): """Validate user ID is selected and exists in 'users' table.""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_36k_train_011622
10,553
permissive
[ { "docstring": "Create instance.", "name": "__init__", "signature": "def __init__(self, current_user, *args, **kwargs)" }, { "docstring": "Validate user ID is selected and exists in 'users' table.", "name": "validate_user_id", "signature": "def validate_user_id(self, field)" } ]
2
stack_v2_sparse_classes_30k_test_000237
Implement the Python class `PermissionForm` described below. Class description: Permission form. Method signatures and docstrings: - def __init__(self, current_user, *args, **kwargs): Create instance. - def validate_user_id(self, field): Validate user ID is selected and exists in 'users' table.
Implement the Python class `PermissionForm` described below. Class description: Permission form. Method signatures and docstrings: - def __init__(self, current_user, *args, **kwargs): Create instance. - def validate_user_id(self, field): Validate user ID is selected and exists in 'users' table. <|skeleton|> class Pe...
d2b66717d87ee2452edf0f6c04f6fdf4533091ba
<|skeleton|> class PermissionForm: """Permission form.""" def __init__(self, current_user, *args, **kwargs): """Create instance.""" <|body_0|> def validate_user_id(self, field): """Validate user ID is selected and exists in 'users' table.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PermissionForm: """Permission form.""" def __init__(self, current_user, *args, **kwargs): """Create instance.""" super(PermissionForm, self).__init__(*args, **kwargs) self.current_user = current_user self.user_id.choices = [(-1, _('--- Select User ---'))] + [(user.id, user...
the_stack_v2_python_sparse
xl_auth/permission/forms.py
libris/xl_auth
train
8
2e15561c381df2c7cea833256eea7e0e80a66a3a
[ "if isinstance(text, unicode):\n return text\nreturn unicode(text, encoding, errors=errors)", "if isinstance(text, unicode):\n return text.encode('utf8')\nreturn unicode(text, encoding, errors=errors).encode('utf8')" ]
<|body_start_0|> if isinstance(text, unicode): return text return unicode(text, encoding, errors=errors) <|end_body_0|> <|body_start_1|> if isinstance(text, unicode): return text.encode('utf8') return unicode(text, encoding, errors=errors).encode('utf8') <|end_bo...
Encoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Encoder: def str2uni(text, encoding='utf8', errors='strict'): """Convert `text` to unicode. Parameters ---------- text : str Input text. errors : str, optional Error handling behaviour, used as parameter for `unicode` function (python2 only). encoding : str, optional Encoding of `text` f...
stack_v2_sparse_classes_36k_train_011623
9,000
no_license
[ { "docstring": "Convert `text` to unicode. Parameters ---------- text : str Input text. errors : str, optional Error handling behaviour, used as parameter for `unicode` function (python2 only). encoding : str, optional Encoding of `text` for `unicode` function (python2 only). Returns ------- str Unicode version...
2
stack_v2_sparse_classes_30k_train_001233
Implement the Python class `Encoder` described below. Class description: Implement the Encoder class. Method signatures and docstrings: - def str2uni(text, encoding='utf8', errors='strict'): Convert `text` to unicode. Parameters ---------- text : str Input text. errors : str, optional Error handling behaviour, used a...
Implement the Python class `Encoder` described below. Class description: Implement the Encoder class. Method signatures and docstrings: - def str2uni(text, encoding='utf8', errors='strict'): Convert `text` to unicode. Parameters ---------- text : str Input text. errors : str, optional Error handling behaviour, used a...
b798e7b1286e043c5685aa8375022ee50f91024a
<|skeleton|> class Encoder: def str2uni(text, encoding='utf8', errors='strict'): """Convert `text` to unicode. Parameters ---------- text : str Input text. errors : str, optional Error handling behaviour, used as parameter for `unicode` function (python2 only). encoding : str, optional Encoding of `text` f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Encoder: def str2uni(text, encoding='utf8', errors='strict'): """Convert `text` to unicode. Parameters ---------- text : str Input text. errors : str, optional Error handling behaviour, used as parameter for `unicode` function (python2 only). encoding : str, optional Encoding of `text` for `unicode` f...
the_stack_v2_python_sparse
utils/other_utils.py
duytinvo/sequence_labeller
train
3
8d8515bf8a5aceea7b95a52ee632ca9eac95fa12
[ "content = [w for w in menu_list]\nheight = len(menu_list)\nwidth = 0\nfor entry in menu_list:\n if len(entry.original_widget.text) > width:\n width = len(entry.original_widget.text)\nself._listbox = urwid.AttrWrap(urwid.ListBox(content), attr[0])\noverlay = urwid.Overlay(self._listbox, body, 'center', wi...
<|body_start_0|> content = [w for w in menu_list] height = len(menu_list) width = 0 for entry in menu_list: if len(entry.original_widget.text) > width: width = len(entry.original_widget.text) self._listbox = urwid.AttrWrap(urwid.ListBox(content), attr[...
Creates a popup menu on top of another BoxWidget. Attributes: selected -- Contains the item the user has selected by pressing <RETURN>, or None if nothing has been selected.
Popup
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Popup: """Creates a popup menu on top of another BoxWidget. Attributes: selected -- Contains the item the user has selected by pressing <RETURN>, or None if nothing has been selected.""" def __init__(self, menu_list, attr, pos, body): """menu_list -- a list of strings with the menu e...
stack_v2_sparse_classes_36k_train_011624
45,709
no_license
[ { "docstring": "menu_list -- a list of strings with the menu entries attr -- a tuple (background, active_item) of attributes pos -- a tuple (x, y), position of the menu widget body -- widget displayed beneath the message widget", "name": "__init__", "signature": "def __init__(self, menu_list, attr, pos,...
2
null
Implement the Python class `Popup` described below. Class description: Creates a popup menu on top of another BoxWidget. Attributes: selected -- Contains the item the user has selected by pressing <RETURN>, or None if nothing has been selected. Method signatures and docstrings: - def __init__(self, menu_list, attr, p...
Implement the Python class `Popup` described below. Class description: Creates a popup menu on top of another BoxWidget. Attributes: selected -- Contains the item the user has selected by pressing <RETURN>, or None if nothing has been selected. Method signatures and docstrings: - def __init__(self, menu_list, attr, p...
0ac6653219c2701c13c508c5c4fc9bc3437eea06
<|skeleton|> class Popup: """Creates a popup menu on top of another BoxWidget. Attributes: selected -- Contains the item the user has selected by pressing <RETURN>, or None if nothing has been selected.""" def __init__(self, menu_list, attr, pos, body): """menu_list -- a list of strings with the menu e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Popup: """Creates a popup menu on top of another BoxWidget. Attributes: selected -- Contains the item the user has selected by pressing <RETURN>, or None if nothing has been selected.""" def __init__(self, menu_list, attr, pos, body): """menu_list -- a list of strings with the menu entries attr -...
the_stack_v2_python_sparse
repoData/socketubs-pyhn/allPythonContent.py
aCoffeeYin/pyreco
train
0
e0adfb50c1bd69ef89412b53925f436a7192be76
[ "if intervals == None or len(intervals) == 0:\n return [newInterval]\nres = []\ni = 0\nwhile i < len(intervals):\n if intervals[i].end < newInterval.start:\n res.append(intervals[i])\n i += 1\n continue\n if intervals[i].start > newInterval.end:\n res.append(newInterval)\n ...
<|body_start_0|> if intervals == None or len(intervals) == 0: return [newInterval] res = [] i = 0 while i < len(intervals): if intervals[i].end < newInterval.start: res.append(intervals[i]) i += 1 continue ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def insert_before(self, intervals, newInterval): """:type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]""" <|body_0|> def insert(self, intervals, newInterval): """:type intervals: List[List[int]] :type newInterval: List[int] :...
stack_v2_sparse_classes_36k_train_011625
2,021
no_license
[ { "docstring": ":type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]", "name": "insert_before", "signature": "def insert_before(self, intervals, newInterval)" }, { "docstring": ":type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]]", ...
2
stack_v2_sparse_classes_30k_train_021509
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def insert_before(self, intervals, newInterval): :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] - def insert(self, intervals, newInterval): :t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def insert_before(self, intervals, newInterval): :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] - def insert(self, intervals, newInterval): :t...
238995bd23c8a6c40c6035890e94baa2473d4bbc
<|skeleton|> class Solution: def insert_before(self, intervals, newInterval): """:type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]""" <|body_0|> def insert(self, intervals, newInterval): """:type intervals: List[List[int]] :type newInterval: List[int] :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def insert_before(self, intervals, newInterval): """:type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]""" if intervals == None or len(intervals) == 0: return [newInterval] res = [] i = 0 while i < len(intervals): ...
the_stack_v2_python_sparse
problems/InsertInterval.py
wan-catherine/Leetcode
train
5
38db0a0fb7dc7f33f73137602a12c097b8cc68fe
[ "super().__init__()\ndeconv_kwargs = {'kernel_size': 3, 'padding': 1}\ndeconv_kwargs.update(kwargs)\nself.stride = stride\nself.outp = 1 if stride == 2 else 0\nself.use_upsampling = use_upsampling\nif in_c != out_c or stride > 1:\n assert self.use_upsampling == True, 'Input needs to be adjusted in (h,w) and/or n...
<|body_start_0|> super().__init__() deconv_kwargs = {'kernel_size': 3, 'padding': 1} deconv_kwargs.update(kwargs) self.stride = stride self.outp = 1 if stride == 2 else 0 self.use_upsampling = use_upsampling if in_c != out_c or stride > 1: assert self....
A module that implements a single flow of residual operation for ResNet. Each conv layer uses kernel of size 3x3, stride=stride, and padding=1. First the input's (h,w) are shrinked by `stride`, then the num of channels is increased to out_c via subsequent conv operations. input ---> (bn-relu-convTranspose2d) -> z1 --->...
ResidualDeconv
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResidualDeconv: """A module that implements a single flow of residual operation for ResNet. Each conv layer uses kernel of size 3x3, stride=stride, and padding=1. First the input's (h,w) are shrinked by `stride`, then the num of channels is increased to out_c via subsequent conv operations. input...
stack_v2_sparse_classes_36k_train_011626
6,408
no_license
[ { "docstring": "To double the input's (h,w), ie. stride=2, use kernel_size=3, padding=1, stride=2, output_padding=1 When the output needs bo have the same (h,w) as the input, ie. stride=1, use output_padding = 0", "name": "__init__", "signature": "def __init__(self, in_c, out_c, *, stride=2, use_upsampl...
2
null
Implement the Python class `ResidualDeconv` described below. Class description: A module that implements a single flow of residual operation for ResNet. Each conv layer uses kernel of size 3x3, stride=stride, and padding=1. First the input's (h,w) are shrinked by `stride`, then the num of channels is increased to out_...
Implement the Python class `ResidualDeconv` described below. Class description: A module that implements a single flow of residual operation for ResNet. Each conv layer uses kernel of size 3x3, stride=stride, and padding=1. First the input's (h,w) are shrinked by `stride`, then the num of channels is increased to out_...
6f6e8ee74bc9f597def9559f74a6841c37c0a214
<|skeleton|> class ResidualDeconv: """A module that implements a single flow of residual operation for ResNet. Each conv layer uses kernel of size 3x3, stride=stride, and padding=1. First the input's (h,w) are shrinked by `stride`, then the num of channels is increased to out_c via subsequent conv operations. input...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResidualDeconv: """A module that implements a single flow of residual operation for ResNet. Each conv layer uses kernel of size 3x3, stride=stride, and padding=1. First the input's (h,w) are shrinked by `stride`, then the num of channels is increased to out_c via subsequent conv operations. input ---> (bn-rel...
the_stack_v2_python_sparse
src/models/resnet_deconv.py
cocoaaa/Tenenbaum2000
train
0
1401cc908f52a3afd8d9cbcac01e8902dfb3b2b9
[ "len_a = self.get_length(headA)\nlen_b = self.get_length(headB)\nlonger_list = len_a if len_a >= len_b else len_b\nk = len_a - len_b if len_a >= len_b else len_b - len_a\nif len_a >= len_b:\n for _ in range(k):\n headA = headA.next\nelse:\n for _ in range(k):\n headB = headB.next\nwhile headA !=...
<|body_start_0|> len_a = self.get_length(headA) len_b = self.get_length(headB) longer_list = len_a if len_a >= len_b else len_b k = len_a - len_b if len_a >= len_b else len_b - len_a if len_a >= len_b: for _ in range(k): headA = headA.next else...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_0|> def get_length(self, head): """Return the length of the linked list""" <|body_1|> <|end_skeleton|> <|body_start_0|> len_a = self.ge...
stack_v2_sparse_classes_36k_train_011627
1,702
permissive
[ { "docstring": ":type head1, head1: ListNode :rtype: ListNode", "name": "getIntersectionNode", "signature": "def getIntersectionNode(self, headA, headB)" }, { "docstring": "Return the length of the linked list", "name": "get_length", "signature": "def get_length(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_009354
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode - def get_length(self, head): Return the length of the linked list
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode - def get_length(self, head): Return the length of the linked list <|skeleton|> class ...
547c200b627c774535bc22880b16d5390183aeba
<|skeleton|> class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_0|> def get_length(self, head): """Return the length of the linked list""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" len_a = self.get_length(headA) len_b = self.get_length(headB) longer_list = len_a if len_a >= len_b else len_b k = len_a - len_b if len_a >= len_b else len_b - len...
the_stack_v2_python_sparse
easy/160_intersection_of_two_linked_list.py
Sukhrobjon/leetcode
train
0
cbcc0ea464e8a19eab943526758560c312febd77
[ "parser = reqparse.RequestParser()\nparser.add_argument('user', type=str, location='args')\nargs = parser.parse_args()\nuser = args['user']\nif user is None:\n return errors.all_errors('CLIENT_MISSING_PARAMETER', 'user (str) parameter is required')\ntry:\n check_existing_key = ApiKeys.query.filter_by(user=use...
<|body_start_0|> parser = reqparse.RequestParser() parser.add_argument('user', type=str, location='args') args = parser.parse_args() user = args['user'] if user is None: return errors.all_errors('CLIENT_MISSING_PARAMETER', 'user (str) parameter is required') t...
ApiKey
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT", "BSD-3-Clause", "GPL-1.0-or-later", "AGPL-3.0-only", "AGPL-3.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApiKey: def get(self): """Retrieve API key of the user --- tags: - User Management parameters: - in: body name: body schema: required: - user properties: user: type: string description: user of the SOCA user responses: 200: description: Return the token associated to the user 203: descri...
stack_v2_sparse_classes_36k_train_011628
6,408
permissive
[ { "docstring": "Retrieve API key of the user --- tags: - User Management parameters: - in: body name: body schema: required: - user properties: user: type: string description: user of the SOCA user responses: 200: description: Return the token associated to the user 203: description: No token detected 400: desc...
2
stack_v2_sparse_classes_30k_train_010122
Implement the Python class `ApiKey` described below. Class description: Implement the ApiKey class. Method signatures and docstrings: - def get(self): Retrieve API key of the user --- tags: - User Management parameters: - in: body name: body schema: required: - user properties: user: type: string description: user of...
Implement the Python class `ApiKey` described below. Class description: Implement the ApiKey class. Method signatures and docstrings: - def get(self): Retrieve API key of the user --- tags: - User Management parameters: - in: body name: body schema: required: - user properties: user: type: string description: user of...
e1617b14bb1b4a29a5bc6e02fa76c1312a333389
<|skeleton|> class ApiKey: def get(self): """Retrieve API key of the user --- tags: - User Management parameters: - in: body name: body schema: required: - user properties: user: type: string description: user of the SOCA user responses: 200: description: Return the token associated to the user 203: descri...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ApiKey: def get(self): """Retrieve API key of the user --- tags: - User Management parameters: - in: body name: body schema: required: - user properties: user: type: string description: user of the SOCA user responses: 200: description: Return the token associated to the user 203: description: No toke...
the_stack_v2_python_sparse
source/soca/cluster_web_ui/api/v1/user/api_key.py
awslabs/scale-out-computing-on-aws
train
110
0ce35f4a37ef0f9b0bc791242bb3dc0e16daf286
[ "self._compute = compute_client.apitools_client\nself._messages = compute_client.messages\nself._http = compute_client.apitools_client.http\nself._batch_url = compute_client.batch_url", "errors = []\nrequests = []\nzone_names = set()\nfor resource_ref in resource_refs:\n if resource_ref.zone not in zone_names:...
<|body_start_0|> self._compute = compute_client.apitools_client self._messages = compute_client.messages self._http = compute_client.apitools_client.http self._batch_url = compute_client.batch_url <|end_body_0|> <|body_start_1|> errors = [] requests = [] zone_nam...
A (small) collection of utils for working with zones.
ZoneResourceFetcher
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZoneResourceFetcher: """A (small) collection of utils for working with zones.""" def __init__(self, compute_client): """Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class depending on "base_classes" class layout (properties side-derive...
stack_v2_sparse_classes_36k_train_011629
4,350
permissive
[ { "docstring": "Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class depending on \"base_classes\" class layout (properties side-derived from one of base_class class). This function can be used to avoid unfeasible inheritance and use composition instead when refact...
3
null
Implement the Python class `ZoneResourceFetcher` described below. Class description: A (small) collection of utils for working with zones. Method signatures and docstrings: - def __init__(self, compute_client): Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class dependi...
Implement the Python class `ZoneResourceFetcher` described below. Class description: A (small) collection of utils for working with zones. Method signatures and docstrings: - def __init__(self, compute_client): Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class dependi...
c98b58aeb0994e011df960163541e9379ae7ea06
<|skeleton|> class ZoneResourceFetcher: """A (small) collection of utils for working with zones.""" def __init__(self, compute_client): """Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class depending on "base_classes" class layout (properties side-derive...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ZoneResourceFetcher: """A (small) collection of utils for working with zones.""" def __init__(self, compute_client): """Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class depending on "base_classes" class layout (properties side-derived from one of...
the_stack_v2_python_sparse
google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/zone_utils.py
KaranToor/MA450
train
1
ea572610a435687ba7aeb220e785bbdceb38619f
[ "self.width = width\nself.height = height\nself.food = deque([(item[0], item[1]) for item in food])\nself.snake = deque([(0, 0)])\nself.offsets = {'R': (0, 1), 'L': (0, -1), 'U': (-1, 0), 'D': (1, 0)}", "row_offset, col_offset = self.offsets[direction]\nrow, col = self.snake[0]\nnew_row, new_col = (row + row_offs...
<|body_start_0|> self.width = width self.height = height self.food = deque([(item[0], item[1]) for item in food]) self.snake = deque([(0, 0)]) self.offsets = {'R': (0, 1), 'L': (0, -1), 'U': (-1, 0), 'D': (1, 0)} <|end_body_0|> <|body_start_1|> row_offset, col_offset = s...
SnakeGame
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t...
stack_v2_sparse_classes_36k_train_011630
1,713
permissive
[ { "docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].", "name": "__init__", "signature": "def __init__(self, widt...
2
null
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -...
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -...
bf03743a3676ca9a8c107f92cf3858b6887d0308
<|skeleton|> class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a...
the_stack_v2_python_sparse
python/353_design_snake_game.py
liaison/LeetCode
train
17
a59b3e9bdad38206fb724febb069a86cf5cc96ae
[ "i, j, n = (0, len(A) - 1, len(A))\nwhile i + 1 < n and A[i] < A[i + 1]:\n i += 1\nwhile j > 0 and A[j - 1] > A[j]:\n j -= 1\nreturn 0 < i == j < n - 1", "if len(A) < 3:\n return False\nif A[0] >= A[1]:\n return False\nclimb = True\nfor a, b in zip(A, A[1:]):\n if climb:\n if a < b:\n ...
<|body_start_0|> i, j, n = (0, len(A) - 1, len(A)) while i + 1 < n and A[i] < A[i + 1]: i += 1 while j > 0 and A[j - 1] > A[j]: j -= 1 return 0 < i == j < n - 1 <|end_body_0|> <|body_start_1|> if len(A) < 3: return False if A[0] >= A[1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def validMountainArray(self, A): """:type A: List[int] :rtype: bool""" <|body_0|> def validMountainArray(self, A): """:type A: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> i, j, n = (0, len(A) - 1, len(A)) ...
stack_v2_sparse_classes_36k_train_011631
839
no_license
[ { "docstring": ":type A: List[int] :rtype: bool", "name": "validMountainArray", "signature": "def validMountainArray(self, A)" }, { "docstring": ":type A: List[int] :rtype: bool", "name": "validMountainArray", "signature": "def validMountainArray(self, A)" } ]
2
stack_v2_sparse_classes_30k_train_016721
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def validMountainArray(self, A): :type A: List[int] :rtype: bool - def validMountainArray(self, A): :type A: List[int] :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def validMountainArray(self, A): :type A: List[int] :rtype: bool - def validMountainArray(self, A): :type A: List[int] :rtype: bool <|skeleton|> class Solution: def validMo...
c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0
<|skeleton|> class Solution: def validMountainArray(self, A): """:type A: List[int] :rtype: bool""" <|body_0|> def validMountainArray(self, A): """:type A: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def validMountainArray(self, A): """:type A: List[int] :rtype: bool""" i, j, n = (0, len(A) - 1, len(A)) while i + 1 < n and A[i] < A[i + 1]: i += 1 while j > 0 and A[j - 1] > A[j]: j -= 1 return 0 < i == j < n - 1 def validMountai...
the_stack_v2_python_sparse
code/941#Valid Mountain Array.py
EachenKuang/LeetCode
train
28
01d958fe033b0bec75d9314add6be9c67e5c3dcd
[ "self.obs_type = obs_type\nself.stale_age = stale_age\nself.old_timestamp = None\nself.old_value = None", "if self.obs_type not in record:\n raise weewx.CannotCalculate(self.obs_type)\nderivative = None\nif record[self.obs_type] is not None:\n if self.old_timestamp:\n if record['dateTime'] < self.old...
<|body_start_0|> self.obs_type = obs_type self.stale_age = stale_age self.old_timestamp = None self.old_value = None <|end_body_0|> <|body_start_1|> if self.obs_type not in record: raise weewx.CannotCalculate(self.obs_type) derivative = None if record...
Calculate time derivative for a specific observation type.
TimeDerivative
[ "GPL-1.0-or-later", "GPL-3.0-only", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TimeDerivative: """Calculate time derivative for a specific observation type.""" def __init__(self, obs_type, stale_age): """Initialize. obs_type: the observation type for which the derivative will be calculated. stale_age: Derivatives are calculated as a difference over time. This i...
stack_v2_sparse_classes_36k_train_011632
2,064
permissive
[ { "docstring": "Initialize. obs_type: the observation type for which the derivative will be calculated. stale_age: Derivatives are calculated as a difference over time. This is how old the old value can be and still be considered useful.", "name": "__init__", "signature": "def __init__(self, obs_type, s...
2
null
Implement the Python class `TimeDerivative` described below. Class description: Calculate time derivative for a specific observation type. Method signatures and docstrings: - def __init__(self, obs_type, stale_age): Initialize. obs_type: the observation type for which the derivative will be calculated. stale_age: Der...
Implement the Python class `TimeDerivative` described below. Class description: Calculate time derivative for a specific observation type. Method signatures and docstrings: - def __init__(self, obs_type, stale_age): Initialize. obs_type: the observation type for which the derivative will be calculated. stale_age: Der...
7085654f455d39b06acc688738fde27e1f78ad1e
<|skeleton|> class TimeDerivative: """Calculate time derivative for a specific observation type.""" def __init__(self, obs_type, stale_age): """Initialize. obs_type: the observation type for which the derivative will be calculated. stale_age: Derivatives are calculated as a difference over time. This i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TimeDerivative: """Calculate time derivative for a specific observation type.""" def __init__(self, obs_type, stale_age): """Initialize. obs_type: the observation type for which the derivative will be calculated. stale_age: Derivatives are calculated as a difference over time. This is how old the...
the_stack_v2_python_sparse
dist/weewx-4.3.0b2/bin/weeutil/timediff.py
tomdotorg/docker-weewx
train
21
918bff455975ffdd513038de15195eaf39667f01
[ "self._list = []\nself._value = {}\nself._length = capacity", "ans = self._value.get(key)\nif ans is not None:\n self.set(key, ans)\n return ans\nreturn -1", "if not self._value.get(key):\n if len(self._list) == self._length:\n del self._value[self._list[0]]\n self._list[0:1] = []\nelse:\...
<|body_start_0|> self._list = [] self._value = {} self._length = capacity <|end_body_0|> <|body_start_1|> ans = self._value.get(key) if ans is not None: self.set(key, ans) return ans return -1 <|end_body_1|> <|body_start_2|> if not self._...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_011633
869
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
3
stack_v2_sparse_classes_30k_train_012065
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> cla...
bd6b18f134336513bbc3112be6e33c79374a7cb1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self._list = [] self._value = {} self._length = capacity def get(self, key): """:rtype: int""" ans = self._value.get(key) if ans is not None: self.set(key, ans) ...
the_stack_v2_python_sparse
python/146. LRU Cache.py
AlisonZXQ/leetcode
train
1
90df319fe3828a41e093c3cf1750d0cb985b4698
[ "if target_vector is None:\n target_vector = np.zeros(cluster_subspace.num_orbits)\nif target_weights is None:\n target_weights = np.ones(cluster_subspace.num_orbits - 1)\nif interaction_tensors is None:\n interaction_tensors = (0.0,) + tuple((sum((m * tensor for i, (m, tensor) in enumerate(zip(orbit.bit_c...
<|body_start_0|> if target_vector is None: target_vector = np.zeros(cluster_subspace.num_orbits) if target_weights is None: target_weights = np.ones(cluster_subspace.num_orbits - 1) if interaction_tensors is None: interaction_tensors = (0.0,) + tuple((sum((m *...
Compute distances from a fixed cluster interaction vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the cluster interaction vector, f_T is the target vector, and L is the diameter for which all correlation values of clusters of smaller diameter are exactly equal to the...
ClusterInteractionDistanceProcessor
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClusterInteractionDistanceProcessor: """Compute distances from a fixed cluster interaction vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the cluster interaction vector, f_T is the target vector, and L is the diameter for which all correlation ...
stack_v2_sparse_classes_36k_train_011634
17,001
permissive
[ { "docstring": "Initialize a CorrelationDistanceProcessor. Args: cluster_subspace (ClusterSubspace): a cluster subspace supercell_matrix (ndarray): an array representing the supercell matrix with respect to the Cluster Expansion prim structure. interaction_tensors (sequence of ndarray): optional Sequence of nda...
3
null
Implement the Python class `ClusterInteractionDistanceProcessor` described below. Class description: Compute distances from a fixed cluster interaction vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the cluster interaction vector, f_T is the target vector, and L is ...
Implement the Python class `ClusterInteractionDistanceProcessor` described below. Class description: Compute distances from a fixed cluster interaction vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the cluster interaction vector, f_T is the target vector, and L is ...
457518b9a27729fd4d5c1c23231bd37f8fee364b
<|skeleton|> class ClusterInteractionDistanceProcessor: """Compute distances from a fixed cluster interaction vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the cluster interaction vector, f_T is the target vector, and L is the diameter for which all correlation ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClusterInteractionDistanceProcessor: """Compute distances from a fixed cluster interaction vector. The distance used to measure distance is, .. math:: d = -wL + ||W^T(f - f_T)||_1 where f is the cluster interaction vector, f_T is the target vector, and L is the diameter for which all correlation values of clu...
the_stack_v2_python_sparse
smol/moca/processor/distance.py
CederGroupHub/smol
train
40
421b264ed83f666dc9998d21f67a5b38a797eba7
[ "def target1(x, pattern: BaseGeometry, pos: BaseGeometry):\n params = _TargetTransformParams(x[0], x[1], x[2], x[3])\n pos_trans = _target_affine_transform(pos, params)\n pos_overlap = pattern.intersection(pos_trans).area\n false_pos_overlap = pos_trans.difference(pattern).area\n return false_pos_ove...
<|body_start_0|> def target1(x, pattern: BaseGeometry, pos: BaseGeometry): params = _TargetTransformParams(x[0], x[1], x[2], x[3]) pos_trans = _target_affine_transform(pos, params) pos_overlap = pattern.intersection(pos_trans).area false_pos_overlap = pos_trans.di...
Aligner
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Aligner: def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix: """this method try to apply an affine transformation on pos, so the overlap between pattern and pos is maximized :param pattern: keep-it-still background :param pos: a shape we try to align it with pat...
stack_v2_sparse_classes_36k_train_011635
6,594
no_license
[ { "docstring": "this method try to apply an affine transformation on pos, so the overlap between pattern and pos is maximized :param pattern: keep-it-still background :param pos: a shape we try to align it with pattern :return: transformation parameters", "name": "align", "signature": "def align(self, p...
2
stack_v2_sparse_classes_30k_train_019686
Implement the Python class `Aligner` described below. Class description: Implement the Aligner class. Method signatures and docstrings: - def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix: this method try to apply an affine transformation on pos, so the overlap between pattern and pos is ma...
Implement the Python class `Aligner` described below. Class description: Implement the Aligner class. Method signatures and docstrings: - def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix: this method try to apply an affine transformation on pos, so the overlap between pattern and pos is ma...
86446637d87077388b318ce9be7317139b5e5428
<|skeleton|> class Aligner: def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix: """this method try to apply an affine transformation on pos, so the overlap between pattern and pos is maximized :param pattern: keep-it-still background :param pos: a shape we try to align it with pat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Aligner: def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix: """this method try to apply an affine transformation on pos, so the overlap between pattern and pos is maximized :param pattern: keep-it-still background :param pos: a shape we try to align it with pattern :return: ...
the_stack_v2_python_sparse
backend/prototype/shape_match.py
snowdmonkey/solar
train
1
dcc0d7caad437457765389524b9c16a6abd2bb2f
[ "super().__init__()\nimport sklearn\nimport sklearn.discriminant_analysis\nself.model = sklearn.discriminant_analysis.LinearDiscriminantAnalysis", "specs = super(LinearDiscriminantAnalysisClassifier, cls).getInputSpecification()\nspecs.description = \"The \\\\xmlNode{LinearDiscriminantAnalysisClassifier} is a cla...
<|body_start_0|> super().__init__() import sklearn import sklearn.discriminant_analysis self.model = sklearn.discriminant_analysis.LinearDiscriminantAnalysis <|end_body_0|> <|body_start_1|> specs = super(LinearDiscriminantAnalysisClassifier, cls).getInputSpecification() ...
KNeighborsClassifier Classifier implementing the k-nearest neighbors vote.
LinearDiscriminantAnalysisClassifier
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearDiscriminantAnalysisClassifier: """KNeighborsClassifier Classifier implementing the k-nearest neighbors vote.""" def __init__(self): """Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None""" <|body_0|> def getInputSpec...
stack_v2_sparse_classes_36k_train_011636
7,036
permissive
[ { "docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for...
3
null
Implement the Python class `LinearDiscriminantAnalysisClassifier` described below. Class description: KNeighborsClassifier Classifier implementing the k-nearest neighbors vote. Method signatures and docstrings: - def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, Non...
Implement the Python class `LinearDiscriminantAnalysisClassifier` described below. Class description: KNeighborsClassifier Classifier implementing the k-nearest neighbors vote. Method signatures and docstrings: - def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, Non...
2b16e7aa3325fe84cab2477947a951414c635381
<|skeleton|> class LinearDiscriminantAnalysisClassifier: """KNeighborsClassifier Classifier implementing the k-nearest neighbors vote.""" def __init__(self): """Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None""" <|body_0|> def getInputSpec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearDiscriminantAnalysisClassifier: """KNeighborsClassifier Classifier implementing the k-nearest neighbors vote.""" def __init__(self): """Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None""" super().__init__() import sklearn ...
the_stack_v2_python_sparse
ravenframework/SupervisedLearning/ScikitLearn/DiscriminantAnalysis/LinearDiscriminantAnalysis.py
idaholab/raven
train
201
03cf94c6ce8ba1a25d1d14423071f393a949d212
[ "if root:\n if root.left and root.right:\n return self.isSameTree(root.left, root.right)\n elif not root.left and (not root.right):\n return True\n else:\n return False\nelse:\n return True", "if not (p and q or (not p and (not q))):\n return False\nif p:\n if p.val != q.val...
<|body_start_0|> if root: if root.left and root.right: return self.isSameTree(root.left, root.right) elif not root.left and (not root.right): return True else: return False else: return True <|end_body_0|> <...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isSameTree(self, p, q): """:type p: TreeNode :type q: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if root: if root.le...
stack_v2_sparse_classes_36k_train_011637
885
no_license
[ { "docstring": ":type root: TreeNode :rtype: bool", "name": "isSymmetric", "signature": "def isSymmetric(self, root)" }, { "docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool", "name": "isSameTree", "signature": "def isSameTree(self, p, q)" } ]
2
stack_v2_sparse_classes_30k_train_021103
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSymmetric(self, root): :type root: TreeNode :rtype: bool - def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSymmetric(self, root): :type root: TreeNode :rtype: bool - def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool <|skeleton|> class Solution: d...
2711bc08f15266bec4ca135e8e3e629df46713eb
<|skeleton|> class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isSameTree(self, p, q): """:type p: TreeNode :type q: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" if root: if root.left and root.right: return self.isSameTree(root.left, root.right) elif not root.left and (not root.right): return True else: ...
the_stack_v2_python_sparse
0.算法/101_Symmetric_Tree.py
unlimitediw/CheckCode
train
0
8f137a8946329e233cbd259009419d3f32b7a449
[ "user = request.user\nif not way_id:\n data = [way.get_way_with_routes() for way in user.ways.all()]\n return JsonResponse(data, status=200, safe=False)\nway = Way.get_by_id(obj_id=way_id)\nif not way:\n return RESPONSE_400_OBJECT_NOT_FOUND\nif not way.user == user:\n return RESPONSE_403_ACCESS_DENIED\n...
<|body_start_0|> user = request.user if not way_id: data = [way.get_way_with_routes() for way in user.ways.all()] return JsonResponse(data, status=200, safe=False) way = Way.get_by_id(obj_id=way_id) if not way: return RESPONSE_400_OBJECT_NOT_FOUND ...
Class-based view for way model.
WayView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WayView: """Class-based view for way model.""" def get(self, request, way_id=None): """Method for HTTP GET request :param request: client HttpRequest. Is required :type request: HttpRequest :param way_id: id of Way model :type way_id: int :return JsonResponse with way data and list w...
stack_v2_sparse_classes_36k_train_011638
7,225
no_license
[ { "docstring": "Method for HTTP GET request :param request: client HttpRequest. Is required :type request: HttpRequest :param way_id: id of Way model :type way_id: int :return JsonResponse with way data and list with routes and status 200 if parameters are good and way_id is specified, JsonResponse with all way...
3
null
Implement the Python class `WayView` described below. Class description: Class-based view for way model. Method signatures and docstrings: - def get(self, request, way_id=None): Method for HTTP GET request :param request: client HttpRequest. Is required :type request: HttpRequest :param way_id: id of Way model :type ...
Implement the Python class `WayView` described below. Class description: Class-based view for way model. Method signatures and docstrings: - def get(self, request, way_id=None): Method for HTTP GET request :param request: client HttpRequest. Is required :type request: HttpRequest :param way_id: id of Way model :type ...
c5f533bd049f6939037b14045e2aa2550aaac36a
<|skeleton|> class WayView: """Class-based view for way model.""" def get(self, request, way_id=None): """Method for HTTP GET request :param request: client HttpRequest. Is required :type request: HttpRequest :param way_id: id of Way model :type way_id: int :return JsonResponse with way data and list w...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WayView: """Class-based view for way model.""" def get(self, request, way_id=None): """Method for HTTP GET request :param request: client HttpRequest. Is required :type request: HttpRequest :param way_id: id of Way model :type way_id: int :return JsonResponse with way data and list with routes an...
the_stack_v2_python_sparse
way_to_home/way/views.py
Lv-365python/wayToHome
train
1
817f8c4a36a79b254fc6e92bfa08df0426a5bd93
[ "self.depth = depth\nself.qubits = qubits\nself.quantum_program = QuantumProgram()\nself.quantum_register = self.quantum_program.create_quantum_register('qr', qubits)\nself.classical_register = self.quantum_program.create_classical_register('cr', qubits)\nif seed is not None:\n random.seed(a=seed)", "circuit_n...
<|body_start_0|> self.depth = depth self.qubits = qubits self.quantum_program = QuantumProgram() self.quantum_register = self.quantum_program.create_quantum_register('qr', qubits) self.classical_register = self.quantum_program.create_classical_register('cr', qubits) if se...
Generate circuits with random operations for profiling.
RandomQasmGenerator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomQasmGenerator: """Generate circuits with random operations for profiling.""" def __init__(self, seed=None, qubits=16, depth=40): """Args: seed: Random number seed. If none, don't seed the generator. depth: Number of operations in the circuit. qubits: Number of qubits in the cir...
stack_v2_sparse_classes_36k_train_011639
4,544
permissive
[ { "docstring": "Args: seed: Random number seed. If none, don't seed the generator. depth: Number of operations in the circuit. qubits: Number of qubits in the circuit.", "name": "__init__", "signature": "def __init__(self, seed=None, qubits=16, depth=40)" }, { "docstring": "Creates a circuit Gen...
2
stack_v2_sparse_classes_30k_train_020452
Implement the Python class `RandomQasmGenerator` described below. Class description: Generate circuits with random operations for profiling. Method signatures and docstrings: - def __init__(self, seed=None, qubits=16, depth=40): Args: seed: Random number seed. If none, don't seed the generator. depth: Number of opera...
Implement the Python class `RandomQasmGenerator` described below. Class description: Generate circuits with random operations for profiling. Method signatures and docstrings: - def __init__(self, seed=None, qubits=16, depth=40): Args: seed: Random number seed. If none, don't seed the generator. depth: Number of opera...
e0f8d9fd61322623fe59a11b4d03cbd3f54d9015
<|skeleton|> class RandomQasmGenerator: """Generate circuits with random operations for profiling.""" def __init__(self, seed=None, qubits=16, depth=40): """Args: seed: Random number seed. If none, don't seed the generator. depth: Number of operations in the circuit. qubits: Number of qubits in the cir...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomQasmGenerator: """Generate circuits with random operations for profiling.""" def __init__(self, seed=None, qubits=16, depth=40): """Args: seed: Random number seed. If none, don't seed the generator. depth: Number of operations in the circuit. qubits: Number of qubits in the circuit.""" ...
the_stack_v2_python_sparse
tools/random_qasm_generator.py
sulavtimilsina/qiskit-terra
train
1
3cf63d4630aa0a0d5d7db7d48d5654514830631a
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s).
EventListenerServicer
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventListenerServicer: """EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s).""" def SendEvents(self, request_iterator, context): """Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1...
stack_v2_sparse_classes_36k_train_011640
5,031
permissive
[ { "docstring": "Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1) intermediate tensors from a debugged graph being executed, which can be sent from DebugIdentity ops configured with grpc URLs. 2) GraphDefs of partition graphs, which can b...
3
null
Implement the Python class `EventListenerServicer` described below. Class description: EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s). Method signatures and docstrings: - def SendEvents(self, request_iterator, context): Client(s) can use this RPC method to send the EventListener Event...
Implement the Python class `EventListenerServicer` described below. Class description: EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s). Method signatures and docstrings: - def SendEvents(self, request_iterator, context): Client(s) can use this RPC method to send the EventListener Event...
a7f3934a67900720af3d3b15389551483bee50b8
<|skeleton|> class EventListenerServicer: """EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s).""" def SendEvents(self, request_iterator, context): """Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EventListenerServicer: """EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s).""" def SendEvents(self, request_iterator, context): """Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1) intermediat...
the_stack_v2_python_sparse
tensorflow/python/debug/lib/debug_service_pb2_grpc.py
tensorflow/tensorflow
train
208,740
230f5f17b1dc1a7d637581d25d54f89adaa38d6f
[ "super(CNN, self).__init__()\nself.cnn = nn.SequentialCell([nn.Conv1d(n_in, n_hid, kernel_size=5, pad_mode='valid', has_bias=True, weight_init=init.Normal(math.sqrt(2.0 / (5 * n_hid))), bias_init=init.Constant(0.1)), nn.ReLU(), MyBatchNorm1d(n_hid, dim=1), nn.Dropout(p=do_prob), nn.MaxPool1d(kernel_size=2, stride=2...
<|body_start_0|> super(CNN, self).__init__() self.cnn = nn.SequentialCell([nn.Conv1d(n_in, n_hid, kernel_size=5, pad_mode='valid', has_bias=True, weight_init=init.Normal(math.sqrt(2.0 / (5 * n_hid))), bias_init=init.Constant(0.1)), nn.ReLU(), MyBatchNorm1d(n_hid, dim=1), nn.Dropout(p=do_prob), nn.MaxPoo...
CNN
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CNN: def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): """Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dimension. do_prob : float, optional rate of dropout. The default is 0..""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_011641
9,199
permissive
[ { "docstring": "Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dimension. do_prob : float, optional rate of dropout. The default is 0..", "name": "__init__", "signature": "def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0...
2
stack_v2_sparse_classes_30k_train_009214
Implement the Python class `CNN` described below. Class description: Implement the CNN class. Method signatures and docstrings: - def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dime...
Implement the Python class `CNN` described below. Class description: Implement the CNN class. Method signatures and docstrings: - def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dime...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class CNN: def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): """Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dimension. do_prob : float, optional rate of dropout. The default is 0..""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CNN: def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): """Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dimension. do_prob : float, optional rate of dropout. The default is 0..""" super(CNN, self).__init__(...
the_stack_v2_python_sparse
research/gnn/nri-mpm/models/base.py
mindspore-ai/models
train
301
c2dad5c69981fc815e3c0878c4b852f0c3da5a04
[ "f = self.dtype_f(self.init)\nself.AMat.mult(u, f)\nfa = self.init.getVecArray(f)\nxa = self.init.getVecArray(u)\nfor i in range(self.xs, self.xe):\n for j in range(self.ys, self.ye):\n fa[i, j, 0] += -xa[i, j, 0] * xa[i, j, 1] ** 2 + self.A * (1 - xa[i, j, 0])\n fa[i, j, 1] += xa[i, j, 0] * xa[i, ...
<|body_start_0|> f = self.dtype_f(self.init) self.AMat.mult(u, f) fa = self.init.getVecArray(f) xa = self.init.getVecArray(u) for i in range(self.xs, self.xe): for j in range(self.ys, self.ye): fa[i, j, 0] += -xa[i, j, 0] * xa[i, j, 1] ** 2 + self.A * ...
Problem class implementing the fully-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc
petsc_grayscott_fullyimplicit
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class petsc_grayscott_fullyimplicit: """Problem class implementing the fully-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc""" def eval_f(self, u, t): """Routine to evaluate the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: t...
stack_v2_sparse_classes_36k_train_011642
20,605
permissive
[ { "docstring": "Routine to evaluate the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS", "name": "eval_f", "signature": "def eval_f(self, u, t)" }, { "docstring": "Nonlinear solver for (I-factor*F)(u) = rhs Args: rhs (dtype_f): right-hand side for the lin...
2
null
Implement the Python class `petsc_grayscott_fullyimplicit` described below. Class description: Problem class implementing the fully-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc Method signatures and docstrings: - def eval_f(self, u, t): Routine to evaluate the RHS Args: u (dtype_u): c...
Implement the Python class `petsc_grayscott_fullyimplicit` described below. Class description: Problem class implementing the fully-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc Method signatures and docstrings: - def eval_f(self, u, t): Routine to evaluate the RHS Args: u (dtype_u): c...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class petsc_grayscott_fullyimplicit: """Problem class implementing the fully-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc""" def eval_f(self, u, t): """Routine to evaluate the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class petsc_grayscott_fullyimplicit: """Problem class implementing the fully-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc""" def eval_f(self, u, t): """Routine to evaluate the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS""" ...
the_stack_v2_python_sparse
pySDC/implementations/problem_classes/GrayScott_2D_PETSc_periodic.py
Parallel-in-Time/pySDC
train
30
a155f34bbe13a1ec52071b4086b404e330d3827a
[ "stack = []\nfor token in tokens:\n if token not in ('+', '-', '*', '/'):\n stack.append(token)\n else:\n x, y = (int(stack.pop()), int(stack.pop()))\n if token == '+':\n stack.append(x + y)\n elif token == '-':\n stack.append(y - x)\n elif token == '*'...
<|body_start_0|> stack = [] for token in tokens: if token not in ('+', '-', '*', '/'): stack.append(token) else: x, y = (int(stack.pop()), int(stack.pop())) if token == '+': stack.append(x + y) el...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def evalRPN(self, tokens: List[str]) -> int: """栈""" <|body_0|> def evalRPNArray(self, tokens: List[str]) -> int: """数组模拟栈""" <|body_1|> <|end_skeleton|> <|body_start_0|> stack = [] for token in tokens: if token not in ...
stack_v2_sparse_classes_36k_train_011643
1,540
no_license
[ { "docstring": "栈", "name": "evalRPN", "signature": "def evalRPN(self, tokens: List[str]) -> int" }, { "docstring": "数组模拟栈", "name": "evalRPNArray", "signature": "def evalRPNArray(self, tokens: List[str]) -> int" } ]
2
stack_v2_sparse_classes_30k_train_007936
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def evalRPN(self, tokens: List[str]) -> int: 栈 - def evalRPNArray(self, tokens: List[str]) -> int: 数组模拟栈
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def evalRPN(self, tokens: List[str]) -> int: 栈 - def evalRPNArray(self, tokens: List[str]) -> int: 数组模拟栈 <|skeleton|> class Solution: def evalRPN(self, tokens: List[str]) -...
52756b30e9d51794591aca030bc918e707f473f1
<|skeleton|> class Solution: def evalRPN(self, tokens: List[str]) -> int: """栈""" <|body_0|> def evalRPNArray(self, tokens: List[str]) -> int: """数组模拟栈""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def evalRPN(self, tokens: List[str]) -> int: """栈""" stack = [] for token in tokens: if token not in ('+', '-', '*', '/'): stack.append(token) else: x, y = (int(stack.pop()), int(stack.pop())) if token ==...
the_stack_v2_python_sparse
150.逆波兰表达式求值/solution.py
QtTao/daily_leetcode
train
0
5c0ebdbadc44c0e63f02830f0d70a756f1273091
[ "name = homework.get_slug()\nrepos_root = Config.REPOS_ROOT + '/' + name\ntry:\n os.mkdir(repos_root)\nexcept FileExistsError:\n pass\nrepositories = Repository.clone(Repository.search(name), repos_root, homework)\nfor repo in repositories:\n Repository.parse(repo)", "repos = []\nresponse_len = Config.GI...
<|body_start_0|> name = homework.get_slug() repos_root = Config.REPOS_ROOT + '/' + name try: os.mkdir(repos_root) except FileExistsError: pass repositories = Repository.clone(Repository.search(name), repos_root, homework) for repo in repositories: ...
Repository
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Repository: def clone_n_parse(homework): """Clone all repositories for given homework and parse all solution files for each repository""" <|body_0|> def search(name): """Searches for gitea repositories with given name. Returns a list of dictionaries representing repo...
stack_v2_sparse_classes_36k_train_011644
6,212
no_license
[ { "docstring": "Clone all repositories for given homework and parse all solution files for each repository", "name": "clone_n_parse", "signature": "def clone_n_parse(homework)" }, { "docstring": "Searches for gitea repositories with given name. Returns a list of dictionaries representing reposit...
6
stack_v2_sparse_classes_30k_train_014815
Implement the Python class `Repository` described below. Class description: Implement the Repository class. Method signatures and docstrings: - def clone_n_parse(homework): Clone all repositories for given homework and parse all solution files for each repository - def search(name): Searches for gitea repositories wi...
Implement the Python class `Repository` described below. Class description: Implement the Repository class. Method signatures and docstrings: - def clone_n_parse(homework): Clone all repositories for given homework and parse all solution files for each repository - def search(name): Searches for gitea repositories wi...
86f343f8fc734207799fdc30b2266e982be24213
<|skeleton|> class Repository: def clone_n_parse(homework): """Clone all repositories for given homework and parse all solution files for each repository""" <|body_0|> def search(name): """Searches for gitea repositories with given name. Returns a list of dictionaries representing repo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Repository: def clone_n_parse(homework): """Clone all repositories for given homework and parse all solution files for each repository""" name = homework.get_slug() repos_root = Config.REPOS_ROOT + '/' + name try: os.mkdir(repos_root) except FileExistsError:...
the_stack_v2_python_sparse
app/repository.py
KSET/OKOSL_homeworks
train
1
3516fd875d8d17c1990134a41508fcdc715dc79c
[ "self.id = identifier\nself.name = name\nself.wfos = wfos if wfos is not None else []\nself.geometry = Point([lon, lat])", "if self.name is None:\n return f'(({self.id}))'\nreturn self.name", "if key == 'lat':\n return self.geometry.y\nif key == 'lon':\n return self.geometry.x\nreturn getattr(self, key...
<|body_start_0|> self.id = identifier self.name = name self.wfos = wfos if wfos is not None else [] self.geometry = Point([lon, lat]) <|end_body_0|> <|body_start_1|> if self.name is None: return f'(({self.id}))' return self.name <|end_body_1|> <|body_start_2...
National Weather Service Location Idenitifiers (NWSLI)
NWSLI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NWSLI: """National Weather Service Location Idenitifiers (NWSLI)""" def __init__(self, identifier, name=None, wfos=None, lon=0, lat=0): """Constructor Args: identifier(str): The string identifier for this NWSLI name(str, optional): The free-form text name of this location wfo(list, o...
stack_v2_sparse_classes_36k_train_011645
1,359
permissive
[ { "docstring": "Constructor Args: identifier(str): The string identifier for this NWSLI name(str, optional): The free-form text name of this location wfo(list, optional): The wfo(s) associated with this NWSLI lon(float, optional): The longitude in decimal degrees lat(float, optional): The latitude in decimal de...
3
stack_v2_sparse_classes_30k_train_010137
Implement the Python class `NWSLI` described below. Class description: National Weather Service Location Idenitifiers (NWSLI) Method signatures and docstrings: - def __init__(self, identifier, name=None, wfos=None, lon=0, lat=0): Constructor Args: identifier(str): The string identifier for this NWSLI name(str, option...
Implement the Python class `NWSLI` described below. Class description: National Weather Service Location Idenitifiers (NWSLI) Method signatures and docstrings: - def __init__(self, identifier, name=None, wfos=None, lon=0, lat=0): Constructor Args: identifier(str): The string identifier for this NWSLI name(str, option...
460f44394be05e1b655111595a3d7de3f7e47757
<|skeleton|> class NWSLI: """National Weather Service Location Idenitifiers (NWSLI)""" def __init__(self, identifier, name=None, wfos=None, lon=0, lat=0): """Constructor Args: identifier(str): The string identifier for this NWSLI name(str, optional): The free-form text name of this location wfo(list, o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NWSLI: """National Weather Service Location Idenitifiers (NWSLI)""" def __init__(self, identifier, name=None, wfos=None, lon=0, lat=0): """Constructor Args: identifier(str): The string identifier for this NWSLI name(str, optional): The free-form text name of this location wfo(list, optional): The...
the_stack_v2_python_sparse
src/pyiem/nws/nwsli.py
akrherz/pyIEM
train
38
a198b6670e57eaaaf383b6271f5d6cc0750bd141
[ "row, col = (len(board), len(board[0]))\nflags = [[False] * col] * row\nprint(flags)\nfor i in range(row):\n for j in range(col):\n count_1 = 0\n print('i,j:', i, j)\n print('第', i, j, '个 flags', flags[i][j])\n flags[i][j] = False\n for [x, y] in [[-1, -1], [-1, 0], [-1, 1], [0...
<|body_start_0|> row, col = (len(board), len(board[0])) flags = [[False] * col] * row print(flags) for i in range(row): for j in range(col): count_1 = 0 print('i,j:', i, j) print('第', i, j, '个 flags', flags[i][j]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def gameOfLife(self, board) -> None: """Do not return anything, modify board in-place instead.""" <|body_0|> def gameOfLife_2(self, board) -> None: """Do not return anything, modify board in-place instead.""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_011646
4,020
no_license
[ { "docstring": "Do not return anything, modify board in-place instead.", "name": "gameOfLife", "signature": "def gameOfLife(self, board) -> None" }, { "docstring": "Do not return anything, modify board in-place instead.", "name": "gameOfLife_2", "signature": "def gameOfLife_2(self, board...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def gameOfLife(self, board) -> None: Do not return anything, modify board in-place instead. - def gameOfLife_2(self, board) -> None: Do not return anything, modify board in-place...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def gameOfLife(self, board) -> None: Do not return anything, modify board in-place instead. - def gameOfLife_2(self, board) -> None: Do not return anything, modify board in-place...
e29b8b553adaaa2ab55851fa79b21df84eb17452
<|skeleton|> class Solution: def gameOfLife(self, board) -> None: """Do not return anything, modify board in-place instead.""" <|body_0|> def gameOfLife_2(self, board) -> None: """Do not return anything, modify board in-place instead.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def gameOfLife(self, board) -> None: """Do not return anything, modify board in-place instead.""" row, col = (len(board), len(board[0])) flags = [[False] * col] * row print(flags) for i in range(row): for j in range(col): count_1 = ...
the_stack_v2_python_sparse
289_生命游戏.py
Yujunw/leetcode_python
train
0
421560b36a98fd94be0190d8421d18f4e66d66ab
[ "if not root:\n return\nleft = self.flatten(root.left)\nright = self.flatten(root.right)\nroot.right = left\nnode, next_ = (root, root.right)\nwhile next_:\n node.left, node, next_ = (None, next_, next_.right)\nnode.right = right\nreturn root", "nodes = list()\n\ndef dfs(root):\n if not root:\n re...
<|body_start_0|> if not root: return left = self.flatten(root.left) right = self.flatten(root.right) root.right = left node, next_ = (root, root.right) while next_: node.left, node, next_ = (None, next_, next_.right) node.right = right ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def flatten(self, root: TreeNode) -> None: """Do not return anything, modify root in-place instead.""" <|body_0|> def flatten(self, root: TreeNode) -> None: """Do not return anything, modify root in-place instead.""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_36k_train_011647
1,279
no_license
[ { "docstring": "Do not return anything, modify root in-place instead.", "name": "flatten", "signature": "def flatten(self, root: TreeNode) -> None" }, { "docstring": "Do not return anything, modify root in-place instead.", "name": "flatten", "signature": "def flatten(self, root: TreeNode...
2
stack_v2_sparse_classes_30k_train_018283
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead. - def flatten(self, root: TreeNode) -> None: Do not return anything, modify root ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead. - def flatten(self, root: TreeNode) -> None: Do not return anything, modify root ...
5d29bcf7ea1a9e489a92bc36d2158456de25829e
<|skeleton|> class Solution: def flatten(self, root: TreeNode) -> None: """Do not return anything, modify root in-place instead.""" <|body_0|> def flatten(self, root: TreeNode) -> None: """Do not return anything, modify root in-place instead.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def flatten(self, root: TreeNode) -> None: """Do not return anything, modify root in-place instead.""" if not root: return left = self.flatten(root.left) right = self.flatten(root.right) root.right = left node, next_ = (root, root.right) ...
the_stack_v2_python_sparse
114.二叉树展开为链表.py
oceanbei333/leetcode
train
0
7b2b1c18377a9cb3b9cf0ce37624c37013f4c92c
[ "items = self.node(parent)\nif items and kwargs:\n for item in items:\n for key, value in kwargs.iteritems():\n setattr(item, key, value)\nreturn items", "try:\n return self.node.scope[name]\nexcept KeyError:\n msg = \"'%s' object has no attribute '%s'\"\n raise AttributeError(msg % ...
<|body_start_0|> items = self.node(parent) if items and kwargs: for item in items: for key, value in kwargs.iteritems(): setattr(item, key, value) return items <|end_body_0|> <|body_start_1|> try: return self.node.scope[name] ...
A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code.
TemplateInstance
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemplateInstance: """A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code.""" def __call__(self, parent=None, **kwargs): """Instantiate the list of items for the template. Paramet...
stack_v2_sparse_classes_36k_train_011648
8,361
permissive
[ { "docstring": "Instantiate the list of items for the template. Parameters ---------- parent : Object, optional The parent object for the generated objects. **kwargs Additional keyword arguments to apply to the returned items. Returns ------- result : list The list of objects generated by the template.", "n...
2
stack_v2_sparse_classes_30k_train_017580
Implement the Python class `TemplateInstance` described below. Class description: A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code. Method signatures and docstrings: - def __call__(self, parent=None, **kwargs)...
Implement the Python class `TemplateInstance` described below. Class description: A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code. Method signatures and docstrings: - def __call__(self, parent=None, **kwargs)...
1544e7fb371b8f941cfa2fde682795e479380284
<|skeleton|> class TemplateInstance: """A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code.""" def __call__(self, parent=None, **kwargs): """Instantiate the list of items for the template. Paramet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TemplateInstance: """A class representing a template instantiation. Instances of this class are created by instances of Template. They should not be created directly by user code.""" def __call__(self, parent=None, **kwargs): """Instantiate the list of items for the template. Parameters ---------...
the_stack_v2_python_sparse
enaml/core/template.py
MatthieuDartiailh/enaml
train
26
c6a2e843cdec45985dca42d733c47ba5d87c8bb7
[ "user_id = request.user.pk\nqueryset = User.objects.filter(id=user_id)\nserializer = UserSerializer(queryset, many=True)\nreturn Response(serializer.data[0])", "user_id = request.user.pk\ntry:\n update_user = User.objects.get(id=user_id)\n update_user.name = request.data['name']\n update_user.nickname = ...
<|body_start_0|> user_id = request.user.pk queryset = User.objects.filter(id=user_id) serializer = UserSerializer(queryset, many=True) return Response(serializer.data[0]) <|end_body_0|> <|body_start_1|> user_id = request.user.pk try: update_user = User.object...
MyPageView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyPageView: def get(self, request): """나의 정보 api --- 결과: 나의정보(이메일,이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 반환""" <|body_0|> def patch(self, request): """회원수정 api --- 결과: 나의정보(이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 수정 후 저장""" <|body_1|> def delete(self, request):...
stack_v2_sparse_classes_36k_train_011649
4,479
no_license
[ { "docstring": "나의 정보 api --- 결과: 나의정보(이메일,이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 반환", "name": "get", "signature": "def get(self, request)" }, { "docstring": "회원수정 api --- 결과: 나의정보(이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 수정 후 저장", "name": "patch", "signature": "def patch(self, request)" }, ...
3
stack_v2_sparse_classes_30k_val_000972
Implement the Python class `MyPageView` described below. Class description: Implement the MyPageView class. Method signatures and docstrings: - def get(self, request): 나의 정보 api --- 결과: 나의정보(이메일,이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 반환 - def patch(self, request): 회원수정 api --- 결과: 나의정보(이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비...
Implement the Python class `MyPageView` described below. Class description: Implement the MyPageView class. Method signatures and docstrings: - def get(self, request): 나의 정보 api --- 결과: 나의정보(이메일,이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 반환 - def patch(self, request): 회원수정 api --- 결과: 나의정보(이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비...
54cbf4ee4e4a38e1e30722472715e89eb9fc84a2
<|skeleton|> class MyPageView: def get(self, request): """나의 정보 api --- 결과: 나의정보(이메일,이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 반환""" <|body_0|> def patch(self, request): """회원수정 api --- 결과: 나의정보(이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 수정 후 저장""" <|body_1|> def delete(self, request):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyPageView: def get(self, request): """나의 정보 api --- 결과: 나의정보(이메일,이름,닉네임,연락처), 관심정보(주량,최애술,최애안주,최애콤비) 반환""" user_id = request.user.pk queryset = User.objects.filter(id=user_id) serializer = UserSerializer(queryset, many=True) return Response(serializer.data[0]) def...
the_stack_v2_python_sparse
mypage/views.py
liketoy/honsuri-backend
train
0
e5101eb2823b74724e422188dda13b0345cf4723
[ "threading.Thread.__init__(self)\nself.daemon = True\nself.metaQueue = metaQueue\nself.commandsQueue = commandsQueue\nself.text = text", "self.commandsQueue.join()\nif self.text:\n common.ThreadSafePrint(self.text)\nself.metaQueue.task_done()" ]
<|body_start_0|> threading.Thread.__init__(self) self.daemon = True self.metaQueue = metaQueue self.commandsQueue = commandsQueue self.text = text <|end_body_0|> <|body_start_1|> self.commandsQueue.join() if self.text: common.ThreadSafePrint(self.text...
Ожидаем завершения обработки очереди команд и выводим заданный текст
SocialBotLauncherWaitingThread
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SocialBotLauncherWaitingThread: """Ожидаем завершения обработки очереди команд и выводим заданный текст""" def __init__(self, metaQueue, commandsQueue, text=None): """Инициализация""" <|body_0|> def run(self): """Главный метод""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_011650
7,553
no_license
[ { "docstring": "Инициализация", "name": "__init__", "signature": "def __init__(self, metaQueue, commandsQueue, text=None)" }, { "docstring": "Главный метод", "name": "run", "signature": "def run(self)" } ]
2
null
Implement the Python class `SocialBotLauncherWaitingThread` described below. Class description: Ожидаем завершения обработки очереди команд и выводим заданный текст Method signatures and docstrings: - def __init__(self, metaQueue, commandsQueue, text=None): Инициализация - def run(self): Главный метод
Implement the Python class `SocialBotLauncherWaitingThread` described below. Class description: Ожидаем завершения обработки очереди команд и выводим заданный текст Method signatures and docstrings: - def __init__(self, metaQueue, commandsQueue, text=None): Инициализация - def run(self): Главный метод <|skeleton|> c...
d2771bf04aa187dda6d468883a5a167237589369
<|skeleton|> class SocialBotLauncherWaitingThread: """Ожидаем завершения обработки очереди команд и выводим заданный текст""" def __init__(self, metaQueue, commandsQueue, text=None): """Инициализация""" <|body_0|> def run(self): """Главный метод""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SocialBotLauncherWaitingThread: """Ожидаем завершения обработки очереди команд и выводим заданный текст""" def __init__(self, metaQueue, commandsQueue, text=None): """Инициализация""" threading.Thread.__init__(self) self.daemon = True self.metaQueue = metaQueue sel...
the_stack_v2_python_sparse
stumbleupon/botlaunch.py
cash2one/doorscenter
train
0
2e15561c381df2c7cea833256eea7e0e80a66a3a
[ "print('Writing tokens into %s file: ' % filename)\nwith open(filename, 'w') as f:\n for word, idx in tok2idx.iteritems():\n if idx != len(tok2idx) - 1:\n f.write('{} {}\\n'.format(word, idx))\n else:\n f.write('{} {}'.format(word, idx))\nprint('\\t- Done: {} tokens.'.format(l...
<|body_start_0|> print('Writing tokens into %s file: ' % filename) with open(filename, 'w') as f: for word, idx in tok2idx.iteritems(): if idx != len(tok2idx) - 1: f.write('{} {}\n'.format(word, idx)) else: f.write('{} {...
RWfile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RWfile: def write_vocab(tok2idx, filename): """Writes a vocab to a file Writes one word per line. Args: vocab: iterable that yields word filename: path to vocab file Returns: write a word per line""" <|body_0|> def load_vocab(filename): """Loads vocab from a file Arg...
stack_v2_sparse_classes_36k_train_011651
9,000
no_license
[ { "docstring": "Writes a vocab to a file Writes one word per line. Args: vocab: iterable that yields word filename: path to vocab file Returns: write a word per line", "name": "write_vocab", "signature": "def write_vocab(tok2idx, filename)" }, { "docstring": "Loads vocab from a file Args: filena...
2
stack_v2_sparse_classes_30k_train_006931
Implement the Python class `RWfile` described below. Class description: Implement the RWfile class. Method signatures and docstrings: - def write_vocab(tok2idx, filename): Writes a vocab to a file Writes one word per line. Args: vocab: iterable that yields word filename: path to vocab file Returns: write a word per l...
Implement the Python class `RWfile` described below. Class description: Implement the RWfile class. Method signatures and docstrings: - def write_vocab(tok2idx, filename): Writes a vocab to a file Writes one word per line. Args: vocab: iterable that yields word filename: path to vocab file Returns: write a word per l...
b798e7b1286e043c5685aa8375022ee50f91024a
<|skeleton|> class RWfile: def write_vocab(tok2idx, filename): """Writes a vocab to a file Writes one word per line. Args: vocab: iterable that yields word filename: path to vocab file Returns: write a word per line""" <|body_0|> def load_vocab(filename): """Loads vocab from a file Arg...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RWfile: def write_vocab(tok2idx, filename): """Writes a vocab to a file Writes one word per line. Args: vocab: iterable that yields word filename: path to vocab file Returns: write a word per line""" print('Writing tokens into %s file: ' % filename) with open(filename, 'w') as f: ...
the_stack_v2_python_sparse
utils/other_utils.py
duytinvo/sequence_labeller
train
3
78ab31b9110b2db8827f9d727aa675481686baaf
[ "label = SettingSidebarLabel(text=name, uid=uid, menu=self)\nif len(self.buttons_layout.children) == 0:\n label.selected = True\nif self.buttons_layout is not None:\n self.buttons_layout.add_widget(label)", "for button in self.buttons_layout.children:\n if button.uid != self.selected_uid:\n button...
<|body_start_0|> label = SettingSidebarLabel(text=name, uid=uid, menu=self) if len(self.buttons_layout.children) == 0: label.selected = True if self.buttons_layout is not None: self.buttons_layout.add_widget(label) <|end_body_0|> <|body_start_1|> for button in se...
The menu used by :class:`InterfaceWithSidebar`. It provides a sidebar with an entry for each settings panel, which the user may click to select.
MenuSidebar
[ "LGPL-2.1-only", "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MenuSidebar: """The menu used by :class:`InterfaceWithSidebar`. It provides a sidebar with an entry for each settings panel, which the user may click to select.""" def add_item(self, name, uid): """This method is used to add new panels to the menu. :Parameters: `name`: The name (a st...
stack_v2_sparse_classes_36k_train_011652
45,276
permissive
[ { "docstring": "This method is used to add new panels to the menu. :Parameters: `name`: The name (a string) of the panel. It should be used to represent the panel in the menu. `uid`: The name (an int) of the panel. It should be used internally to represent the panel and used to set self.selected_uid when the pa...
2
null
Implement the Python class `MenuSidebar` described below. Class description: The menu used by :class:`InterfaceWithSidebar`. It provides a sidebar with an entry for each settings panel, which the user may click to select. Method signatures and docstrings: - def add_item(self, name, uid): This method is used to add ne...
Implement the Python class `MenuSidebar` described below. Class description: The menu used by :class:`InterfaceWithSidebar`. It provides a sidebar with an entry for each settings panel, which the user may click to select. Method signatures and docstrings: - def add_item(self, name, uid): This method is used to add ne...
ca1b918c656f23e401707388f25f4a63d9b8ae7d
<|skeleton|> class MenuSidebar: """The menu used by :class:`InterfaceWithSidebar`. It provides a sidebar with an entry for each settings panel, which the user may click to select.""" def add_item(self, name, uid): """This method is used to add new panels to the menu. :Parameters: `name`: The name (a st...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MenuSidebar: """The menu used by :class:`InterfaceWithSidebar`. It provides a sidebar with an entry for each settings panel, which the user may click to select.""" def add_item(self, name, uid): """This method is used to add new panels to the menu. :Parameters: `name`: The name (a string) of the ...
the_stack_v2_python_sparse
kivy/uix/settings.py
kivy/kivy
train
16,076
8c0d72ae7cc97b27b3868462300ef474434533dd
[ "discussion = Discussion.query.get(discussion_id)\nif discussion is None:\n return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found')\ndiscussion.view_count += 1\ndb.session.commit()\nreturn discussion", "discussion = Discussion.query.get(discussion_id)\nif discussion is None:\n return abort(HTT...
<|body_start_0|> discussion = Discussion.query.get(discussion_id) if discussion is None: return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found') discussion.view_count += 1 db.session.commit() return discussion <|end_body_0|> <|body_start_1|> dis...
DiscussionItem
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiscussionItem: def get(self, discussion_id): """Get discussion info * This action **increases the views count**""" <|body_0|> def patch(self, discussion_id): """Edit discussion info * User can edit **their discussion** (not frozen) * User with permission to **"edit ...
stack_v2_sparse_classes_36k_train_011653
3,433
permissive
[ { "docstring": "Get discussion info * This action **increases the views count**", "name": "get", "signature": "def get(self, discussion_id)" }, { "docstring": "Edit discussion info * User can edit **their discussion** (not frozen) * User with permission to **\"edit discussions\"** can edit the d...
3
null
Implement the Python class `DiscussionItem` described below. Class description: Implement the DiscussionItem class. Method signatures and docstrings: - def get(self, discussion_id): Get discussion info * This action **increases the views count** - def patch(self, discussion_id): Edit discussion info * User can edit *...
Implement the Python class `DiscussionItem` described below. Class description: Implement the DiscussionItem class. Method signatures and docstrings: - def get(self, discussion_id): Get discussion info * This action **increases the views count** - def patch(self, discussion_id): Edit discussion info * User can edit *...
dce87ffe395ae4bd08b47f28e07594e1889da819
<|skeleton|> class DiscussionItem: def get(self, discussion_id): """Get discussion info * This action **increases the views count**""" <|body_0|> def patch(self, discussion_id): """Edit discussion info * User can edit **their discussion** (not frozen) * User with permission to **"edit ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiscussionItem: def get(self, discussion_id): """Get discussion info * This action **increases the views count**""" discussion = Discussion.query.get(discussion_id) if discussion is None: return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found') discussi...
the_stack_v2_python_sparse
src/backend/app/api/public/discussions/discussion/discussion.py
aimanow/sft
train
0
5715f7d24162506d83ec7477e829ef9175953b85
[ "objFile = open(FileName, 'r')\nfor line in objFile:\n lstData = line.split(',')\n dicRow = {'Task': lstData[0].strip(), 'Priority': lstData[1].strip()}\n lstTable.append(dicRow)\nobjFile.close()\nreturn lstTable", "print('\\n Menu of Options\\n 1) Show current data\\n 2) Add a new item.\\n 3...
<|body_start_0|> objFile = open(FileName, 'r') for line in objFile: lstData = line.split(',') dicRow = {'Task': lstData[0].strip(), 'Priority': lstData[1].strip()} lstTable.append(dicRow) objFile.close() return lstTable <|end_body_0|> <|body_start_1|>...
Desc: A section of functions with in a class Functions: ReadFileData() menu() RawData() AddData() RemoveData() SaveData()
PresentationFunctions
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PresentationFunctions: """Desc: A section of functions with in a class Functions: ReadFileData() menu() RawData() AddData() RemoveData() SaveData()""" def ReadFileData(FileName): """Desc: This Function reads from a text file and writes it to a dictionary then appends it in a list obj...
stack_v2_sparse_classes_36k_train_011654
8,289
no_license
[ { "docstring": "Desc: This Function reads from a text file and writes it to a dictionary then appends it in a list objFile: Text file variable for the text file to be opened open: Opens the file at the directory listed in FileName FileName: Variable where input of directory needs to be line: Line in the text fi...
6
stack_v2_sparse_classes_30k_train_002338
Implement the Python class `PresentationFunctions` described below. Class description: Desc: A section of functions with in a class Functions: ReadFileData() menu() RawData() AddData() RemoveData() SaveData() Method signatures and docstrings: - def ReadFileData(FileName): Desc: This Function reads from a text file an...
Implement the Python class `PresentationFunctions` described below. Class description: Desc: A section of functions with in a class Functions: ReadFileData() menu() RawData() AddData() RemoveData() SaveData() Method signatures and docstrings: - def ReadFileData(FileName): Desc: This Function reads from a text file an...
209b826ea0d8c2fcdd82c3d8493b322ba00f2543
<|skeleton|> class PresentationFunctions: """Desc: A section of functions with in a class Functions: ReadFileData() menu() RawData() AddData() RemoveData() SaveData()""" def ReadFileData(FileName): """Desc: This Function reads from a text file and writes it to a dictionary then appends it in a list obj...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PresentationFunctions: """Desc: A section of functions with in a class Functions: ReadFileData() menu() RawData() AddData() RemoveData() SaveData()""" def ReadFileData(FileName): """Desc: This Function reads from a text file and writes it to a dictionary then appends it in a list objFile: Text fi...
the_stack_v2_python_sparse
Module06/Assignment06/Assignment06.py
gjkim44/Test
train
0
a0a5e946f0cd499d8594073f283852e5b5f6a194
[ "super().__init__()\nallowed = list(IMG_TRANSFORMS.keys())\nif not all([tr in allowed for tr in img_transforms]):\n raise ValueError(f'Wrong img transformation. Got: {img_transforms}. Allowed: {allowed}.')\nallowed = list(NORM_TRANSFORMS.keys()) + [None]\nif normalization not in allowed:\n raise ValueError(f'...
<|body_start_0|> super().__init__() allowed = list(IMG_TRANSFORMS.keys()) if not all([tr in allowed for tr in img_transforms]): raise ValueError(f'Wrong img transformation. Got: {img_transforms}. Allowed: {allowed}.') allowed = list(NORM_TRANSFORMS.keys()) + [None] if...
TrainDatasetBase
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TrainDatasetBase: def __init__(self, img_transforms: List[str], inst_transforms: List[str], normalization: str=None, return_inst: bool=False, return_binary: bool=True, return_type: bool=True, return_sem: bool=False, return_weight: bool=False, **kwargs) -> None: """Training dataset basecl...
stack_v2_sparse_classes_36k_train_011655
6,392
permissive
[ { "docstring": "Training dataset baseclass. Parameters ---------- img_transforms : List[str] A list containing all the transformations that are applied to the input images and corresponding masks. Allowed ones: \"blur\", \"non_spatial\", \"non_rigid\", \"rigid\", \"hue_sat\", \"random_crop\", \"center_crop\", \...
2
stack_v2_sparse_classes_30k_train_007785
Implement the Python class `TrainDatasetBase` described below. Class description: Implement the TrainDatasetBase class. Method signatures and docstrings: - def __init__(self, img_transforms: List[str], inst_transforms: List[str], normalization: str=None, return_inst: bool=False, return_binary: bool=True, return_type:...
Implement the Python class `TrainDatasetBase` described below. Class description: Implement the TrainDatasetBase class. Method signatures and docstrings: - def __init__(self, img_transforms: List[str], inst_transforms: List[str], normalization: str=None, return_inst: bool=False, return_binary: bool=True, return_type:...
7f79405012eb934b419bbdba8de23f35e840ca85
<|skeleton|> class TrainDatasetBase: def __init__(self, img_transforms: List[str], inst_transforms: List[str], normalization: str=None, return_inst: bool=False, return_binary: bool=True, return_type: bool=True, return_sem: bool=False, return_weight: bool=False, **kwargs) -> None: """Training dataset basecl...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TrainDatasetBase: def __init__(self, img_transforms: List[str], inst_transforms: List[str], normalization: str=None, return_inst: bool=False, return_binary: bool=True, return_type: bool=True, return_sem: bool=False, return_weight: bool=False, **kwargs) -> None: """Training dataset baseclass. Parameter...
the_stack_v2_python_sparse
cellseg_models_pytorch/datasets/_base_dataset.py
okunator/cellseg_models.pytorch
train
43
2698e7f76fb281f94e39a4d9fb828ca79de8c800
[ "self.head = None\nself.tail = None\nself.cnt = 0", "if index >= self.cnt or index < 0:\n return -1\ncurr = self.head\nfor i in range(index):\n curr = curr.next\nreturn curr.val", "node = ListNode(val)\nif self.head is None:\n self.head = node\n self.tail = node\nelse:\n self.head.prev = node\n ...
<|body_start_0|> self.head = None self.tail = None self.cnt = 0 <|end_body_0|> <|body_start_1|> if index >= self.cnt or index < 0: return -1 curr = self.head for i in range(index): curr = curr.next return curr.val <|end_body_1|> <|body_st...
MyLinkedList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyLinkedList: def __init__(self): """Initialize your data structure here.""" <|body_0|> def get(self, index): """Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: int :rtype: int""" <|body_1|> def add...
stack_v2_sparse_classes_36k_train_011656
5,409
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: int :rtype: int", "name": "get", "signature": "def get(s...
6
null
Implement the Python class `MyLinkedList` described below. Class description: Implement the MyLinkedList class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def get(self, index): Get the value of the index-th node in the linked list. If the index is invalid, return -1...
Implement the Python class `MyLinkedList` described below. Class description: Implement the MyLinkedList class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def get(self, index): Get the value of the index-th node in the linked list. If the index is invalid, return -1...
4d73e4c1f2017828ff2d36058819988146356abe
<|skeleton|> class MyLinkedList: def __init__(self): """Initialize your data structure here.""" <|body_0|> def get(self, index): """Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: int :rtype: int""" <|body_1|> def add...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyLinkedList: def __init__(self): """Initialize your data structure here.""" self.head = None self.tail = None self.cnt = 0 def get(self, index): """Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: int :rtype: ...
the_stack_v2_python_sparse
python/leetcode/system_design/707_design_linked_list.py
zchen0211/topcoder
train
0
5d3d9db9b20a368869d6dff5d8433bc27781b601
[ "self.url = url\nself.location = location\nself.geo = None\nself.produce = None", "if self.url.startswith('file:'):\n with open(self.url[6:]) as jsonfile:\n json_data = json.load(jsonfile)\nelse:\n response = magtag.network.fetch(self.url)\n if response.status_code == 200:\n json_data = res...
<|body_start_0|> self.url = url self.location = location self.geo = None self.produce = None <|end_body_0|> <|body_start_1|> if self.url.startswith('file:'): with open(self.url[6:]) as jsonfile: json_data = json.load(jsonfile) else: ...
Class to generate seasonal produce lists from server-based JSON data.
Produce
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Produce: """Class to generate seasonal produce lists from server-based JSON data.""" def __init__(self, url, location): """Constructor""" <|body_0|> def fetch(self, magtag=None): """Retrieves current seasonal produce data from server, does some deserializing and ...
stack_v2_sparse_classes_36k_train_011657
8,879
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, url, location)" }, { "docstring": "Retrieves current seasonal produce data from server, does some deserializing and processing for later filtering. This is currently tied to a MagTag object -- would prefer to func...
4
stack_v2_sparse_classes_30k_train_004392
Implement the Python class `Produce` described below. Class description: Class to generate seasonal produce lists from server-based JSON data. Method signatures and docstrings: - def __init__(self, url, location): Constructor - def fetch(self, magtag=None): Retrieves current seasonal produce data from server, does so...
Implement the Python class `Produce` described below. Class description: Class to generate seasonal produce lists from server-based JSON data. Method signatures and docstrings: - def __init__(self, url, location): Constructor - def fetch(self, magtag=None): Retrieves current seasonal produce data from server, does so...
5eaa7a15a437c533b89f359a25983e24bb6b5438
<|skeleton|> class Produce: """Class to generate seasonal produce lists from server-based JSON data.""" def __init__(self, url, location): """Constructor""" <|body_0|> def fetch(self, magtag=None): """Retrieves current seasonal produce data from server, does some deserializing and ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Produce: """Class to generate seasonal produce lists from server-based JSON data.""" def __init__(self, url, location): """Constructor""" self.url = url self.location = location self.geo = None self.produce = None def fetch(self, magtag=None): """Retri...
the_stack_v2_python_sparse
MagTag_Seasonal_Produce/produce.py
adafruit/Adafruit_Learning_System_Guides
train
937
ea0a5546d075ac8df98d2a3cf61382bf514b33df
[ "try:\n prepend = COLOR_CODES[color] if color else ''\n append = COLOR_CODES['reset'] if color else ''\nexcept KeyError:\n prepend = ''\n append = ''\nself.txt = prepend + txt + append\nself.newline = newline", "self.start = time()\nif not self.newline:\n print(self.txt + '... ', end='')\n sys.s...
<|body_start_0|> try: prepend = COLOR_CODES[color] if color else '' append = COLOR_CODES['reset'] if color else '' except KeyError: prepend = '' append = '' self.txt = prepend + txt + append self.newline = newline <|end_body_0|> <|body_sta...
Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something
Timer
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Timer: """Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something""" def __init__(self, txt: str, newline: bool=False, color: str=None): """Parameters ---------- txt: str Name of this timer. newline: bool Wheter you want prints to end with newlin...
stack_v2_sparse_classes_36k_train_011658
1,784
permissive
[ { "docstring": "Parameters ---------- txt: str Name of this timer. newline: bool Wheter you want prints to end with newlines. color: str One of 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', or 'white'.", "name": "__init__", "signature": "def __init__(self, txt: str, newline: bool=False, ...
3
stack_v2_sparse_classes_30k_train_007291
Implement the Python class `Timer` described below. Class description: Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something Method signatures and docstrings: - def __init__(self, txt: str, newline: bool=False, color: str=None): Parameters ---------- txt: str Name of this timer...
Implement the Python class `Timer` described below. Class description: Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something Method signatures and docstrings: - def __init__(self, txt: str, newline: bool=False, color: str=None): Parameters ---------- txt: str Name of this timer...
229456e0d4a9b73c0fd1069b062ca02c49dece00
<|skeleton|> class Timer: """Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something""" def __init__(self, txt: str, newline: bool=False, color: str=None): """Parameters ---------- txt: str Name of this timer. newline: bool Wheter you want prints to end with newlin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Timer: """Example of usage: with Timer("TimedFunction", newline=True, color='blue'): ... # do something""" def __init__(self, txt: str, newline: bool=False, color: str=None): """Parameters ---------- txt: str Name of this timer. newline: bool Wheter you want prints to end with newlines. color: st...
the_stack_v2_python_sparse
dwi_ml/experiment_utils/timer.py
scil-vital/dwi_ml
train
8
8fb7a4d6d30caf511926517ede2956aeb46c728c
[ "if not self.caller.location or not self.caller.location.allow_combat:\n self.msg(\"Can't fight here!\")\n raise InterruptCommand()", "self.args = args = self.args.strip()\nself.lhs, self.rhs = ('', '')\nif not args:\n return\nif ' on ' in args:\n lhs, rhs = args.split(' on ', 1)\nelse:\n lhs, *rhs...
<|body_start_0|> if not self.caller.location or not self.caller.location.allow_combat: self.msg("Can't fight here!") raise InterruptCommand() <|end_body_0|> <|body_start_1|> self.args = args = self.args.strip() self.lhs, self.rhs = ('', '') if not args: ...
Parent class for all twitch-combat commnads.
_BaseTwitchCombatCommand
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0", "CC-BY-3.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _BaseTwitchCombatCommand: """Parent class for all twitch-combat commnads.""" def at_pre_command(self): """Called before parsing.""" <|body_0|> def parse(self): """Handle parsing of most supported combat syntaxes (except stunts). <action> [<target>|<item>] or <act...
stack_v2_sparse_classes_36k_train_011659
18,175
permissive
[ { "docstring": "Called before parsing.", "name": "at_pre_command", "signature": "def at_pre_command(self)" }, { "docstring": "Handle parsing of most supported combat syntaxes (except stunts). <action> [<target>|<item>] or <action> <item> [on] <target> Use 'on' to differentiate if names/items hav...
3
stack_v2_sparse_classes_30k_train_000368
Implement the Python class `_BaseTwitchCombatCommand` described below. Class description: Parent class for all twitch-combat commnads. Method signatures and docstrings: - def at_pre_command(self): Called before parsing. - def parse(self): Handle parsing of most supported combat syntaxes (except stunts). <action> [<ta...
Implement the Python class `_BaseTwitchCombatCommand` described below. Class description: Parent class for all twitch-combat commnads. Method signatures and docstrings: - def at_pre_command(self): Called before parsing. - def parse(self): Handle parsing of most supported combat syntaxes (except stunts). <action> [<ta...
b3ca58b5c1325a3bf57051dfe23560a08d2947b7
<|skeleton|> class _BaseTwitchCombatCommand: """Parent class for all twitch-combat commnads.""" def at_pre_command(self): """Called before parsing.""" <|body_0|> def parse(self): """Handle parsing of most supported combat syntaxes (except stunts). <action> [<target>|<item>] or <act...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _BaseTwitchCombatCommand: """Parent class for all twitch-combat commnads.""" def at_pre_command(self): """Called before parsing.""" if not self.caller.location or not self.caller.location.allow_combat: self.msg("Can't fight here!") raise InterruptCommand() def...
the_stack_v2_python_sparse
evennia/contrib/tutorials/evadventure/combat_twitch.py
evennia/evennia
train
1,781
40c4fba5035b15fb6efa1167d4c6f28dea89cc35
[ "parser.add_argument('sink_name', help='The name for the sink.')\nparser.add_argument('destination', help='The destination must be a fully qualified BigQuery resource name. The destination can be for the same Google Cloud project or for a different Google Cloud project in the same organization.')\nparser.add_argume...
<|body_start_0|> parser.add_argument('sink_name', help='The name for the sink.') parser.add_argument('destination', help='The destination must be a fully qualified BigQuery resource name. The destination can be for the same Google Cloud project or for a different Google Cloud project in the same organiz...
Creates a sink.
Create
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Create: """Creates a sink.""" def Args(parser): """Register flags for this command.""" <|body_0|> def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this com...
stack_v2_sparse_classes_36k_train_011660
3,928
permissive
[ { "docstring": "Register flags for this command.", "name": "Args", "signature": "def Args(parser)" }, { "docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The created...
2
null
Implement the Python class `Create` described below. Class description: Creates a sink. Method signatures and docstrings: - def Args(parser): Register flags for this command. - def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were...
Implement the Python class `Create` described below. Class description: Creates a sink. Method signatures and docstrings: - def Args(parser): Register flags for this command. - def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were...
85bb264e273568b5a0408f733b403c56373e2508
<|skeleton|> class Create: """Creates a sink.""" def Args(parser): """Register flags for this command.""" <|body_0|> def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this com...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Create: """Creates a sink.""" def Args(parser): """Register flags for this command.""" parser.add_argument('sink_name', help='The name for the sink.') parser.add_argument('destination', help='The destination must be a fully qualified BigQuery resource name. The destination can be ...
the_stack_v2_python_sparse
google-cloud-sdk/lib/surface/trace/sinks/create.py
bopopescu/socialliteapp
train
0
343ce02f0094686a96dabe662cd1effc7ecf7c73
[ "row = len(M)\ncolumn = len(M[0])\nret = [[0] * column for x in range(row)]\nfor i in range(row):\n for j in range(column):\n ret[i][j] = self.get_num_of_num_filter(M, i, j, row, column)\nreturn ret", "ret = 0\nret_num = 0\nfor i in range(x - 1, x + 2):\n for j in range(y - 1, y + 2):\n if 0 <...
<|body_start_0|> row = len(M) column = len(M[0]) ret = [[0] * column for x in range(row)] for i in range(row): for j in range(column): ret[i][j] = self.get_num_of_num_filter(M, i, j, row, column) return ret <|end_body_0|> <|body_start_1|> ret ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def imageSmoother(self, M): """:type M: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def get_num_of_num_filter(self, image, x, y, row, column): """:type image:list[list[int]] :type x: int :type y: int :type row: int :type column: int :rtype : int""...
stack_v2_sparse_classes_36k_train_011661
2,520
no_license
[ { "docstring": ":type M: List[List[int]] :rtype: List[List[int]]", "name": "imageSmoother", "signature": "def imageSmoother(self, M)" }, { "docstring": ":type image:list[list[int]] :type x: int :type y: int :type row: int :type column: int :rtype : int", "name": "get_num_of_num_filter", ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def imageSmoother(self, M): :type M: List[List[int]] :rtype: List[List[int]] - def get_num_of_num_filter(self, image, x, y, row, column): :type image:list[list[int]] :type x: int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def imageSmoother(self, M): :type M: List[List[int]] :rtype: List[List[int]] - def get_num_of_num_filter(self, image, x, y, row, column): :type image:list[list[int]] :type x: int...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def imageSmoother(self, M): """:type M: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def get_num_of_num_filter(self, image, x, y, row, column): """:type image:list[list[int]] :type x: int :type y: int :type row: int :type column: int :rtype : int""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def imageSmoother(self, M): """:type M: List[List[int]] :rtype: List[List[int]]""" row = len(M) column = len(M[0]) ret = [[0] * column for x in range(row)] for i in range(row): for j in range(column): ret[i][j] = self.get_num_of_num...
the_stack_v2_python_sparse
python/leetcode/661_Image_Smoother.py
bobcaoge/my-code
train
0
62da1c75cfc3b08a5c306e4bee070e1e3de30cf2
[ "self.snake = collections.deque([(0, 0)])\nself.snake_set = {(0, 0): 1}\nself.width = width\nself.height = height\nself.food = food\nself.food_index = 0\nself.movement = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}", "newHead = (self.snake[0][0] + self.movement[direction][0], self.snake[0][1] + self.mov...
<|body_start_0|> self.snake = collections.deque([(0, 0)]) self.snake_set = {(0, 0): 1} self.width = width self.height = height self.food = food self.food_index = 0 self.movement = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]} <|end_body_0|> <|body_start_...
SnakeGame
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t...
stack_v2_sparse_classes_36k_train_011662
15,245
no_license
[ { "docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].", "name": "__init__", "signature": "def __init__(self, widt...
2
stack_v2_sparse_classes_30k_train_002236
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -...
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -...
035ef08434fa1ca781a6fb2f9eed3538b7d20c02
<|skeleton|> class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a...
the_stack_v2_python_sparse
leetcode_python/Design/design-snake-game.py
yennanliu/CS_basics
train
64
381789bae6d2d87363a5e0c651b765565a2019c1
[ "self.folder_base = folder\nsuper().__init__(folder, image_extension='JPG')\nif not self.explicit_extrinsics_paths:\n self.explicit_extrinsics_paths = self.__generate_extrinsics_from_reconstruction()", "reconstruction_path = os.path.join(self.folder_base, 'reconstruction', 'data.mat')\nextrinsics_path_template...
<|body_start_0|> self.folder_base = folder super().__init__(folder, image_extension='JPG') if not self.explicit_extrinsics_paths: self.explicit_extrinsics_paths = self.__generate_extrinsics_from_reconstruction() <|end_body_0|> <|body_start_1|> reconstruction_path = os.path.j...
Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif data will be used.
LundDatasetLoader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LundDatasetLoader: """Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif data will be used.""" def __init__...
stack_v2_sparse_classes_36k_train_011663
2,397
permissive
[ { "docstring": "Initialize object to load image data from a specified folder on disk Args: folder: the base folder for a given scene.", "name": "__init__", "signature": "def __init__(self, folder: str) -> None" }, { "docstring": "Extract extrinsics from mat file and stores them as numpy arrays. ...
2
stack_v2_sparse_classes_30k_train_017014
Implement the Python class `LundDatasetLoader` described below. Class description: Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif ...
Implement the Python class `LundDatasetLoader` described below. Class description: Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif ...
245fb4d90bf6d63d45af8f77a4debfe46ea52ff0
<|skeleton|> class LundDatasetLoader: """Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif data will be used.""" def __init__...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LundDatasetLoader: """Simple loader class that reads from a folder on disk. Folder layout structure: - RGB Images: images/ - Extrinsics data (optional): extrinsics/ - numpy array with the same name as images If explicit intrinsics are not provided, the exif data will be used.""" def __init__(self, folder...
the_stack_v2_python_sparse
gtsfm/loader/lund_dataset_loader.py
asa/gtsfm
train
0
36f4eddd7c3ffbb7af96c4c5fde322ae25efe9f7
[ "super().__init__(add_help=False, **kwargs)\nif config_options:\n self.add_argument('-c', '--show-config', action='store_true', default=False, dest='show_config', help='Show the configuration parameters.')\n self.add_argument('-a', '--attributes-level', default=0, type=int, dest='attributes_level', help='Set ...
<|body_start_0|> super().__init__(add_help=False, **kwargs) if config_options: self.add_argument('-c', '--show-config', action='store_true', default=False, dest='show_config', help='Show the configuration parameters.') self.add_argument('-a', '--attributes-level', default=0, type...
The base class for the option parser.
ArgumentParserBase
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArgumentParserBase: """The base class for the option parser.""" def __init__(self, config_options=False, sort_options=False, **kwargs): """Initialise the class. :param config_options: True/False show configuration options :param sort_options: True/False show argument sorting options"...
stack_v2_sparse_classes_36k_train_011664
39,454
permissive
[ { "docstring": "Initialise the class. :param config_options: True/False show configuration options :param sort_options: True/False show argument sorting options", "name": "__init__", "signature": "def __init__(self, config_options=False, sort_options=False, **kwargs)" }, { "docstring": "Parse th...
3
stack_v2_sparse_classes_30k_train_016702
Implement the Python class `ArgumentParserBase` described below. Class description: The base class for the option parser. Method signatures and docstrings: - def __init__(self, config_options=False, sort_options=False, **kwargs): Initialise the class. :param config_options: True/False show configuration options :para...
Implement the Python class `ArgumentParserBase` described below. Class description: The base class for the option parser. Method signatures and docstrings: - def __init__(self, config_options=False, sort_options=False, **kwargs): Initialise the class. :param config_options: True/False show configuration options :para...
88bf7f7c5ac44defc046ebf0719cde748092cfff
<|skeleton|> class ArgumentParserBase: """The base class for the option parser.""" def __init__(self, config_options=False, sort_options=False, **kwargs): """Initialise the class. :param config_options: True/False show configuration options :param sort_options: True/False show argument sorting options"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ArgumentParserBase: """The base class for the option parser.""" def __init__(self, config_options=False, sort_options=False, **kwargs): """Initialise the class. :param config_options: True/False show configuration options :param sort_options: True/False show argument sorting options""" su...
the_stack_v2_python_sparse
src/dials/util/options.py
dials/dials
train
71
e08c8f6be26f584a8d3174e4862ed7a88d85b385
[ "try:\n logger.info('服务器地址为空的rsever注册测试')\n self.login()\n self.register_rserver('', readconfig.name, readconfig.pwd, readconfig.machineName)\n sleep(3)\n self.assertEqual(self.error_hint(), u'服务器地址不能为空!')\n WebDriverWait(self.driver, 5, 0.5).until(ES.alert_is_present())\n sleep(2)\n self.ac...
<|body_start_0|> try: logger.info('服务器地址为空的rsever注册测试') self.login() self.register_rserver('', readconfig.name, readconfig.pwd, readconfig.machineName) sleep(3) self.assertEqual(self.error_hint(), u'服务器地址不能为空!') WebDriverWait(self.driver, 5...
快速配置,rserver注册相关测试
ConfigureRegisterTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigureRegisterTest: """快速配置,rserver注册相关测试""" def test_register1(self): """服务器地址为空的rsever注册测试""" <|body_0|> def test_register2(self): """服务账号为空的rsever注册测试""" <|body_1|> def test_register3(self): """服务昵称为空的rsever注册测试""" <|body_2|> ...
stack_v2_sparse_classes_36k_train_011665
4,945
no_license
[ { "docstring": "服务器地址为空的rsever注册测试", "name": "test_register1", "signature": "def test_register1(self)" }, { "docstring": "服务账号为空的rsever注册测试", "name": "test_register2", "signature": "def test_register2(self)" }, { "docstring": "服务昵称为空的rsever注册测试", "name": "test_register3", ...
6
stack_v2_sparse_classes_30k_train_000147
Implement the Python class `ConfigureRegisterTest` described below. Class description: 快速配置,rserver注册相关测试 Method signatures and docstrings: - def test_register1(self): 服务器地址为空的rsever注册测试 - def test_register2(self): 服务账号为空的rsever注册测试 - def test_register3(self): 服务昵称为空的rsever注册测试 - def test_register4(self): 非白名单的用户注册 -...
Implement the Python class `ConfigureRegisterTest` described below. Class description: 快速配置,rserver注册相关测试 Method signatures and docstrings: - def test_register1(self): 服务器地址为空的rsever注册测试 - def test_register2(self): 服务账号为空的rsever注册测试 - def test_register3(self): 服务昵称为空的rsever注册测试 - def test_register4(self): 非白名单的用户注册 -...
fd552eeb47fd4838c2c5caef4deea7480ab75ce9
<|skeleton|> class ConfigureRegisterTest: """快速配置,rserver注册相关测试""" def test_register1(self): """服务器地址为空的rsever注册测试""" <|body_0|> def test_register2(self): """服务账号为空的rsever注册测试""" <|body_1|> def test_register3(self): """服务昵称为空的rsever注册测试""" <|body_2|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigureRegisterTest: """快速配置,rserver注册相关测试""" def test_register1(self): """服务器地址为空的rsever注册测试""" try: logger.info('服务器地址为空的rsever注册测试') self.login() self.register_rserver('', readconfig.name, readconfig.pwd, readconfig.machineName) sleep(3...
the_stack_v2_python_sparse
test_case/A003_configure_register_test.py
luhuifnag/AVA_UIauto_test
train
0
bfdd49cd90a026198a67008d7f3c9a5d10e9bb98
[ "import itertools\nfor p in itertools.permutations(pieces):\n l = list(chain.from_iterable(p))\n if l == arr:\n return True\nreturn False", "mp = {x[0]: x for x in pieces}\nret = []\nfor num in arr:\n ret += mp.get(num, [])\nreturn ret == arr" ]
<|body_start_0|> import itertools for p in itertools.permutations(pieces): l = list(chain.from_iterable(p)) if l == arr: return True return False <|end_body_0|> <|body_start_1|> mp = {x[0]: x for x in pieces} ret = [] for num in ar...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canFormArray_TLE(self, arr, pieces): """:type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all subset and compare with arr. general solution but TLE.""" <|body_0|> def canFormArra...
stack_v2_sparse_classes_36k_train_011666
2,422
no_license
[ { "docstring": ":type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all subset and compare with arr. general solution but TLE.", "name": "canFormArray_TLE", "signature": "def canFormArray_TLE(self, arr, pieces)" }, { ...
2
stack_v2_sparse_classes_30k_train_010427
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canFormArray_TLE(self, arr, pieces): :type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canFormArray_TLE(self, arr, pieces): :type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all ...
02726da394971ef02616a038dadc126c6ff260de
<|skeleton|> class Solution: def canFormArray_TLE(self, arr, pieces): """:type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all subset and compare with arr. general solution but TLE.""" <|body_0|> def canFormArra...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canFormArray_TLE(self, arr, pieces): """:type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all subset and compare with arr. general solution but TLE.""" import itertools for p in itertools.p...
the_stack_v2_python_sparse
N1640_CheckArrayFormationThroughConcatenation.py
zerghua/leetcode-python
train
2
0569be77a6d67aa51f731f17f6fcd0ae387e6eb9
[ "self.server = server\nself.NN = NN\nself.op = optimizer\nself.criterion = criterion\nnum_servers = server.num_servers\nnum_customers = len(server.customer_rewards)\nself.state_to_basis = {}\nfor free_servers in range(num_servers + 1):\n for customer in range(num_customers):\n basis = torch.zeros((num_ser...
<|body_start_0|> self.server = server self.NN = NN self.op = optimizer self.criterion = criterion num_servers = server.num_servers num_customers = len(server.customer_rewards) self.state_to_basis = {} for free_servers in range(num_servers + 1): ...
Agent object that uses differential semi-gradient SARSA to find optimal policy.
Agent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Agent: """Agent object that uses differential semi-gradient SARSA to find optimal policy.""" def __init__(self, server, NN, optimizer, criterion): """Initializes the agent. @type server: ServerQueue Server queue environment. @type NN: NeuralNet Neural network for computing the state-...
stack_v2_sparse_classes_36k_train_011667
8,549
permissive
[ { "docstring": "Initializes the agent. @type server: ServerQueue Server queue environment. @type NN: NeuralNet Neural network for computing the state-action values @type optimizer: optimizer Optimizer from the torch.optim module. @type scheduler: lr_scheduler Learning rate scheduler from the torch.optim module....
5
stack_v2_sparse_classes_30k_test_000165
Implement the Python class `Agent` described below. Class description: Agent object that uses differential semi-gradient SARSA to find optimal policy. Method signatures and docstrings: - def __init__(self, server, NN, optimizer, criterion): Initializes the agent. @type server: ServerQueue Server queue environment. @t...
Implement the Python class `Agent` described below. Class description: Agent object that uses differential semi-gradient SARSA to find optimal policy. Method signatures and docstrings: - def __init__(self, server, NN, optimizer, criterion): Initializes the agent. @type server: ServerQueue Server queue environment. @t...
127d3fe10fe5774be7f8db3b00f6737f3eed363d
<|skeleton|> class Agent: """Agent object that uses differential semi-gradient SARSA to find optimal policy.""" def __init__(self, server, NN, optimizer, criterion): """Initializes the agent. @type server: ServerQueue Server queue environment. @type NN: NeuralNet Neural network for computing the state-...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Agent: """Agent object that uses differential semi-gradient SARSA to find optimal policy.""" def __init__(self, server, NN, optimizer, criterion): """Initializes the agent. @type server: ServerQueue Server queue environment. @type NN: NeuralNet Neural network for computing the state-action values...
the_stack_v2_python_sparse
Ch10/access_control/server_queue.py
lolcharles2/Reinforcement_learning_book_implementations
train
0
13bfc82205060e869be1b0269cb60790f7616558
[ "page = request.args.get('page', 1, type=int)\nper_page = request.args.get('per_page', 10, type=int)\norderBy = request.args.get('orderBy', '', type=str)\ndesc = request.args.get('desc', 'False', type=str)\ntopicTitle = request.args.get('topicTitle', '', type=str)\nreportId = request.args.get('reportId', '', type=i...
<|body_start_0|> page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', 10, type=int) orderBy = request.args.get('orderBy', '', type=str) desc = request.args.get('desc', 'False', type=str) topicTitle = request.args.get('topicTitle', '', type=str) ...
SimilarityAlgorithmsController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimilarityAlgorithmsController: def get(self): """Returns a page of tweets with scores""" <|body_0|> def post(self): """Calculates the similarity between tweets of a topic and a report using various algorithms""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_011668
3,460
no_license
[ { "docstring": "Returns a page of tweets with scores", "name": "get", "signature": "def get(self)" }, { "docstring": "Calculates the similarity between tweets of a topic and a report using various algorithms", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_007129
Implement the Python class `SimilarityAlgorithmsController` described below. Class description: Implement the SimilarityAlgorithmsController class. Method signatures and docstrings: - def get(self): Returns a page of tweets with scores - def post(self): Calculates the similarity between tweets of a topic and a report...
Implement the Python class `SimilarityAlgorithmsController` described below. Class description: Implement the SimilarityAlgorithmsController class. Method signatures and docstrings: - def get(self): Returns a page of tweets with scores - def post(self): Calculates the similarity between tweets of a topic and a report...
e8d5fd562724df1ad26b90d0c731e133b052df24
<|skeleton|> class SimilarityAlgorithmsController: def get(self): """Returns a page of tweets with scores""" <|body_0|> def post(self): """Calculates the similarity between tweets of a topic and a report using various algorithms""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimilarityAlgorithmsController: def get(self): """Returns a page of tweets with scores""" page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', 10, type=int) orderBy = request.args.get('orderBy', '', type=str) desc = request.args.get('desc...
the_stack_v2_python_sparse
app/main/controllers/similarityAlgorithmsController.py
ProyectoFinal2020/TweetAnalyzer-Backend
train
0
46b1c23f2c736425f31da4a8156aba803b8a11eb
[ "super().__init__(fmt, datefmt, style)\nself.enable_color = enable_color\nself.name_colors = {}", "rec = logging.getLogRecordFactory()(level=record.levelno, **record.__dict__)\ntry:\n rec.message = rec.getMessage()\nexcept Exception as e:\n rec.message = 'Bad message (%r): %r' % (e, rec.__dict__)\nrec.ascti...
<|body_start_0|> super().__init__(fmt, datefmt, style) self.enable_color = enable_color self.name_colors = {} <|end_body_0|> <|body_start_1|> rec = logging.getLogRecordFactory()(level=record.levelno, **record.__dict__) try: rec.message = rec.getMessage() exce...
Log formatter for Python logging module. This formatter assigns a color to individual logger names. Note that it may overlap because the number of defined colors is only 6. The following additional variables are available n a format string to colorize the output. * ``time_color`` * ``time_color_end`` * ``name_color`` *...
LogFormatter
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogFormatter: """Log formatter for Python logging module. This formatter assigns a color to individual logger names. Note that it may overlap because the number of defined colors is only 6. The following additional variables are available n a format string to colorize the output. * ``time_color``...
stack_v2_sparse_classes_36k_train_011669
6,001
permissive
[ { "docstring": "Initialize the formatter with specified format strings. Parameters ---------- fmt : str Format string. datefmt : str Date format. style : str Style parameter. enable_color : bool Whether to enable color output.", "name": "__init__", "signature": "def __init__(self, fmt=None, datefmt=None...
4
null
Implement the Python class `LogFormatter` described below. Class description: Log formatter for Python logging module. This formatter assigns a color to individual logger names. Note that it may overlap because the number of defined colors is only 6. The following additional variables are available n a format string t...
Implement the Python class `LogFormatter` described below. Class description: Log formatter for Python logging module. This formatter assigns a color to individual logger names. Note that it may overlap because the number of defined colors is only 6. The following additional variables are available n a format string t...
ab8352716c973eef9c224ff80d0dd66b95c606a3
<|skeleton|> class LogFormatter: """Log formatter for Python logging module. This formatter assigns a color to individual logger names. Note that it may overlap because the number of defined colors is only 6. The following additional variables are available n a format string to colorize the output. * ``time_color``...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogFormatter: """Log formatter for Python logging module. This formatter assigns a color to individual logger names. Note that it may overlap because the number of defined colors is only 6. The following additional variables are available n a format string to colorize the output. * ``time_color`` * ``time_col...
the_stack_v2_python_sparse
jaffle/logging.py
daniel-covelli/jaffle
train
0
a2fa9eceb408a52e7cf5872cb1865cf8e7f95a64
[ "if not node:\n return (True, 0, MAX_INT, MIN_INT)\nif node.left is None and node.right is None:\n self.maxTotal = max(self.maxTotal, 1)\n return (True, 1, node.val, node.val)\nisBSTLeft, totalLeft, minLeft, maxLeft = self.postorder(node.left)\nisBSTRight, totalRight, minRight, maxRight = self.postorder(no...
<|body_start_0|> if not node: return (True, 0, MAX_INT, MIN_INT) if node.left is None and node.right is None: self.maxTotal = max(self.maxTotal, 1) return (True, 1, node.val, node.val) isBSTLeft, totalLeft, minLeft, maxLeft = self.postorder(node.left) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def postorder(self, node: TreeNode) -> Tuple[bool, int, int, int]: """@return: the status of a tree with node as root 1. Whether this tree is BST 2. Total node count 3. The minimum node value 4. The maximum node value""" <|body_0|> def largestBSTSubtree(self, root:...
stack_v2_sparse_classes_36k_train_011670
2,207
no_license
[ { "docstring": "@return: the status of a tree with node as root 1. Whether this tree is BST 2. Total node count 3. The minimum node value 4. The maximum node value", "name": "postorder", "signature": "def postorder(self, node: TreeNode) -> Tuple[bool, int, int, int]" }, { "docstring": "Same ques...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorder(self, node: TreeNode) -> Tuple[bool, int, int, int]: @return: the status of a tree with node as root 1. Whether this tree is BST 2. Total node count 3. The minimum ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorder(self, node: TreeNode) -> Tuple[bool, int, int, int]: @return: the status of a tree with node as root 1. Whether this tree is BST 2. Total node count 3. The minimum ...
ad2f5bd0aec3d2c2c77b7c18627c1dd8fe8c0653
<|skeleton|> class Solution: def postorder(self, node: TreeNode) -> Tuple[bool, int, int, int]: """@return: the status of a tree with node as root 1. Whether this tree is BST 2. Total node count 3. The minimum node value 4. The maximum node value""" <|body_0|> def largestBSTSubtree(self, root:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def postorder(self, node: TreeNode) -> Tuple[bool, int, int, int]: """@return: the status of a tree with node as root 1. Whether this tree is BST 2. Total node count 3. The minimum node value 4. The maximum node value""" if not node: return (True, 0, MAX_INT, MIN_INT) ...
the_stack_v2_python_sparse
333 Largest BST Subtree.py
jz33/LeetCodeSolutions
train
8
a52197b59eda44c3b937a925affb83433f628d98
[ "super().__init__()\nKp = diagonalize_gain(to_tensor(Kp))\nKd = diagonalize_gain(to_tensor(Kd))\nassert Kp.shape == torch.Size([6, 6])\nassert Kd.shape == torch.Size([6, 6])\nself.Kp = torch.nn.Parameter(Kp)\nself.Kd = torch.nn.Parameter(Kd)\nself.robot_model = robot_model", "ee_pos_current, ee_quat_current = sel...
<|body_start_0|> super().__init__() Kp = diagonalize_gain(to_tensor(Kp)) Kd = diagonalize_gain(to_tensor(Kd)) assert Kp.shape == torch.Size([6, 6]) assert Kd.shape == torch.Size([6, 6]) self.Kp = torch.nn.Parameter(Kp) self.Kd = torch.nn.Parameter(Kd) self...
PD feedback control in operational space. Errors are computed in Cartesian space, then projected back into joint space to compute joint torques. nA is the action dimension and N is the number of degrees of freedom Module parameters: - Kp: P gain matrix of shape (nA, N) - Kd: D gain matrix of shape (nA, N)
OperationalSpacePD
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OperationalSpacePD: """PD feedback control in operational space. Errors are computed in Cartesian space, then projected back into joint space to compute joint torques. nA is the action dimension and N is the number of degrees of freedom Module parameters: - Kp: P gain matrix of shape (nA, N) - Kd...
stack_v2_sparse_classes_36k_train_011671
9,060
permissive
[ { "docstring": "Args: Kp: P gain matrix of shape (nA, N) or shape (N,) representing a N-by-N diagonal matrix (if nA=N) Kd: D gain matrix of shape (nA, N) or shape (N,) representing a N-by-N diagonal matrix (if nA=N) robot_model: A valid robot model module from torchcontrol.models", "name": "__init__", "...
2
stack_v2_sparse_classes_30k_train_009868
Implement the Python class `OperationalSpacePD` described below. Class description: PD feedback control in operational space. Errors are computed in Cartesian space, then projected back into joint space to compute joint torques. nA is the action dimension and N is the number of degrees of freedom Module parameters: - ...
Implement the Python class `OperationalSpacePD` described below. Class description: PD feedback control in operational space. Errors are computed in Cartesian space, then projected back into joint space to compute joint torques. nA is the action dimension and N is the number of degrees of freedom Module parameters: - ...
1b2ea8528d4fb9ad72cec9c766be4cbdbdf76f18
<|skeleton|> class OperationalSpacePD: """PD feedback control in operational space. Errors are computed in Cartesian space, then projected back into joint space to compute joint torques. nA is the action dimension and N is the number of degrees of freedom Module parameters: - Kp: P gain matrix of shape (nA, N) - Kd...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OperationalSpacePD: """PD feedback control in operational space. Errors are computed in Cartesian space, then projected back into joint space to compute joint torques. nA is the action dimension and N is the number of degrees of freedom Module parameters: - Kp: P gain matrix of shape (nA, N) - Kd: D gain matr...
the_stack_v2_python_sparse
polymetis/python/torchcontrol/modules/feedback.py
facebookresearch/polymetis
train
44
9b09f6925ad2fda7f3f4ebbfd3f22dc9f9432627
[ "super(TenorNetworkModule, self).__init__()\nself.setup_weights()\nself.init_parameters()", "self.weight_matrix = torch.nn.Parameter(torch.Tensor(256, 256, 16))\nself.weight_matrix_block = torch.nn.Parameter(torch.Tensor(16, 2 * 256))\nself.bias = torch.nn.Parameter(torch.Tensor(16, 1))", "torch.nn.init.xavier_...
<|body_start_0|> super(TenorNetworkModule, self).__init__() self.setup_weights() self.init_parameters() <|end_body_0|> <|body_start_1|> self.weight_matrix = torch.nn.Parameter(torch.Tensor(256, 256, 16)) self.weight_matrix_block = torch.nn.Parameter(torch.Tensor(16, 2 * 256)) ...
SimGNN Tensor Network module to calculate similarity vector.
TenorNetworkModule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TenorNetworkModule: """SimGNN Tensor Network module to calculate similarity vector.""" def __init__(self): """:param args: Arguments object.""" <|body_0|> def setup_weights(self): """Defining weights.""" <|body_1|> def init_parameters(self): ...
stack_v2_sparse_classes_36k_train_011672
4,926
no_license
[ { "docstring": ":param args: Arguments object.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Defining weights.", "name": "setup_weights", "signature": "def setup_weights(self)" }, { "docstring": "Initializing weights.", "name": "init_parameters", ...
4
stack_v2_sparse_classes_30k_train_021353
Implement the Python class `TenorNetworkModule` described below. Class description: SimGNN Tensor Network module to calculate similarity vector. Method signatures and docstrings: - def __init__(self): :param args: Arguments object. - def setup_weights(self): Defining weights. - def init_parameters(self): Initializing...
Implement the Python class `TenorNetworkModule` described below. Class description: SimGNN Tensor Network module to calculate similarity vector. Method signatures and docstrings: - def __init__(self): :param args: Arguments object. - def setup_weights(self): Defining weights. - def init_parameters(self): Initializing...
96b3cb5b392f08924ac0fd6df5eea2b6f680c1c8
<|skeleton|> class TenorNetworkModule: """SimGNN Tensor Network module to calculate similarity vector.""" def __init__(self): """:param args: Arguments object.""" <|body_0|> def setup_weights(self): """Defining weights.""" <|body_1|> def init_parameters(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TenorNetworkModule: """SimGNN Tensor Network module to calculate similarity vector.""" def __init__(self): """:param args: Arguments object.""" super(TenorNetworkModule, self).__init__() self.setup_weights() self.init_parameters() def setup_weights(self): """D...
the_stack_v2_python_sparse
models/graph_similarity.py
GPNU-Frank/ABN_FER
train
1
c188c7d5519946c0894cc0465caf51a6f79290c6
[ "def bivariate(data):\n return holoviews.Bivariate(data, *args, **kwargs)\ndefault_bokeh_opts = {'height': 350, 'width': 400, 'tools': ['hover'], 'shared_axes': False}\ndefault_mpl_opts = {}\nmpl_opts, bokeh_opts = self.update_default_opts(default_mpl_opts, mpl_opts, default_bokeh_opts, bokeh_opts)\nsuper(Bivari...
<|body_start_0|> def bivariate(data): return holoviews.Bivariate(data, *args, **kwargs) default_bokeh_opts = {'height': 350, 'width': 400, 'tools': ['hover'], 'shared_axes': False} default_mpl_opts = {} mpl_opts, bokeh_opts = self.update_default_opts(default_mpl_opts, mpl_opt...
Create a ``holoviews.Bivariate`` plot that plots steaming data. The streaming process is handled using a :class:`Pipe`.
Bivariate
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bivariate: """Create a ``holoviews.Bivariate`` plot that plots steaming data. The streaming process is handled using a :class:`Pipe`.""" def __init__(self, data=None, bokeh_opts=None, mpl_opts=None, *args, **kwargs): """Initialize a :class:`Bivariate`. Args: data: Passed to ``holovie...
stack_v2_sparse_classes_36k_train_011673
22,669
permissive
[ { "docstring": "Initialize a :class:`Bivariate`. Args: data: Passed to ``holoviews.Bivariate``. bokeh_opts: Default options for the plot when rendered using the \"bokeh\" backend. mpl_opts: Default options for the plot when rendered using the \"matplotlib\" backend. *args: Passed to ``holoviews.Bivariate``. **k...
2
stack_v2_sparse_classes_30k_train_005343
Implement the Python class `Bivariate` described below. Class description: Create a ``holoviews.Bivariate`` plot that plots steaming data. The streaming process is handled using a :class:`Pipe`. Method signatures and docstrings: - def __init__(self, data=None, bokeh_opts=None, mpl_opts=None, *args, **kwargs): Initial...
Implement the Python class `Bivariate` described below. Class description: Create a ``holoviews.Bivariate`` plot that plots steaming data. The streaming process is handled using a :class:`Pipe`. Method signatures and docstrings: - def __init__(self, data=None, bokeh_opts=None, mpl_opts=None, *args, **kwargs): Initial...
5e69c50e5b220859d65406d803086406b50a8e78
<|skeleton|> class Bivariate: """Create a ``holoviews.Bivariate`` plot that plots steaming data. The streaming process is handled using a :class:`Pipe`.""" def __init__(self, data=None, bokeh_opts=None, mpl_opts=None, *args, **kwargs): """Initialize a :class:`Bivariate`. Args: data: Passed to ``holovie...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Bivariate: """Create a ``holoviews.Bivariate`` plot that plots steaming data. The streaming process is handled using a :class:`Pipe`.""" def __init__(self, data=None, bokeh_opts=None, mpl_opts=None, *args, **kwargs): """Initialize a :class:`Bivariate`. Args: data: Passed to ``holoviews.Bivariate`...
the_stack_v2_python_sparse
fragile/dataviz/streaming.py
sergio-hcsoft/fragile-1
train
0
e3556fcfbfb2469184e9c829f6ef1cf18b030162
[ "self.delay = delay\nself.ticks = ticks\nself.tick_count = 0\nself.timer = None\nself.done = False", "if not self.timer:\n self.timer = now\n return True\nelif not self.done and now - self.timer > self.delay:\n self.tick_count += 1\n self.timer = now\n if self.ticks != -1 and self.tick_count >= sel...
<|body_start_0|> self.delay = delay self.ticks = ticks self.tick_count = 0 self.timer = None self.done = False <|end_body_0|> <|body_start_1|> if not self.timer: self.timer = now return True elif not self.done and now - self.timer > self.d...
A very simple timer for events that are not directly tied to animation.
Timer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Timer: """A very simple timer for events that are not directly tied to animation.""" def __init__(self, delay, ticks=-1): """The delay is given in milliseconds; ticks is the number of ticks the timer will make before flipping self.done to True. Pass a value of -1 to bypass this.""" ...
stack_v2_sparse_classes_36k_train_011674
11,413
no_license
[ { "docstring": "The delay is given in milliseconds; ticks is the number of ticks the timer will make before flipping self.done to True. Pass a value of -1 to bypass this.", "name": "__init__", "signature": "def __init__(self, delay, ticks=-1)" }, { "docstring": "Returns true if a tick worth of t...
2
null
Implement the Python class `Timer` described below. Class description: A very simple timer for events that are not directly tied to animation. Method signatures and docstrings: - def __init__(self, delay, ticks=-1): The delay is given in milliseconds; ticks is the number of ticks the timer will make before flipping s...
Implement the Python class `Timer` described below. Class description: A very simple timer for events that are not directly tied to animation. Method signatures and docstrings: - def __init__(self, delay, ticks=-1): The delay is given in milliseconds; ticks is the number of ticks the timer will make before flipping s...
cee7e4b5dc28c57a6c912852827652b5f51005ae
<|skeleton|> class Timer: """A very simple timer for events that are not directly tied to animation.""" def __init__(self, delay, ticks=-1): """The delay is given in milliseconds; ticks is the number of ticks the timer will make before flipping self.done to True. Pass a value of -1 to bypass this.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Timer: """A very simple timer for events that are not directly tied to animation.""" def __init__(self, delay, ticks=-1): """The delay is given in milliseconds; ticks is the number of ticks the timer will make before flipping self.done to True. Pass a value of -1 to bypass this.""" self.d...
the_stack_v2_python_sparse
IE_games_3/cabbages-and-kings-master/data/tools.py
IndexErrorCoders/PygamesCompilation
train
2
c01ddf1193a1d44a0a89c05efc524b313f967a8b
[ "if len(nums) < 2:\n return []\ni, j = (0, len(nums) - 1)\nresult = []\nunique_num = []\nwhile i < j:\n sum = nums[i] + nums[j]\n if sum > target:\n j -= 1\n elif sum < target:\n i += 1\n elif nums[i] in unique_num:\n i += 1\n else:\n result.append([nums[i], nums[j]])\n...
<|body_start_0|> if len(nums) < 2: return [] i, j = (0, len(nums) - 1) result = [] unique_num = [] while i < j: sum = nums[i] + nums[j] if sum > target: j -= 1 elif sum < target: i += 1 el...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def twoSum(self, nums, target): """:param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], -2) [[-2, 0]]""" <|body_0|> def threeSum(self, nums, target): """...
stack_v2_sparse_classes_36k_train_011675
3,912
no_license
[ { "docstring": ":param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], -2) [[-2, 0]]", "name": "twoSum", "signature": "def twoSum(self, nums, target)" }, { "docstring": ":param nums: :param targ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums, target): :param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums, target): :param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1,...
3b13a02f9c8273f9794a57b948d2655792707f37
<|skeleton|> class Solution: def twoSum(self, nums, target): """:param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], -2) [[-2, 0]]""" <|body_0|> def threeSum(self, nums, target): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def twoSum(self, nums, target): """:param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], -2) [[-2, 0]]""" if len(nums) < 2: return [] i, j = (0, len(nums) - 1) ...
the_stack_v2_python_sparse
4sum.py
gsy/leetcode
train
1
c4e747d728a5317e3f5d232b080730bbc6c6c114
[ "dp = [[0] * (n + 1) for _ in range(n + 1)]\nfor i in range(n, 0, -1):\n for j in range(i + 1, n + 1):\n dp[i][j] = min((k + max(dp[i][k - 1], dp[k + 1][j]) for k in range(i, j)))\nreturn dp[1][n]", "def search(left, right):\n if left >= right:\n return 0\n if dp[left][right]:\n retu...
<|body_start_0|> dp = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n, 0, -1): for j in range(i + 1, n + 1): dp[i][j] = min((k + max(dp[i][k - 1], dp[k + 1][j]) for k in range(i, j))) return dp[1][n] <|end_body_0|> <|body_start_1|> def search(left, rig...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" <|body_0|> def getMoneyAmount_recursive(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> dp = [[0] * (n + 1) for _ in range(n + 1)] fo...
stack_v2_sparse_classes_36k_train_011676
2,412
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "getMoneyAmount", "signature": "def getMoneyAmount(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "getMoneyAmount_recursive", "signature": "def getMoneyAmount_recursive(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_013693
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMoneyAmount(self, n): :type n: int :rtype: int - def getMoneyAmount_recursive(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMoneyAmount(self, n): :type n: int :rtype: int - def getMoneyAmount_recursive(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def getMoneyAmount(self...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" <|body_0|> def getMoneyAmount_recursive(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" dp = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n, 0, -1): for j in range(i + 1, n + 1): dp[i][j] = min((k + max(dp[i][k - 1], dp[k + 1][j]) for k in range(i, j))) return...
the_stack_v2_python_sparse
src/lt_375.py
oxhead/CodingYourWay
train
0
2e16908284f82b4a9583f1cc79854abe3ea7a9b6
[ "q = deque()\nans = 0\nM, N = (len(A), len(A[0]))\nfor j in range(N):\n for i in range(M):\n if A[i][j] != '0':\n ans += 1\n A[i][j] = '0'\n q.append((i, j))\n while q:\n it, jt = q.popleft()\n for diff in [(0, -1), (0, 1), (-1, 0), (1, 0)]:\n ...
<|body_start_0|> q = deque() ans = 0 M, N = (len(A), len(A[0])) for j in range(N): for i in range(M): if A[i][j] != '0': ans += 1 A[i][j] = '0' q.append((i, j)) while q: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numIslands(self, A: List[List[str]]) -> int: """BFS 모든 원소가 1이여도, bfs로 진행시 대각선에 해당하는 만큼만 한번에 저장하게 되어 공간을 엄청 줄일 수 있다!!!!! O(MN) / O(min(M,N))""" <|body_0|> def numIslands(self, A: List[List[str]]) -> int: """DFS O(MN) / O(MN)""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_011677
1,586
no_license
[ { "docstring": "BFS 모든 원소가 1이여도, bfs로 진행시 대각선에 해당하는 만큼만 한번에 저장하게 되어 공간을 엄청 줄일 수 있다!!!!! O(MN) / O(min(M,N))", "name": "numIslands", "signature": "def numIslands(self, A: List[List[str]]) -> int" }, { "docstring": "DFS O(MN) / O(MN)", "name": "numIslands", "signature": "def numIslands(sel...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numIslands(self, A: List[List[str]]) -> int: BFS 모든 원소가 1이여도, bfs로 진행시 대각선에 해당하는 만큼만 한번에 저장하게 되어 공간을 엄청 줄일 수 있다!!!!! O(MN) / O(min(M,N)) - def numIslands(self, A: List[List[s...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numIslands(self, A: List[List[str]]) -> int: BFS 모든 원소가 1이여도, bfs로 진행시 대각선에 해당하는 만큼만 한번에 저장하게 되어 공간을 엄청 줄일 수 있다!!!!! O(MN) / O(min(M,N)) - def numIslands(self, A: List[List[s...
c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1
<|skeleton|> class Solution: def numIslands(self, A: List[List[str]]) -> int: """BFS 모든 원소가 1이여도, bfs로 진행시 대각선에 해당하는 만큼만 한번에 저장하게 되어 공간을 엄청 줄일 수 있다!!!!! O(MN) / O(min(M,N))""" <|body_0|> def numIslands(self, A: List[List[str]]) -> int: """DFS O(MN) / O(MN)""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numIslands(self, A: List[List[str]]) -> int: """BFS 모든 원소가 1이여도, bfs로 진행시 대각선에 해당하는 만큼만 한번에 저장하게 되어 공간을 엄청 줄일 수 있다!!!!! O(MN) / O(min(M,N))""" q = deque() ans = 0 M, N = (len(A), len(A[0])) for j in range(N): for i in range(M): ...
the_stack_v2_python_sparse
Leetcode/Number_of_Islands.py
hanwgyu/algorithm_problem_solving
train
5
9202d2e7929f8e5c3556ea256de476a3e1ab9cf5
[ "kwargs['type'] = 'identifier'\nif 'meta' not in kwargs:\n kwargs['meta'] = {}\nkwargs['meta']['type'] = kwargs['type']\nsuper().__init__(field_id, **kwargs)", "unique = set()\nfor value in self.values:\n unique.add(value)\nreturn unique", "unique = set()\nfor entry in entries:\n unique.add(entry)\nret...
<|body_start_0|> kwargs['type'] = 'identifier' if 'meta' not in kwargs: kwargs['meta'] = {} kwargs['meta']['type'] = kwargs['type'] super().__init__(field_id, **kwargs) <|end_body_0|> <|body_start_1|> unique = set() for value in self.values: uniqu...
Class for record identifiers.
Identifier
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Identifier: """Class for record identifiers.""" def __init__(self, field_id, **kwargs): """Init Identifier class.""" <|body_0|> def to_set(self): """Create a set of identifiers.""" <|body_1|> def check_unique(entries): """Check all entries ar...
stack_v2_sparse_classes_36k_train_011678
11,877
permissive
[ { "docstring": "Init Identifier class.", "name": "__init__", "signature": "def __init__(self, field_id, **kwargs)" }, { "docstring": "Create a set of identifiers.", "name": "to_set", "signature": "def to_set(self)" }, { "docstring": "Check all entries are unique.", "name": "c...
4
stack_v2_sparse_classes_30k_train_008310
Implement the Python class `Identifier` described below. Class description: Class for record identifiers. Method signatures and docstrings: - def __init__(self, field_id, **kwargs): Init Identifier class. - def to_set(self): Create a set of identifiers. - def check_unique(entries): Check all entries are unique. - def...
Implement the Python class `Identifier` described below. Class description: Class for record identifiers. Method signatures and docstrings: - def __init__(self, field_id, **kwargs): Init Identifier class. - def to_set(self): Create a set of identifiers. - def check_unique(entries): Check all entries are unique. - def...
052a26316d19a48981417bf340d9f57e2cdc653a
<|skeleton|> class Identifier: """Class for record identifiers.""" def __init__(self, field_id, **kwargs): """Init Identifier class.""" <|body_0|> def to_set(self): """Create a set of identifiers.""" <|body_1|> def check_unique(entries): """Check all entries ar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Identifier: """Class for record identifiers.""" def __init__(self, field_id, **kwargs): """Init Identifier class.""" kwargs['type'] = 'identifier' if 'meta' not in kwargs: kwargs['meta'] = {} kwargs['meta']['type'] = kwargs['type'] super().__init__(fiel...
the_stack_v2_python_sparse
src/blobtools/lib/field.py
blobtoolkit/blobtoolkit
train
32
f6a9da15cd7d656815adf5d4625f848a44487e39
[ "if la:\n return la.size() ** 2 + la[0]\nelse:\n return 0", "if sexpr == 0:\n return self(0)\nif sexpr.support() == [[]]:\n return self._from_dict({self.one_basis(): sexpr.coefficient([])}, remove_zeros=False)\nout = self.zero()\nwhile sexpr:\n mup = max(sexpr.support(), key=self._my_key)\n out ...
<|body_start_0|> if la: return la.size() ** 2 + la[0] else: return 0 <|end_body_0|> <|body_start_1|> if sexpr == 0: return self(0) if sexpr.support() == [[]]: return self._from_dict({self.one_basis(): sexpr.coefficient([])}, remove_zeros=F...
generic_character
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class generic_character: def _my_key(self, la): """A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key value is `|\\lambda|^2 + \\lambda_0` and using the ``max`` function on a list of Partitions. Of course it i...
stack_v2_sparse_classes_36k_train_011679
16,482
no_license
[ { "docstring": "A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key value is `|\\\\lambda|^2 + \\\\lambda_0` and using the ``max`` function on a list of Partitions. Of course it is possible that this rank function is equal for s...
2
stack_v2_sparse_classes_30k_train_010104
Implement the Python class `generic_character` described below. Class description: Implement the generic_character class. Method signatures and docstrings: - def _my_key(self, la): A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key v...
Implement the Python class `generic_character` described below. Class description: Implement the generic_character class. Method signatures and docstrings: - def _my_key(self, la): A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key v...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class generic_character: def _my_key(self, la): """A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key value is `|\\lambda|^2 + \\lambda_0` and using the ``max`` function on a list of Partitions. Of course it i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class generic_character: def _my_key(self, la): """A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key value is `|\\lambda|^2 + \\lambda_0` and using the ``max`` function on a list of Partitions. Of course it is possible tha...
the_stack_v2_python_sparse
sage/src/sage/combinat/sf/character.py
bopopescu/geosci
train
0
a46302460e41d7e6228f31f04df0902e6bd490ba
[ "UserModel = get_user_model()\nemail = self.cleaned_data['email']\nself.users_cache = UserModel._default_manager.filter(email__iexact=email, is_active=True)\nif not len(self.users_cache):\n raise forms.ValidationError(self.error_messages['unknown'])\nif any((not is_password_usable(user.password) for user in self...
<|body_start_0|> UserModel = get_user_model() email = self.cleaned_data['email'] self.users_cache = UserModel._default_manager.filter(email__iexact=email, is_active=True) if not len(self.users_cache): raise forms.ValidationError(self.error_messages['unknown']) if any(...
EmailPasswordResetForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmailPasswordResetForm: def clean_email(self): """Validates that an active user exists with the given email address.""" <|body_0|> def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_toke...
stack_v2_sparse_classes_36k_train_011680
25,410
no_license
[ { "docstring": "Validates that an active user exists with the given email address.", "name": "clean_email", "signature": "def clean_email(self)" }, { "docstring": "Generates a one-use only link for resetting password and sends to the user.", "name": "save", "signature": "def save(self, d...
2
stack_v2_sparse_classes_30k_train_018260
Implement the Python class `EmailPasswordResetForm` described below. Class description: Implement the EmailPasswordResetForm class. Method signatures and docstrings: - def clean_email(self): Validates that an active user exists with the given email address. - def save(self, domain_override=None, email_template_name='...
Implement the Python class `EmailPasswordResetForm` described below. Class description: Implement the EmailPasswordResetForm class. Method signatures and docstrings: - def clean_email(self): Validates that an active user exists with the given email address. - def save(self, domain_override=None, email_template_name='...
61e082814d25c81007a2ff0cfae7f3a06c8c291d
<|skeleton|> class EmailPasswordResetForm: def clean_email(self): """Validates that an active user exists with the given email address.""" <|body_0|> def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_toke...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EmailPasswordResetForm: def clean_email(self): """Validates that an active user exists with the given email address.""" UserModel = get_user_model() email = self.cleaned_data['email'] self.users_cache = UserModel._default_manager.filter(email__iexact=email, is_active=True) ...
the_stack_v2_python_sparse
accounts/forms.py
cash2one/source
train
0
3aebbe5d5b739303dd15b72ea10cfe8bd40ff2db
[ "if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\nretangle = []\nres = 0\nfor arr in matrix:\n if len(retangle) == 0:\n retangle = [int(x) for x in arr]\n else:\n for j in range(len(arr)):\n if arr[j] == '0':\n retangle[j] = 0\n else:\n ...
<|body_start_0|> if len(matrix) == 0 or len(matrix[0]) == 0: return 0 retangle = [] res = 0 for arr in matrix: if len(retangle) == 0: retangle = [int(x) for x in arr] else: for j in range(len(arr)): i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maximalRectangle(self, matrix): """classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0], ] for each row, we accumulate the ones on the grids on position in previous row...
stack_v2_sparse_classes_36k_train_011681
2,976
no_license
[ { "docstring": "classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0], ] for each row, we accumulate the ones on the grids on position in previous row and find the area of the current histogram [1,0,1,0,0] <...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalRectangle(self, matrix): classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalRectangle(self, matrix): classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1...
1bd17e867d1d557a6ebbbd99f693d5fbd9f5b61e
<|skeleton|> class Solution: def maximalRectangle(self, matrix): """classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0], ] for each row, we accumulate the ones on the grids on position in previous row...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maximalRectangle(self, matrix): """classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0], ] for each row, we accumulate the ones on the grids on position in previous row and find the ...
the_stack_v2_python_sparse
leetcode/85-maximal-retangle/main.py
shriharshs/AlgoDaily
train
0
65e156ce4e5dfb4474607b009d4a81dcd7204be5
[ "ObjectManager.__init__(self)\nself.getters.update({'session_template': 'get_foreign_key', 'max': 'get_general', 'min': 'get_general', 'resource_type': 'get_foreign_key'})\nself.setters.update({'session_template': 'set_foreign_key', 'max': 'set_general', 'min': 'set_general', 'resource_type': 'set_foreign_key'})\ns...
<|body_start_0|> ObjectManager.__init__(self) self.getters.update({'session_template': 'get_foreign_key', 'max': 'get_general', 'min': 'get_general', 'resource_type': 'get_foreign_key'}) self.setters.update({'session_template': 'set_foreign_key', 'max': 'set_general', 'min': 'set_general', 'reso...
Manage SessionTemplateResourceTypeRequirements in the Power Reg system
SessionTemplateResourceTypeRequirementManager
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionTemplateResourceTypeRequirementManager: """Manage SessionTemplateResourceTypeRequirements in the Power Reg system""" def __init__(self): """constructor""" <|body_0|> def create(self, auth_token, session_template_id, resource_type_id, min, max): """Create a...
stack_v2_sparse_classes_36k_train_011682
2,098
permissive
[ { "docstring": "constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Create a new SessionTemplateResourceTypeRequirement @param session_template_id Foreign key for an session_template @param resource_type_id Foreign key for an resource_type @param min Minimum nu...
2
stack_v2_sparse_classes_30k_train_012084
Implement the Python class `SessionTemplateResourceTypeRequirementManager` described below. Class description: Manage SessionTemplateResourceTypeRequirements in the Power Reg system Method signatures and docstrings: - def __init__(self): constructor - def create(self, auth_token, session_template_id, resource_type_id...
Implement the Python class `SessionTemplateResourceTypeRequirementManager` described below. Class description: Manage SessionTemplateResourceTypeRequirements in the Power Reg system Method signatures and docstrings: - def __init__(self): constructor - def create(self, auth_token, session_template_id, resource_type_id...
a59457bc37f0501aea1f54d006a6de94ff80511c
<|skeleton|> class SessionTemplateResourceTypeRequirementManager: """Manage SessionTemplateResourceTypeRequirements in the Power Reg system""" def __init__(self): """constructor""" <|body_0|> def create(self, auth_token, session_template_id, resource_type_id, min, max): """Create a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SessionTemplateResourceTypeRequirementManager: """Manage SessionTemplateResourceTypeRequirements in the Power Reg system""" def __init__(self): """constructor""" ObjectManager.__init__(self) self.getters.update({'session_template': 'get_foreign_key', 'max': 'get_general', 'min': '...
the_stack_v2_python_sparse
pr_services/event_system/session_template_resource_type_requirement_manager.py
ninemoreminutes/openassign-server
train
0
b5558d4c02340a7240356d68b7833e1dcf71dda0
[ "self._graph = graph\nself._type = t\nself._batch_size = batch_size\nself._strategy = strategy\nself._client = self._graph.get_client()\nself._node_from = node_from\nif self._node_from == pywrap.NodeFrom.NODE:\n if self._type not in self._graph.get_node_decoders().keys():\n raise ValueError('Graph has no ...
<|body_start_0|> self._graph = graph self._type = t self._batch_size = batch_size self._strategy = strategy self._client = self._graph.get_client() self._node_from = node_from if self._node_from == pywrap.NodeFrom.NODE: if self._type not in self._graph...
Sampling nodes from graph.
NodeSampler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NodeSampler: """Sampling nodes from graph.""" def __init__(self, graph, t, batch_size, strategy='by_order', node_from=pywrap.NodeFrom.NODE): """Create a Base NodeSampler.. Args: graph (`Graph` object): The graph which sample from. t (string): type of node or egde. If t is a type of n...
stack_v2_sparse_classes_36k_train_011683
4,632
permissive
[ { "docstring": "Create a Base NodeSampler.. Args: graph (`Graph` object): The graph which sample from. t (string): type of node or egde. If t is a type of node, then `NodeSampler` will sample from node source. Else if `t` is a type of edge, then `node_from=EDGE_SRC` indicates that the nodes will be sampled from...
2
stack_v2_sparse_classes_30k_train_018014
Implement the Python class `NodeSampler` described below. Class description: Sampling nodes from graph. Method signatures and docstrings: - def __init__(self, graph, t, batch_size, strategy='by_order', node_from=pywrap.NodeFrom.NODE): Create a Base NodeSampler.. Args: graph (`Graph` object): The graph which sample fr...
Implement the Python class `NodeSampler` described below. Class description: Sampling nodes from graph. Method signatures and docstrings: - def __init__(self, graph, t, batch_size, strategy='by_order', node_from=pywrap.NodeFrom.NODE): Create a Base NodeSampler.. Args: graph (`Graph` object): The graph which sample fr...
1827c28c570c355e513f24b6a61a88457cfecdaf
<|skeleton|> class NodeSampler: """Sampling nodes from graph.""" def __init__(self, graph, t, batch_size, strategy='by_order', node_from=pywrap.NodeFrom.NODE): """Create a Base NodeSampler.. Args: graph (`Graph` object): The graph which sample from. t (string): type of node or egde. If t is a type of n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NodeSampler: """Sampling nodes from graph.""" def __init__(self, graph, t, batch_size, strategy='by_order', node_from=pywrap.NodeFrom.NODE): """Create a Base NodeSampler.. Args: graph (`Graph` object): The graph which sample from. t (string): type of node or egde. If t is a type of node, then `No...
the_stack_v2_python_sparse
graphlearn/python/sampler/node_sampler.py
lorinlee/graph-learn
train
0
43c98885deaf83d02e1da14a2443529426613e01
[ "self.stack = []\ntemp = root\nwhile temp != None:\n self.stack.append(temp)\n temp = temp.left", "if len(self.stack) != 0:\n return True\nelse:\n return False", "if len(self.stack) != 0:\n curr = self.stack.pop()\n nextsmall = curr\n if curr.right != None:\n curr = curr.right\n ...
<|body_start_0|> self.stack = [] temp = root while temp != None: self.stack.append(temp) temp = temp.left <|end_body_0|> <|body_start_1|> if len(self.stack) != 0: return True else: return False <|end_body_1|> <|body_start_2|> ...
BSTIterator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BSTIterator: def __init__(self, root): """:type root: TreeNode""" <|body_0|> def hasNext(self): """:rtype: bool""" <|body_1|> def next(self): """:rtype: int""" <|body_2|> <|end_skeleton|> <|body_start_0|> self.stack = [] ...
stack_v2_sparse_classes_36k_train_011684
1,326
no_license
[ { "docstring": ":type root: TreeNode", "name": "__init__", "signature": "def __init__(self, root)" }, { "docstring": ":rtype: bool", "name": "hasNext", "signature": "def hasNext(self)" }, { "docstring": ":rtype: int", "name": "next", "signature": "def next(self)" } ]
3
stack_v2_sparse_classes_30k_train_002266
Implement the Python class `BSTIterator` described below. Class description: Implement the BSTIterator class. Method signatures and docstrings: - def __init__(self, root): :type root: TreeNode - def hasNext(self): :rtype: bool - def next(self): :rtype: int
Implement the Python class `BSTIterator` described below. Class description: Implement the BSTIterator class. Method signatures and docstrings: - def __init__(self, root): :type root: TreeNode - def hasNext(self): :rtype: bool - def next(self): :rtype: int <|skeleton|> class BSTIterator: def __init__(self, root...
466dbaef48b28ad1b44944cb3eb830b0cd7c7c97
<|skeleton|> class BSTIterator: def __init__(self, root): """:type root: TreeNode""" <|body_0|> def hasNext(self): """:rtype: bool""" <|body_1|> def next(self): """:rtype: int""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BSTIterator: def __init__(self, root): """:type root: TreeNode""" self.stack = [] temp = root while temp != None: self.stack.append(temp) temp = temp.left def hasNext(self): """:rtype: bool""" if len(self.stack) != 0: ret...
the_stack_v2_python_sparse
Pythons Solutions/Trees/BST_iterator.py
dexteridea22/Interviewbit-Selected_Problems
train
1
01853c6bdbaf75a647589944a91b0f565170fd0e
[ "parser.add_argument('--lambda_side', type=float, default=1.0, help='weight for side output loss')\nparser.add_argument('--lambda_fused', type=float, default=1.0, help='weight for fused loss')\nreturn parser", "BaseModel.__init__(self, opt)\nself.loss_names = ['side', 'fused', 'total']\nself.display_sides = opt.d...
<|body_start_0|> parser.add_argument('--lambda_side', type=float, default=1.0, help='weight for side output loss') parser.add_argument('--lambda_fused', type=float, default=1.0, help='weight for fused loss') return parser <|end_body_0|> <|body_start_1|> BaseModel.__init__(self, opt) ...
This class implements the DeepCrack model. DeepCrack paper: https://www.sciencedirect.com/science/article/pii/S0925231219300566
DeepCrackModel
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeepCrackModel: """This class implements the DeepCrack model. DeepCrack paper: https://www.sciencedirect.com/science/article/pii/S0925231219300566""" def modify_commandline_options(parser, is_train=True): """Add new dataset-specific options, and rewrite default values for existing op...
stack_v2_sparse_classes_36k_train_011685
5,693
permissive
[ { "docstring": "Add new dataset-specific options, and rewrite default values for existing options.", "name": "modify_commandline_options", "signature": "def modify_commandline_options(parser, is_train=True)" }, { "docstring": "Initialize the DeepCrack class. Parameters: opt (Option class)-- stor...
6
stack_v2_sparse_classes_30k_train_021379
Implement the Python class `DeepCrackModel` described below. Class description: This class implements the DeepCrack model. DeepCrack paper: https://www.sciencedirect.com/science/article/pii/S0925231219300566 Method signatures and docstrings: - def modify_commandline_options(parser, is_train=True): Add new dataset-spe...
Implement the Python class `DeepCrackModel` described below. Class description: This class implements the DeepCrack model. DeepCrack paper: https://www.sciencedirect.com/science/article/pii/S0925231219300566 Method signatures and docstrings: - def modify_commandline_options(parser, is_train=True): Add new dataset-spe...
e23af48e7c155b04a9c40013fb5a6616e4102484
<|skeleton|> class DeepCrackModel: """This class implements the DeepCrack model. DeepCrack paper: https://www.sciencedirect.com/science/article/pii/S0925231219300566""" def modify_commandline_options(parser, is_train=True): """Add new dataset-specific options, and rewrite default values for existing op...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeepCrackModel: """This class implements the DeepCrack model. DeepCrack paper: https://www.sciencedirect.com/science/article/pii/S0925231219300566""" def modify_commandline_options(parser, is_train=True): """Add new dataset-specific options, and rewrite default values for existing options.""" ...
the_stack_v2_python_sparse
models/deepcrack_model.py
yhlleo/DeepSegmentor
train
228
1f8ca18039b8aa35ca6fbf9aae0fd16af10e45e0
[ "func = chain_transform(self._default_units())\ndata_pack = data_pack.apply_on_text(func, verbose=verbose)\nvocab_unit = build_vocab_unit(data_pack, verbose=verbose)\nself._context['vocab_unit'] = vocab_unit\nreturn self", "data_pack = data_pack.copy()\nunits_ = self._default_units()\nunits_.append(self._context[...
<|body_start_0|> func = chain_transform(self._default_units()) data_pack = data_pack.apply_on_text(func, verbose=verbose) vocab_unit = build_vocab_unit(data_pack, verbose=verbose) self._context['vocab_unit'] = vocab_unit return self <|end_body_0|> <|body_start_1|> data_p...
Naive preprocessor. Example: >>> import matchzoo as mz >>> train_data = mz.datasets.toy.load_data() >>> test_data = mz.datasets.toy.load_data(stage='test') >>> preprocessor = mz.preprocessors.NaivePreprocessor() >>> train_data_processed = preprocessor.fit_transform(train_data, ... verbose=0) >>> type(train_data_process...
NaivePreprocessor
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NaivePreprocessor: """Naive preprocessor. Example: >>> import matchzoo as mz >>> train_data = mz.datasets.toy.load_data() >>> test_data = mz.datasets.toy.load_data(stage='test') >>> preprocessor = mz.preprocessors.NaivePreprocessor() >>> train_data_processed = preprocessor.fit_transform(train_dat...
stack_v2_sparse_classes_36k_train_011686
2,402
permissive
[ { "docstring": "Fit pre-processing context for transformation. :param data_pack: data_pack to be preprocessed. :param verbose: Verbosity. :return: class:`NaivePreprocessor` instance.", "name": "fit", "signature": "def fit(self, data_pack: DataPack, verbose: int=1)" }, { "docstring": "Apply trans...
2
null
Implement the Python class `NaivePreprocessor` described below. Class description: Naive preprocessor. Example: >>> import matchzoo as mz >>> train_data = mz.datasets.toy.load_data() >>> test_data = mz.datasets.toy.load_data(stage='test') >>> preprocessor = mz.preprocessors.NaivePreprocessor() >>> train_data_processed...
Implement the Python class `NaivePreprocessor` described below. Class description: Naive preprocessor. Example: >>> import matchzoo as mz >>> train_data = mz.datasets.toy.load_data() >>> test_data = mz.datasets.toy.load_data(stage='test') >>> preprocessor = mz.preprocessors.NaivePreprocessor() >>> train_data_processed...
4198ebce942f4afe7ddca6a96ab6f4464ade4518
<|skeleton|> class NaivePreprocessor: """Naive preprocessor. Example: >>> import matchzoo as mz >>> train_data = mz.datasets.toy.load_data() >>> test_data = mz.datasets.toy.load_data(stage='test') >>> preprocessor = mz.preprocessors.NaivePreprocessor() >>> train_data_processed = preprocessor.fit_transform(train_dat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NaivePreprocessor: """Naive preprocessor. Example: >>> import matchzoo as mz >>> train_data = mz.datasets.toy.load_data() >>> test_data = mz.datasets.toy.load_data(stage='test') >>> preprocessor = mz.preprocessors.NaivePreprocessor() >>> train_data_processed = preprocessor.fit_transform(train_data, ... verbos...
the_stack_v2_python_sparse
poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/preprocessors/naive_preprocessor.py
microsoft/ContextualSP
train
332
61d160842ef84f27c2cb9d56eadb23b74f3ad5ea
[ "self.plugin_bundle_id = plugin_bundle_id\nself.filter_browsers = filter_browsers\nself.filter_sockets = filter_sockets\nself.vendor_config = vendor_config", "if dictionary is None:\n return None\nvendor_config = None\nif dictionary.get('VendorConfig') != None:\n vendor_config = list()\n for structure in...
<|body_start_0|> self.plugin_bundle_id = plugin_bundle_id self.filter_browsers = filter_browsers self.filter_sockets = filter_sockets self.vendor_config = vendor_config <|end_body_0|> <|body_start_1|> if dictionary is None: return None vendor_config = None ...
Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers (bool): Whether or not to enable browser traffic filtering (one of true, false). Defaults to true ...
AddNetworkSmProfileClarityModel
[ "MIT", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddNetworkSmProfileClarityModel: """Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers (bool): Whether or not to enable browse...
stack_v2_sparse_classes_36k_train_011687
3,010
permissive
[ { "docstring": "Constructor for the AddNetworkSmProfileClarityModel class", "name": "__init__", "signature": "def __init__(self, vendor_config=None, plugin_bundle_id=None, filter_browsers=None, filter_sockets=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dic...
2
null
Implement the Python class `AddNetworkSmProfileClarityModel` described below. Class description: Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers ...
Implement the Python class `AddNetworkSmProfileClarityModel` described below. Class description: Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers ...
9894089eb013318243ae48869cc5130eb37f80c0
<|skeleton|> class AddNetworkSmProfileClarityModel: """Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers (bool): Whether or not to enable browse...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddNetworkSmProfileClarityModel: """Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers (bool): Whether or not to enable browser traffic fil...
the_stack_v2_python_sparse
meraki_sdk/models/add_network_sm_profile_clarity_model.py
RaulCatalano/meraki-python-sdk
train
1
fa089dd1fa2f10166899721113db99d56d7e047a
[ "application_session = self.fetch_and_populate_application_session(token, application_session_id)\nnamespace = self.get_application_session_namespace(application_session)\nself.ensure_namespace(namespace)\nself.logger.info('provisioning %s in namespace %s on cluster %s', application_session['name'], namespace, self...
<|body_start_0|> application_session = self.fetch_and_populate_application_session(token, application_session_id) namespace = self.get_application_session_namespace(application_session) self.ensure_namespace(namespace) self.logger.info('provisioning %s in namespace %s on cluster %s', app...
OpenShift Template Driver allows provisioning application_sessions in an existing OpenShift cluster, using an Openshift Template. All the templates require a label defined in the template, like - "label: app: <app_label>" Similar to the openshift driver, it needs credentials for the cluster in the cluster config Since ...
OpenShiftTemplateDriver
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpenShiftTemplateDriver: """OpenShift Template Driver allows provisioning application_sessions in an existing OpenShift cluster, using an Openshift Template. All the templates require a label defined in the template, like - "label: app: <app_label>" Similar to the openshift driver, it needs crede...
stack_v2_sparse_classes_36k_train_011688
9,209
permissive
[ { "docstring": "Implements provisioning, called by superclass. A namespace is created if necessary.", "name": "do_provision", "signature": "def do_provision(self, token, application_session_id)" }, { "docstring": "Implements readiness checking, called by superclass. Checks that all the pods are ...
4
stack_v2_sparse_classes_30k_train_020430
Implement the Python class `OpenShiftTemplateDriver` described below. Class description: OpenShift Template Driver allows provisioning application_sessions in an existing OpenShift cluster, using an Openshift Template. All the templates require a label defined in the template, like - "label: app: <app_label>" Similar ...
Implement the Python class `OpenShiftTemplateDriver` described below. Class description: OpenShift Template Driver allows provisioning application_sessions in an existing OpenShift cluster, using an Openshift Template. All the templates require a label defined in the template, like - "label: app: <app_label>" Similar ...
438afb30f826d401bbf1f4d569d57e1c9e71761f
<|skeleton|> class OpenShiftTemplateDriver: """OpenShift Template Driver allows provisioning application_sessions in an existing OpenShift cluster, using an Openshift Template. All the templates require a label defined in the template, like - "label: app: <app_label>" Similar to the openshift driver, it needs crede...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OpenShiftTemplateDriver: """OpenShift Template Driver allows provisioning application_sessions in an existing OpenShift cluster, using an Openshift Template. All the templates require a label defined in the template, like - "label: app: <app_label>" Similar to the openshift driver, it needs credentials for th...
the_stack_v2_python_sparse
pebbles/drivers/provisioning/openshift_template_driver.py
CSCfi/pebbles
train
4
351ab2297381688a4177253566b4ff1c76897526
[ "cost_s = sorted(costs)\nans = 0\nfor i in range(len(cost_s)):\n if coins >= cost_s[i]:\n coins -= cost_s[i]\n ans += 1\nreturn ans", "def select_sort(l):\n \"\"\"\n\n :param l: 需要排序的列\n :return: 有序列\n \"\"\"\n for i in range(len(l) - 1):\n min_index ...
<|body_start_0|> cost_s = sorted(costs) ans = 0 for i in range(len(cost_s)): if coins >= cost_s[i]: coins -= cost_s[i] ans += 1 return ans <|end_body_0|> <|body_start_1|> def select_sort(l): """ :param ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxIceCream(self, costs: List[int], coins: int) -> int: """不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数""" <|body_0|> def maxIceCream(self, costs: List[int], coins: int) -> int: """二分排序 :param costs: :param coins: ...
stack_v2_sparse_classes_36k_train_011689
2,488
no_license
[ { "docstring": "不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数", "name": "maxIceCream", "signature": "def maxIceCream(self, costs: List[int], coins: int) -> int" }, { "docstring": "二分排序 :param costs: :param coins: :return:", "name": "maxIceCream", "si...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxIceCream(self, costs: List[int], coins: int) -> int: 不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数 - def maxIceCream(self, costs: Lis...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxIceCream(self, costs: List[int], coins: int) -> int: 不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数 - def maxIceCream(self, costs: Lis...
b1680014ce3f55ba952a1e64241c0cbb783cc436
<|skeleton|> class Solution: def maxIceCream(self, costs: List[int], coins: int) -> int: """不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数""" <|body_0|> def maxIceCream(self, costs: List[int], coins: int) -> int: """二分排序 :param costs: :param coins: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxIceCream(self, costs: List[int], coins: int) -> int: """不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数""" cost_s = sorted(costs) ans = 0 for i in range(len(cost_s)): if coins >= cost_s[i]: coins -...
the_stack_v2_python_sparse
a_1833.py
sun510001/leetcode_jianzhi_offer_2
train
0
42f403058a24f9aebf8858fed3d72445fb5957e4
[ "self.num_dim = 2\nself.reflect_index = [1, 2]\nsuper(SharpClawSolver2D, self).__init__(riemann_solver, claw_package)", "self._apply_bcs(state)\nq = self.qbc\ngrid = state.grid\nnum_ghost = self.num_ghost\nmx = grid.num_cells[0]\nmy = grid.num_cells[1]\nmaxm = max(mx, my)\nif self.kernel_language == 'Fortran':\n ...
<|body_start_0|> self.num_dim = 2 self.reflect_index = [1, 2] super(SharpClawSolver2D, self).__init__(riemann_solver, claw_package) <|end_body_0|> <|body_start_1|> self._apply_bcs(state) q = self.qbc grid = state.grid num_ghost = self.num_ghost mx = grid....
Two Dimensional SharpClawSolver
SharpClawSolver2D
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SharpClawSolver2D: """Two Dimensional SharpClawSolver""" def __init__(self, riemann_solver=None, claw_package=None): """Create 2D SharpClaw solver See :class:`SharpClawSolver2D` for more info.""" <|body_0|> def dq_hyperbolic(self, state): """Compute dq/dt * (delt...
stack_v2_sparse_classes_36k_train_011690
38,052
permissive
[ { "docstring": "Create 2D SharpClaw solver See :class:`SharpClawSolver2D` for more info.", "name": "__init__", "signature": "def __init__(self, riemann_solver=None, claw_package=None)" }, { "docstring": "Compute dq/dt * (delta t) for the hyperbolic hyperbolic system Note that the capa array, if ...
2
stack_v2_sparse_classes_30k_train_018207
Implement the Python class `SharpClawSolver2D` described below. Class description: Two Dimensional SharpClawSolver Method signatures and docstrings: - def __init__(self, riemann_solver=None, claw_package=None): Create 2D SharpClaw solver See :class:`SharpClawSolver2D` for more info. - def dq_hyperbolic(self, state): ...
Implement the Python class `SharpClawSolver2D` described below. Class description: Two Dimensional SharpClawSolver Method signatures and docstrings: - def __init__(self, riemann_solver=None, claw_package=None): Create 2D SharpClaw solver See :class:`SharpClawSolver2D` for more info. - def dq_hyperbolic(self, state): ...
6323b7295b80f33285b958b1a2144f88f51be4b1
<|skeleton|> class SharpClawSolver2D: """Two Dimensional SharpClawSolver""" def __init__(self, riemann_solver=None, claw_package=None): """Create 2D SharpClaw solver See :class:`SharpClawSolver2D` for more info.""" <|body_0|> def dq_hyperbolic(self, state): """Compute dq/dt * (delt...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SharpClawSolver2D: """Two Dimensional SharpClawSolver""" def __init__(self, riemann_solver=None, claw_package=None): """Create 2D SharpClaw solver See :class:`SharpClawSolver2D` for more info.""" self.num_dim = 2 self.reflect_index = [1, 2] super(SharpClawSolver2D, self)._...
the_stack_v2_python_sparse
src/pyclaw/sharpclaw/solver.py
clawpack/pyclaw
train
124
bf3389342c767b67123b2a4e7b4514c6ed6210b7
[ "time_tolerance = time_tolerance if time_tolerance is not None else math.inf\nif time in self._items:\n return self._items[time]\nelif time_tolerance > 0.0:\n return self._get_interpolated_value(time, time_tolerance)\nelse:\n raise KeyError", "time_list = list(self._items.keys())\ntime_list.sort()\nserie...
<|body_start_0|> time_tolerance = time_tolerance if time_tolerance is not None else math.inf if time in self._items: return self._items[time] elif time_tolerance > 0.0: return self._get_interpolated_value(time, time_tolerance) else: raise KeyError <|en...
Interpolate Time Series It is possible to interpolate values for times not defined in the series
InterpolatedTimeSeries
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InterpolatedTimeSeries: """Interpolate Time Series It is possible to interpolate values for times not defined in the series""" def get_value(self, time, time_tolerance=None, **kwargs): """Get item's value at the specified time If the specified time isn't defined in the series, the it...
stack_v2_sparse_classes_36k_train_011691
3,918
no_license
[ { "docstring": "Get item's value at the specified time If the specified time isn't defined in the series, the item's value is calculated based on interpolation of two consecutive values v1 and v2 with times t1 and t2 respectively such that (t1 <= time <= t2). The interpolation is calculated only if (time - t1 <...
3
null
Implement the Python class `InterpolatedTimeSeries` described below. Class description: Interpolate Time Series It is possible to interpolate values for times not defined in the series Method signatures and docstrings: - def get_value(self, time, time_tolerance=None, **kwargs): Get item's value at the specified time ...
Implement the Python class `InterpolatedTimeSeries` described below. Class description: Interpolate Time Series It is possible to interpolate values for times not defined in the series Method signatures and docstrings: - def get_value(self, time, time_tolerance=None, **kwargs): Get item's value at the specified time ...
ce7045918f60c92ce1ed5ca4389b969bf28e6b82
<|skeleton|> class InterpolatedTimeSeries: """Interpolate Time Series It is possible to interpolate values for times not defined in the series""" def get_value(self, time, time_tolerance=None, **kwargs): """Get item's value at the specified time If the specified time isn't defined in the series, the it...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InterpolatedTimeSeries: """Interpolate Time Series It is possible to interpolate values for times not defined in the series""" def get_value(self, time, time_tolerance=None, **kwargs): """Get item's value at the specified time If the specified time isn't defined in the series, the item's value is...
the_stack_v2_python_sparse
sp/core/time_series/interpolated.py
adysonmaia/phd-sp-dynamic
train
0
f3089e133b65d4afec817a342fb66fe627ab2005
[ "def serializeHelper(node):\n if not node:\n vals.append('#')\n return\n vals.append(str(node.val))\n serializeHelper(node.left)\n serializeHelper(node.right)\nvals = []\nserializeHelper(root)\nreturn ' '.join(vals)", "def deserializeHelper():\n val = next(vals)\n if val == '#':\n ...
<|body_start_0|> def serializeHelper(node): if not node: vals.append('#') return vals.append(str(node.val)) serializeHelper(node.left) serializeHelper(node.right) vals = [] serializeHelper(root) return ' '.jo...
Codec
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_011692
2,569
permissive
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
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:...
4dc4e6642dc92f1983c13564cc0fd99917cab358
<|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_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def serializeHelper(node): if not node: vals.append('#') return vals.append(str(node.val)) serializeHelper(node.left) ...
the_stack_v2_python_sparse
Python/serialize-and-deserialize-binary-tree.py
kamyu104/LeetCode-Solutions
train
4,549
82c1c5a9a0a9878ff8adf882f7e9760f46f95427
[ "obj = structures.DeepReferenceDict({'key': {'sub_key': {'value': 'foo'}}})\nself.assertEqual('foo', obj['key']['sub_key']['value'])\nself.assertEqual('foo', obj['key.sub_key.value'])", "obj = structures.DeepReferenceDict({'key': {}})\nwith self.assertRaises(KeyError):\n _ = obj['key.sub_key.value']" ]
<|body_start_0|> obj = structures.DeepReferenceDict({'key': {'sub_key': {'value': 'foo'}}}) self.assertEqual('foo', obj['key']['sub_key']['value']) self.assertEqual('foo', obj['key.sub_key.value']) <|end_body_0|> <|body_start_1|> obj = structures.DeepReferenceDict({'key': {}}) w...
Test the deep reference dict structure.
DeepReferenceDictTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeepReferenceDictTestCase: """Test the deep reference dict structure.""" def test_deep_reference(self): """Delimited keys are accessible.""" <|body_0|> def test_deep_reference_error(self): """Missing keys raise error.""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_011693
6,032
permissive
[ { "docstring": "Delimited keys are accessible.", "name": "test_deep_reference", "signature": "def test_deep_reference(self)" }, { "docstring": "Missing keys raise error.", "name": "test_deep_reference_error", "signature": "def test_deep_reference_error(self)" } ]
2
null
Implement the Python class `DeepReferenceDictTestCase` described below. Class description: Test the deep reference dict structure. Method signatures and docstrings: - def test_deep_reference(self): Delimited keys are accessible. - def test_deep_reference_error(self): Missing keys raise error.
Implement the Python class `DeepReferenceDictTestCase` described below. Class description: Test the deep reference dict structure. Method signatures and docstrings: - def test_deep_reference(self): Delimited keys are accessible. - def test_deep_reference_error(self): Missing keys raise error. <|skeleton|> class Deep...
17471c436621ebfd978b51225fa4de05367a53e1
<|skeleton|> class DeepReferenceDictTestCase: """Test the deep reference dict structure.""" def test_deep_reference(self): """Delimited keys are accessible.""" <|body_0|> def test_deep_reference_error(self): """Missing keys raise error.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeepReferenceDictTestCase: """Test the deep reference dict structure.""" def test_deep_reference(self): """Delimited keys are accessible.""" obj = structures.DeepReferenceDict({'key': {'sub_key': {'value': 'foo'}}}) self.assertEqual('foo', obj['key']['sub_key']['value']) s...
the_stack_v2_python_sparse
grow/common/structures_test.py
grow/grow
train
352
3ea83523a12430699362eb30ec88df8fe7caa889
[ "try:\n super().perform_authentication(request)\nexcept Exception:\n pass", "s = CartSelectAllSerializer(data=request.data)\ns.is_valid(raise_exception=True)\nselected = s.validated_data.get('selected')\nuser = request.user\nif user.is_authenticated():\n strict_redis = get_redis_connection('carts')\n ...
<|body_start_0|> try: super().perform_authentication(request) except Exception: pass <|end_body_0|> <|body_start_1|> s = CartSelectAllSerializer(data=request.data) s.is_valid(raise_exception=True) selected = s.validated_data.get('selected') user =...
购物车全选和全不选
CartSelectAllView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CartSelectAllView: """购物车全选和全不选""" def perform_authentication(self, request): """drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可""" <|body_0|> def put(self, request): """全选或全不选""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_36k_train_011694
12,969
no_license
[ { "docstring": "drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可", "name": "perform_authentication", "signature": "def perform_authentication(self, request)" }, { "docstring": "全选或全不选", "name": "put", "signature": "def put(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_006039
Implement the Python class `CartSelectAllView` described below. Class description: 购物车全选和全不选 Method signatures and docstrings: - def perform_authentication(self, request): drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可 - def put(self, request): 全选或全不选
Implement the Python class `CartSelectAllView` described below. Class description: 购物车全选和全不选 Method signatures and docstrings: - def perform_authentication(self, request): drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可 - def put(self, request): 全选或全不选 <|skeleton|> class CartSelectAl...
12b52f21a4ec20b4853870468c28d2385dc185a8
<|skeleton|> class CartSelectAllView: """购物车全选和全不选""" def perform_authentication(self, request): """drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可""" <|body_0|> def put(self, request): """全选或全不选""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CartSelectAllView: """购物车全选和全不选""" def perform_authentication(self, request): """drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可""" try: super().perform_authentication(request) except Exception: pass def put(self, reque...
the_stack_v2_python_sparse
django_prj/meiduo/meiduo_mall/meiduo_mall/apps/carts/views.py
123wuyu/demo_prj
train
1
6985b6c65debb674fa4b3f3e4ff38a644d1f69aa
[ "self.x = TT.matrix('x')\nif sparse_input:\n self.x = SS.csr_matrix('x')\nself.targets = TT.matrix('targets')\nself.weights = TT.matrix('weights')\nif self.weighted:\n return [self.x, self.targets, self.weights]\nreturn [self.x, self.targets]", "err = outputs[self.output_name()] - self.targets\nif self.weig...
<|body_start_0|> self.x = TT.matrix('x') if sparse_input: self.x = SS.csr_matrix('x') self.targets = TT.matrix('targets') self.weights = TT.matrix('weights') if self.weighted: return [self.x, self.targets, self.weights] return [self.x, self.targets...
A regression model attempts to produce a target output. Regression models are trained by optimizing a (possibly regularized) loss that centers around some measurement of error with respect to the target outputs. This regression model implementation uses the mean squared error. If we have a labeled dataset containing :m...
Regressor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Regressor: """A regression model attempts to produce a target output. Regression models are trained by optimizing a (possibly regularized) loss that centers around some measurement of error with respect to the target outputs. This regression model implementation uses the mean squared error. If we...
stack_v2_sparse_classes_36k_train_011695
18,849
permissive
[ { "docstring": "Setup Theano variables for our network. Parameters ---------- sparse_input : bool If True, create an input variable that can hold a sparse matrix. Defaults to False, which assumes all arrays are dense. Returns ------- vars : list of theano variables A list of the variables that this network requ...
2
stack_v2_sparse_classes_30k_train_020339
Implement the Python class `Regressor` described below. Class description: A regression model attempts to produce a target output. Regression models are trained by optimizing a (possibly regularized) loss that centers around some measurement of error with respect to the target outputs. This regression model implementa...
Implement the Python class `Regressor` described below. Class description: A regression model attempts to produce a target output. Regression models are trained by optimizing a (possibly regularized) loss that centers around some measurement of error with respect to the target outputs. This regression model implementa...
06b5b6f5de05220702f34c943f309d8188010b57
<|skeleton|> class Regressor: """A regression model attempts to produce a target output. Regression models are trained by optimizing a (possibly regularized) loss that centers around some measurement of error with respect to the target outputs. This regression model implementation uses the mean squared error. If we...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Regressor: """A regression model attempts to produce a target output. Regression models are trained by optimizing a (possibly regularized) loss that centers around some measurement of error with respect to the target outputs. This regression model implementation uses the mean squared error. If we have a label...
the_stack_v2_python_sparse
code/seq2seq_graph/src/theanets-0.6.1/theanets/feedforward.py
scylla/masters_thesis
train
2
f48c8bed0752f6a8c52f88ff97e588ac951420da
[ "Offsets.__init__(self, **kwargs)\nself.center = center\nself.target = target", "target = [image.header[x] for x in self.target]\ncenter = [image.header[x] for x in self.center]\nimage.meta['offsets'] = np.subtract(target, center)\nreturn image" ]
<|body_start_0|> Offsets.__init__(self, **kwargs) self.center = center self.target = target <|end_body_0|> <|body_start_1|> target = [image.header[x] for x in self.target] center = [image.header[x] for x in self.center] image.meta['offsets'] = np.subtract(target, center)...
An offset-calculation method based on fits headers.
FitsHeaderOffsets
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FitsHeaderOffsets: """An offset-calculation method based on fits headers.""" def __init__(self, target: Tuple[str, str], center: Tuple[str, str]=('DET-CPX1', 'DET-CPX2'), **kwargs: Any): """Initializes new fits header offsets.""" <|body_0|> async def __call__(self, image...
stack_v2_sparse_classes_36k_train_011696
1,149
permissive
[ { "docstring": "Initializes new fits header offsets.", "name": "__init__", "signature": "def __init__(self, target: Tuple[str, str], center: Tuple[str, str]=('DET-CPX1', 'DET-CPX2'), **kwargs: Any)" }, { "docstring": "Processes an image and sets x/y pixel offset to reference in offset attribute....
2
stack_v2_sparse_classes_30k_train_013075
Implement the Python class `FitsHeaderOffsets` described below. Class description: An offset-calculation method based on fits headers. Method signatures and docstrings: - def __init__(self, target: Tuple[str, str], center: Tuple[str, str]=('DET-CPX1', 'DET-CPX2'), **kwargs: Any): Initializes new fits header offsets. ...
Implement the Python class `FitsHeaderOffsets` described below. Class description: An offset-calculation method based on fits headers. Method signatures and docstrings: - def __init__(self, target: Tuple[str, str], center: Tuple[str, str]=('DET-CPX1', 'DET-CPX2'), **kwargs: Any): Initializes new fits header offsets. ...
2d7a06e5485b61b6ca7e51d99b08651ea6021086
<|skeleton|> class FitsHeaderOffsets: """An offset-calculation method based on fits headers.""" def __init__(self, target: Tuple[str, str], center: Tuple[str, str]=('DET-CPX1', 'DET-CPX2'), **kwargs: Any): """Initializes new fits header offsets.""" <|body_0|> async def __call__(self, image...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FitsHeaderOffsets: """An offset-calculation method based on fits headers.""" def __init__(self, target: Tuple[str, str], center: Tuple[str, str]=('DET-CPX1', 'DET-CPX2'), **kwargs: Any): """Initializes new fits header offsets.""" Offsets.__init__(self, **kwargs) self.center = cent...
the_stack_v2_python_sparse
pyobs/images/processors/offsets/fitsheader.py
pyobs/pyobs-core
train
9
635c27c54eaab446f8dd127f7ec00278f2a4194f
[ "self._verbose = rospy.get_param('~verbose', False)\ntime_limit = rospy.get_param('~time_limit', 10)\nplanner_commands = rospy.get_param('~planner_commands')\nself.verbose_print(planner_commands)\nif not planner_commands:\n raise Exception('Command to execute planner not provided')\nself._action_server = actionl...
<|body_start_0|> self._verbose = rospy.get_param('~verbose', False) time_limit = rospy.get_param('~time_limit', 10) planner_commands = rospy.get_param('~planner_commands') self.verbose_print(planner_commands) if not planner_commands: raise Exception('Command to execut...
A wrapper around planner which calls the appropriate scripts with appropriate parameters wrapped inside an action server.
TaskPlannerServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskPlannerServer: """A wrapper around planner which calls the appropriate scripts with appropriate parameters wrapped inside an action server.""" def __init__(self): """- initialising subscribers, publishers and action server, - reading ros parameters.""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_011697
4,837
no_license
[ { "docstring": "- initialising subscribers, publishers and action server, - reading ros parameters.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Callback function to handle plan action clients' goals. :goal: PlanGoal :returns: None", "name": "_plan_execute_cb", ...
4
stack_v2_sparse_classes_30k_train_011493
Implement the Python class `TaskPlannerServer` described below. Class description: A wrapper around planner which calls the appropriate scripts with appropriate parameters wrapped inside an action server. Method signatures and docstrings: - def __init__(self): - initialising subscribers, publishers and action server,...
Implement the Python class `TaskPlannerServer` described below. Class description: A wrapper around planner which calls the appropriate scripts with appropriate parameters wrapped inside an action server. Method signatures and docstrings: - def __init__(self): - initialising subscribers, publishers and action server,...
8129cd48351159508cae3438a8b8b3d776c771ca
<|skeleton|> class TaskPlannerServer: """A wrapper around planner which calls the appropriate scripts with appropriate parameters wrapped inside an action server.""" def __init__(self): """- initialising subscribers, publishers and action server, - reading ros parameters.""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TaskPlannerServer: """A wrapper around planner which calls the appropriate scripts with appropriate parameters wrapped inside an action server.""" def __init__(self): """- initialising subscribers, publishers and action server, - reading ros parameters.""" self._verbose = rospy.get_param(...
the_stack_v2_python_sparse
mir_planning/mir_task_planning/ros/scripts/task_planner_server
b-it-bots/mas_industrial_robotics
train
25
edc08358dfe490040078f3a0ff0f77674aa04d46
[ "self._server = server\nself._port = port\nself._password = password\nself.cmus = None", "try:\n self.cmus = remote.PyCmus(server=self._server, port=self._port, password=self._password)\nexcept exceptions.InvalidPassword:\n _LOGGER.error('The provided password was rejected by cmus')" ]
<|body_start_0|> self._server = server self._port = port self._password = password self.cmus = None <|end_body_0|> <|body_start_1|> try: self.cmus = remote.PyCmus(server=self._server, port=self._port, password=self._password) except exceptions.InvalidPassword...
Representation of a cmus connection.
CmusRemote
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CmusRemote: """Representation of a cmus connection.""" def __init__(self, server, port, password): """Initialize the cmus remote.""" <|body_0|> def connect(self): """Connect to the cmus server.""" <|body_1|> <|end_skeleton|> <|body_start_0|> sel...
stack_v2_sparse_classes_36k_train_011698
7,140
permissive
[ { "docstring": "Initialize the cmus remote.", "name": "__init__", "signature": "def __init__(self, server, port, password)" }, { "docstring": "Connect to the cmus server.", "name": "connect", "signature": "def connect(self)" } ]
2
null
Implement the Python class `CmusRemote` described below. Class description: Representation of a cmus connection. Method signatures and docstrings: - def __init__(self, server, port, password): Initialize the cmus remote. - def connect(self): Connect to the cmus server.
Implement the Python class `CmusRemote` described below. Class description: Representation of a cmus connection. Method signatures and docstrings: - def __init__(self, server, port, password): Initialize the cmus remote. - def connect(self): Connect to the cmus server. <|skeleton|> class CmusRemote: """Represent...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class CmusRemote: """Representation of a cmus connection.""" def __init__(self, server, port, password): """Initialize the cmus remote.""" <|body_0|> def connect(self): """Connect to the cmus server.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CmusRemote: """Representation of a cmus connection.""" def __init__(self, server, port, password): """Initialize the cmus remote.""" self._server = server self._port = port self._password = password self.cmus = None def connect(self): """Connect to the...
the_stack_v2_python_sparse
homeassistant/components/cmus/media_player.py
home-assistant/core
train
35,501
4037a4e74a43efd5962495331eec325c0a98f2c3
[ "super(ScalingUpExecuteWebhookTest, self).setUp()\nself.create_group_response = self.autoscale_behaviors.create_scaling_group_given(gc_min_entities=self.gc_min_entities_alt)\nself.group = self.create_group_response.entity\nself.resources.add(self.group, self.empty_scaling_group)", "policy_up = {'change': 1}\nexec...
<|body_start_0|> super(ScalingUpExecuteWebhookTest, self).setUp() self.create_group_response = self.autoscale_behaviors.create_scaling_group_given(gc_min_entities=self.gc_min_entities_alt) self.group = self.create_group_response.entity self.resources.add(self.group, self.empty_scaling_gr...
System tests to verify execute scaling policies scenarios
ScalingUpExecuteWebhookTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScalingUpExecuteWebhookTest: """System tests to verify execute scaling policies scenarios""" def setUp(self): """Create a scaling group with minentities over zero""" <|body_0|> def test_system_execute_webhook_scale_up_change(self): """Create a scale up policy wit...
stack_v2_sparse_classes_36k_train_011699
3,280
permissive
[ { "docstring": "Create a scaling group with minentities over zero", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Create a scale up policy with change and execute its webhook", "name": "test_system_execute_webhook_scale_up_change", "signature": "def test_system_execu...
4
null
Implement the Python class `ScalingUpExecuteWebhookTest` described below. Class description: System tests to verify execute scaling policies scenarios Method signatures and docstrings: - def setUp(self): Create a scaling group with minentities over zero - def test_system_execute_webhook_scale_up_change(self): Create ...
Implement the Python class `ScalingUpExecuteWebhookTest` described below. Class description: System tests to verify execute scaling policies scenarios Method signatures and docstrings: - def setUp(self): Create a scaling group with minentities over zero - def test_system_execute_webhook_scale_up_change(self): Create ...
7199cdd67255fe116dbcbedea660c13453671134
<|skeleton|> class ScalingUpExecuteWebhookTest: """System tests to verify execute scaling policies scenarios""" def setUp(self): """Create a scaling group with minentities over zero""" <|body_0|> def test_system_execute_webhook_scale_up_change(self): """Create a scale up policy wit...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScalingUpExecuteWebhookTest: """System tests to verify execute scaling policies scenarios""" def setUp(self): """Create a scaling group with minentities over zero""" super(ScalingUpExecuteWebhookTest, self).setUp() self.create_group_response = self.autoscale_behaviors.create_scali...
the_stack_v2_python_sparse
autoscale_cloudroast/test_repo/autoscale/system/policies/test_system_execute_webhook_scaleup.py
rackerlabs/otter
train
20