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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
353b928a0c095125f0c40e13d38bb35faa419df1 | [
"left, right = (0, 19)\nwhile left <= right:\n mid = left + (right - left) / 2\n if 3 ** mid == n:\n return True\n elif 3 ** mid > n:\n right = mid - 1\n else:\n left = mid + 1\nreturn False",
"while n > 1 and n % 3 == 0:\n n /= 3\nreturn n == 1"
] | <|body_start_0|>
left, right = (0, 19)
while left <= right:
mid = left + (right - left) / 2
if 3 ** mid == n:
return True
elif 3 ** mid > n:
right = mid - 1
else:
left = mid + 1
return False
<|end_bod... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfThree(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfThree2(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right = (0, 19)
while left <= right:
... | stack_v2_sparse_classes_36k_train_019000 | 597 | permissive | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfThree",
"signature": "def isPowerOfThree(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfThree2",
"signature": "def isPowerOfThree2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001017 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfThree(self, n): :type n: int :rtype: bool
- def isPowerOfThree2(self, n): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfThree(self, n): :type n: int :rtype: bool
- def isPowerOfThree2(self, n): :type n: int :rtype: bool
<|skeleton|>
class Solution:
def isPowerOfThree(self, n):
... | c8bf33af30569177c5276ffcd72a8d93ba4c402a | <|skeleton|>
class Solution:
def isPowerOfThree(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfThree2(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfThree(self, n):
""":type n: int :rtype: bool"""
left, right = (0, 19)
while left <= right:
mid = left + (right - left) / 2
if 3 ** mid == n:
return True
elif 3 ** mid > n:
right = mid - 1
... | the_stack_v2_python_sparse | 301-400/321-330/326-powerOfThree/powerOfThree.py | xuychen/Leetcode | train | 0 | |
310567f7edd54dc4b982c6e3a380e736f8b62779 | [
"kwargs.update({'auto_id': 'id_contact_quickbutton_%s'})\nsuper(AddContactQuickbuttonForm, self).__init__(*args, **kwargs)\nself.fields['account'].queryset = Account.objects.all()",
"for email in self.cleaned_data['emails']:\n validate_email(email)\n if Contact.objects.filter(email_addresses__email_address_... | <|body_start_0|>
kwargs.update({'auto_id': 'id_contact_quickbutton_%s'})
super(AddContactQuickbuttonForm, self).__init__(*args, **kwargs)
self.fields['account'].queryset = Account.objects.all()
<|end_body_0|>
<|body_start_1|>
for email in self.cleaned_data['emails']:
validat... | Form to add an account with the absolute minimum of information. | AddContactQuickbuttonForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddContactQuickbuttonForm:
"""Form to add an account with the absolute minimum of information."""
def __init__(self, *args, **kwargs):
"""Overload super().__init__ to change auto_id to prevent clashing form field id's with other forms."""
<|body_0|>
def clean_emails(self... | stack_v2_sparse_classes_36k_train_019001 | 11,738 | no_license | [
{
"docstring": "Overload super().__init__ to change auto_id to prevent clashing form field id's with other forms.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Prevent multiple contacts with the same email address when adding",
"name": "clean_ema... | 4 | stack_v2_sparse_classes_30k_train_011517 | Implement the Python class `AddContactQuickbuttonForm` described below.
Class description:
Form to add an account with the absolute minimum of information.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Overload super().__init__ to change auto_id to prevent clashing form field id's with othe... | Implement the Python class `AddContactQuickbuttonForm` described below.
Class description:
Form to add an account with the absolute minimum of information.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Overload super().__init__ to change auto_id to prevent clashing form field id's with othe... | 0a284e2aae3ca08955215418a76bb70ad9af1f81 | <|skeleton|>
class AddContactQuickbuttonForm:
"""Form to add an account with the absolute minimum of information."""
def __init__(self, *args, **kwargs):
"""Overload super().__init__ to change auto_id to prevent clashing form field id's with other forms."""
<|body_0|>
def clean_emails(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddContactQuickbuttonForm:
"""Form to add an account with the absolute minimum of information."""
def __init__(self, *args, **kwargs):
"""Overload super().__init__ to change auto_id to prevent clashing form field id's with other forms."""
kwargs.update({'auto_id': 'id_contact_quickbutton_... | the_stack_v2_python_sparse | lily/contacts/forms.py | rmoorman/hellolily | train | 0 |
33d21395285617850f59e68074defa3edbba3cd1 | [
"self.board = board\nself.archive = archive\nself.archive.visitedStates[str(self.board.changeable)] = 'beginning!'\nself.save = save",
"print('[' + time.strftime('%H:%M:%S') + ']' + ' Running algorithm...\\n')\nwhile self.board.checkSolution() != 0:\n children = self.board.createChildren()\n childToCheck = ... | <|body_start_0|>
self.board = board
self.archive = archive
self.archive.visitedStates[str(self.board.changeable)] = 'beginning!'
self.save = save
<|end_body_0|>
<|body_start_1|>
print('[' + time.strftime('%H:%M:%S') + ']' + ' Running algorithm...\n')
while self.board.che... | Random | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Random:
def __init__(self, board, archive, save):
"""Takes all information of the board with it's state as the beginning of the game. Args: board (class): Containing all information of the game. archive (class): Containing the archive class. save (class): Containing the save class."""
... | stack_v2_sparse_classes_36k_train_019002 | 1,929 | no_license | [
{
"docstring": "Takes all information of the board with it's state as the beginning of the game. Args: board (class): Containing all information of the game. archive (class): Containing the archive class. save (class): Containing the save class.",
"name": "__init__",
"signature": "def __init__(self, boa... | 2 | stack_v2_sparse_classes_30k_train_010473 | Implement the Python class `Random` described below.
Class description:
Implement the Random class.
Method signatures and docstrings:
- def __init__(self, board, archive, save): Takes all information of the board with it's state as the beginning of the game. Args: board (class): Containing all information of the game... | Implement the Python class `Random` described below.
Class description:
Implement the Random class.
Method signatures and docstrings:
- def __init__(self, board, archive, save): Takes all information of the board with it's state as the beginning of the game. Args: board (class): Containing all information of the game... | 4d1eb8a94e38e256699c964b0c7147364ece099a | <|skeleton|>
class Random:
def __init__(self, board, archive, save):
"""Takes all information of the board with it's state as the beginning of the game. Args: board (class): Containing all information of the game. archive (class): Containing the archive class. save (class): Containing the save class."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Random:
def __init__(self, board, archive, save):
"""Takes all information of the board with it's state as the beginning of the game. Args: board (class): Containing all information of the game. archive (class): Containing the archive class. save (class): Containing the save class."""
self.boa... | the_stack_v2_python_sparse | src/algorithms/random.py | KevinVuongly/ProgrAmsterdam | train | 0 | |
fdfb16032d63dccfe736757871f28ac55b96b3da | [
"self.label = label\nwith h5py.File(filename, 'r') as f:\n data = f[self.label]\n self.distance = data['D'].value\n self.N = len(self.distance)\n glon = data['glon'].value\n glat = data['glat'].value\n self.coord = get_coordinates(glon, glat)\nself.unit_vector = coord_to_uv(self.coord)",
"write_... | <|body_start_0|>
self.label = label
with h5py.File(filename, 'r') as f:
data = f[self.label]
self.distance = data['D'].value
self.N = len(self.distance)
glon = data['glon'].value
glat = data['glat'].value
self.coord = get_coordinate... | Stores the data and parameters for sources. | Source | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Source:
"""Stores the data and parameters for sources."""
def __init__(self, filename, label):
"""Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier"""
<|body_0|>
def plot(self, style, skymap):
"""Plo... | stack_v2_sparse_classes_36k_train_019003 | 15,467 | no_license | [
{
"docstring": "Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier",
"name": "__init__",
"signature": "def __init__(self, filename, label)"
},
{
"docstring": "Plot the sources on a map of the sky. Called by Data.show() :param style: ... | 4 | stack_v2_sparse_classes_30k_train_016383 | Implement the Python class `Source` described below.
Class description:
Stores the data and parameters for sources.
Method signatures and docstrings:
- def __init__(self, filename, label): Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier
- def plot(self... | Implement the Python class `Source` described below.
Class description:
Stores the data and parameters for sources.
Method signatures and docstrings:
- def __init__(self, filename, label): Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier
- def plot(self... | 0c1894ce8d9f5daed539240d3ac86e645d6de44c | <|skeleton|>
class Source:
"""Stores the data and parameters for sources."""
def __init__(self, filename, label):
"""Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier"""
<|body_0|>
def plot(self, style, skymap):
"""Plo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Source:
"""Stores the data and parameters for sources."""
def __init__(self, filename, label):
"""Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier"""
self.label = label
with h5py.File(filename, 'r') as f:
... | the_stack_v2_python_sparse | stan_implementation/analysis_interface/interfaces/data.py | cescalara/soiaporn_model | train | 1 |
57ed9ad48a7a70730d60af5cde3eb362941d9d37 | [
"self.check_connection()\nconnection = self.context.connection\nstdout = self.context.terminal.stdout\ntypename = self.arguments[0]\ntyp = self.resolve_singular_type(typename)\nbase = self.resolve_base(self.options)\nobj = self.read_input()\nif obj is None:\n obj = schema.new(typ)\n obj = self.update_object(o... | <|body_start_0|>
self.check_connection()
connection = self.context.connection
stdout = self.context.terminal.stdout
typename = self.arguments[0]
typ = self.resolve_singular_type(typename)
base = self.resolve_base(self.options)
obj = self.read_input()
if ob... | CreateCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateCommand:
def execute(self):
"""Execute the "create" command."""
<|body_0|>
def show_help(self):
"""Show help for "create"."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.check_connection()
connection = self.context.connection
... | stack_v2_sparse_classes_36k_train_019004 | 4,279 | permissive | [
{
"docstring": "Execute the \"create\" command.",
"name": "execute",
"signature": "def execute(self)"
},
{
"docstring": "Show help for \"create\".",
"name": "show_help",
"signature": "def show_help(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001032 | Implement the Python class `CreateCommand` described below.
Class description:
Implement the CreateCommand class.
Method signatures and docstrings:
- def execute(self): Execute the "create" command.
- def show_help(self): Show help for "create". | Implement the Python class `CreateCommand` described below.
Class description:
Implement the CreateCommand class.
Method signatures and docstrings:
- def execute(self): Execute the "create" command.
- def show_help(self): Show help for "create".
<|skeleton|>
class CreateCommand:
def execute(self):
"""Ex... | 202272404e0770616a650c360fe1f19a82d80be0 | <|skeleton|>
class CreateCommand:
def execute(self):
"""Execute the "create" command."""
<|body_0|>
def show_help(self):
"""Show help for "create"."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateCommand:
def execute(self):
"""Execute the "create" command."""
self.check_connection()
connection = self.context.connection
stdout = self.context.terminal.stdout
typename = self.arguments[0]
typ = self.resolve_singular_type(typename)
base = self.r... | the_stack_v2_python_sparse | lib/rhevsh/command/create.py | geertj/rhevsh | train | 0 | |
2fe38135901178a44aa571c1ef5376ccaa8ec003 | [
"super().__init__()\noutput_dim = output_dim or input_dim\nself.composition = composition_resolver.make(composition)\nself.qualifier_composition = composition_resolver.make(qualifier_composition)\nself.qualifier_aggregation = qualifier_aggregation_resolver.make(qualifier_aggregation, pos_kwargs=qualifier_aggregatio... | <|body_start_0|>
super().__init__()
output_dim = output_dim or input_dim
self.composition = composition_resolver.make(composition)
self.qualifier_composition = composition_resolver.make(qualifier_composition)
self.qualifier_aggregation = qualifier_aggregation_resolver.make(qualif... | StarE's convolution layer with qualifiers. | StarEConvLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StarEConvLayer:
"""StarE's convolution layer with qualifiers."""
def __init__(self, input_dim: int, output_dim: Optional[int]=None, dropout: float=0.2, activation: Hint[nn.Module]=nn.ReLU, composition: Hint[Composition]=None, qualifier_aggregation: Hint[QualifierAggregation]=None, qualifier_... | stack_v2_sparse_classes_36k_train_019005 | 9,675 | permissive | [
{
"docstring": "Initialize the layer. :param input_dim: The input dimension (entity and relation representations). :param output_dim: The output dimension. Defaults to the input dimension. :param dropout: The dropout to apply to the updated entity representations from forward / backward edges (but not for self-... | 3 | stack_v2_sparse_classes_30k_train_016100 | Implement the Python class `StarEConvLayer` described below.
Class description:
StarE's convolution layer with qualifiers.
Method signatures and docstrings:
- def __init__(self, input_dim: int, output_dim: Optional[int]=None, dropout: float=0.2, activation: Hint[nn.Module]=nn.ReLU, composition: Hint[Composition]=None... | Implement the Python class `StarEConvLayer` described below.
Class description:
StarE's convolution layer with qualifiers.
Method signatures and docstrings:
- def __init__(self, input_dim: int, output_dim: Optional[int]=None, dropout: float=0.2, activation: Hint[nn.Module]=nn.ReLU, composition: Hint[Composition]=None... | 4921523143ae1f7683091b37174aef6fdc19b74f | <|skeleton|>
class StarEConvLayer:
"""StarE's convolution layer with qualifiers."""
def __init__(self, input_dim: int, output_dim: Optional[int]=None, dropout: float=0.2, activation: Hint[nn.Module]=nn.ReLU, composition: Hint[Composition]=None, qualifier_aggregation: Hint[QualifierAggregation]=None, qualifier_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StarEConvLayer:
"""StarE's convolution layer with qualifiers."""
def __init__(self, input_dim: int, output_dim: Optional[int]=None, dropout: float=0.2, activation: Hint[nn.Module]=nn.ReLU, composition: Hint[Composition]=None, qualifier_aggregation: Hint[QualifierAggregation]=None, qualifier_aggregation_k... | the_stack_v2_python_sparse | src/mphrqe/layer/gnn.py | HyperQueryEmbedding/hqe | train | 1 |
5ba7d5df3e648385df930df49e46dba548beffd8 | [
"super().__init__(mol, cuda)\nself.fc1 = nn.Linear(1, 16, bias=False)\nself.fc2 = nn.Linear(16, 1, bias=False)\nself.nl_func = torch.nn.Sigmoid()\neps = 1.0\nself.fc1.weight.data *= eps\nself.fc2.weight.data *= eps",
"original_shape = ree.shape\nx = ree.reshape(-1, 1)\nx = self.fc1(x)\nx = self.nl_func(x)\nx = se... | <|body_start_0|>
super().__init__(mol, cuda)
self.fc1 = nn.Linear(1, 16, bias=False)
self.fc2 = nn.Linear(16, 1, bias=False)
self.nl_func = torch.nn.Sigmoid()
eps = 1.0
self.fc1.weight.data *= eps
self.fc2.weight.data *= eps
<|end_body_0|>
<|body_start_1|>
... | BackFlowKernelFullyConnected | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackFlowKernelFullyConnected:
def __init__(self, mol, cuda):
"""Compute the back flow kernel, i.e. the function f(rij) where rij is the distance between electron i and j This kernel is used in the backflow transformation .. math: q_i = r_i + \\sum_{j\\neq i} f(r_{ij}) (r_i-r_j)"""
... | stack_v2_sparse_classes_36k_train_019006 | 1,192 | permissive | [
{
"docstring": "Compute the back flow kernel, i.e. the function f(rij) where rij is the distance between electron i and j This kernel is used in the backflow transformation .. math: q_i = r_i + \\\\sum_{j\\\\neq i} f(r_{ij}) (r_i-r_j)",
"name": "__init__",
"signature": "def __init__(self, mol, cuda)"
... | 2 | stack_v2_sparse_classes_30k_train_001372 | Implement the Python class `BackFlowKernelFullyConnected` described below.
Class description:
Implement the BackFlowKernelFullyConnected class.
Method signatures and docstrings:
- def __init__(self, mol, cuda): Compute the back flow kernel, i.e. the function f(rij) where rij is the distance between electron i and j T... | Implement the Python class `BackFlowKernelFullyConnected` described below.
Class description:
Implement the BackFlowKernelFullyConnected class.
Method signatures and docstrings:
- def __init__(self, mol, cuda): Compute the back flow kernel, i.e. the function f(rij) where rij is the distance between electron i and j T... | 439a79e97ee63057e3032d28a1a5ebafd2d5b5e4 | <|skeleton|>
class BackFlowKernelFullyConnected:
def __init__(self, mol, cuda):
"""Compute the back flow kernel, i.e. the function f(rij) where rij is the distance between electron i and j This kernel is used in the backflow transformation .. math: q_i = r_i + \\sum_{j\\neq i} f(r_{ij}) (r_i-r_j)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackFlowKernelFullyConnected:
def __init__(self, mol, cuda):
"""Compute the back flow kernel, i.e. the function f(rij) where rij is the distance between electron i and j This kernel is used in the backflow transformation .. math: q_i = r_i + \\sum_{j\\neq i} f(r_{ij}) (r_i-r_j)"""
super().__in... | the_stack_v2_python_sparse | qmctorch/wavefunction/orbitals/backflow/kernels/backflow_kernel_fully_connected.py | NLESC-JCER/QMCTorch | train | 22 | |
76fc7ebd3d4cc5f7797c0ef151d1cbecdadf21bc | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PrinterShare()",
"from .group import Group\nfrom .printer import Printer\nfrom .printer_base import PrinterBase\nfrom .printer_share_viewpoint import PrinterShareViewpoint\nfrom .user import User\nfrom .group import Group\nfrom .printe... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return PrinterShare()
<|end_body_0|>
<|body_start_1|>
from .group import Group
from .printer import Printer
from .printer_base import PrinterBase
from .printer_share_viewpoint i... | PrinterShare | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrinterShare:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterShare:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_36k_train_019007 | 4,184 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: PrinterShare",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | null | Implement the Python class `PrinterShare` described below.
Class description:
Implement the PrinterShare class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterShare: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `PrinterShare` described below.
Class description:
Implement the PrinterShare class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterShare: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PrinterShare:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterShare:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrinterShare:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterShare:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: PrinterShare""... | the_stack_v2_python_sparse | msgraph/generated/models/printer_share.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
99471dc8d8095ae4c2b829f35bee4b4dd6dc7bf4 | [
"self._file_path = file_path\nself._nbd_path = '/dev/nbd' + str(LoadNbdImage.nbd_port % 16)\nLoadNbdImage.nbd_port = (LoadNbdImage.nbd_port + 1) % 16",
"mountpath = self._nbd_path\nlogging.debug('Starting qemu block device emulation ' + mountpath + ' from image ' + self._file_path)\nmodprobe_cmd = ['modprobe', 'n... | <|body_start_0|>
self._file_path = file_path
self._nbd_path = '/dev/nbd' + str(LoadNbdImage.nbd_port % 16)
LoadNbdImage.nbd_port = (LoadNbdImage.nbd_port + 1) % 16
<|end_body_0|>
<|body_start_1|>
mountpath = self._nbd_path
logging.debug('Starting qemu block device emulation ' + ... | Mounts virtual disk via qemu-nbd | LoadNbdImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadNbdImage:
"""Mounts virtual disk via qemu-nbd"""
def __init__(self, file_path):
"""Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open"""
<|body_0|>
def __enter__(self):
"""Map disk image as a... | stack_v2_sparse_classes_36k_train_019008 | 8,532 | no_license | [
{
"docstring": "Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open",
"name": "__init__",
"signature": "def __init__(self, file_path)"
},
{
"docstring": "Map disk image as a device.",
"name": "__enter__",
"signature": "de... | 3 | null | Implement the Python class `LoadNbdImage` described below.
Class description:
Mounts virtual disk via qemu-nbd
Method signatures and docstrings:
- def __init__(self, file_path): Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open
- def __enter__(self)... | Implement the Python class `LoadNbdImage` described below.
Class description:
Mounts virtual disk via qemu-nbd
Method signatures and docstrings:
- def __init__(self, file_path): Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open
- def __enter__(self)... | e01a7e11931a61ae91b9cadbc961d703f8c77925 | <|skeleton|>
class LoadNbdImage:
"""Mounts virtual disk via qemu-nbd"""
def __init__(self, file_path):
"""Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open"""
<|body_0|>
def __enter__(self):
"""Map disk image as a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadNbdImage:
"""Mounts virtual disk via qemu-nbd"""
def __init__(self, file_path):
"""Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open"""
self._file_path = file_path
self._nbd_path = '/dev/nbd' + str(LoadNbdIma... | the_stack_v2_python_sparse | Migrate/Linux_GC/NbdBundle_utils.py | migrate2iaas/cloudscraper-engine | train | 1 |
5d9b10994e1c8a53e55e6d0357f14a3e76b0a343 | [
"motif_info = Motif.objects.get(pk=kwargs['motif_pk'])\nmotifinfo_serializer = self.serializer_class(motif_info)\ncontent = {'motifInfo': motifinfo_serializer.data}\nreturn Response(content, status=status.HTTP_200_OK)",
"motif_info = Motif.objects.get(pk=kwargs['motif_pk'])\nif self.request.user.is_authenticated:... | <|body_start_0|>
motif_info = Motif.objects.get(pk=kwargs['motif_pk'])
motifinfo_serializer = self.serializer_class(motif_info)
content = {'motifInfo': motifinfo_serializer.data}
return Response(content, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
motif_info = Mot... | 모티프 세부페이지 조회 | MotifDetailRetrieveUpdateDestroyView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotifDetailRetrieveUpdateDestroyView:
"""모티프 세부페이지 조회"""
def get(self, request, *args, **kwargs):
"""모티프 세부 정보와 연결된 작품 정보"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""모티프 제목 수정"""
<|body_1|>
def delete(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_36k_train_019009 | 6,610 | no_license | [
{
"docstring": "모티프 세부 정보와 연결된 작품 정보",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "모티프 제목 수정",
"name": "put",
"signature": "def put(self, request, *args, **kwargs)"
},
{
"docstring": "모티프 삭제",
"name": "delete",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_009954 | Implement the Python class `MotifDetailRetrieveUpdateDestroyView` described below.
Class description:
모티프 세부페이지 조회
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 모티프 세부 정보와 연결된 작품 정보
- def put(self, request, *args, **kwargs): 모티프 제목 수정
- def delete(self, request, *args, **kwargs): 모티프 삭제 | Implement the Python class `MotifDetailRetrieveUpdateDestroyView` described below.
Class description:
모티프 세부페이지 조회
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 모티프 세부 정보와 연결된 작품 정보
- def put(self, request, *args, **kwargs): 모티프 제목 수정
- def delete(self, request, *args, **kwargs): 모티프 삭제... | 4031afe1b5d45865a61f4ff4136a8314258a917a | <|skeleton|>
class MotifDetailRetrieveUpdateDestroyView:
"""모티프 세부페이지 조회"""
def get(self, request, *args, **kwargs):
"""모티프 세부 정보와 연결된 작품 정보"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""모티프 제목 수정"""
<|body_1|>
def delete(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MotifDetailRetrieveUpdateDestroyView:
"""모티프 세부페이지 조회"""
def get(self, request, *args, **kwargs):
"""모티프 세부 정보와 연결된 작품 정보"""
motif_info = Motif.objects.get(pk=kwargs['motif_pk'])
motifinfo_serializer = self.serializer_class(motif_info)
content = {'motifInfo': motifinfo_ser... | the_stack_v2_python_sparse | django_app/motif/apis/motifs.py | Monaegi/Julia-WordyGallery | train | 1 |
c0d6d78684b6939d2a5782ed7631cee4e471df98 | [
"if s is not None and t is not None and (abs(len(s) - len(t)) == 1):\n dic = {}\n for i, x in enumerate(s):\n if x not in dic:\n dic[x] = [i]\n else:\n dic[x].append(i)\n other_dic = {}\n for j, y in enumerate(t):\n if y not in dic:\n return y\n ... | <|body_start_0|>
if s is not None and t is not None and (abs(len(s) - len(t)) == 1):
dic = {}
for i, x in enumerate(s):
if x not in dic:
dic[x] = [i]
else:
dic[x].append(i)
other_dic = {}
for ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find_diff_non_sorted(self, s, t):
"""worst case: if the extra character is one of the duplicate values complexity: O(n) + O(m) + O(distinct characters in t): n => len(s), m => len(t) O(m)"""
<|body_0|>
def findTheDifference(self, s, t):
""":type s: str ... | stack_v2_sparse_classes_36k_train_019010 | 2,381 | no_license | [
{
"docstring": "worst case: if the extra character is one of the duplicate values complexity: O(n) + O(m) + O(distinct characters in t): n => len(s), m => len(t) O(m)",
"name": "find_diff_non_sorted",
"signature": "def find_diff_non_sorted(self, s, t)"
},
{
"docstring": ":type s: str :type t: st... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_diff_non_sorted(self, s, t): worst case: if the extra character is one of the duplicate values complexity: O(n) + O(m) + O(distinct characters in t): n => len(s), m => l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_diff_non_sorted(self, s, t): worst case: if the extra character is one of the duplicate values complexity: O(n) + O(m) + O(distinct characters in t): n => len(s), m => l... | d551b46c949e12c373250d88959a83f995b80ed9 | <|skeleton|>
class Solution:
def find_diff_non_sorted(self, s, t):
"""worst case: if the extra character is one of the duplicate values complexity: O(n) + O(m) + O(distinct characters in t): n => len(s), m => len(t) O(m)"""
<|body_0|>
def findTheDifference(self, s, t):
""":type s: str ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def find_diff_non_sorted(self, s, t):
"""worst case: if the extra character is one of the duplicate values complexity: O(n) + O(m) + O(distinct characters in t): n => len(s), m => len(t) O(m)"""
if s is not None and t is not None and (abs(len(s) - len(t)) == 1):
dic = {}
... | the_stack_v2_python_sparse | oj/leet_code/leet-code-389.py | PollobAtGit/python-101 | train | 0 | |
73d67deb2b33517744f2fa03192e41fa115352de | [
"recipe = {'flour': 500, 'sugar': 200, 'eggs': 1}\navailable = {'flour': 1200, 'sugar': 1200, 'eggs': 5, 'milk': 200}\nself.assertEqual(main.cakes(recipe, available), 2)",
"recipe = {'apples': 3, 'flour': 300, 'sugar': 150, 'milk': 100, 'oil': 100}\navailable = {'sugar': 500, 'flour': 2000, 'milk': 2000}\nself.as... | <|body_start_0|>
recipe = {'flour': 500, 'sugar': 200, 'eggs': 1}
available = {'flour': 1200, 'sugar': 1200, 'eggs': 5, 'milk': 200}
self.assertEqual(main.cakes(recipe, available), 2)
<|end_body_0|>
<|body_start_1|>
recipe = {'apples': 3, 'flour': 300, 'sugar': 150, 'milk': 100, 'oil': ... | SampleTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleTests:
def test_extra_stock(self):
"""Should ignore extra available ingredients"""
<|body_0|>
def test_missing_ingredient(self):
"""Should count missing available ingredients as 0"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
recipe = {'flou... | stack_v2_sparse_classes_36k_train_019011 | 718 | no_license | [
{
"docstring": "Should ignore extra available ingredients",
"name": "test_extra_stock",
"signature": "def test_extra_stock(self)"
},
{
"docstring": "Should count missing available ingredients as 0",
"name": "test_missing_ingredient",
"signature": "def test_missing_ingredient(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012285 | Implement the Python class `SampleTests` described below.
Class description:
Implement the SampleTests class.
Method signatures and docstrings:
- def test_extra_stock(self): Should ignore extra available ingredients
- def test_missing_ingredient(self): Should count missing available ingredients as 0 | Implement the Python class `SampleTests` described below.
Class description:
Implement the SampleTests class.
Method signatures and docstrings:
- def test_extra_stock(self): Should ignore extra available ingredients
- def test_missing_ingredient(self): Should count missing available ingredients as 0
<|skeleton|>
cla... | 48b27bca47133357be68735e68b97e68e36246be | <|skeleton|>
class SampleTests:
def test_extra_stock(self):
"""Should ignore extra available ingredients"""
<|body_0|>
def test_missing_ingredient(self):
"""Should count missing available ingredients as 0"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SampleTests:
def test_extra_stock(self):
"""Should ignore extra available ingredients"""
recipe = {'flour': 500, 'sugar': 200, 'eggs': 1}
available = {'flour': 1200, 'sugar': 1200, 'eggs': 5, 'milk': 200}
self.assertEqual(main.cakes(recipe, available), 2)
def test_missing_... | the_stack_v2_python_sparse | @Codewars/5_pete-the-baker/tests.py | hosmanadam/coding-challenges | train | 0 | |
205d6d848c7c4171ccde137e7fc7c2521fe8c86a | [
"inputSpecification = super().getInputSpecification()\ninputSpecification.addSubSimple('label', InputTypes.StringType)\ninputSpecification.addSubSimple('clusterIDs', InputTypes.IntegerListType)\nreturn inputSpecification",
"super().__init__()\nself.setInputDataType('dict')\nself.keepInputMeta(True)\nself.outputMu... | <|body_start_0|>
inputSpecification = super().getInputSpecification()
inputSpecification.addSubSimple('label', InputTypes.StringType)
inputSpecification.addSubSimple('clusterIDs', InputTypes.IntegerListType)
return inputSpecification
<|end_body_0|>
<|body_start_1|>
super().__ini... | This Post-Processor filters out the points or histories accordingly to a chosen clustering label | dataObjectLabelFilter | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are ret... | stack_v2_sparse_classes_36k_train_019012 | 5,021 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_012705 | Implement the Python class `dataObjectLabelFilter` described below.
Class description:
This Post-Processor filters out the points or histories accordingly to a chosen clustering label
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data... | Implement the Python class `dataObjectLabelFilter` described below.
Class description:
This Post-Processor filters out the points or histories accordingly to a chosen clustering label
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the s... | the_stack_v2_python_sparse | ravenframework/Models/PostProcessors/dataObjectLabelFilter.py | idaholab/raven | train | 201 |
04a80cdb3be33cbb185f369a30b4ec3122a588d3 | [
"self.cfg_spec = ConfigObj(config_spec_text.splitlines(), list_values=False)\nself.cfg_filename = filename\nvalid = Validator()\nif not os.path.exists(self.cfg_filename):\n cfg = ConfigObj(configspec=self.cfg_spec, stringify=True, list_values=True)\n cfg.filename = self.cfg_filename\n test = cfg.validate(v... | <|body_start_0|>
self.cfg_spec = ConfigObj(config_spec_text.splitlines(), list_values=False)
self.cfg_filename = filename
valid = Validator()
if not os.path.exists(self.cfg_filename):
cfg = ConfigObj(configspec=self.cfg_spec, stringify=True, list_values=True)
cfg.... | Configuration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
def __init__(self, filename):
"""Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters"""
<|body_0|>
def save_config(self, new_config):
"""Writes the config file upon exiting the prog... | stack_v2_sparse_classes_36k_train_019013 | 3,999 | no_license | [
{
"docstring": "Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Writes the config file upon exiting the program",
"name": "save_conf... | 2 | stack_v2_sparse_classes_30k_train_011244 | Implement the Python class `Configuration` described below.
Class description:
Implement the Configuration class.
Method signatures and docstrings:
- def __init__(self, filename): Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters
- def save_conf... | Implement the Python class `Configuration` described below.
Class description:
Implement the Configuration class.
Method signatures and docstrings:
- def __init__(self, filename): Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters
- def save_conf... | adf081cd95afd9487d0028235eea58a72a1cc05c | <|skeleton|>
class Configuration:
def __init__(self, filename):
"""Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters"""
<|body_0|>
def save_config(self, new_config):
"""Writes the config file upon exiting the prog... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Configuration:
def __init__(self, filename):
"""Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters"""
self.cfg_spec = ConfigObj(config_spec_text.splitlines(), list_values=False)
self.cfg_filename = filename
... | the_stack_v2_python_sparse | dreampy3/utils/configuration.py | lmt-heterodyne/dreampy3 | train | 0 | |
5ad40d28d2b2e035ecbb3e9e06dcc2808518ea6d | [
"output = [0] * (rowIndex + 1)\nfor i in range(rowIndex + 1):\n previous = output[0] = 1\n for j in range(1, i + 1):\n previous, output[j] = (output[j], previous + output[j])\nreturn output",
"if rowIndex < 0:\n return []\noutput = [None] * (rowIndex + 1)\noutput[0] = 1\nfor i in range(1, rowIndex... | <|body_start_0|>
output = [0] * (rowIndex + 1)
for i in range(rowIndex + 1):
previous = output[0] = 1
for j in range(1, i + 1):
previous, output[j] = (output[j], previous + output[j])
return output
<|end_body_0|>
<|body_start_1|>
if rowIndex < 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow_verbose(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
output = [0] * (rowIndex + 1)
... | stack_v2_sparse_classes_36k_train_019014 | 1,604 | no_license | [
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow",
"signature": "def getRow(self, rowIndex)"
},
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow_verbose",
"signature": "def getRow_verbose(self, rowIndex)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow_verbose(self, rowIndex): :type rowIndex: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow_verbose(self, rowIndex): :type rowIndex: int :rtype: List[int]
<|skeleton|>
class Solution:
d... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow_verbose(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
output = [0] * (rowIndex + 1)
for i in range(rowIndex + 1):
previous = output[0] = 1
for j in range(1, i + 1):
previous, output[j] = (output[j], previous + output[j... | the_stack_v2_python_sparse | src/lt_119.py | oxhead/CodingYourWay | train | 0 | |
5adbf625442d0c86ea01be2e168dada03e9165ca | [
"current_entries = CurrentEntry.objects.filter(user=self.request.user)\npayouts = Payout.objects.filter(entry__in=current_entries)\nlineup_map = {}\nfor entry in current_entries:\n lineup_map[entry.lineup.pk] = entry.lineup\ntotal_buyins = 0\nnum_entries = 0\nwinnings = 0\npossible = 0\ncontest_map = {}\nfor lin... | <|body_start_0|>
current_entries = CurrentEntry.objects.filter(user=self.request.user)
payouts = Payout.objects.filter(entry__in=current_entries)
lineup_map = {}
for entry in current_entries:
lineup_map[entry.lineup.pk] = entry.lineup
total_buyins = 0
num_entr... | inherits UserPlayHistoryAPIView for the get_history_data() method. get the entry history & the Current lineups for a user on a day. | UserPlayHistoryWithCurrentAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPlayHistoryWithCurrentAPIView:
"""inherits UserPlayHistoryAPIView for the get_history_data() method. get the entry history & the Current lineups for a user on a day."""
def get_current_data(self):
"""get the Current lineup data"""
<|body_0|>
def get(self, request, ye... | stack_v2_sparse_classes_36k_train_019015 | 29,459 | no_license | [
{
"docstring": "get the Current lineup data",
"name": "get_current_data",
"signature": "def get_current_data(self)"
},
{
"docstring": "Given the 'task' parameter, return the status of the task (ie: the buyin) :param request: :param format: :return:",
"name": "get",
"signature": "def get(... | 2 | null | Implement the Python class `UserPlayHistoryWithCurrentAPIView` described below.
Class description:
inherits UserPlayHistoryAPIView for the get_history_data() method. get the entry history & the Current lineups for a user on a day.
Method signatures and docstrings:
- def get_current_data(self): get the Current lineup ... | Implement the Python class `UserPlayHistoryWithCurrentAPIView` described below.
Class description:
inherits UserPlayHistoryAPIView for the get_history_data() method. get the entry history & the Current lineups for a user on a day.
Method signatures and docstrings:
- def get_current_data(self): get the Current lineup ... | 4796fa9d88b56f80def011e2b043ce595bfce8c4 | <|skeleton|>
class UserPlayHistoryWithCurrentAPIView:
"""inherits UserPlayHistoryAPIView for the get_history_data() method. get the entry history & the Current lineups for a user on a day."""
def get_current_data(self):
"""get the Current lineup data"""
<|body_0|>
def get(self, request, ye... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPlayHistoryWithCurrentAPIView:
"""inherits UserPlayHistoryAPIView for the get_history_data() method. get the entry history & the Current lineups for a user on a day."""
def get_current_data(self):
"""get the Current lineup data"""
current_entries = CurrentEntry.objects.filter(user=sel... | the_stack_v2_python_sparse | contest/views.py | nakamotohideyoshi/draftboard-web | train | 0 |
f592472ac4961f7bf39d3c5c435f05315a830840 | [
"from .models import TrainConfig\npool_over = [CoreConfig(), ReadoutConfig(), Seed(), ShifterConfig(), ModulatorConfig(), TrainConfig()]\nh = self.heading.primary_key\nfor e in chain(*map(attrgetter('heading.primary_key'), pool_over), attrs):\n if e not in attrs:\n h.remove(e)\nreturn self * dj.U(*h).aggr... | <|body_start_0|>
from .models import TrainConfig
pool_over = [CoreConfig(), ReadoutConfig(), Seed(), ShifterConfig(), ModulatorConfig(), TrainConfig()]
h = self.heading.primary_key
for e in chain(*map(attrgetter('heading.primary_key'), pool_over), attrs):
if e not in attrs:
... | CorePlusReadoutModel | [
"MIT",
"CC-BY-NC-ND-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorePlusReadoutModel:
def best_modulo(self, *attrs):
"""Returns: best model according to validation error"""
<|body_0|>
def build_model(self, key=None, img_shape=None, n_neurons=None, burn_in=15):
"""Builds a specified model Args: key: key for CNNParameters used to l... | stack_v2_sparse_classes_36k_train_019016 | 10,246 | permissive | [
{
"docstring": "Returns: best model according to validation error",
"name": "best_modulo",
"signature": "def best_modulo(self, *attrs)"
},
{
"docstring": "Builds a specified model Args: key: key for CNNParameters used to load the parameter of the model. If None, (self & key) must be non-empty so... | 2 | stack_v2_sparse_classes_30k_train_013205 | Implement the Python class `CorePlusReadoutModel` described below.
Class description:
Implement the CorePlusReadoutModel class.
Method signatures and docstrings:
- def best_modulo(self, *attrs): Returns: best model according to validation error
- def build_model(self, key=None, img_shape=None, n_neurons=None, burn_in... | Implement the Python class `CorePlusReadoutModel` described below.
Class description:
Implement the CorePlusReadoutModel class.
Method signatures and docstrings:
- def best_modulo(self, *attrs): Returns: best model according to validation error
- def build_model(self, key=None, img_shape=None, n_neurons=None, burn_in... | e1cfb3c0611d6a9f8a27bfa79404e46ccd0a838c | <|skeleton|>
class CorePlusReadoutModel:
def best_modulo(self, *attrs):
"""Returns: best model according to validation error"""
<|body_0|>
def build_model(self, key=None, img_shape=None, n_neurons=None, burn_in=15):
"""Builds a specified model Args: key: key for CNNParameters used to l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CorePlusReadoutModel:
def best_modulo(self, *attrs):
"""Returns: best model according to validation error"""
from .models import TrainConfig
pool_over = [CoreConfig(), ReadoutConfig(), Seed(), ShifterConfig(), ModulatorConfig(), TrainConfig()]
h = self.heading.primary_key
... | the_stack_v2_python_sparse | nips2018/movie/_utils.py | nkarantzas/Sinz2018_NIPS | train | 0 | |
8c8238b8bab8f285a02a2c26dcdf8fce399d5ebd | [
"environment = SandboxEnvironment(client_id=PAYPAL_CLIENT_ID, client_secret=PAYPAL_CLIENT_SECRET)\nself.client = PayPalHttpClient(environment)\nself.process_notification = {PayPalStrings.WEBHOOK_APPROVED.value: self.capture, PayPalStrings.WEBHOOK_COMPLETED.value: self.fulfill}",
"capture_id = wh_data['resource'][... | <|body_start_0|>
environment = SandboxEnvironment(client_id=PAYPAL_CLIENT_ID, client_secret=PAYPAL_CLIENT_SECRET)
self.client = PayPalHttpClient(environment)
self.process_notification = {PayPalStrings.WEBHOOK_APPROVED.value: self.capture, PayPalStrings.WEBHOOK_COMPLETED.value: self.fulfill}
<|en... | Клиент платёжной системы PayPal. Содержит методы для инициализации сессии и обработки платежей в виде PayPal Checkout - выписки, захвата, верификации и завершения Checkout. | PaypalClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaypalClient:
"""Клиент платёжной системы PayPal. Содержит методы для инициализации сессии и обработки платежей в виде PayPal Checkout - выписки, захвата, верификации и завершения Checkout."""
def __init__(self) -> None:
"""Инициализирует сессию работы с системой PayPal."""
<... | stack_v2_sparse_classes_36k_train_019017 | 8,853 | no_license | [
{
"docstring": "Инициализирует сессию работы с системой PayPal.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Завершает заказ, уведомляет клиента.",
"name": "fulfill",
"signature": "def fulfill(self, wh_data: Dict[str, Any]) -> None"
},
{
"doc... | 6 | stack_v2_sparse_classes_30k_train_011715 | Implement the Python class `PaypalClient` described below.
Class description:
Клиент платёжной системы PayPal. Содержит методы для инициализации сессии и обработки платежей в виде PayPal Checkout - выписки, захвата, верификации и завершения Checkout.
Method signatures and docstrings:
- def __init__(self) -> None: Ини... | Implement the Python class `PaypalClient` described below.
Class description:
Клиент платёжной системы PayPal. Содержит методы для инициализации сессии и обработки платежей в виде PayPal Checkout - выписки, захвата, верификации и завершения Checkout.
Method signatures and docstrings:
- def __init__(self) -> None: Ини... | 015adcc4e138cdcc6163c0f7cb8a5fd6abe43266 | <|skeleton|>
class PaypalClient:
"""Клиент платёжной системы PayPal. Содержит методы для инициализации сессии и обработки платежей в виде PayPal Checkout - выписки, захвата, верификации и завершения Checkout."""
def __init__(self) -> None:
"""Инициализирует сессию работы с системой PayPal."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaypalClient:
"""Клиент платёжной системы PayPal. Содержит методы для инициализации сессии и обработки платежей в виде PayPal Checkout - выписки, захвата, верификации и завершения Checkout."""
def __init__(self) -> None:
"""Инициализирует сессию работы с системой PayPal."""
environment = ... | the_stack_v2_python_sparse | billing/paypal/client.py | half-cat/gu-chatbot-01 | train | 0 |
db66c9975d076099c7957f1b3acde7c65f25f5d1 | [
"if not array:\n return 0\ndp = [1]\nanswer = 1\nfor i in range(1, len(array)):\n maxLIS = 1\n for j in range(0, i):\n if array[i] > array[j] and dp[j] + 1 > maxLIS:\n maxLIS = dp[j] + 1\n dp.append(maxLIS)\n answer = max(answer, maxLIS)\nreturn answer",
"def binarySearch(nums, st... | <|body_start_0|>
if not array:
return 0
dp = [1]
answer = 1
for i in range(1, len(array)):
maxLIS = 1
for j in range(0, i):
if array[i] > array[j] and dp[j] + 1 > maxLIS:
maxLIS = dp[j] + 1
dp.append(maxL... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestIncreasingSubsequence(self, array):
""":type array: List[int] :rtype: int"""
<|body_0|>
def LIS(self, array):
""":type array: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not array:
return... | stack_v2_sparse_classes_36k_train_019018 | 1,474 | no_license | [
{
"docstring": ":type array: List[int] :rtype: int",
"name": "longestIncreasingSubsequence",
"signature": "def longestIncreasingSubsequence(self, array)"
},
{
"docstring": ":type array: List[int] :rtype: int",
"name": "LIS",
"signature": "def LIS(self, array)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013825 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestIncreasingSubsequence(self, array): :type array: List[int] :rtype: int
- def LIS(self, array): :type array: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestIncreasingSubsequence(self, array): :type array: List[int] :rtype: int
- def LIS(self, array): :type array: List[int] :rtype: int
<|skeleton|>
class Solution:
de... | fa624b702129fa3efd6997791e4cd37c420e114e | <|skeleton|>
class Solution:
def longestIncreasingSubsequence(self, array):
""":type array: List[int] :rtype: int"""
<|body_0|>
def LIS(self, array):
""":type array: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestIncreasingSubsequence(self, array):
""":type array: List[int] :rtype: int"""
if not array:
return 0
dp = [1]
answer = 1
for i in range(1, len(array)):
maxLIS = 1
for j in range(0, i):
if array[i] >... | the_stack_v2_python_sparse | p62/p62.py | zois-tasoulas/DailyInterviewPro | train | 0 | |
8f9826e7d97a95917e39842cb642baf24cc5eaac | [
"def partition(nums, left, right):\n pivot = nums[left]\n while left < right:\n while left < right and nums[right] >= pivot:\n right -= 1\n nums[left] = nums[right]\n while left < right and nums[left] <= pivot:\n left += 1\n nums[right] = nums[left]\n nums[... | <|body_start_0|>
def partition(nums, left, right):
pivot = nums[left]
while left < right:
while left < right and nums[right] >= pivot:
right -= 1
nums[left] = nums[right]
while left < right and nums[left] <= pivot:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def min_k_num(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。"""
<|body_0|>
def min_k_num1(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间复杂度为O(nlogk)。"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_019019 | 2,555 | no_license | [
{
"docstring": "给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。",
"name": "min_k_num",
"signature": "def min_k_num(self, nums, k)"
},
{
"docstring": "给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间复杂度为O(nlogk)。",
"name": "min_k_num1",
"signature": "def min_k_num1(self... | 2 | stack_v2_sparse_classes_30k_train_003897 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_k_num(self, nums, k): 给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。
- def min_k_num1(self, nums, k): 给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_k_num(self, nums, k): 给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。
- def min_k_num1(self, nums, k): 给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间... | ca4dacda39dc12d53ed8d4448b3356a3f2936603 | <|skeleton|>
class Solution:
def min_k_num(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。"""
<|body_0|>
def min_k_num1(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间复杂度为O(nlogk)。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def min_k_num(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。"""
def partition(nums, left, right):
pivot = nums[left]
while left < right:
while left < right and nums[right] >= pivot:
... | the_stack_v2_python_sparse | book/面试题40-最小的k个数.py | lcqbit11/algorithms | train | 0 | |
dedcf12b8adf97baa7b82b4cffa72d9680cd50be | [
"mappings = super().get_mapping(index=index, params=params or {})\nif self.client.__es_version__ == '6':\n for index_name in mappings.keys():\n mappings[index_name]['mappings'] = mappings[index_name]['mappings'][DOC_TYPE]\nreturn mappings",
"if self.client.__es_version__ == '6':\n return super().put_... | <|body_start_0|>
mappings = super().get_mapping(index=index, params=params or {})
if self.client.__es_version__ == '6':
for index_name in mappings.keys():
mappings[index_name]['mappings'] = mappings[index_name]['mappings'][DOC_TYPE]
return mappings
<|end_body_0|>
<|b... | Compatibility wrapper around the ES IndicesClient from elasticsearch-py that handles incompatibilities to let Richie run ES6 and ES7. | ElasticsearchIndicesClientCompat7to6 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticsearchIndicesClientCompat7to6:
"""Compatibility wrapper around the ES IndicesClient from elasticsearch-py that handles incompatibilities to let Richie run ES6 and ES7."""
def get_mapping(self, index=None, params=None):
"""Pluck from the dummy type in the mapping if using ES6, ... | stack_v2_sparse_classes_36k_train_019020 | 3,810 | permissive | [
{
"docstring": "Pluck from the dummy type in the mapping if using ES6, which nests the actual mapping info under the document type.",
"name": "get_mapping",
"signature": "def get_mapping(self, index=None, params=None)"
},
{
"docstring": "Add our dummy type in kwargs of the put_mapping call to sa... | 2 | null | Implement the Python class `ElasticsearchIndicesClientCompat7to6` described below.
Class description:
Compatibility wrapper around the ES IndicesClient from elasticsearch-py that handles incompatibilities to let Richie run ES6 and ES7.
Method signatures and docstrings:
- def get_mapping(self, index=None, params=None)... | Implement the Python class `ElasticsearchIndicesClientCompat7to6` described below.
Class description:
Compatibility wrapper around the ES IndicesClient from elasticsearch-py that handles incompatibilities to let Richie run ES6 and ES7.
Method signatures and docstrings:
- def get_mapping(self, index=None, params=None)... | f2d46fc46b271eb3b4d565039a29c15ba15f027c | <|skeleton|>
class ElasticsearchIndicesClientCompat7to6:
"""Compatibility wrapper around the ES IndicesClient from elasticsearch-py that handles incompatibilities to let Richie run ES6 and ES7."""
def get_mapping(self, index=None, params=None):
"""Pluck from the dummy type in the mapping if using ES6, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticsearchIndicesClientCompat7to6:
"""Compatibility wrapper around the ES IndicesClient from elasticsearch-py that handles incompatibilities to let Richie run ES6 and ES7."""
def get_mapping(self, index=None, params=None):
"""Pluck from the dummy type in the mapping if using ES6, which nests t... | the_stack_v2_python_sparse | src/richie/apps/search/elasticsearch.py | openfun/richie | train | 238 |
7980062b4013dc253e530a99f78a67d8565a519d | [
"last_year = datetime.today().replace(year=datetime.today().year - 1)\nfor item in response.css('.entry p'):\n if item.xpath('.//span'):\n continue\n start = self._parse_start(item, response)\n if not start or (start < last_year and (not self.settings.getbool('CITY_SCRAPERS_ARCHIVE'))):\n ret... | <|body_start_0|>
last_year = datetime.today().replace(year=datetime.today().year - 1)
for item in response.css('.entry p'):
if item.xpath('.//span'):
continue
start = self._parse_start(item, response)
if not start or (start < last_year and (not self.se... | ChiInfrastructureTrustSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChiInfrastructureTrustSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_start(self, item, response):
"""Parse start datetime as a ... | stack_v2_sparse_classes_36k_train_019021 | 3,561 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse start datetime as a naive datetime object.",
"name": "_parse_start"... | 4 | null | Implement the Python class `ChiInfrastructureTrustSpider` described below.
Class description:
Implement the ChiInfrastructureTrustSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scr... | Implement the Python class `ChiInfrastructureTrustSpider` described below.
Class description:
Implement the ChiInfrastructureTrustSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scr... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class ChiInfrastructureTrustSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_start(self, item, response):
"""Parse start datetime as a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChiInfrastructureTrustSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs."""
last_year = datetime.today().replace(year=datetime.today().year - 1)
for item in response.css('.ent... | the_stack_v2_python_sparse | city_scrapers/spiders/chi_infrastructure_trust.py | City-Bureau/city-scrapers | train | 308 | |
be76ad3d413e402df7e6ac137d0d26a444ef98f9 | [
"super().__init__(max_number=max_number, min_number=min_number, seed=seed)\nself.stamp_size = stamp_size\nself.mag_name = mag_name\nif min_number < 1:\n raise ValueError('At least 1 bright galaxy will be added, so need min_number >=1.')",
"if self.mag_name not in table.colnames:\n raise ValueError(f\"Catalo... | <|body_start_0|>
super().__init__(max_number=max_number, min_number=min_number, seed=seed)
self.stamp_size = stamp_size
self.mag_name = mag_name
if min_number < 1:
raise ValueError('At least 1 bright galaxy will be added, so need min_number >=1.')
<|end_body_0|>
<|body_start... | Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization. | BasicSampling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicSampling:
"""Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization."""
def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_name: str='i_ab', seed: int=DEFAULT_SEED):
"""Initializes the ... | stack_v2_sparse_classes_36k_train_019022 | 12,943 | permissive | [
{
"docstring": "Initializes the basic sampling function. Args: max_number: Defined in parent class. min_number: Defined in parent class. stamp_size: Size of the desired stamp. seed: Seed to initialize randomness for reproducibility. mag_name: Name of the magnitude column in the catalog for cuts.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_002196 | Implement the Python class `BasicSampling` described below.
Class description:
Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization.
Method signatures and docstrings:
- def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_na... | Implement the Python class `BasicSampling` described below.
Class description:
Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization.
Method signatures and docstrings:
- def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_na... | f5b716a373f130238100db8980aa0d282822983a | <|skeleton|>
class BasicSampling:
"""Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization."""
def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_name: str='i_ab', seed: int=DEFAULT_SEED):
"""Initializes the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicSampling:
"""Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization."""
def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_name: str='i_ab', seed: int=DEFAULT_SEED):
"""Initializes the basic samplin... | the_stack_v2_python_sparse | btk/sampling_functions.py | LSSTDESC/BlendingToolKit | train | 22 |
3f60918da0a8a5c5a2bc156aef2277b8fc282960 | [
"db = self.db_obj.create(db_name)\ntry:\n self.db_obj.createCollection(db, collection, scope)\n created_Collection = self.db_obj.collectionObject(db, collection, scope)\n created_CollectionName = self.collection_obj.collectionName(created_Collection)\n assert created_CollectionName == collection, 'Scope... | <|body_start_0|>
db = self.db_obj.create(db_name)
try:
self.db_obj.createCollection(db, collection, scope)
created_Collection = self.db_obj.collectionObject(db, collection, scope)
created_CollectionName = self.collection_obj.collectionName(created_Collection)
... | TestScopeCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestScopeCollection:
def test_scope_collection_name_with_space(self, db_name, scope, collection):
"""@summary: Creating scope and collections with space in names"""
<|body_0|>
def test_same_collection_in_different_scope(self, db_name, no_of_scope, collection):
"""@su... | stack_v2_sparse_classes_36k_train_019023 | 4,538 | no_license | [
{
"docstring": "@summary: Creating scope and collections with space in names",
"name": "test_scope_collection_name_with_space",
"signature": "def test_scope_collection_name_with_space(self, db_name, scope, collection)"
},
{
"docstring": "@summary: Creating collection with same name in different ... | 4 | null | Implement the Python class `TestScopeCollection` described below.
Class description:
Implement the TestScopeCollection class.
Method signatures and docstrings:
- def test_scope_collection_name_with_space(self, db_name, scope, collection): @summary: Creating scope and collections with space in names
- def test_same_co... | Implement the Python class `TestScopeCollection` described below.
Class description:
Implement the TestScopeCollection class.
Method signatures and docstrings:
- def test_scope_collection_name_with_space(self, db_name, scope, collection): @summary: Creating scope and collections with space in names
- def test_same_co... | 9d78bd43665de2a0099d3e2ecf94495f3379f8fa | <|skeleton|>
class TestScopeCollection:
def test_scope_collection_name_with_space(self, db_name, scope, collection):
"""@summary: Creating scope and collections with space in names"""
<|body_0|>
def test_same_collection_in_different_scope(self, db_name, no_of_scope, collection):
"""@su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestScopeCollection:
def test_scope_collection_name_with_space(self, db_name, scope, collection):
"""@summary: Creating scope and collections with space in names"""
db = self.db_obj.create(db_name)
try:
self.db_obj.createCollection(db, collection, scope)
created... | the_stack_v2_python_sparse | testsuites/CBLTester/CBL_Functional_tests/APITests/test_scopesCollections.py | couchbaselabs/mobile-testkit | train | 15 | |
e2167a7a9ed7fca76e924eafff1113f689c2db97 | [
"self.num_classes = num_classes\nself.shape = shape\nself.is_infer = is_infer\nself.image_vector_size = shape[0] * shape[1]\nself.__declare_input_layers__()\nself.__build_nn__()",
"self.image = layer.data(name='image', type=paddle.data_type.dense_vector(self.image_vector_size), height=self.shape[0], width=self.sh... | <|body_start_0|>
self.num_classes = num_classes
self.shape = shape
self.is_infer = is_infer
self.image_vector_size = shape[0] * shape[1]
self.__declare_input_layers__()
self.__build_nn__()
<|end_body_0|>
<|body_start_1|>
self.image = layer.data(name='image', type... | Model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type shape: tuple of 2 int :param is_infer: The boolean parameter indicating inferring or training. :t... | stack_v2_sparse_classes_36k_train_019024 | 4,286 | permissive | [
{
"docstring": ":param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type shape: tuple of 2 int :param is_infer: The boolean parameter indicating inferring or training. :type shape: bool",
"name": "__init__",
"signature": "def __init__(s... | 4 | stack_v2_sparse_classes_30k_train_020074 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, num_classes, shape, is_infer=False): :param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type sha... | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, num_classes, shape, is_infer=False): :param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type sha... | 420527996b6da60ca401717a734329f126ed0680 | <|skeleton|>
class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type shape: tuple of 2 int :param is_infer: The boolean parameter indicating inferring or training. :t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type shape: tuple of 2 int :param is_infer: The boolean parameter indicating inferring or training. :type shape: boo... | the_stack_v2_python_sparse | legacy/scene_text_recognition/network_conf.py | chenbjin/models | train | 3 | |
696b75df0b02aaf3e5e4cf1316447ab127349268 | [
"self.ids = [i for i in range(0, len(matches))]\nself.size = len(matches)\nself.sz = [1 for x in range(0, len(matches))]",
"root = i\nwhile root != self.ids[root]:\n root = self.ids[root]\nwhile i != root:\n next = self.ids[i]\n self.ids[i] = root\n i = next\nreturn root",
"root1 = self.find(i)\nroo... | <|body_start_0|>
self.ids = [i for i in range(0, len(matches))]
self.size = len(matches)
self.sz = [1 for x in range(0, len(matches))]
<|end_body_0|>
<|body_start_1|>
root = i
while root != self.ids[root]:
root = self.ids[root]
while i != root:
ne... | This class implements the UnionFind algorithm - attributes: - ids - list containing representative of a given object - size - the size of the overall graph - sz - the sz of each set | UnionFind | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnionFind:
"""This class implements the UnionFind algorithm - attributes: - ids - list containing representative of a given object - size - the size of the overall graph - sz - the sz of each set"""
def __init__(self, matches):
"""This coresponds to the make_set operation :param matc... | stack_v2_sparse_classes_36k_train_019025 | 1,636 | no_license | [
{
"docstring": "This coresponds to the make_set operation :param matches: list, of stops",
"name": "__init__",
"signature": "def __init__(self, matches)"
},
{
"docstring": "This implements the find algorithm with path compreshion :param i: stop to find :return: the representative of a given stop... | 3 | stack_v2_sparse_classes_30k_train_006785 | Implement the Python class `UnionFind` described below.
Class description:
This class implements the UnionFind algorithm - attributes: - ids - list containing representative of a given object - size - the size of the overall graph - sz - the sz of each set
Method signatures and docstrings:
- def __init__(self, matche... | Implement the Python class `UnionFind` described below.
Class description:
This class implements the UnionFind algorithm - attributes: - ids - list containing representative of a given object - size - the size of the overall graph - sz - the sz of each set
Method signatures and docstrings:
- def __init__(self, matche... | 69dd19d531bd8a9768a017a7a376c6f28c9ff0c8 | <|skeleton|>
class UnionFind:
"""This class implements the UnionFind algorithm - attributes: - ids - list containing representative of a given object - size - the size of the overall graph - sz - the sz of each set"""
def __init__(self, matches):
"""This coresponds to the make_set operation :param matc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnionFind:
"""This class implements the UnionFind algorithm - attributes: - ids - list containing representative of a given object - size - the size of the overall graph - sz - the sz of each set"""
def __init__(self, matches):
"""This coresponds to the make_set operation :param matches: list, of... | the_stack_v2_python_sparse | version_1_0/gtfs/unused/union_find.py | ajtrasatti/Marta_Trip_Chaining | train | 0 |
5e45f898473d8664befd3d2f16c416a7138cd3f2 | [
"concept_parsers.ConceptParser([flags.GetReplicationPresentationSpec('The Replication to create.')]).AddToParser(parser)\nreplications_flags.AddReplicationVolumeArg(parser)\nreplications_flags.AddReplicationReplicationScheduleArg(parser)\nreplications_flags.AddReplicationDestinationVolumeParametersArg(parser)\nflag... | <|body_start_0|>
concept_parsers.ConceptParser([flags.GetReplicationPresentationSpec('The Replication to create.')]).AddToParser(parser)
replications_flags.AddReplicationVolumeArg(parser)
replications_flags.AddReplicationReplicationScheduleArg(parser)
replications_flags.AddReplicationDes... | Create a Cloud NetApp Volume Replication. | Create | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Create a Cloud NetApp Volume Replication."""
def Args(parser):
"""Add args for creating a Replication."""
<|body_0|>
def Run(self, args):
"""Create a Cloud NetApp Volume Replication in the current project."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_019026 | 4,060 | permissive | [
{
"docstring": "Add args for creating a Replication.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Create a Cloud NetApp Volume Replication in the current project.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003967 | Implement the Python class `Create` described below.
Class description:
Create a Cloud NetApp Volume Replication.
Method signatures and docstrings:
- def Args(parser): Add args for creating a Replication.
- def Run(self, args): Create a Cloud NetApp Volume Replication in the current project. | Implement the Python class `Create` described below.
Class description:
Create a Cloud NetApp Volume Replication.
Method signatures and docstrings:
- def Args(parser): Add args for creating a Replication.
- def Run(self, args): Create a Cloud NetApp Volume Replication in the current project.
<|skeleton|>
class Creat... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Create:
"""Create a Cloud NetApp Volume Replication."""
def Args(parser):
"""Add args for creating a Replication."""
<|body_0|>
def Run(self, args):
"""Create a Cloud NetApp Volume Replication in the current project."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
"""Create a Cloud NetApp Volume Replication."""
def Args(parser):
"""Add args for creating a Replication."""
concept_parsers.ConceptParser([flags.GetReplicationPresentationSpec('The Replication to create.')]).AddToParser(parser)
replications_flags.AddReplicationVolumeArg(p... | the_stack_v2_python_sparse | lib/surface/netapp/volumes/replications/create.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
ac2fa46c1256e00fdb5c4366c251eec604b2ff03 | [
"left, right = (0, len(nums))\nwhile left < right:\n mid = (left + right) // 2\n if target == nums[mid]:\n return mid\n elif target > nums[mid]:\n left = mid + 1\n else:\n right = mid\nreturn -1",
"left, right = (0, len(nums))\nwhile left < right:\n mid = (left + right) // 2\n ... | <|body_start_0|>
left, right = (0, len(nums))
while left < right:
mid = (left + right) // 2
if target == nums[mid]:
return mid
elif target > nums[mid]:
left = mid + 1
else:
right = mid
return -1
<|end... | BinarySearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySearch:
def findExact(self, nums, target):
"""input nums is a sorted array find the index of target in nums if target cannot be found, return -1"""
<|body_0|>
def lower_bound(self, nums, target):
"""similar to C++'s lower_bound input nums is a sorted array find... | stack_v2_sparse_classes_36k_train_019027 | 2,189 | no_license | [
{
"docstring": "input nums is a sorted array find the index of target in nums if target cannot be found, return -1",
"name": "findExact",
"signature": "def findExact(self, nums, target)"
},
{
"docstring": "similar to C++'s lower_bound input nums is a sorted array find the index of a number in nu... | 3 | null | Implement the Python class `BinarySearch` described below.
Class description:
Implement the BinarySearch class.
Method signatures and docstrings:
- def findExact(self, nums, target): input nums is a sorted array find the index of target in nums if target cannot be found, return -1
- def lower_bound(self, nums, target... | Implement the Python class `BinarySearch` described below.
Class description:
Implement the BinarySearch class.
Method signatures and docstrings:
- def findExact(self, nums, target): input nums is a sorted array find the index of target in nums if target cannot be found, return -1
- def lower_bound(self, nums, target... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class BinarySearch:
def findExact(self, nums, target):
"""input nums is a sorted array find the index of target in nums if target cannot be found, return -1"""
<|body_0|>
def lower_bound(self, nums, target):
"""similar to C++'s lower_bound input nums is a sorted array find... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinarySearch:
def findExact(self, nums, target):
"""input nums is a sorted array find the index of target in nums if target cannot be found, return -1"""
left, right = (0, len(nums))
while left < right:
mid = (left + right) // 2
if target == nums[mid]:
... | the_stack_v2_python_sparse | Search.py | cybelewang/leetcode-python | train | 0 | |
71156aeeb4aa55a28606b2986da44c480f05d46a | [
"if args.target_instance:\n raise exceptions.ToolException('You cannot specify [--target-instance] for a global forwarding rule.')\nif args.target_pool:\n raise exceptions.ToolException('You cannot specify [--target-pool] for a global forwarding rule.')\nif getattr(args, 'backend_service', None):\n raise e... | <|body_start_0|>
if args.target_instance:
raise exceptions.ToolException('You cannot specify [--target-instance] for a global forwarding rule.')
if args.target_pool:
raise exceptions.ToolException('You cannot specify [--target-pool] for a global forwarding rule.')
if geta... | Base class for modifying forwarding rule targets. | ForwardingRulesTargetMutator | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForwardingRulesTargetMutator:
"""Base class for modifying forwarding rule targets."""
def ValidateGlobalArgs(self, args):
"""Validate the global forwarding rules args."""
<|body_0|>
def GetGlobalTarget(self, args):
"""Return the forwarding target for a globally s... | stack_v2_sparse_classes_36k_train_019028 | 7,875 | permissive | [
{
"docstring": "Validate the global forwarding rules args.",
"name": "ValidateGlobalArgs",
"signature": "def ValidateGlobalArgs(self, args)"
},
{
"docstring": "Return the forwarding target for a globally scoped request.",
"name": "GetGlobalTarget",
"signature": "def GetGlobalTarget(self,... | 5 | stack_v2_sparse_classes_30k_train_001019 | Implement the Python class `ForwardingRulesTargetMutator` described below.
Class description:
Base class for modifying forwarding rule targets.
Method signatures and docstrings:
- def ValidateGlobalArgs(self, args): Validate the global forwarding rules args.
- def GetGlobalTarget(self, args): Return the forwarding ta... | Implement the Python class `ForwardingRulesTargetMutator` described below.
Class description:
Base class for modifying forwarding rule targets.
Method signatures and docstrings:
- def ValidateGlobalArgs(self, args): Validate the global forwarding rules args.
- def GetGlobalTarget(self, args): Return the forwarding ta... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class ForwardingRulesTargetMutator:
"""Base class for modifying forwarding rule targets."""
def ValidateGlobalArgs(self, args):
"""Validate the global forwarding rules args."""
<|body_0|>
def GetGlobalTarget(self, args):
"""Return the forwarding target for a globally s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForwardingRulesTargetMutator:
"""Base class for modifying forwarding rule targets."""
def ValidateGlobalArgs(self, args):
"""Validate the global forwarding rules args."""
if args.target_instance:
raise exceptions.ToolException('You cannot specify [--target-instance] for a glob... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/forwarding_rules_utils.py | KaranToor/MA450 | train | 1 |
4d788b6707e63595772759a162b3c62bf18d8c5b | [
"extension = os.path.splitext(path)[1].lower()\nif extension:\n if extension[0] == '.':\n extension = extension[1:]\nreturn extension",
"paths = []\nfor path in glob.glob(path_mask):\n extension = self._get_normalized_extension(path)\n if not allowed_formats or extension in allowed_formats:\n ... | <|body_start_0|>
extension = os.path.splitext(path)[1].lower()
if extension:
if extension[0] == '.':
extension = extension[1:]
return extension
<|end_body_0|>
<|body_start_1|>
paths = []
for path in glob.glob(path_mask):
extension = self._... | Files Manager is responsive for data serialization and files operations. All files loading and saving operations are recommended to be performed via FilesManager class. Also, it's recommended to work with FM using absolute paths to avoid relative paths mess. | FilesManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilesManager:
"""Files Manager is responsive for data serialization and files operations. All files loading and saving operations are recommended to be performed via FilesManager class. Also, it's recommended to work with FM using absolute paths to avoid relative paths mess."""
def _get_norm... | stack_v2_sparse_classes_36k_train_019029 | 7,035 | permissive | [
{
"docstring": "Get normalized file extension. :param path: path :type path: str|basestring :return: lowercased extension without dot :rtype: str|basestring",
"name": "_get_normalized_extension",
"signature": "def _get_normalized_extension(self, path)"
},
{
"docstring": "Find all files of allowe... | 5 | stack_v2_sparse_classes_30k_train_000531 | Implement the Python class `FilesManager` described below.
Class description:
Files Manager is responsive for data serialization and files operations. All files loading and saving operations are recommended to be performed via FilesManager class. Also, it's recommended to work with FM using absolute paths to avoid rel... | Implement the Python class `FilesManager` described below.
Class description:
Files Manager is responsive for data serialization and files operations. All files loading and saving operations are recommended to be performed via FilesManager class. Also, it's recommended to work with FM using absolute paths to avoid rel... | 768ac74a420f822261c4eb8da72f1d8af3c6bbff | <|skeleton|>
class FilesManager:
"""Files Manager is responsive for data serialization and files operations. All files loading and saving operations are recommended to be performed via FilesManager class. Also, it's recommended to work with FM using absolute paths to avoid relative paths mess."""
def _get_norm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilesManager:
"""Files Manager is responsive for data serialization and files operations. All files loading and saving operations are recommended to be performed via FilesManager class. Also, it's recommended to work with FM using absolute paths to avoid relative paths mess."""
def _get_normalized_extens... | the_stack_v2_python_sparse | nailgun/nailgun/plugins/loaders/files_manager.py | dis-xcom/fuel-web | train | 0 |
3b21e2d89332a9f41311a972ea796464078cd055 | [
"self.sensor_refresh_rates = sensor_refresh_rates\nself.plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')\nself.plugins = sensors_list\nself.statistics = {}\nfor sensor in self.plugins:\n self.statistics[sensor.name] = sensor.currentValue\nself.stop_event = stop_event",
"for sensor in self.plugin... | <|body_start_0|>
self.sensor_refresh_rates = sensor_refresh_rates
self.plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')
self.plugins = sensors_list
self.statistics = {}
for sensor in self.plugins:
self.statistics[sensor.name] = sensor.currentValue
... | Statistics | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Statistics:
def __init__(self, sensors_list, stop_event, sensor_refresh_rates):
"""Record keeping for primitive system parameters"""
<|body_0|>
def generate(self):
"""Generate the stats using the plugins list periodically"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_019030 | 1,217 | permissive | [
{
"docstring": "Record keeping for primitive system parameters",
"name": "__init__",
"signature": "def __init__(self, sensors_list, stop_event, sensor_refresh_rates)"
},
{
"docstring": "Generate the stats using the plugins list periodically",
"name": "generate",
"signature": "def generat... | 2 | stack_v2_sparse_classes_30k_train_019290 | Implement the Python class `Statistics` described below.
Class description:
Implement the Statistics class.
Method signatures and docstrings:
- def __init__(self, sensors_list, stop_event, sensor_refresh_rates): Record keeping for primitive system parameters
- def generate(self): Generate the stats using the plugins ... | Implement the Python class `Statistics` described below.
Class description:
Implement the Statistics class.
Method signatures and docstrings:
- def __init__(self, sensors_list, stop_event, sensor_refresh_rates): Record keeping for primitive system parameters
- def generate(self): Generate the stats using the plugins ... | 2258dd996da03ac84d1ca3fb09ef51e83a409140 | <|skeleton|>
class Statistics:
def __init__(self, sensors_list, stop_event, sensor_refresh_rates):
"""Record keeping for primitive system parameters"""
<|body_0|>
def generate(self):
"""Generate the stats using the plugins list periodically"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Statistics:
def __init__(self, sensors_list, stop_event, sensor_refresh_rates):
"""Record keeping for primitive system parameters"""
self.sensor_refresh_rates = sensor_refresh_rates
self.plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')
self.plugins = sensors_list... | the_stack_v2_python_sparse | ptop/statistics/statistics.py | leovarmak/ptop | train | 1 | |
4c6045b0f0c5d3fac93c3347501c6282707ed5c5 | [
"if seed == -1:\n self.seed = int(datetime.datetime.now().strftime('%M%S'))\nelse:\n self.seed = seed\nself.cursor = self.seed",
"self.infile = open('D:\\\\war-and-peace.txt', 'rb')\nterm = 1\nself.number = 0\nlength = 3226615\nstep = 200\nwhile term < 33:\n self.infile.seek(self.cursor)\n bits_a = se... | <|body_start_0|>
if seed == -1:
self.seed = int(datetime.datetime.now().strftime('%M%S'))
else:
self.seed = seed
self.cursor = self.seed
<|end_body_0|>
<|body_start_1|>
self.infile = open('D:\\war-and-peace.txt', 'rb')
term = 1
self.number = 0
... | WarAndPeacePseudoRandomNumberGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarAndPeacePseudoRandomNumberGenerator:
def __init__(self, seed=-1):
"""constructor that initializes seed, cursor"""
<|body_0|>
def random(self):
"""Generate the random number by using the seed and the code book"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_019031 | 8,225 | no_license | [
{
"docstring": "constructor that initializes seed, cursor",
"name": "__init__",
"signature": "def __init__(self, seed=-1)"
},
{
"docstring": "Generate the random number by using the seed and the code book",
"name": "random",
"signature": "def random(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000503 | Implement the Python class `WarAndPeacePseudoRandomNumberGenerator` described below.
Class description:
Implement the WarAndPeacePseudoRandomNumberGenerator class.
Method signatures and docstrings:
- def __init__(self, seed=-1): constructor that initializes seed, cursor
- def random(self): Generate the random number ... | Implement the Python class `WarAndPeacePseudoRandomNumberGenerator` described below.
Class description:
Implement the WarAndPeacePseudoRandomNumberGenerator class.
Method signatures and docstrings:
- def __init__(self, seed=-1): constructor that initializes seed, cursor
- def random(self): Generate the random number ... | 679cee68c075040f4da6f4bf4038faeae4fa7494 | <|skeleton|>
class WarAndPeacePseudoRandomNumberGenerator:
def __init__(self, seed=-1):
"""constructor that initializes seed, cursor"""
<|body_0|>
def random(self):
"""Generate the random number by using the seed and the code book"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WarAndPeacePseudoRandomNumberGenerator:
def __init__(self, seed=-1):
"""constructor that initializes seed, cursor"""
if seed == -1:
self.seed = int(datetime.datetime.now().strftime('%M%S'))
else:
self.seed = seed
self.cursor = self.seed
def random(s... | the_stack_v2_python_sparse | Python/Assignment0702.py | LannyX/Past_School_Projects | train | 0 | |
5cbe6ae88821219c29c6cde40bcd0652fc08e99e | [
"super(HAN, self).__init__()\nself.contextSize = contextSize\nself.emb = nn.Embedding(vocabSize, embSize)\nself.wordBiGRU = nn.GRU(embSize, hiddenSize, numLayers, bias, batchFirst, dropout, bidirectional)\nself.wordLinear = nn.Linear(2 * hiddenSize, contextSize)\nself.wordattention = Attention()\nself.sentenceBiGRU... | <|body_start_0|>
super(HAN, self).__init__()
self.contextSize = contextSize
self.emb = nn.Embedding(vocabSize, embSize)
self.wordBiGRU = nn.GRU(embSize, hiddenSize, numLayers, bias, batchFirst, dropout, bidirectional)
self.wordLinear = nn.Linear(2 * hiddenSize, contextSize)
... | HAN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HAN:
def __init__(self, vocabSize, numClasses, embSize=embSize, hiddenSize=hiddenSize, numLayers=numLayers, bias=bias, batchFirst=batchFirst, dropout=dropout, bidirectional=bidirectional, contextSize=contextSize):
"""@doc: HAN @author: Alpaca-Man @date: 2021/2/26 @param: { vocabSize: 单词表... | stack_v2_sparse_classes_36k_train_019032 | 4,525 | no_license | [
{
"docstring": "@doc: HAN @author: Alpaca-Man @date: 2021/2/26 @param: { vocabSize: 单词表长度 numClasses: 标签种类数量 embSize: 词向量维度 default 200 hiddenSize: 单向 GRU 隐藏层维度 default 50 numLayers: 双向 GRU 层数 default 1 bias: 偏置 default True batchFirst: 输入序列的第一维度是不是批次 default True dropout: 失活率 default 0 bidirectional: 双向 GRU de... | 2 | stack_v2_sparse_classes_30k_train_003164 | Implement the Python class `HAN` described below.
Class description:
Implement the HAN class.
Method signatures and docstrings:
- def __init__(self, vocabSize, numClasses, embSize=embSize, hiddenSize=hiddenSize, numLayers=numLayers, bias=bias, batchFirst=batchFirst, dropout=dropout, bidirectional=bidirectional, conte... | Implement the Python class `HAN` described below.
Class description:
Implement the HAN class.
Method signatures and docstrings:
- def __init__(self, vocabSize, numClasses, embSize=embSize, hiddenSize=hiddenSize, numLayers=numLayers, bias=bias, batchFirst=batchFirst, dropout=dropout, bidirectional=bidirectional, conte... | 49824925970f0439634dc66a7f19edc512f18a5f | <|skeleton|>
class HAN:
def __init__(self, vocabSize, numClasses, embSize=embSize, hiddenSize=hiddenSize, numLayers=numLayers, bias=bias, batchFirst=batchFirst, dropout=dropout, bidirectional=bidirectional, contextSize=contextSize):
"""@doc: HAN @author: Alpaca-Man @date: 2021/2/26 @param: { vocabSize: 单词表... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HAN:
def __init__(self, vocabSize, numClasses, embSize=embSize, hiddenSize=hiddenSize, numLayers=numLayers, bias=bias, batchFirst=batchFirst, dropout=dropout, bidirectional=bidirectional, contextSize=contextSize):
"""@doc: HAN @author: Alpaca-Man @date: 2021/2/26 @param: { vocabSize: 单词表长度 numClasses:... | the_stack_v2_python_sparse | HAN/demo/HAN.py | Alpaca-Man/NLP-Newcomer | train | 1 | |
748f6671399641fc2c28caa98032679a5ed29ab9 | [
"\"\"\"测试添加购物车\"\"\"\nadd = AddGwcPage(self.driver)\nadd.going_fenlei()\nadd.add_gwc()\ndy = add.dy_add_gwc()\nself.assertEqual(dy, '1')",
"\"\"\"测试添加多个商品\"\"\"\nsort = HomePage(self.driver)\nsort.click_sort()\nadd = AddGwcPage(self.driver)\nadd.add_gwc()\nadd.add_gwc()\nadd.add_gwc()\nadd.add_gwc()\ndy = add.dy_... | <|body_start_0|>
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.going_fenlei()
add.add_gwc()
dy = add.dy_add_gwc()
self.assertEqual(dy, '1')
<|end_body_0|>
<|body_start_1|>
"""测试添加多个商品"""
sort = HomePage(self.driver)
sort.click_sort()
add... | AddgwcTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
<|body_0|>
def test_add_goods(self):
"""MRYX_ST_classification_009"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.g... | stack_v2_sparse_classes_36k_train_019033 | 1,517 | no_license | [
{
"docstring": "MRYX_ST_classification_004",
"name": "test_add_gwc",
"signature": "def test_add_gwc(self)"
},
{
"docstring": "MRYX_ST_classification_009",
"name": "test_add_goods",
"signature": "def test_add_goods(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017759 | Implement the Python class `AddgwcTest` described below.
Class description:
Implement the AddgwcTest class.
Method signatures and docstrings:
- def test_add_gwc(self): MRYX_ST_classification_004
- def test_add_goods(self): MRYX_ST_classification_009 | Implement the Python class `AddgwcTest` described below.
Class description:
Implement the AddgwcTest class.
Method signatures and docstrings:
- def test_add_gwc(self): MRYX_ST_classification_004
- def test_add_goods(self): MRYX_ST_classification_009
<|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
... | 2325c7854c5625babdb51b5c5e40fa860813a400 | <|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
<|body_0|>
def test_add_goods(self):
"""MRYX_ST_classification_009"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.going_fenlei()
add.add_gwc()
dy = add.dy_add_gwc()
self.assertEqual(dy, '1')
def test_add_goods(self):
"""MRYX_ST_classifica... | the_stack_v2_python_sparse | testcase/test_add_gwc.py | danyubiao/mryx | train | 0 | |
7f5fa07dfdf47d370aabd0df0809d47e09be453a | [
"q = [(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if not r]\nfor i, j in q:\n for row_index, col_index in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):\n if 0 <= row_index < len(rooms) and 0 <= col_index < len(rooms[0]) and (rooms[row_index][col_index] > 2 ** 30):\n roo... | <|body_start_0|>
q = [(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if not r]
for i, j in q:
for row_index, col_index in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
if 0 <= row_index < len(rooms) and 0 <= col_index < len(rooms[0]) and (rooms[row_index... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wallsAndGates(self, rooms):
""":type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. BFS (start from gate who is r in the code and represented as 0) beats 78.90%"""
<|body_0|>
def wallsAndGates1(self, rooms):
"... | stack_v2_sparse_classes_36k_train_019034 | 1,565 | no_license | [
{
"docstring": ":type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. BFS (start from gate who is r in the code and represented as 0) beats 78.90%",
"name": "wallsAndGates",
"signature": "def wallsAndGates(self, rooms)"
},
{
"docstring": ":type rooms: L... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wallsAndGates(self, rooms): :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. BFS (start from gate who is r in the code and rep... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wallsAndGates(self, rooms): :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. BFS (start from gate who is r in the code and rep... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def wallsAndGates(self, rooms):
""":type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. BFS (start from gate who is r in the code and represented as 0) beats 78.90%"""
<|body_0|>
def wallsAndGates1(self, rooms):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wallsAndGates(self, rooms):
""":type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. BFS (start from gate who is r in the code and represented as 0) beats 78.90%"""
q = [(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if... | the_stack_v2_python_sparse | LeetCode/286_walls_and_gates.py | yao23/Machine_Learning_Playground | train | 12 | |
3630e1d4935221b7a211f876330c73a3eba414bf | [
"try:\n params = request._serialize()\n body = self.call('CreateCredential', params)\n response = json.loads(body)\n if 'Error' not in response['Response']:\n model = models.CreateCredentialResponse()\n model._deserialize(response['Response'])\n return model\n else:\n code... | <|body_start_0|>
try:
params = request._serialize()
body = self.call('CreateCredential', params)
response = json.loads(body)
if 'Error' not in response['Response']:
model = models.CreateCredentialResponse()
model._deserialize(respon... | TdidClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TdidClient:
def CreateCredential(self, request):
"""创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialRequest` :rtype: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialResponse`"""
<|bod... | stack_v2_sparse_classes_36k_train_019035 | 5,585 | permissive | [
{
"docstring": "创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialRequest` :rtype: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialResponse`",
"name": "CreateCredential",
"signature": "def CreateCredential(sel... | 4 | null | Implement the Python class `TdidClient` described below.
Class description:
Implement the TdidClient class.
Method signatures and docstrings:
- def CreateCredential(self, request): 创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialReq... | Implement the Python class `TdidClient` described below.
Class description:
Implement the TdidClient class.
Method signatures and docstrings:
- def CreateCredential(self, request): 创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialReq... | baed8b8e84ed0e8dd19600225796a75405cb922c | <|skeleton|>
class TdidClient:
def CreateCredential(self, request):
"""创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialRequest` :rtype: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialResponse`"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TdidClient:
def CreateCredential(self, request):
"""创建凭证 :param request: Request instance for CreateCredential. :type request: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialRequest` :rtype: :class:`tencentcloud.tdid.v20210519.models.CreateCredentialResponse`"""
try:
pa... | the_stack_v2_python_sparse | tencentcloud/tdid/v20210519/tdid_client.py | WANGMUXIAN/tencentcloud-sdk-python | train | 0 | |
c2cb678146ea4a762ee80322f2d21e95345e7527 | [
"self.pattern = pattern\nself.index = index\nself.alive = True\nself.color = qy.graphics.colors.get_color(index)\nself.xdata = np.arange(HISTORY_SIZE)\nself.ydata = np.ones([HISTORY_SIZE]) * -1\nself.plot_curve = axes.plot([], [], color=self.color, lw=2, linestyle='-')[0]\nself.max_line = axes.plot([], [], color=se... | <|body_start_0|>
self.pattern = pattern
self.index = index
self.alive = True
self.color = qy.graphics.colors.get_color(index)
self.xdata = np.arange(HISTORY_SIZE)
self.ydata = np.ones([HISTORY_SIZE]) * -1
self.plot_curve = axes.plot([], [], color=self.color, lw=2,... | curve | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class curve:
def __init__(self, pattern, index, axes):
"""An object representing a curve"""
<|body_0|>
def add_point(self, value):
"""Add a point to the curve and wrap around when we run out of history"""
<|body_1|>
def update(self):
"""Draw the curve"... | stack_v2_sparse_classes_36k_train_019036 | 4,797 | no_license | [
{
"docstring": "An object representing a curve",
"name": "__init__",
"signature": "def __init__(self, pattern, index, axes)"
},
{
"docstring": "Add a point to the curve and wrap around when we run out of history",
"name": "add_point",
"signature": "def add_point(self, value)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_013307 | Implement the Python class `curve` described below.
Class description:
Implement the curve class.
Method signatures and docstrings:
- def __init__(self, pattern, index, axes): An object representing a curve
- def add_point(self, value): Add a point to the curve and wrap around when we run out of history
- def update(... | Implement the Python class `curve` described below.
Class description:
Implement the curve class.
Method signatures and docstrings:
- def __init__(self, pattern, index, axes): An object representing a curve
- def add_point(self, value): Add a point to the curve and wrap around when we run out of history
- def update(... | 219b5ddb0aaf184249b8ce66120933c9dd05f774 | <|skeleton|>
class curve:
def __init__(self, pattern, index, axes):
"""An object representing a curve"""
<|body_0|>
def add_point(self, value):
"""Add a point to the curve and wrap around when we run out of history"""
<|body_1|>
def update(self):
"""Draw the curve"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class curve:
def __init__(self, pattern, index, axes):
"""An object representing a curve"""
self.pattern = pattern
self.index = index
self.alive = True
self.color = qy.graphics.colors.get_color(index)
self.xdata = np.arange(HISTORY_SIZE)
self.ydata = np.ones([... | the_stack_v2_python_sparse | qy/gui/wxgraph.py | bongkokwei/qy | train | 0 | |
225549c3b8e1e926c9f724090095c17ca657b958 | [
"@lru_cache(None)\ndef dfs(index: int, hasPre: bool, root: bool) -> int:\n \"\"\"当前在index 前一个点是否选择 第一个点是否选择\"\"\"\n if index == n:\n return -INF if hasPre and root else 0\n res = dfs(index + 1, False, root)\n if not hasPre:\n res = max(res, dfs(index + 1, True) + nums[index], root)\n re... | <|body_start_0|>
@lru_cache(None)
def dfs(index: int, hasPre: bool, root: bool) -> int:
"""当前在index 前一个点是否选择 第一个点是否选择"""
if index == n:
return -INF if hasPre and root else 0
res = dfs(index + 1, False, root)
if not hasPre:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums: List[int]) -> int:
"""dfs 考虑第一个选还是不选"""
<|body_0|>
def rob2(self, nums: List[int]) -> int:
"""dp 考虑第一个选还是不选"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
@lru_cache(None)
def dfs(index: int, hasPre: bool, root... | stack_v2_sparse_classes_36k_train_019037 | 1,519 | no_license | [
{
"docstring": "dfs 考虑第一个选还是不选",
"name": "rob",
"signature": "def rob(self, nums: List[int]) -> int"
},
{
"docstring": "dp 考虑第一个选还是不选",
"name": "rob2",
"signature": "def rob2(self, nums: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: dfs 考虑第一个选还是不选
- def rob2(self, nums: List[int]) -> int: dp 考虑第一个选还是不选 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: dfs 考虑第一个选还是不选
- def rob2(self, nums: List[int]) -> int: dp 考虑第一个选还是不选
<|skeleton|>
class Solution:
def rob(self, nums: List[int]) ->... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def rob(self, nums: List[int]) -> int:
"""dfs 考虑第一个选还是不选"""
<|body_0|>
def rob2(self, nums: List[int]) -> int:
"""dp 考虑第一个选还是不选"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums: List[int]) -> int:
"""dfs 考虑第一个选还是不选"""
@lru_cache(None)
def dfs(index: int, hasPre: bool, root: bool) -> int:
"""当前在index 前一个点是否选择 第一个点是否选择"""
if index == n:
return -INF if hasPre and root else 0
res = d... | the_stack_v2_python_sparse | 11_动态规划/acwingdp专项练习/环形与后效性处理/213. 打家劫舍 II-环形分类讨论.py | 981377660LMT/algorithm-study | train | 225 | |
48a7b5ad1722b9e2581d8a408e5369de223b4d5f | [
"if not s:\n return False\nsetS = set(s)\nl = [s.count(i) % 2 for i in setS]\nif l.count(1) > 1:\n return False\nreturn True",
"if s == s[::-1]:\n return True\ncnt = collections.Counter(s)\nc = 0\nfor key in cnt:\n if cnt[key] % 2 > 0:\n c += 1\n if c > 1:\n return False\nreturn True"... | <|body_start_0|>
if not s:
return False
setS = set(s)
l = [s.count(i) % 2 for i in setS]
if l.count(1) > 1:
return False
return True
<|end_body_0|>
<|body_start_1|>
if s == s[::-1]:
return True
cnt = collections.Counter(s)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPermutePalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def canPermutePalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s:
return False
setS =... | stack_v2_sparse_classes_36k_train_019038 | 829 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "canPermutePalindrome",
"signature": "def canPermutePalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "canPermutePalindrome",
"signature": "def canPermutePalindrome(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPermutePalindrome(self, s): :type s: str :rtype: bool
- def canPermutePalindrome(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPermutePalindrome(self, s): :type s: str :rtype: bool
- def canPermutePalindrome(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def canPermutePalin... | 8bb17099be02d997d554519be360ef4aa1c028e3 | <|skeleton|>
class Solution:
def canPermutePalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def canPermutePalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canPermutePalindrome(self, s):
""":type s: str :rtype: bool"""
if not s:
return False
setS = set(s)
l = [s.count(i) % 2 for i in setS]
if l.count(1) > 1:
return False
return True
def canPermutePalindrome(self, s):
... | the_stack_v2_python_sparse | Google/1. easy/266. Palindrome Permutation.py | yemao616/summer18 | train | 0 | |
479c8b711df7bd95d1c9d587ade2469d33f3b92f | [
"self.DetectorObj = Detector(light_type, position, angle)\nself.detector_type = self.DetectorObj.detector_type\nself.psd = self.DetectorObj.psd\nself.intensity = self.DetectorObj.intensity\nself.database = self.DetectorObj.database\nself.position = self.DetectorObj.position\nself.angle = self.DetectorObj.angle\nsel... | <|body_start_0|>
self.DetectorObj = Detector(light_type, position, angle)
self.detector_type = self.DetectorObj.detector_type
self.psd = self.DetectorObj.psd
self.intensity = self.DetectorObj.intensity
self.database = self.DetectorObj.database
self.position = self.Detecto... | TestDetectorTypes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDetectorTypes:
def setUp(self):
"""Setup function TestTypes for class Detector"""
<|body_0|>
def test_types(self):
"""Function to test data types for class Detector"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.DetectorObj = Detector(ligh... | stack_v2_sparse_classes_36k_train_019039 | 1,617 | permissive | [
{
"docstring": "Setup function TestTypes for class Detector",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Function to test data types for class Detector",
"name": "test_types",
"signature": "def test_types(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002366 | Implement the Python class `TestDetectorTypes` described below.
Class description:
Implement the TestDetectorTypes class.
Method signatures and docstrings:
- def setUp(self): Setup function TestTypes for class Detector
- def test_types(self): Function to test data types for class Detector | Implement the Python class `TestDetectorTypes` described below.
Class description:
Implement the TestDetectorTypes class.
Method signatures and docstrings:
- def setUp(self): Setup function TestTypes for class Detector
- def test_types(self): Function to test data types for class Detector
<|skeleton|>
class TestDete... | 825a0eab64be709efe161b9a48eb54c4bc5c1bef | <|skeleton|>
class TestDetectorTypes:
def setUp(self):
"""Setup function TestTypes for class Detector"""
<|body_0|>
def test_types(self):
"""Function to test data types for class Detector"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDetectorTypes:
def setUp(self):
"""Setup function TestTypes for class Detector"""
self.DetectorObj = Detector(light_type, position, angle)
self.detector_type = self.DetectorObj.detector_type
self.psd = self.DetectorObj.psd
self.intensity = self.DetectorObj.intensity... | the_stack_v2_python_sparse | VLC_devel/class_structure/__auto_gen__/test_Detector.py | wenh81/vlc_simulator | train | 0 | |
cbf66a1f03d221085e335d2ae0825b51d8336023 | [
"p = 3\npoint1 = np.array(point1)\npoint2 = np.array(point2)\nreturn np.sum(np.absolute(np.subtract(point1, point2)) ** p) ** (1 / p)\nraise NotImplementedError\nraise NotImplementedError",
"point1 = np.array(point1)\npoint2 = np.array(point2)\nreturn np.sqrt(np.sum((point1 - point2) ** 2))\nraise NotImplementedE... | <|body_start_0|>
p = 3
point1 = np.array(point1)
point2 = np.array(point2)
return np.sum(np.absolute(np.subtract(point1, point2)) ** p) ** (1 / p)
raise NotImplementedError
raise NotImplementedError
<|end_body_0|>
<|body_start_1|>
point1 = np.array(point1)
... | Distances | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Distances:
def minkowski_distance(point1, point2):
"""Minkowski distance is the generalized version of Euclidean Distance It is also know as L-p norm (where p>=1) that you have studied in class For our assignment we need to take p=3 Information on Minkowski distance - https://en.wikipedi... | stack_v2_sparse_classes_36k_train_019040 | 19,229 | permissive | [
{
"docstring": "Minkowski distance is the generalized version of Euclidean Distance It is also know as L-p norm (where p>=1) that you have studied in class For our assignment we need to take p=3 Information on Minkowski distance - https://en.wikipedia.org/wiki/Minkowski_distance :param point1: List[float] :para... | 5 | stack_v2_sparse_classes_30k_train_004730 | Implement the Python class `Distances` described below.
Class description:
Implement the Distances class.
Method signatures and docstrings:
- def minkowski_distance(point1, point2): Minkowski distance is the generalized version of Euclidean Distance It is also know as L-p norm (where p>=1) that you have studied in cl... | Implement the Python class `Distances` described below.
Class description:
Implement the Distances class.
Method signatures and docstrings:
- def minkowski_distance(point1, point2): Minkowski distance is the generalized version of Euclidean Distance It is also know as L-p norm (where p>=1) that you have studied in cl... | 385e1a152abfadcc754429c1b1d0fcb2f3d63c6a | <|skeleton|>
class Distances:
def minkowski_distance(point1, point2):
"""Minkowski distance is the generalized version of Euclidean Distance It is also know as L-p norm (where p>=1) that you have studied in class For our assignment we need to take p=3 Information on Minkowski distance - https://en.wikipedi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Distances:
def minkowski_distance(point1, point2):
"""Minkowski distance is the generalized version of Euclidean Distance It is also know as L-p norm (where p>=1) that you have studied in class For our assignment we need to take p=3 Information on Minkowski distance - https://en.wikipedia.org/wiki/Min... | the_stack_v2_python_sparse | PA1/KNN/utils.py | kester2015/CSCI-567-Machine-Learning | train | 0 | |
da34c3f5ebfb7c342b52fd829cbd21838c150cf6 | [
"super(Filterer, self).__init__()\nself.expression = expression\nself.target = target\nself._event = event\nself._regex = None\nreturn",
"if self._event is None:\n self._event = DummyEvent()\nreturn self._event",
"if self._regex is None:\n self._regex = re.compile(self.expression)\nreturn self._regex",
... | <|body_start_0|>
super(Filterer, self).__init__()
self.expression = expression
self.target = target
self._event = event
self._regex = None
return
<|end_body_0|>
<|body_start_1|>
if self._event is None:
self._event = DummyEvent()
return self._e... | A Filterer filters out strings that don't match an expression. | Filterer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filterer:
"""A Filterer filters out strings that don't match an expression."""
def __init__(self, expression, target, event=None):
""":param: - `expression`: A regular expression. - `target`: a target to send matching strings to - `event`: an Event to activate flow through the filter... | stack_v2_sparse_classes_36k_train_019041 | 1,774 | permissive | [
{
"docstring": ":param: - `expression`: A regular expression. - `target`: a target to send matching strings to - `event`: an Event to activate flow through the filter",
"name": "__init__",
"signature": "def __init__(self, expression, target, event=None)"
},
{
"docstring": ":return: threading eve... | 4 | stack_v2_sparse_classes_30k_val_000566 | Implement the Python class `Filterer` described below.
Class description:
A Filterer filters out strings that don't match an expression.
Method signatures and docstrings:
- def __init__(self, expression, target, event=None): :param: - `expression`: A regular expression. - `target`: a target to send matching strings t... | Implement the Python class `Filterer` described below.
Class description:
A Filterer filters out strings that don't match an expression.
Method signatures and docstrings:
- def __init__(self, expression, target, event=None): :param: - `expression`: A regular expression. - `target`: a target to send matching strings t... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class Filterer:
"""A Filterer filters out strings that don't match an expression."""
def __init__(self, expression, target, event=None):
""":param: - `expression`: A regular expression. - `target`: a target to send matching strings to - `event`: an Event to activate flow through the filter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Filterer:
"""A Filterer filters out strings that don't match an expression."""
def __init__(self, expression, target, event=None):
""":param: - `expression`: A regular expression. - `target`: a target to send matching strings to - `event`: an Event to activate flow through the filter"""
s... | the_stack_v2_python_sparse | apetools/commons/filterer.py | russell-n/oldape | train | 0 |
8f7020f1b1247b60d6f0eb3a9f030ad1a8ef62a9 | [
"self.spy_on(AsanaWorkspaceListView.get, owner=AsanaWorkspaceListView, call_fake=lambda self, request: HttpResponse('{}', content_type='application/json'))\nrsp = self.client.get(local_site_reverse('asana-workspace-list'))\nself.assertEqual(rsp.status_code, 200)",
"self.spy_on(AsanaTaskSearchView.get, owner=Asana... | <|body_start_0|>
self.spy_on(AsanaWorkspaceListView.get, owner=AsanaWorkspaceListView, call_fake=lambda self, request: HttpResponse('{}', content_type='application/json'))
rsp = self.client.get(local_site_reverse('asana-workspace-list'))
self.assertEqual(rsp.status_code, 200)
<|end_body_0|>
<|b... | Tests for Asana. | AsanaIntegrationTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsanaIntegrationTests:
"""Tests for Asana."""
def test_workspace_list(self):
"""Testing AsanaWorkspaceListView"""
<|body_0|>
def test_task_search(self):
"""Testing AsanaTaskSearchView"""
<|body_1|>
def test_task_search_unpublished(self):
"""T... | stack_v2_sparse_classes_36k_train_019042 | 4,041 | permissive | [
{
"docstring": "Testing AsanaWorkspaceListView",
"name": "test_workspace_list",
"signature": "def test_workspace_list(self)"
},
{
"docstring": "Testing AsanaTaskSearchView",
"name": "test_task_search",
"signature": "def test_task_search(self)"
},
{
"docstring": "Testing AsanaTask... | 5 | stack_v2_sparse_classes_30k_val_000749 | Implement the Python class `AsanaIntegrationTests` described below.
Class description:
Tests for Asana.
Method signatures and docstrings:
- def test_workspace_list(self): Testing AsanaWorkspaceListView
- def test_task_search(self): Testing AsanaTaskSearchView
- def test_task_search_unpublished(self): Testing AsanaTas... | Implement the Python class `AsanaIntegrationTests` described below.
Class description:
Tests for Asana.
Method signatures and docstrings:
- def test_workspace_list(self): Testing AsanaWorkspaceListView
- def test_task_search(self): Testing AsanaTaskSearchView
- def test_task_search_unpublished(self): Testing AsanaTas... | 52bbaecc1227764f3e9a66f03226e0013f2b0c48 | <|skeleton|>
class AsanaIntegrationTests:
"""Tests for Asana."""
def test_workspace_list(self):
"""Testing AsanaWorkspaceListView"""
<|body_0|>
def test_task_search(self):
"""Testing AsanaTaskSearchView"""
<|body_1|>
def test_task_search_unpublished(self):
"""T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsanaIntegrationTests:
"""Tests for Asana."""
def test_workspace_list(self):
"""Testing AsanaWorkspaceListView"""
self.spy_on(AsanaWorkspaceListView.get, owner=AsanaWorkspaceListView, call_fake=lambda self, request: HttpResponse('{}', content_type='application/json'))
rsp = self.c... | the_stack_v2_python_sparse | rbintegrations/asana/tests.py | reviewboard/rbintegrations | train | 0 |
5bb07109a927817dcbe841a1183ae684b807ad4d | [
"self.cluster_identifiers = cluster_identifiers\nself.is_active = is_active\nself.is_deleted = is_deleted\nself.region_ids = region_ids\nself.tenant_id = tenant_id\nself.tenant_name = tenant_name\nself.tenant_type = tenant_type",
"if dictionary is None:\n return None\ncluster_identifiers = None\nif dictionary.... | <|body_start_0|>
self.cluster_identifiers = cluster_identifiers
self.is_active = is_active
self.is_deleted = is_deleted
self.region_ids = region_ids
self.tenant_id = tenant_id
self.tenant_name = tenant_name
self.tenant_type = tenant_type
<|end_body_0|>
<|body_sta... | Implementation of the 'McmUserProfile' model. TODO: type description here. Attributes: cluster_identifiers (list of ClusterIdentifier): Specifies the list of clusters. This is only valid if tenant type is OnPrem. is_active (bool): Specifies whether or not the tenant is active. is_deleted (bool): Specifies whether or no... | McmUserProfile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class McmUserProfile:
"""Implementation of the 'McmUserProfile' model. TODO: type description here. Attributes: cluster_identifiers (list of ClusterIdentifier): Specifies the list of clusters. This is only valid if tenant type is OnPrem. is_active (bool): Specifies whether or not the tenant is active. ... | stack_v2_sparse_classes_36k_train_019043 | 3,425 | permissive | [
{
"docstring": "Constructor for the McmUserProfile class",
"name": "__init__",
"signature": "def __init__(self, cluster_identifiers=None, is_active=None, is_deleted=None, region_ids=None, tenant_id=None, tenant_name=None, tenant_type=None)"
},
{
"docstring": "Creates an instance of this model fr... | 2 | null | Implement the Python class `McmUserProfile` described below.
Class description:
Implementation of the 'McmUserProfile' model. TODO: type description here. Attributes: cluster_identifiers (list of ClusterIdentifier): Specifies the list of clusters. This is only valid if tenant type is OnPrem. is_active (bool): Specifie... | Implement the Python class `McmUserProfile` described below.
Class description:
Implementation of the 'McmUserProfile' model. TODO: type description here. Attributes: cluster_identifiers (list of ClusterIdentifier): Specifies the list of clusters. This is only valid if tenant type is OnPrem. is_active (bool): Specifie... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class McmUserProfile:
"""Implementation of the 'McmUserProfile' model. TODO: type description here. Attributes: cluster_identifiers (list of ClusterIdentifier): Specifies the list of clusters. This is only valid if tenant type is OnPrem. is_active (bool): Specifies whether or not the tenant is active. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class McmUserProfile:
"""Implementation of the 'McmUserProfile' model. TODO: type description here. Attributes: cluster_identifiers (list of ClusterIdentifier): Specifies the list of clusters. This is only valid if tenant type is OnPrem. is_active (bool): Specifies whether or not the tenant is active. is_deleted (b... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mcm_user_profile.py | cohesity/management-sdk-python | train | 24 |
7a52729afd66878cf5bb3d80fb169202e724bcef | [
"self.s = s\nself.t = t\nself.dict = {}\nself.m = len(s)\nself.n = len(t)\n\ndef dfs(i, j):\n if j >= self.n:\n return 1\n if i >= self.m:\n return 0\n if (i, j) in self.dict:\n return self.dict[i, j]\n if self.s[i] == self.t[j]:\n a = dfs(i + 1, j) + dfs(i + 1, j + 1)\n e... | <|body_start_0|>
self.s = s
self.t = t
self.dict = {}
self.m = len(s)
self.n = len(t)
def dfs(i, j):
if j >= self.n:
return 1
if i >= self.m:
return 0
if (i, j) in self.dict:
return self.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int"""
<|body_0|>
def numDistinct_1(self, s, t):
""":type s: str :type t: str :rtype: int 252ms"""
<|body_1|>
def numDistinct_2(self, s, t):
""":type s: str :type t: str ... | stack_v2_sparse_classes_36k_train_019044 | 14,277 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: int",
"name": "numDistinct",
"signature": "def numDistinct(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: int 252ms",
"name": "numDistinct_1",
"signature": "def numDistinct_1(self, s, t)"
},
{
"docstring": ":typ... | 4 | stack_v2_sparse_classes_30k_train_000019 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDistinct(self, s, t): :type s: str :type t: str :rtype: int
- def numDistinct_1(self, s, t): :type s: str :type t: str :rtype: int 252ms
- def numDistinct_2(self, s, t): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDistinct(self, s, t): :type s: str :type t: str :rtype: int
- def numDistinct_1(self, s, t): :type s: str :type t: str :rtype: int 252ms
- def numDistinct_2(self, s, t): :... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int"""
<|body_0|>
def numDistinct_1(self, s, t):
""":type s: str :type t: str :rtype: int 252ms"""
<|body_1|>
def numDistinct_2(self, s, t):
""":type s: str :type t: str ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int"""
self.s = s
self.t = t
self.dict = {}
self.m = len(s)
self.n = len(t)
def dfs(i, j):
if j >= self.n:
return 1
if i >= self.m:
... | the_stack_v2_python_sparse | DistinctSubsequences_HARD_115.py | 953250587/leetcode-python | train | 2 | |
f711134f727746337ffa8ca1d324831a185afde8 | [
"newalphabets = []\nmaxcount = 0\nfor i in s:\n if i not in newalphabets:\n newalphabets.append(i)\n else:\n newalphabets = newalphabets[newalphabets.index(i) + 1:]\n newalphabets.append(i)\n if maxcount < len(newalphabets):\n maxcount = len(newalphabets)\nreturn maxcount",
"n... | <|body_start_0|>
newalphabets = []
maxcount = 0
for i in s:
if i not in newalphabets:
newalphabets.append(i)
else:
newalphabets = newalphabets[newalphabets.index(i) + 1:]
newalphabets.append(i)
if maxcount < len(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
newalphabets = []
maxcount = 0
... | stack_v2_sparse_classes_36k_train_019045 | 2,187 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring2",
"signature": "def lengthOfLongestSubstring2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020147 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthOf... | 786075e0f9f61cf062703bc0b41cc3191d77f033 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
newalphabets = []
maxcount = 0
for i in s:
if i not in newalphabets:
newalphabets.append(i)
else:
newalphabets = newalphabets[newalphabets.ind... | the_stack_v2_python_sparse | 3_lengthOfLongestSubstring.py | Anirban2404/LeetCodePractice | train | 1 | |
e84be0586edee80e04b2403c807a77b2ec25fede | [
"if request.user.is_staff or request.method in permissions.SAFE_METHODS:\n return True\ntry:\n org = Organization.objects.get(pk=request.data['organization'])\n is_in_org = org.is_admin(request.user) or org.is_member(request.user)\n return is_in_org and super().has_permission(request, view)\nexcept KeyE... | <|body_start_0|>
if request.user.is_staff or request.method in permissions.SAFE_METHODS:
return True
try:
org = Organization.objects.get(pk=request.data['organization'])
is_in_org = org.is_admin(request.user) or org.is_member(request.user)
return is_in_org... | Custom to check if user belongs to org | IsOrgAdminOrMember | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsOrgAdminOrMember:
"""Custom to check if user belongs to org"""
def has_permission(self, request, view):
"""if user is staff or if SAFE request, we're done otherwise check model object perms try for user object if request.user is member or admin of org check perms except: this is or... | stack_v2_sparse_classes_36k_train_019046 | 5,524 | permissive | [
{
"docstring": "if user is staff or if SAFE request, we're done otherwise check model object perms try for user object if request.user is member or admin of org check perms except: this is org object, check permissions",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
... | 2 | stack_v2_sparse_classes_30k_val_000234 | Implement the Python class `IsOrgAdminOrMember` described below.
Class description:
Custom to check if user belongs to org
Method signatures and docstrings:
- def has_permission(self, request, view): if user is staff or if SAFE request, we're done otherwise check model object perms try for user object if request.user... | Implement the Python class `IsOrgAdminOrMember` described below.
Class description:
Custom to check if user belongs to org
Method signatures and docstrings:
- def has_permission(self, request, view): if user is staff or if SAFE request, we're done otherwise check model object perms try for user object if request.user... | 40d9608295daefc5e1cd83afd84ecb5b0518cc3d | <|skeleton|>
class IsOrgAdminOrMember:
"""Custom to check if user belongs to org"""
def has_permission(self, request, view):
"""if user is staff or if SAFE request, we're done otherwise check model object perms try for user object if request.user is member or admin of org check perms except: this is or... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsOrgAdminOrMember:
"""Custom to check if user belongs to org"""
def has_permission(self, request, view):
"""if user is staff or if SAFE request, we're done otherwise check model object perms try for user object if request.user is member or admin of org check perms except: this is org object, che... | the_stack_v2_python_sparse | app/squac/permissions.py | pnsn/squacapi | train | 7 |
0170bb51f7fd819d904993d49e39490e9376a418 | [
"super().__init__(original_radiis, radii, outer_polygon)\nself.points_locations = []\nself.labels = []\nself.wanted_size = wanted_size\nself.load_save = load_save\nself.seed = seed\nfile_name, _ = os.path.splitext(class_path)\ntype_area_name = file_name.split('/')[-1]\nself.full_base_dir = os.path.join(CACHE_BASE_D... | <|body_start_0|>
super().__init__(original_radiis, radii, outer_polygon)
self.points_locations = []
self.labels = []
self.wanted_size = wanted_size
self.load_save = load_save
self.seed = seed
file_name, _ = os.path.splitext(class_path)
type_area_name = fil... | A dataset contains only one class | ClassDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassDataset:
"""A dataset contains only one class"""
def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=None, load_save=True, return_point=False, seed=None, only_higher_than=... | stack_v2_sparse_classes_36k_train_019047 | 4,446 | no_license | [
{
"docstring": "Args: class_path: The path to the data of the first class wanted in the dataset class_label: The label of the first class wanted in the dataset original_radiis: outer_polygon:",
"name": "__init__",
"signature": "def __init__(self, class_path: str, class_label: float, original_radiis: Lis... | 3 | stack_v2_sparse_classes_30k_train_014865 | Implement the Python class `ClassDataset` described below.
Class description:
A dataset contains only one class
Method signatures and docstrings:
- def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=No... | Implement the Python class `ClassDataset` described below.
Class description:
A dataset contains only one class
Method signatures and docstrings:
- def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=No... | 69c8f1b40de3011d61c7a2720d006c131d6e9a1c | <|skeleton|>
class ClassDataset:
"""A dataset contains only one class"""
def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=None, load_save=True, return_point=False, seed=None, only_higher_than=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassDataset:
"""A dataset contains only one class"""
def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=None, load_save=True, return_point=False, seed=None, only_higher_than=None):
... | the_stack_v2_python_sparse | topo2vec/datasets/class_dataset.py | urielsinger/topo2vec | train | 2 |
b497b821e44b172745f74e29be8c5765a100419d | [
"before = stackless.getruncount()\nthread, task = self.create_thread_task()\ntry:\n after = stackless.getruncount()\n self.assertEqual(before, after)\n task.remove()\n after = stackless.getruncount()\n self.assertEqual(before, after)\nfinally:\n thread.join()",
"thread, task = self.create_thread... | <|body_start_0|>
before = stackless.getruncount()
thread, task = self.create_thread_task()
try:
after = stackless.getruncount()
self.assertEqual(before, after)
task.remove()
after = stackless.getruncount()
self.assertEqual(before, after... | TestRemove | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRemove:
def test_remove_balance(self):
"""Test that remove from the runqueue of a remote thread does not affect the bookkeeping of the current thread."""
<|body_0|>
def test_insert_balance(self):
"""Test that insert into the runqueue of a remote thread does not a... | stack_v2_sparse_classes_36k_train_019048 | 19,302 | permissive | [
{
"docstring": "Test that remove from the runqueue of a remote thread does not affect the bookkeeping of the current thread.",
"name": "test_remove_balance",
"signature": "def test_remove_balance(self)"
},
{
"docstring": "Test that insert into the runqueue of a remote thread does not affect the ... | 2 | stack_v2_sparse_classes_30k_train_007399 | Implement the Python class `TestRemove` described below.
Class description:
Implement the TestRemove class.
Method signatures and docstrings:
- def test_remove_balance(self): Test that remove from the runqueue of a remote thread does not affect the bookkeeping of the current thread.
- def test_insert_balance(self): T... | Implement the Python class `TestRemove` described below.
Class description:
Implement the TestRemove class.
Method signatures and docstrings:
- def test_remove_balance(self): Test that remove from the runqueue of a remote thread does not affect the bookkeeping of the current thread.
- def test_insert_balance(self): T... | 7edf8148e34b9f73ca6433ceb43a1770f4fa32c1 | <|skeleton|>
class TestRemove:
def test_remove_balance(self):
"""Test that remove from the runqueue of a remote thread does not affect the bookkeeping of the current thread."""
<|body_0|>
def test_insert_balance(self):
"""Test that insert into the runqueue of a remote thread does not a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRemove:
def test_remove_balance(self):
"""Test that remove from the runqueue of a remote thread does not affect the bookkeeping of the current thread."""
before = stackless.getruncount()
thread, task = self.create_thread_task()
try:
after = stackless.getruncount... | the_stack_v2_python_sparse | libs/stackless/Stackless/unittests/test_thread.py | masomel/py-import-analysis | train | 1 | |
f2e3089fd4f1179f25a16c39cadd49fb3d572b09 | [
"assert check_argument_types()\nsuper(StyleEncoder, self).__init__()\nself.ref_enc = ReferenceEncoder(idim=idim, conv_layers=conv_layers, conv_chans_list=conv_chans_list, conv_kernel_size=conv_kernel_size, conv_stride=conv_stride, gru_layers=gru_layers, gru_units=gru_units)\nself.stl = StyleTokenLayer(ref_embed_dim... | <|body_start_0|>
assert check_argument_types()
super(StyleEncoder, self).__init__()
self.ref_enc = ReferenceEncoder(idim=idim, conv_layers=conv_layers, conv_chans_list=conv_chans_list, conv_kernel_size=conv_kernel_size, conv_stride=conv_stride, gru_layers=gru_layers, gru_units=gru_units)
... | Style encoder. This module is style encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org/abs/1803.09017 Parameters ---------- idim : ... | StyleEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleEncoder:
"""Style encoder. This module is style encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org/abs/... | stack_v2_sparse_classes_36k_train_019049 | 10,798 | permissive | [
{
"docstring": "Initilize global style encoder module.",
"name": "__init__",
"signature": "def __init__(self, idim: int=80, gst_tokens: int=10, gst_token_dim: int=256, gst_heads: int=4, conv_layers: int=6, conv_chans_list: Sequence[int]=(32, 32, 64, 64, 128, 128), conv_kernel_size: int=3, conv_stride: i... | 2 | null | Implement the Python class `StyleEncoder` described below.
Class description:
Style encoder. This module is style encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Sp... | Implement the Python class `StyleEncoder` described below.
Class description:
Style encoder. This module is style encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Sp... | 8705a2a8405e3c63f2174d69880d2b5525a6c9fd | <|skeleton|>
class StyleEncoder:
"""Style encoder. This module is style encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org/abs/... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StyleEncoder:
"""Style encoder. This module is style encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org/abs/1803.09017 Pa... | the_stack_v2_python_sparse | parakeet/modules/style_encoder.py | PaddlePaddle/Parakeet | train | 609 |
948200a3aa71ad284b4e952656ffb33e90ff03fc | [
"num_stack = []\nstr_stack = []\nans = ''\ni = 0\nwhile i < len(s):\n if s[i].isdigit():\n count = 0\n while s[i].isdigit():\n count = count * 10 + int(s[i])\n i += 1\n num_stack.append(count)\n elif s[i] == '[':\n str_stack.append(ans)\n ans = ''\n ... | <|body_start_0|>
num_stack = []
str_stack = []
ans = ''
i = 0
while i < len(s):
if s[i].isdigit():
count = 0
while s[i].isdigit():
count = count * 10 + int(s[i])
i += 1
num_stack.a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeString2(self, s):
"""使用 stack :type s: str :rtype: str"""
<|body_0|>
def decodeString(self, s):
"""更清晰的 stack :type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num_stack = []
str_stack = []
... | stack_v2_sparse_classes_36k_train_019050 | 2,320 | no_license | [
{
"docstring": "使用 stack :type s: str :rtype: str",
"name": "decodeString2",
"signature": "def decodeString2(self, s)"
},
{
"docstring": "更清晰的 stack :type s: str :rtype: str",
"name": "decodeString",
"signature": "def decodeString(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString2(self, s): 使用 stack :type s: str :rtype: str
- def decodeString(self, s): 更清晰的 stack :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString2(self, s): 使用 stack :type s: str :rtype: str
- def decodeString(self, s): 更清晰的 stack :type s: str :rtype: str
<|skeleton|>
class Solution:
def decodeString... | 852fad258f5070c7b93c35252f7404e85e709ea6 | <|skeleton|>
class Solution:
def decodeString2(self, s):
"""使用 stack :type s: str :rtype: str"""
<|body_0|>
def decodeString(self, s):
"""更清晰的 stack :type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def decodeString2(self, s):
"""使用 stack :type s: str :rtype: str"""
num_stack = []
str_stack = []
ans = ''
i = 0
while i < len(s):
if s[i].isdigit():
count = 0
while s[i].isdigit():
count ... | the_stack_v2_python_sparse | 301-400/394. Decode String.py | SunnyMarkLiu/LeetCode | train | 1 | |
17889c6eb7e0816b84fdf03be8a221891bcb466e | [
"res = []\n\ndef dfs(node, count):\n if not node:\n return\n count = count * 10 + node.val if count else node.val\n if not node.left and (not node.right):\n res.append(count)\n return\n dfs(node.left, count)\n dfs(node.right, count)\n return res\ndfs(root, 0)\nreturn sum(res)"... | <|body_start_0|>
res = []
def dfs(node, count):
if not node:
return
count = count * 10 + node.val if count else node.val
if not node.left and (not node.right):
res.append(count)
return
dfs(node.left, count)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbers1(self, root: TreeNode) -> int:
"""递归记录每条path,最后结算"""
<|body_0|>
def sumNumbers2(self, root: TreeNode) -> int:
"""利用队列,每次将当前结点及其sum入队"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
def dfs(node, count):
... | stack_v2_sparse_classes_36k_train_019051 | 1,818 | no_license | [
{
"docstring": "递归记录每条path,最后结算",
"name": "sumNumbers1",
"signature": "def sumNumbers1(self, root: TreeNode) -> int"
},
{
"docstring": "利用队列,每次将当前结点及其sum入队",
"name": "sumNumbers2",
"signature": "def sumNumbers2(self, root: TreeNode) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers1(self, root: TreeNode) -> int: 递归记录每条path,最后结算
- def sumNumbers2(self, root: TreeNode) -> int: 利用队列,每次将当前结点及其sum入队 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers1(self, root: TreeNode) -> int: 递归记录每条path,最后结算
- def sumNumbers2(self, root: TreeNode) -> int: 利用队列,每次将当前结点及其sum入队
<|skeleton|>
class Solution:
def sumNumber... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def sumNumbers1(self, root: TreeNode) -> int:
"""递归记录每条path,最后结算"""
<|body_0|>
def sumNumbers2(self, root: TreeNode) -> int:
"""利用队列,每次将当前结点及其sum入队"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumNumbers1(self, root: TreeNode) -> int:
"""递归记录每条path,最后结算"""
res = []
def dfs(node, count):
if not node:
return
count = count * 10 + node.val if count else node.val
if not node.left and (not node.right):
... | the_stack_v2_python_sparse | 129_sum-root-to-leaf-numbers.py | helloocc/algorithm | train | 1 | |
66690568fc1d7b928c854eef69014e530787aafb | [
"super(RPN, self).__init__()\nself.k = k\nself.conv = nn.Sequential(nn.Conv2d(in_channels, in_channels, kernel_size=window_size, padding=0), nn.ReLU(), nn.Conv2d(in_channels, in_channels, kernel_size=1), nn.ReLU(), nn.Conv2d(in_channels, (4 + 1) * k, kernel_size=1))",
"x = self.conv(x)\nx = x.permute(0, 2, 3, 1).... | <|body_start_0|>
super(RPN, self).__init__()
self.k = k
self.conv = nn.Sequential(nn.Conv2d(in_channels, in_channels, kernel_size=window_size, padding=0), nn.ReLU(), nn.Conv2d(in_channels, in_channels, kernel_size=1), nn.ReLU(), nn.Conv2d(in_channels, (4 + 1) * k, kernel_size=1))
<|end_body_0|>
... | The Region Proposal Network finds interesting regions in an image, which will then be further inspected by the RCNN. | RPN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPN:
"""The Region Proposal Network finds interesting regions in an image, which will then be further inspected by the RCNN."""
def __init__(self, in_channels, k, window_size):
""":param in_channels: Integer. Number of channels of the given feature map. :param k: Integer. Number of a... | stack_v2_sparse_classes_36k_train_019052 | 1,332 | permissive | [
{
"docstring": ":param in_channels: Integer. Number of channels of the given feature map. :param k: Integer. Number of anchors. :param window_size: Integer. The size of the sliding window the RPN uses.",
"name": "__init__",
"signature": "def __init__(self, in_channels, k, window_size)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_018907 | Implement the Python class `RPN` described below.
Class description:
The Region Proposal Network finds interesting regions in an image, which will then be further inspected by the RCNN.
Method signatures and docstrings:
- def __init__(self, in_channels, k, window_size): :param in_channels: Integer. Number of channels... | Implement the Python class `RPN` described below.
Class description:
The Region Proposal Network finds interesting regions in an image, which will then be further inspected by the RCNN.
Method signatures and docstrings:
- def __init__(self, in_channels, k, window_size): :param in_channels: Integer. Number of channels... | 152c52515426a545508580a21687e15706312f99 | <|skeleton|>
class RPN:
"""The Region Proposal Network finds interesting regions in an image, which will then be further inspected by the RCNN."""
def __init__(self, in_channels, k, window_size):
""":param in_channels: Integer. Number of channels of the given feature map. :param k: Integer. Number of a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RPN:
"""The Region Proposal Network finds interesting regions in an image, which will then be further inspected by the RCNN."""
def __init__(self, in_channels, k, window_size):
""":param in_channels: Integer. Number of channels of the given feature map. :param k: Integer. Number of anchors. :para... | the_stack_v2_python_sparse | lib/rpn_efficient.py | mctigger/understandable-faster-rcnn | train | 1 |
ebe80767ea33ac0f78a5127e9a7a4a799da4957c | [
"self.data = list()\nself.data_len = 0\nself.start_idx = -1\nself.size = size\nself.average = None",
"self.data.append(val)\nself.data_len += 1\nprint(self.data_len, val, self.start_idx, self.size)\nif self.data_len <= self.size:\n if self.data_len == 1:\n self.average = self.data[0]\n else:\n ... | <|body_start_0|>
self.data = list()
self.data_len = 0
self.start_idx = -1
self.size = size
self.average = None
<|end_body_0|>
<|body_start_1|>
self.data.append(val)
self.data_len += 1
print(self.data_len, val, self.start_idx, self.size)
if self.da... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.data = list()
self.data_... | stack_v2_sparse_classes_36k_train_019053 | 1,298 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007178 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 5e48a72a20456d5c6ecbefe776a1c5e08d2c7e46 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.data = list()
self.data_len = 0
self.start_idx = -1
self.size = size
self.average = None
def next(self, val):
""":type val: int :rtype: float"""... | the_stack_v2_python_sparse | code_bases/python_coding_practice/moving_average.py | sgarg87/sahilgarg.github.io | train | 0 | |
77e3d562df9d9fcbfa5e8058db904decf2df2dba | [
"for i in self._inOrderGen(self.root):\n if re.match(str(string), str(i[0])):\n yield i[0]",
"def generate(root):\n if root:\n yield list(generate(root.left))\n val = root.val[:5]\n val.append(root.val[5].treestr())\n val.append(root.val[6].treestr())\n yield (root.... | <|body_start_0|>
for i in self._inOrderGen(self.root):
if re.match(str(string), str(i[0])):
yield i[0]
<|end_body_0|>
<|body_start_1|>
def generate(root):
if root:
yield list(generate(root.left))
val = root.val[:5]
... | User_BST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User_BST:
def simsearch(self, string):
"""Simple similarity search for user tree Time complexity: O(n)"""
<|body_0|>
def treestr(self):
"""Returns string of nested lists that can be used to build the tree (using the Date treestr)"""
<|body_1|>
def treebu... | stack_v2_sparse_classes_36k_train_019054 | 9,078 | no_license | [
{
"docstring": "Simple similarity search for user tree Time complexity: O(n)",
"name": "simsearch",
"signature": "def simsearch(self, string)"
},
{
"docstring": "Returns string of nested lists that can be used to build the tree (using the Date treestr)",
"name": "treestr",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_012871 | Implement the Python class `User_BST` described below.
Class description:
Implement the User_BST class.
Method signatures and docstrings:
- def simsearch(self, string): Simple similarity search for user tree Time complexity: O(n)
- def treestr(self): Returns string of nested lists that can be used to build the tree (... | Implement the Python class `User_BST` described below.
Class description:
Implement the User_BST class.
Method signatures and docstrings:
- def simsearch(self, string): Simple similarity search for user tree Time complexity: O(n)
- def treestr(self): Returns string of nested lists that can be used to build the tree (... | ec7d6fc488f7b82c35a073fe3ea374de2aa0b16a | <|skeleton|>
class User_BST:
def simsearch(self, string):
"""Simple similarity search for user tree Time complexity: O(n)"""
<|body_0|>
def treestr(self):
"""Returns string of nested lists that can be used to build the tree (using the Date treestr)"""
<|body_1|>
def treebu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User_BST:
def simsearch(self, string):
"""Simple similarity search for user tree Time complexity: O(n)"""
for i in self._inOrderGen(self.root):
if re.match(str(string), str(i[0])):
yield i[0]
def treestr(self):
"""Returns string of nested lists that can... | the_stack_v2_python_sparse | CEP Y3/Unit 2.10 Final Project/cds_attributetrees.py | HTY2003/CEP-Stuff | train | 0 | |
97b837d05e8224b61c81fcfbfc16dcd68475beef | [
"self.channel_count = channel_count\nself.node = node\nself.port = port\nself.sbt_host_params = sbt_host_params",
"if dictionary is None:\n return None\nchannel_count = dictionary.get('channelCount')\nnode = dictionary.get('node')\nport = dictionary.get('port')\nsbt_host_params = cohesity_management_sdk.models... | <|body_start_0|>
self.channel_count = channel_count
self.node = node
self.port = port
self.sbt_host_params = sbt_host_params
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
channel_count = dictionary.get('channelCount')
node = dicti... | Implementation of the 'OracleDatabaseNode' model. Oracle Database Node. Specifies database node required for the backup and restore. Attributes: channel_count (int): Specifies the number of channels user wants for the backup/recovery of this node. node (string): Specifies the ip of the database node. port (long|int): S... | OracleDatabaseNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OracleDatabaseNode:
"""Implementation of the 'OracleDatabaseNode' model. Oracle Database Node. Specifies database node required for the backup and restore. Attributes: channel_count (int): Specifies the number of channels user wants for the backup/recovery of this node. node (string): Specifies t... | stack_v2_sparse_classes_36k_train_019055 | 2,417 | permissive | [
{
"docstring": "Constructor for the OracleDatabaseNode class",
"name": "__init__",
"signature": "def __init__(self, channel_count=None, node=None, port=None, sbt_host_params=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary ... | 2 | null | Implement the Python class `OracleDatabaseNode` described below.
Class description:
Implementation of the 'OracleDatabaseNode' model. Oracle Database Node. Specifies database node required for the backup and restore. Attributes: channel_count (int): Specifies the number of channels user wants for the backup/recovery o... | Implement the Python class `OracleDatabaseNode` described below.
Class description:
Implementation of the 'OracleDatabaseNode' model. Oracle Database Node. Specifies database node required for the backup and restore. Attributes: channel_count (int): Specifies the number of channels user wants for the backup/recovery o... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OracleDatabaseNode:
"""Implementation of the 'OracleDatabaseNode' model. Oracle Database Node. Specifies database node required for the backup and restore. Attributes: channel_count (int): Specifies the number of channels user wants for the backup/recovery of this node. node (string): Specifies t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OracleDatabaseNode:
"""Implementation of the 'OracleDatabaseNode' model. Oracle Database Node. Specifies database node required for the backup and restore. Attributes: channel_count (int): Specifies the number of channels user wants for the backup/recovery of this node. node (string): Specifies the ip of the ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/oracle_database_node.py | cohesity/management-sdk-python | train | 24 |
31a4a342f31a57810703d08bd801f2a502c019d4 | [
"import bisect\nlen_nums = len(nums)\nlis_arr = [None] * len_nums\nlis_len = 0\nfor i in range(len_nums):\n j = 0\n j = bisect.bisect_left(lis_arr, nums[i], 0, lis_len)\n if lis_len == j:\n lis_len += 1\n lis_arr[j] = nums[i]\nreturn lis_len",
"len_nums = len(nums)\nlis_arr = [None] * len_nums\... | <|body_start_0|>
import bisect
len_nums = len(nums)
lis_arr = [None] * len_nums
lis_len = 0
for i in range(len_nums):
j = 0
j = bisect.bisect_left(lis_arr, nums[i], 0, lis_len)
if lis_len == j:
lis_len += 1
lis_arr[j... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS_dp_nlogn_by_binary_search(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS_dp_n2_by_search(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def lengthOfLIS_dp_n2_revise(self, nums):
... | stack_v2_sparse_classes_36k_train_019056 | 4,367 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS_dp_nlogn_by_binary_search",
"signature": "def lengthOfLIS_dp_nlogn_by_binary_search(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS_dp_n2_by_search",
"signature": "def length... | 5 | stack_v2_sparse_classes_30k_train_012942 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS_dp_nlogn_by_binary_search(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS_dp_n2_by_search(self, nums): :type nums: List[int] :rtype: int
- def le... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS_dp_nlogn_by_binary_search(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS_dp_n2_by_search(self, nums): :type nums: List[int] :rtype: int
- def le... | 83e5dea02e99e512d2b34dac05dabebfdb66ef2a | <|skeleton|>
class Solution:
def lengthOfLIS_dp_nlogn_by_binary_search(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS_dp_n2_by_search(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def lengthOfLIS_dp_n2_revise(self, nums):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS_dp_nlogn_by_binary_search(self, nums):
""":type nums: List[int] :rtype: int"""
import bisect
len_nums = len(nums)
lis_arr = [None] * len_nums
lis_len = 0
for i in range(len_nums):
j = 0
j = bisect.bisect_left(lis... | the_stack_v2_python_sparse | dynamic_programming/300_lengthOfLIS.py | wscheng/LeetCode | train | 0 | |
c87fe27c1723ac436172bcc6e911e7809e0d8363 | [
"super(Encoder, self).__init__(d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=num_layer)\nself.Q = Q\nself.K_s = K_s\nself.mask = mask\nself.initializer = tf.random_normal_initializer(stddev=0.1)\nself.dropout_keep_prob = dropout_keep_prob\nself.use_residual_conn = use_residual_conn",
"start = time.... | <|body_start_0|>
super(Encoder, self).__init__(d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=num_layer)
self.Q = Q
self.K_s = K_s
self.mask = mask
self.initializer = tf.random_normal_initializer(stddev=0.1)
self.dropout_keep_prob = dropout_keep_prob
... | Encoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer, Q, K_s, mask=None, dropout_keep_prob=0.9, use_residual_conn=True):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch... | stack_v2_sparse_classes_36k_train_019057 | 6,839 | permissive | [
{
"docstring": ":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch_size*sequence_length,embed_size]",
"name": "__init__",
"signature": "def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer, Q, K_s, m... | 3 | stack_v2_sparse_classes_30k_train_017971 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer, Q, K_s, mask=None, dropout_keep_prob=0.9, use_residual_conn=True): :param d_model: :param d_k: :par... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer, Q, K_s, mask=None, dropout_keep_prob=0.9, use_residual_conn=True): :param d_model: :param d_k: :par... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class Encoder:
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer, Q, K_s, mask=None, dropout_keep_prob=0.9, use_residual_conn=True):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer, Q, K_s, mask=None, dropout_keep_prob=0.9, use_residual_conn=True):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch_size*sequence... | the_stack_v2_python_sparse | bert_language_understanding-master/bert_language_understanding-master/model/encoder.py | yyht/BERT | train | 37 | |
ee7d52d259b4bf74c3a544385ad0251ef980c1f0 | [
"super(Fuzzy, self).__init__()\nif field_name and value:\n self.set_field(field_name, value)",
"if not isinstance(value, str) or not isinstance(field_name, str):\n raise pylastica.exception.InvalidException('field_name and value parameters must be str.')\nreturn self.set_param(field_name, {'value': value})"... | <|body_start_0|>
super(Fuzzy, self).__init__()
if field_name and value:
self.set_field(field_name, value)
<|end_body_0|>
<|body_start_1|>
if not isinstance(value, str) or not isinstance(field_name, str):
raise pylastica.exception.InvalidException('field_name and value pa... | Fuzzy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fuzzy:
def __init__(self, field_name=None, value=None):
"""Set either both parameters or neither. @param field_name: field name @type field_name: str @param value: search string @type value: str"""
<|body_0|>
def set_field(self, field_name, value):
"""@param field_na... | stack_v2_sparse_classes_36k_train_019058 | 1,434 | permissive | [
{
"docstring": "Set either both parameters or neither. @param field_name: field name @type field_name: str @param value: search string @type value: str",
"name": "__init__",
"signature": "def __init__(self, field_name=None, value=None)"
},
{
"docstring": "@param field_name: @type field_name: str... | 3 | stack_v2_sparse_classes_30k_train_012233 | Implement the Python class `Fuzzy` described below.
Class description:
Implement the Fuzzy class.
Method signatures and docstrings:
- def __init__(self, field_name=None, value=None): Set either both parameters or neither. @param field_name: field name @type field_name: str @param value: search string @type value: str... | Implement the Python class `Fuzzy` described below.
Class description:
Implement the Fuzzy class.
Method signatures and docstrings:
- def __init__(self, field_name=None, value=None): Set either both parameters or neither. @param field_name: field name @type field_name: str @param value: search string @type value: str... | 0fbf68ed3e17d665e3cdf1913444ebf1f72693dd | <|skeleton|>
class Fuzzy:
def __init__(self, field_name=None, value=None):
"""Set either both parameters or neither. @param field_name: field name @type field_name: str @param value: search string @type value: str"""
<|body_0|>
def set_field(self, field_name, value):
"""@param field_na... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fuzzy:
def __init__(self, field_name=None, value=None):
"""Set either both parameters or neither. @param field_name: field name @type field_name: str @param value: search string @type value: str"""
super(Fuzzy, self).__init__()
if field_name and value:
self.set_field(field_... | the_stack_v2_python_sparse | pylastica/query/fuzzy.py | jlinn/pylastica | train | 5 | |
0614b9daee019bb698a7bc855dfb6bb4d67e71c0 | [
"super(CPUTimeProfiler, self).__init__()\nself._identifier = identifier\nself._profile_measurements = {}\nself._sample_file = u'{0:s}-{1!s}.csv'.format(self._FILENAME_PREFIX, identifier)",
"if profile_name not in self._profile_measurements:\n return\nself._profile_measurements[profile_name].SampleStop()",
"i... | <|body_start_0|>
super(CPUTimeProfiler, self).__init__()
self._identifier = identifier
self._profile_measurements = {}
self._sample_file = u'{0:s}-{1!s}.csv'.format(self._FILENAME_PREFIX, identifier)
<|end_body_0|>
<|body_start_1|>
if profile_name not in self._profile_measuremen... | The CPU time profiler. | CPUTimeProfiler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPUTimeProfiler:
"""The CPU time profiler."""
def __init__(self, identifier):
"""Initializes the CPU time profiler object. Args: identifier: the profile identifier."""
<|body_0|>
def StopTiming(self, profile_name):
"""Stops timing CPU time. Args: profile_name: th... | stack_v2_sparse_classes_36k_train_019059 | 4,630 | permissive | [
{
"docstring": "Initializes the CPU time profiler object. Args: identifier: the profile identifier.",
"name": "__init__",
"signature": "def __init__(self, identifier)"
},
{
"docstring": "Stops timing CPU time. Args: profile_name: the name of the profile to sample.",
"name": "StopTiming",
... | 4 | null | Implement the Python class `CPUTimeProfiler` described below.
Class description:
The CPU time profiler.
Method signatures and docstrings:
- def __init__(self, identifier): Initializes the CPU time profiler object. Args: identifier: the profile identifier.
- def StopTiming(self, profile_name): Stops timing CPU time. A... | Implement the Python class `CPUTimeProfiler` described below.
Class description:
The CPU time profiler.
Method signatures and docstrings:
- def __init__(self, identifier): Initializes the CPU time profiler object. Args: identifier: the profile identifier.
- def StopTiming(self, profile_name): Stops timing CPU time. A... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class CPUTimeProfiler:
"""The CPU time profiler."""
def __init__(self, identifier):
"""Initializes the CPU time profiler object. Args: identifier: the profile identifier."""
<|body_0|>
def StopTiming(self, profile_name):
"""Stops timing CPU time. Args: profile_name: th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CPUTimeProfiler:
"""The CPU time profiler."""
def __init__(self, identifier):
"""Initializes the CPU time profiler object. Args: identifier: the profile identifier."""
super(CPUTimeProfiler, self).__init__()
self._identifier = identifier
self._profile_measurements = {}
... | the_stack_v2_python_sparse | plaso/engine/profiler.py | CNR-ITTIG/plasodfaxp | train | 1 |
a12ed7bcb2d5d6bb4440aeac4ef8d57dec03e4e0 | [
"kwargs = {field_name: value for field_name, value in self.cleaned_data.items() if value or value is False or value == 0}\nq_objects = []\nq_filters = []\nfor field_name, custom_field_lookup in self.Meta.field_lookups.iteritems():\n value = self.cleaned_data[field_name]\n if inspect.isfunction(custom_field_lo... | <|body_start_0|>
kwargs = {field_name: value for field_name, value in self.cleaned_data.items() if value or value is False or value == 0}
q_objects = []
q_filters = []
for field_name, custom_field_lookup in self.Meta.field_lookups.iteritems():
value = self.cleaned_data[field_... | Mixin used to create a search form. Allows you to define a list of field-filters pairs used to filter the queryset passed to the form filters can be a combination of list of fields, Q objects and custom filter methods | SearchFormMixin | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchFormMixin:
"""Mixin used to create a search form. Allows you to define a list of field-filters pairs used to filter the queryset passed to the form filters can be a combination of list of fields, Q objects and custom filter methods"""
def filters(self, queryset):
"""Prepares th... | stack_v2_sparse_classes_36k_train_019060 | 3,348 | permissive | [
{
"docstring": "Prepares the dictionary of queryset filters based on the form cleaned data :param Queryset queryset: the queryset to filter through. :returns: tuple of q_objects and kwargs used in filtering the queryset .. warning:: method uses cleaned_data, self.full_clean() must be called first.",
"name":... | 2 | null | Implement the Python class `SearchFormMixin` described below.
Class description:
Mixin used to create a search form. Allows you to define a list of field-filters pairs used to filter the queryset passed to the form filters can be a combination of list of fields, Q objects and custom filter methods
Method signatures a... | Implement the Python class `SearchFormMixin` described below.
Class description:
Mixin used to create a search form. Allows you to define a list of field-filters pairs used to filter the queryset passed to the form filters can be a combination of list of fields, Q objects and custom filter methods
Method signatures a... | a3dc470bd8fd3f01615ff57198dfefc88d3aa50c | <|skeleton|>
class SearchFormMixin:
"""Mixin used to create a search form. Allows you to define a list of field-filters pairs used to filter the queryset passed to the form filters can be a combination of list of fields, Q objects and custom filter methods"""
def filters(self, queryset):
"""Prepares th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchFormMixin:
"""Mixin used to create a search form. Allows you to define a list of field-filters pairs used to filter the queryset passed to the form filters can be a combination of list of fields, Q objects and custom filter methods"""
def filters(self, queryset):
"""Prepares the dictionary ... | the_stack_v2_python_sparse | toolkit/forms/mixins.py | cceit/cce-toolkit | train | 8 |
20ee494ed884a5d0b2e12e7572c6cac7ff23032d | [
"super().__init__(name='image_decoder')\nself.model_size = model_size\ncnn_multiplier = get_cnn_multiplier(self.model_size, override=cnn_multiplier)\nself.input_dims = (4, 4, 8 * cnn_multiplier)\nself.gray_scaled = gray_scaled\nself.dense_layer = tf.keras.layers.Dense(units=int(np.prod(self.input_dims)), activation... | <|body_start_0|>
super().__init__(name='image_decoder')
self.model_size = model_size
cnn_multiplier = get_cnn_multiplier(self.model_size, override=cnn_multiplier)
self.input_dims = (4, 4, 8 * cnn_multiplier)
self.gray_scaled = gray_scaled
self.dense_layer = tf.keras.layer... | A Conv2DTranspose decoder to generate Atari images from a latent space. Wraps an initial single linear layer with a stack of 4 Conv2DTranspose layers (with layer normalization) and a diag Gaussian, from which we then sample the final image. Sampling is done with a fixed stddev=1.0 and using the mean values coming from ... | ConvTransposeAtari | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvTransposeAtari:
"""A Conv2DTranspose decoder to generate Atari images from a latent space. Wraps an initial single linear layer with a stack of 4 Conv2DTranspose layers (with layer normalization) and a diag Gaussian, from which we then sample the final image. Sampling is done with a fixed std... | stack_v2_sparse_classes_36k_train_019061 | 7,241 | permissive | [
{
"docstring": "Initializes a ConvTransposeAtari instance. Args: model_size: The \"Model Size\" used according to [1] Appendinx B. Use None for manually setting the `cnn_multiplier`. cnn_multiplier: Optional override for the additional factor used to multiply the number of filters with each CNN transpose layer.... | 2 | null | Implement the Python class `ConvTransposeAtari` described below.
Class description:
A Conv2DTranspose decoder to generate Atari images from a latent space. Wraps an initial single linear layer with a stack of 4 Conv2DTranspose layers (with layer normalization) and a diag Gaussian, from which we then sample the final i... | Implement the Python class `ConvTransposeAtari` described below.
Class description:
A Conv2DTranspose decoder to generate Atari images from a latent space. Wraps an initial single linear layer with a stack of 4 Conv2DTranspose layers (with layer normalization) and a diag Gaussian, from which we then sample the final i... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class ConvTransposeAtari:
"""A Conv2DTranspose decoder to generate Atari images from a latent space. Wraps an initial single linear layer with a stack of 4 Conv2DTranspose layers (with layer normalization) and a diag Gaussian, from which we then sample the final image. Sampling is done with a fixed std... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvTransposeAtari:
"""A Conv2DTranspose decoder to generate Atari images from a latent space. Wraps an initial single linear layer with a stack of 4 Conv2DTranspose layers (with layer normalization) and a diag Gaussian, from which we then sample the final image. Sampling is done with a fixed stddev=1.0 and u... | the_stack_v2_python_sparse | rllib/algorithms/dreamerv3/tf/models/components/conv_transpose_atari.py | ray-project/ray | train | 29,482 |
08469cb65e3316eca0c1ed79ab17d1948690c970 | [
"if not settings.user.allow_avatar_capability:\n raise ResourceNotAvailableError()\nuser = req.context.get('user')\nuser_id = str(user.id)\nif 'image' not in req.params:\n raise UserAvatarUploadError()\navatar = req.params.get('image').file\navatar_stream = avatar.read()\nif len(avatar_stream) / 1024 > settin... | <|body_start_0|>
if not settings.user.allow_avatar_capability:
raise ResourceNotAvailableError()
user = req.context.get('user')
user_id = str(user.id)
if 'image' not in req.params:
raise UserAvatarUploadError()
avatar = req.params.get('image').file
... | UserAvatarMediaResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAvatarMediaResource:
def on_post(self, req, resp):
"""Consumes and stores avatar for user in current session."""
<|body_0|>
def on_delete(self, req, resp):
"""Delete existing user avatar, will reference default."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_019062 | 7,736 | permissive | [
{
"docstring": "Consumes and stores avatar for user in current session.",
"name": "on_post",
"signature": "def on_post(self, req, resp)"
},
{
"docstring": "Delete existing user avatar, will reference default.",
"name": "on_delete",
"signature": "def on_delete(self, req, resp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010973 | Implement the Python class `UserAvatarMediaResource` described below.
Class description:
Implement the UserAvatarMediaResource class.
Method signatures and docstrings:
- def on_post(self, req, resp): Consumes and stores avatar for user in current session.
- def on_delete(self, req, resp): Delete existing user avatar,... | Implement the Python class `UserAvatarMediaResource` described below.
Class description:
Implement the UserAvatarMediaResource class.
Method signatures and docstrings:
- def on_post(self, req, resp): Consumes and stores avatar for user in current session.
- def on_delete(self, req, resp): Delete existing user avatar,... | e507fe0307d1a7ea29d6c3e20be62fa82a8f109f | <|skeleton|>
class UserAvatarMediaResource:
def on_post(self, req, resp):
"""Consumes and stores avatar for user in current session."""
<|body_0|>
def on_delete(self, req, resp):
"""Delete existing user avatar, will reference default."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAvatarMediaResource:
def on_post(self, req, resp):
"""Consumes and stores avatar for user in current session."""
if not settings.user.allow_avatar_capability:
raise ResourceNotAvailableError()
user = req.context.get('user')
user_id = str(user.id)
if 'ima... | the_stack_v2_python_sparse | blog/resources/users.py | neetjn/py-blog | train | 0 | |
4c6dfd6377704a18011733ac1eba3711582265e5 | [
"self.dic = {}\nself.l = len(words)\nfor index, value in enumerate(words):\n self.dic[value] = self.dic.get(value, []) + [index]",
"l1, l2 = (self.dic[word1], self.dic[word2])\ni = j = 0\nres = self.l\nwhile i < len(l1) and j < len(l2):\n res = min(res, abs(l1[i] - l2[j]))\n if l1[i] < l2[j]:\n i ... | <|body_start_0|>
self.dic = {}
self.l = len(words)
for index, value in enumerate(words):
self.dic[value] = self.dic.get(value, []) + [index]
<|end_body_0|>
<|body_start_1|>
l1, l2 = (self.dic[word1], self.dic[word2])
i = j = 0
res = self.l
while i < l... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_019063 | 2,689 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.dic = {}
self.l = len(words)
for index, value in enumerate(words):
self.dic[value] = self.dic.get(value, []) + [index]
def shortest(self, word1, word... | the_stack_v2_python_sparse | leetcode_python/Hash_table/shortest-word-distance-ii.py | yennanliu/CS_basics | train | 64 | |
d9cac6932cfc363c010de3526ef2b38026607645 | [
"self.config = config_\nself.logger = logging.getLogger('cuda_logger')\nself.RLT = []",
"a = 1.0 * np.array(data)\nn = len(a)\nm, se = (np.mean(a), scipy.stats.sem(a))\nh = se * scipy.stats.t.ppf((1 + confidence) / 2.0, n - 1)\nif confidence == 0:\n return (m, m - se, m + se)\nelse:\n return (m, m - h, m + ... | <|body_start_0|>
self.config = config_
self.logger = logging.getLogger('cuda_logger')
self.RLT = []
<|end_body_0|>
<|body_start_1|>
a = 1.0 * np.array(data)
n = len(a)
m, se = (np.mean(a), scipy.stats.sem(a))
h = se * scipy.stats.t.ppf((1 + confidence) / 2.0, n -... | This class tracks the details about the running RL training | TrainingTracker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingTracker:
"""This class tracks the details about the running RL training"""
def __init__(self, config_):
"""Constructor :param config_: :param S: :param T: :return:"""
<|body_0|>
def mean_confidence_interval(self, data, confidence=0.95):
"""Calculates mean... | stack_v2_sparse_classes_36k_train_019064 | 4,736 | no_license | [
{
"docstring": "Constructor :param config_: :param S: :param T: :return:",
"name": "__init__",
"signature": "def __init__(self, config_)"
},
{
"docstring": "Calculates mean and confidence interval around the data array :param data: :param confidence: :return m, m-h, m+h",
"name": "mean_confi... | 3 | null | Implement the Python class `TrainingTracker` described below.
Class description:
This class tracks the details about the running RL training
Method signatures and docstrings:
- def __init__(self, config_): Constructor :param config_: :param S: :param T: :return:
- def mean_confidence_interval(self, data, confidence=0... | Implement the Python class `TrainingTracker` described below.
Class description:
This class tracks the details about the running RL training
Method signatures and docstrings:
- def __init__(self, config_): Constructor :param config_: :param S: :param T: :return:
- def mean_confidence_interval(self, data, confidence=0... | f7fcd2cc1d6ba18b199d176d4d39193f025ee281 | <|skeleton|>
class TrainingTracker:
"""This class tracks the details about the running RL training"""
def __init__(self, config_):
"""Constructor :param config_: :param S: :param T: :return:"""
<|body_0|>
def mean_confidence_interval(self, data, confidence=0.95):
"""Calculates mean... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainingTracker:
"""This class tracks the details about the running RL training"""
def __init__(self, config_):
"""Constructor :param config_: :param S: :param T: :return:"""
self.config = config_
self.logger = logging.getLogger('cuda_logger')
self.RLT = []
def mean_c... | the_stack_v2_python_sparse | learn_to_earn_framework/tracker/training_tracker.py | transparent-framework/optimize-ride-sharing-earnings | train | 7 |
cba5c6a180efb7a7f707eda93d6c7fa4bdc67032 | [
"if not trans.user_is_admin:\n trans.response.status = 403\n return 'You are not authorized to view the list of forms.'\nquery = trans.sa_session.query(trans.app.model.FormDefinition)\nrval = []\nfor form_definition in query:\n item = form_definition.to_dict(value_mapper={'id': trans.security.encode_id, 'f... | <|body_start_0|>
if not trans.user_is_admin:
trans.response.status = 403
return 'You are not authorized to view the list of forms.'
query = trans.sa_session.query(trans.app.model.FormDefinition)
rval = []
for form_definition in query:
item = form_defin... | FormDefinitionAPIController | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormDefinitionAPIController:
def index(self, trans, **kwd):
"""GET /api/forms Displays a collection (list) of forms."""
<|body_0|>
def show(self, trans, id, **kwd):
"""GET /api/forms/{encoded_form_id} Displays information about a form."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_019065 | 3,129 | permissive | [
{
"docstring": "GET /api/forms Displays a collection (list) of forms.",
"name": "index",
"signature": "def index(self, trans, **kwd)"
},
{
"docstring": "GET /api/forms/{encoded_form_id} Displays information about a form.",
"name": "show",
"signature": "def show(self, trans, id, **kwd)"
... | 3 | stack_v2_sparse_classes_30k_train_020653 | Implement the Python class `FormDefinitionAPIController` described below.
Class description:
Implement the FormDefinitionAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/forms Displays a collection (list) of forms.
- def show(self, trans, id, **kwd): GET /api/forms/{enc... | Implement the Python class `FormDefinitionAPIController` described below.
Class description:
Implement the FormDefinitionAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/forms Displays a collection (list) of forms.
- def show(self, trans, id, **kwd): GET /api/forms/{enc... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class FormDefinitionAPIController:
def index(self, trans, **kwd):
"""GET /api/forms Displays a collection (list) of forms."""
<|body_0|>
def show(self, trans, id, **kwd):
"""GET /api/forms/{encoded_form_id} Displays information about a form."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormDefinitionAPIController:
def index(self, trans, **kwd):
"""GET /api/forms Displays a collection (list) of forms."""
if not trans.user_is_admin:
trans.response.status = 403
return 'You are not authorized to view the list of forms.'
query = trans.sa_session.qu... | the_stack_v2_python_sparse | lib/galaxy/webapps/galaxy/api/forms.py | bwlang/galaxy | train | 0 | |
1b347eeca875b9f23267b7e75ac82238e49b9c2c | [
"super(Inception, self).__init__()\nbranch1_list = [{'type': ConvBNLayer, 'num_channels': num_channels, 'num_filters': ch1x1, 'filter_size': 1, 'stride': 1, 'padding': 0, 'act': 'relu'}]\nself.branch1 = LinConPoo(branch1_list)\nbranch2_list = [{'type': ConvBNLayer, 'num_channels': num_channels, 'num_filters': ch3x3... | <|body_start_0|>
super(Inception, self).__init__()
branch1_list = [{'type': ConvBNLayer, 'num_channels': num_channels, 'num_filters': ch1x1, 'filter_size': 1, 'stride': 1, 'padding': 0, 'act': 'relu'}]
self.branch1 = LinConPoo(branch1_list)
branch2_list = [{'type': ConvBNLayer, 'num_chan... | Inception | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inception:
def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers... | stack_v2_sparse_classes_36k_train_019066 | 22,436 | permissive | [
{
"docstring": "@Brief `Inception` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers of 1x1 conv before 3x3 conv ch3x3 : output channel numbers of 3x3 conv doublech3x3reduced : channel numbers of 1x1 conv before the double 3x3 co... | 2 | stack_v2_sparse_classes_30k_train_008346 | Implement the Python class `Inception` described below.
Class description:
Implement the Inception class.
Method signatures and docstrings:
- def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj): @Brief `Inception` @Parameters num_channels : channel... | Implement the Python class `Inception` described below.
Class description:
Implement the Inception class.
Method signatures and docstrings:
- def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj): @Brief `Inception` @Parameters num_channels : channel... | 78ff3c3ab3906012a0f4a612251347632aa493a7 | <|skeleton|>
class Inception:
def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Inception:
def __init__(self, num_channels, ch1x1, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers of 1x1 conv b... | the_stack_v2_python_sparse | ECO/paddle1.8/model/ECO.py | thinkall/Contrib | train | 1 | |
7a0200b9a1e1b979d9b0547f18368a88268a1fbb | [
"for win_index, window in enumerate(window_seq):\n window = list(window)\n threshold = skimage.filters.threshold_isodata(np.array(window, dtype=float))\n w1 = filter(lambda a: a < threshold, window)\n w2 = filter(lambda a: a >= threshold, window)\n mean1 = self.get_mean(w1)\n mean2 = self.get_mean... | <|body_start_0|>
for win_index, window in enumerate(window_seq):
window = list(window)
threshold = skimage.filters.threshold_isodata(np.array(window, dtype=float))
w1 = filter(lambda a: a < threshold, window)
w2 = filter(lambda a: a >= threshold, window)
... | TODO: not implemented | MinStdOtsuSWFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinStdOtsuSWFilter:
"""TODO: not implemented"""
def aggregate_windows(self, window_seq, **kwargs):
""":param window_seq: :param kwargs: :return:"""
<|body_0|>
def otsu_index(window):
""":param window: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_019067 | 2,345 | permissive | [
{
"docstring": ":param window_seq: :param kwargs: :return:",
"name": "aggregate_windows",
"signature": "def aggregate_windows(self, window_seq, **kwargs)"
},
{
"docstring": ":param window: :return:",
"name": "otsu_index",
"signature": "def otsu_index(window)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000132 | Implement the Python class `MinStdOtsuSWFilter` described below.
Class description:
TODO: not implemented
Method signatures and docstrings:
- def aggregate_windows(self, window_seq, **kwargs): :param window_seq: :param kwargs: :return:
- def otsu_index(window): :param window: :return: | Implement the Python class `MinStdOtsuSWFilter` described below.
Class description:
TODO: not implemented
Method signatures and docstrings:
- def aggregate_windows(self, window_seq, **kwargs): :param window_seq: :param kwargs: :return:
- def otsu_index(window): :param window: :return:
<|skeleton|>
class MinStdOtsuSW... | 617ff45c9c3c96bbd9a975aef15f1b2697282b9c | <|skeleton|>
class MinStdOtsuSWFilter:
"""TODO: not implemented"""
def aggregate_windows(self, window_seq, **kwargs):
""":param window_seq: :param kwargs: :return:"""
<|body_0|>
def otsu_index(window):
""":param window: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinStdOtsuSWFilter:
"""TODO: not implemented"""
def aggregate_windows(self, window_seq, **kwargs):
""":param window_seq: :param kwargs: :return:"""
for win_index, window in enumerate(window_seq):
window = list(window)
threshold = skimage.filters.threshold_isodata(n... | the_stack_v2_python_sparse | shot_detector/filters/sliding_window/min_std_otsu_swfilter.py | w495/python-video-shot-detector | train | 20 |
d9206700a18cd5e5e971b231ee361dce7f91661c | [
"if not isinstance(self.num_qudits, int) or len(qudit_dimensions) != self.num_qudits:\n raise CircuitError(f'Number of flexible qudits ({self.num_qudits}) does not match number of qudit_dimensions {qudit_dimensions}.')\nsuper().__init__(name=name, qudit_dimensions=qudit_dimensions, num_single_qubits=num_single_q... | <|body_start_0|>
if not isinstance(self.num_qudits, int) or len(qudit_dimensions) != self.num_qudits:
raise CircuitError(f'Number of flexible qudits ({self.num_qudits}) does not match number of qudit_dimensions {qudit_dimensions}.')
super().__init__(name=name, qudit_dimensions=qudit_dimensio... | Qudit instruction adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0. | FlexibleQuditInstruction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlexibleQuditInstruction:
"""Qudit instruction adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0."""
def __init__(self, name, qudit_dimensions, num_single_qubits, num_clbits, params, duration=None, unit='dt'):
"""Flexible qudit instruct... | stack_v2_sparse_classes_36k_train_019068 | 7,780 | permissive | [
{
"docstring": "Flexible qudit instruction. Subclasses should only leave the qudit_dimensions argument in constructor, i.e. def __init__(self, qudit_dimensions): ... Raises: CircuitError: If number of qudits does not equal length of qudit_dimensions.",
"name": "__init__",
"signature": "def __init__(self... | 2 | stack_v2_sparse_classes_30k_test_000575 | Implement the Python class `FlexibleQuditInstruction` described below.
Class description:
Qudit instruction adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0.
Method signatures and docstrings:
- def __init__(self, name, qudit_dimensions, num_single_qubits, num_clbits, p... | Implement the Python class `FlexibleQuditInstruction` described below.
Class description:
Qudit instruction adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0.
Method signatures and docstrings:
- def __init__(self, name, qudit_dimensions, num_single_qubits, num_clbits, p... | 9935eedd7d8258619a35424a98f2a71776b61e28 | <|skeleton|>
class FlexibleQuditInstruction:
"""Qudit instruction adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0."""
def __init__(self, name, qudit_dimensions, num_single_qubits, num_clbits, params, duration=None, unit='dt'):
"""Flexible qudit instruct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlexibleQuditInstruction:
"""Qudit instruction adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0."""
def __init__(self, name, qudit_dimensions, num_single_qubits, num_clbits, params, duration=None, unit='dt'):
"""Flexible qudit instruction. Subclass... | the_stack_v2_python_sparse | qiskit_qudits/circuit/flexiblequditinstruction.py | q-inho/QuditsTeam-1 | train | 1 |
1c52d8b098d1bd5059f46f9b66ad5f3475d2e612 | [
"for x in (1.5, 'string'):\n with self.subTest(x=x):\n with self.assertRaises(TypeError):\n factorize(x)",
"for x in (-1, -10, -100):\n with self.subTest(x=x):\n with self.assertRaises(ValueError):\n factorize(x)",
"for x in (0, 1):\n with self.subTest(x=x):\n ... | <|body_start_0|>
for x in (1.5, 'string'):
with self.subTest(x=x):
with self.assertRaises(TypeError):
factorize(x)
<|end_body_0|>
<|body_start_1|>
for x in (-1, -10, -100):
with self.subTest(x=x):
with self.assertRaises(ValueEr... | TestFactorize | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFactorize:
def test_wrong_types_raise_exception(self):
"""аргументы типа float или str вызывают исключение TypeError"""
<|body_0|>
def test_negative(self):
"""отрицательные числа вызывают исключение ValueError"""
<|body_1|>
def test_zero_and_one_case... | stack_v2_sparse_classes_36k_train_019069 | 2,042 | permissive | [
{
"docstring": "аргументы типа float или str вызывают исключение TypeError",
"name": "test_wrong_types_raise_exception",
"signature": "def test_wrong_types_raise_exception(self)"
},
{
"docstring": "отрицательные числа вызывают исключение ValueError",
"name": "test_negative",
"signature":... | 6 | null | Implement the Python class `TestFactorize` described below.
Class description:
Implement the TestFactorize class.
Method signatures and docstrings:
- def test_wrong_types_raise_exception(self): аргументы типа float или str вызывают исключение TypeError
- def test_negative(self): отрицательные числа вызывают исключени... | Implement the Python class `TestFactorize` described below.
Class description:
Implement the TestFactorize class.
Method signatures and docstrings:
- def test_wrong_types_raise_exception(self): аргументы типа float или str вызывают исключение TypeError
- def test_negative(self): отрицательные числа вызывают исключени... | beff426dfeaf71a5cb32b74be81df9540ebece4a | <|skeleton|>
class TestFactorize:
def test_wrong_types_raise_exception(self):
"""аргументы типа float или str вызывают исключение TypeError"""
<|body_0|>
def test_negative(self):
"""отрицательные числа вызывают исключение ValueError"""
<|body_1|>
def test_zero_and_one_case... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFactorize:
def test_wrong_types_raise_exception(self):
"""аргументы типа float или str вызывают исключение TypeError"""
for x in (1.5, 'string'):
with self.subTest(x=x):
with self.assertRaises(TypeError):
factorize(x)
def test_negative(s... | the_stack_v2_python_sparse | Python/Programming-in-Python/2. OOP patterns in Python/Week1/Practices/author_factorize.py | EldanGS/Engineering | train | 0 | |
b0a147986ae90d6e0274dac8275669288a44ea59 | [
"self.max_length = max_length\nself.tmto_lookup = []\nfor i in range(self.max_length + 1):\n self.tmto_lookup.append({})",
"try:\n return (True, self.custom_copy(self.tmto_lookup[length][ip_ngram][target_level]))\nexcept KeyError:\n return (False, None)",
"if ip_ngram not in self.tmto_lookup[length]:\n... | <|body_start_0|>
self.max_length = max_length
self.tmto_lookup = []
for i in range(self.max_length + 1):
self.tmto_lookup.append({})
<|end_body_0|>
<|body_start_1|>
try:
return (True, self.custom_copy(self.tmto_lookup[length][ip_ngram][target_level]))
exc... | Contains all the logic to speed up guess generation by using tmto tricks Creating this as a class so I can easily pass it around | Optimizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Optimizer:
"""Contains all the logic to speed up guess generation by using tmto tricks Creating this as a class so I can easily pass it around"""
def __init__(self, max_length):
"""Initializes the optimizer Inputs: max_length: The maximum length of strings to optimize. Increasing thi... | stack_v2_sparse_classes_36k_train_019070 | 3,380 | no_license | [
{
"docstring": "Initializes the optimizer Inputs: max_length: The maximum length of strings to optimize. Increasing this increases memory requirements",
"name": "__init__",
"signature": "def __init__(self, max_length)"
},
{
"docstring": "Look up a previous result Inputs: ip_ngram: The initial st... | 4 | stack_v2_sparse_classes_30k_train_017025 | Implement the Python class `Optimizer` described below.
Class description:
Contains all the logic to speed up guess generation by using tmto tricks Creating this as a class so I can easily pass it around
Method signatures and docstrings:
- def __init__(self, max_length): Initializes the optimizer Inputs: max_length: ... | Implement the Python class `Optimizer` described below.
Class description:
Contains all the logic to speed up guess generation by using tmto tricks Creating this as a class so I can easily pass it around
Method signatures and docstrings:
- def __init__(self, max_length): Initializes the optimizer Inputs: max_length: ... | 6fed1047838091edec7ce96679c3d0887073ed3b | <|skeleton|>
class Optimizer:
"""Contains all the logic to speed up guess generation by using tmto tricks Creating this as a class so I can easily pass it around"""
def __init__(self, max_length):
"""Initializes the optimizer Inputs: max_length: The maximum length of strings to optimize. Increasing thi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Optimizer:
"""Contains all the logic to speed up guess generation by using tmto tricks Creating this as a class so I can easily pass it around"""
def __init__(self, max_length):
"""Initializes the optimizer Inputs: max_length: The maximum length of strings to optimize. Increasing this increases m... | the_stack_v2_python_sparse | lib_guesser/omen/optimizer.py | lakiw/pcfg_cracker | train | 286 |
0107bb46ea141667222090d2e963665eaeddc7fd | [
"n = len(s)\ndp = [[False] * n for _ in range(n)]\nans = ''\nfor l in range(n):\n for i in range(n):\n j = i + l\n if j >= len(s):\n break\n if l == 0:\n dp[i][j] = True\n elif l == 1:\n dp[i][j] = s[i] == s[j]\n else:\n dp[i][j] = dp... | <|body_start_0|>
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = ''
for l in range(n):
for i in range(n):
j = i + l
if j >= len(s):
break
if l == 0:
dp[i][j] = True
e... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome_dp(self, s: str) -> str:
"""动态规划算法:自底向上解法 算法时间复杂度:O(n^2) 算法空间复杂度:O(n^2) :param s:目标字符串 :return:最长回文子串"""
<|body_0|>
def longestPalindrome_expandAroundCenter(self, s: str) -> str:
"""中心扩展算法, 算法时间复杂度:O(n^2) 算法空间复杂度:O(1) :param s: :return... | stack_v2_sparse_classes_36k_train_019071 | 2,497 | permissive | [
{
"docstring": "动态规划算法:自底向上解法 算法时间复杂度:O(n^2) 算法空间复杂度:O(n^2) :param s:目标字符串 :return:最长回文子串",
"name": "longestPalindrome_dp",
"signature": "def longestPalindrome_dp(self, s: str) -> str"
},
{
"docstring": "中心扩展算法, 算法时间复杂度:O(n^2) 算法空间复杂度:O(1) :param s: :return:",
"name": "longestPalindrome_expa... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_dp(self, s: str) -> str: 动态规划算法:自底向上解法 算法时间复杂度:O(n^2) 算法空间复杂度:O(n^2) :param s:目标字符串 :return:最长回文子串
- def longestPalindrome_expandAroundCenter(self, s: str) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_dp(self, s: str) -> str: 动态规划算法:自底向上解法 算法时间复杂度:O(n^2) 算法空间复杂度:O(n^2) :param s:目标字符串 :return:最长回文子串
- def longestPalindrome_expandAroundCenter(self, s: str) ... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def longestPalindrome_dp(self, s: str) -> str:
"""动态规划算法:自底向上解法 算法时间复杂度:O(n^2) 算法空间复杂度:O(n^2) :param s:目标字符串 :return:最长回文子串"""
<|body_0|>
def longestPalindrome_expandAroundCenter(self, s: str) -> str:
"""中心扩展算法, 算法时间复杂度:O(n^2) 算法空间复杂度:O(1) :param s: :return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome_dp(self, s: str) -> str:
"""动态规划算法:自底向上解法 算法时间复杂度:O(n^2) 算法空间复杂度:O(n^2) :param s:目标字符串 :return:最长回文子串"""
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = ''
for l in range(n):
for i in range(n):
j = i + l
... | the_stack_v2_python_sparse | LeetCode 热题 HOT 100/longestPalindrome.py | MaoningGuan/LeetCode | train | 3 | |
da03f0781c079ff50ff0d2843e904a6c246f423d | [
"super(TestLoadLattice, self).setUp()\nself.tmpLocation = tempfile.mkdtemp(prefix='atomanTest')\nself.mw = mainWindow.MainWindow(None, testing=True)\nself.mw.preferences.renderingForm.maxAtomsAutoRun = 0\nself.mw.show()",
"super(TestLoadLattice, self).tearDown()\nself.mw.close()\nself.mw = None\nshutil.rmtree(sel... | <|body_start_0|>
super(TestLoadLattice, self).setUp()
self.tmpLocation = tempfile.mkdtemp(prefix='atomanTest')
self.mw = mainWindow.MainWindow(None, testing=True)
self.mw.preferences.renderingForm.maxAtomsAutoRun = 0
self.mw.show()
<|end_body_0|>
<|body_start_1|>
super(T... | Test loading a Lattice | TestLoadLattice | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLoadLattice:
"""Test loading a Lattice"""
def setUp(self):
"""Set up the test"""
<|body_0|>
def tearDown(self):
"""Tidy up"""
<|body_1|>
def test_loadLbomdDat(self):
"""GUI: Load LBOMD Lattice"""
<|body_2|>
def test_loadLbomd... | stack_v2_sparse_classes_36k_train_019072 | 3,390 | permissive | [
{
"docstring": "Set up the test",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tidy up",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "GUI: Load LBOMD Lattice",
"name": "test_loadLbomdDat",
"signature": "def test_loadLbomdD... | 4 | stack_v2_sparse_classes_30k_train_017825 | Implement the Python class `TestLoadLattice` described below.
Class description:
Test loading a Lattice
Method signatures and docstrings:
- def setUp(self): Set up the test
- def tearDown(self): Tidy up
- def test_loadLbomdDat(self): GUI: Load LBOMD Lattice
- def test_loadLbomdRef(self): GUI: Load LBOMD REF | Implement the Python class `TestLoadLattice` described below.
Class description:
Test loading a Lattice
Method signatures and docstrings:
- def setUp(self): Set up the test
- def tearDown(self): Tidy up
- def test_loadLbomdDat(self): GUI: Load LBOMD Lattice
- def test_loadLbomdRef(self): GUI: Load LBOMD REF
<|skelet... | e87ac31bbdcf53bb8f3efdfb109787d604890394 | <|skeleton|>
class TestLoadLattice:
"""Test loading a Lattice"""
def setUp(self):
"""Set up the test"""
<|body_0|>
def tearDown(self):
"""Tidy up"""
<|body_1|>
def test_loadLbomdDat(self):
"""GUI: Load LBOMD Lattice"""
<|body_2|>
def test_loadLbomd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLoadLattice:
"""Test loading a Lattice"""
def setUp(self):
"""Set up the test"""
super(TestLoadLattice, self).setUp()
self.tmpLocation = tempfile.mkdtemp(prefix='atomanTest')
self.mw = mainWindow.MainWindow(None, testing=True)
self.mw.preferences.renderingForm.... | the_stack_v2_python_sparse | atoman/slowtests/test_loadLattice.py | chrisdjscott/Atoman | train | 9 |
707e65fde1ad6ebc66c3db09053e9b740eb002af | [
"pk = uuid.uuid4()\npeople = self.context['request'].user.staff.name if self.context['request'].user.staff else '匿名用户'\nreturn Method.objects.create(pk=pk, people=people, **validated_data)",
"instance.name = validated_data.get('name', instance.name)\ninstance.people = validated_data.get('people', instance.people)... | <|body_start_0|>
pk = uuid.uuid4()
people = self.context['request'].user.staff.name if self.context['request'].user.staff else '匿名用户'
return Method.objects.create(pk=pk, people=people, **validated_data)
<|end_body_0|>
<|body_start_1|>
instance.name = validated_data.get('name', instance.... | 应急演练序列化器 | MethodSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethodSerializer:
"""应急演练序列化器"""
def create(self, validated_data):
"""新建"""
<|body_0|>
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pk = uuid.uuid4()
people = self.co... | stack_v2_sparse_classes_36k_train_019073 | 1,545 | no_license | [
{
"docstring": "新建",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "更新,instance为要更新的对象实例",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | null | Implement the Python class `MethodSerializer` described below.
Class description:
应急演练序列化器
Method signatures and docstrings:
- def create(self, validated_data): 新建
- def update(self, instance, validated_data): 更新,instance为要更新的对象实例 | Implement the Python class `MethodSerializer` described below.
Class description:
应急演练序列化器
Method signatures and docstrings:
- def create(self, validated_data): 新建
- def update(self, instance, validated_data): 更新,instance为要更新的对象实例
<|skeleton|>
class MethodSerializer:
"""应急演练序列化器"""
def create(self, validate... | 3645bc3a396727af208db924c6fdee38abc0f894 | <|skeleton|>
class MethodSerializer:
"""应急演练序列化器"""
def create(self, validated_data):
"""新建"""
<|body_0|>
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MethodSerializer:
"""应急演练序列化器"""
def create(self, validated_data):
"""新建"""
pk = uuid.uuid4()
people = self.context['request'].user.staff.name if self.context['request'].user.staff else '匿名用户'
return Method.objects.create(pk=pk, people=people, **validated_data)
def up... | the_stack_v2_python_sparse | ruidun_system/safe/serializers/method_serializer.py | TingxieLi/django-restframework | train | 0 |
a6a271cfa2a1fa3bee66c08c5204020b2147c62e | [
"cli_utils.setup_logging()\ncls.lts = LTSGuestCreateTest()\ncls.lts.setUpClass()\ncls.target_charm_namespace = '~openstack-charmers-next'",
"charm_name = upgrade_utils.extract_charm_name_from_url(charm_url)\nnext_charm_url = zaza.model.get_latest_charm_url('cs:{}/{}'.format(self.target_charm_namespace, charm_name... | <|body_start_0|>
cli_utils.setup_logging()
cls.lts = LTSGuestCreateTest()
cls.lts.setUpClass()
cls.target_charm_namespace = '~openstack-charmers-next'
<|end_body_0|>
<|body_start_1|>
charm_name = upgrade_utils.extract_charm_name_from_url(charm_url)
next_charm_url = zaza.... | Class to encapsulate Charm Upgrade Tests. | FullCloudCharmUpgradeTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullCloudCharmUpgradeTest:
"""Class to encapsulate Charm Upgrade Tests."""
def setUpClass(cls):
"""Run setup for Charm Upgrades."""
<|body_0|>
def get_upgrade_url(self, charm_url):
"""Return the charm_url to upgrade to. :param charm_url: Current charm url. :type ... | stack_v2_sparse_classes_36k_train_019074 | 3,154 | permissive | [
{
"docstring": "Run setup for Charm Upgrades.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Return the charm_url to upgrade to. :param charm_url: Current charm url. :type charm_url: str",
"name": "get_upgrade_url",
"signature": "def get_upgrade_url(self, c... | 3 | stack_v2_sparse_classes_30k_train_003666 | Implement the Python class `FullCloudCharmUpgradeTest` described below.
Class description:
Class to encapsulate Charm Upgrade Tests.
Method signatures and docstrings:
- def setUpClass(cls): Run setup for Charm Upgrades.
- def get_upgrade_url(self, charm_url): Return the charm_url to upgrade to. :param charm_url: Curr... | Implement the Python class `FullCloudCharmUpgradeTest` described below.
Class description:
Class to encapsulate Charm Upgrade Tests.
Method signatures and docstrings:
- def setUpClass(cls): Run setup for Charm Upgrades.
- def get_upgrade_url(self, charm_url): Return the charm_url to upgrade to. :param charm_url: Curr... | 3b17ad9d97c57b6e62797d4e3333e4b83e43a447 | <|skeleton|>
class FullCloudCharmUpgradeTest:
"""Class to encapsulate Charm Upgrade Tests."""
def setUpClass(cls):
"""Run setup for Charm Upgrades."""
<|body_0|>
def get_upgrade_url(self, charm_url):
"""Return the charm_url to upgrade to. :param charm_url: Current charm url. :type ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullCloudCharmUpgradeTest:
"""Class to encapsulate Charm Upgrade Tests."""
def setUpClass(cls):
"""Run setup for Charm Upgrades."""
cli_utils.setup_logging()
cls.lts = LTSGuestCreateTest()
cls.lts.setUpClass()
cls.target_charm_namespace = '~openstack-charmers-next'... | the_stack_v2_python_sparse | zaza/openstack/charm_tests/charm_upgrade/tests.py | openstack-charmers/zaza-openstack-tests | train | 7 |
6a5ced57b222c9373e602c478284197ef74e7c32 | [
"for addr, name in labels.items():\n db_label = session.query(DbLabel).filter_by(kb=db_kb, addr=addr).scalar()\n if db_label is not None:\n if name == db_label.name:\n continue\n db_label.name = name\n else:\n db_label = DbLabel(kb=db_kb, addr=addr, name=name)\n sessi... | <|body_start_0|>
for addr, name in labels.items():
db_label = session.query(DbLabel).filter_by(kb=db_kb, addr=addr).scalar()
if db_label is not None:
if name == db_label.name:
continue
db_label.name = name
else:
... | Serialize/unserialize labels to/from a database session. | LabelsSerializer | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelsSerializer:
"""Serialize/unserialize labels to/from a database session."""
def dump(session, db_kb, labels):
""":param session: :param DbKnowledgeBase db_kb: :param Labels labels: :return: None"""
<|body_0|>
def load(session, db_kb, kb):
""":param session: ... | stack_v2_sparse_classes_36k_train_019075 | 1,425 | permissive | [
{
"docstring": ":param session: :param DbKnowledgeBase db_kb: :param Labels labels: :return: None",
"name": "dump",
"signature": "def dump(session, db_kb, labels)"
},
{
"docstring": ":param session: :param DbKnowledgeBase db_kb: :param KnowledgeBase kb: :return:",
"name": "load",
"signat... | 2 | null | Implement the Python class `LabelsSerializer` described below.
Class description:
Serialize/unserialize labels to/from a database session.
Method signatures and docstrings:
- def dump(session, db_kb, labels): :param session: :param DbKnowledgeBase db_kb: :param Labels labels: :return: None
- def load(session, db_kb, ... | Implement the Python class `LabelsSerializer` described below.
Class description:
Serialize/unserialize labels to/from a database session.
Method signatures and docstrings:
- def dump(session, db_kb, labels): :param session: :param DbKnowledgeBase db_kb: :param Labels labels: :return: None
- def load(session, db_kb, ... | 37e8ca1c3308ec601ad1d7c6bc8081ff38a7cffd | <|skeleton|>
class LabelsSerializer:
"""Serialize/unserialize labels to/from a database session."""
def dump(session, db_kb, labels):
""":param session: :param DbKnowledgeBase db_kb: :param Labels labels: :return: None"""
<|body_0|>
def load(session, db_kb, kb):
""":param session: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelsSerializer:
"""Serialize/unserialize labels to/from a database session."""
def dump(session, db_kb, labels):
""":param session: :param DbKnowledgeBase db_kb: :param Labels labels: :return: None"""
for addr, name in labels.items():
db_label = session.query(DbLabel).filter... | the_stack_v2_python_sparse | angr/angrdb/serializers/labels.py | angr/angr | train | 7,184 |
a81bfb9dd8b85b93314c2e73b6560bc03033e542 | [
"self.master_config = master_config\nself.data_dict = data_dict\nself.base_path = base_path\nself.logger = logger",
"visualizer = None\nif name is None:\n return visualizer\nlower_name = name.lower()\nif lower_name == 'DefaultKerasNetworkVisualizer'.lower():\n visualizer = DefaultKerasNetworkVisualizer(self... | <|body_start_0|>
self.master_config = master_config
self.data_dict = data_dict
self.base_path = base_path
self.logger = logger
<|end_body_0|>
<|body_start_1|>
visualizer = None
if name is None:
return visualizer
lower_name = name.lower()
if lo... | Factory for NetworkVisualizers. | NetworkVisualizerFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkVisualizerFactory:
"""Factory for NetworkVisualizers."""
def __init__(self, master_config, data_dict, base_path, logger=None):
"""Constructor. :param master_config: The master config for the experiment from which all other sub-configs can be obtained. :param data_dict: The dat... | stack_v2_sparse_classes_36k_train_019076 | 4,810 | no_license | [
{
"docstring": "Constructor. :param master_config: The master config for the experiment from which all other sub-configs can be obtained. :param data_dict: The data dictionary used in the evaluator. This is often needed by domains in order that the model is built with the correct dimensionality :param base_path... | 2 | stack_v2_sparse_classes_30k_train_002678 | Implement the Python class `NetworkVisualizerFactory` described below.
Class description:
Factory for NetworkVisualizers.
Method signatures and docstrings:
- def __init__(self, master_config, data_dict, base_path, logger=None): Constructor. :param master_config: The master config for the experiment from which all oth... | Implement the Python class `NetworkVisualizerFactory` described below.
Class description:
Factory for NetworkVisualizers.
Method signatures and docstrings:
- def __init__(self, master_config, data_dict, base_path, logger=None): Constructor. :param master_config: The master config for the experiment from which all oth... | 99c2f401d6c4b203ee439ed607985a918d0c3c7e | <|skeleton|>
class NetworkVisualizerFactory:
"""Factory for NetworkVisualizers."""
def __init__(self, master_config, data_dict, base_path, logger=None):
"""Constructor. :param master_config: The master config for the experiment from which all other sub-configs can be obtained. :param data_dict: The dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworkVisualizerFactory:
"""Factory for NetworkVisualizers."""
def __init__(self, master_config, data_dict, base_path, logger=None):
"""Constructor. :param master_config: The master config for the experiment from which all other sub-configs can be obtained. :param data_dict: The data dictionary ... | the_stack_v2_python_sparse | experimenthost/networkvisualization/network_visualizer_factory.py | Cognizant-CDB-AIA-BAI-AI-OI/LEAF-ENN-Training-V2 | train | 0 |
e690b6a5db5957d2d8ebf43f84e048fbe4ae9433 | [
"if 'QI' not in params:\n params['QI'] = 'IE'\nsuper().__init__(params)\nself.QI = self.get_Qdelta_implicit(self.coll, qd_type=self.params.QI)",
"L = self.level\nP = L.prob\nme = []\nfor m in range(1, self.coll.num_nodes + 1):\n me.append(P.dtype_u(P.init, val=0.0))\n for j in range(1, self.coll.num_node... | <|body_start_0|>
if 'QI' not in params:
params['QI'] = 'IE'
super().__init__(params)
self.QI = self.get_Qdelta_implicit(self.coll, qd_type=self.params.QI)
<|end_body_0|>
<|body_start_1|>
L = self.level
P = L.prob
me = []
for m in range(1, self.coll.nu... | Generic implicit sweeper, expecting lower triangular matrix type as input Attributes: QI: lower triangular matrix | generic_implicit | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class generic_implicit:
"""Generic implicit sweeper, expecting lower triangular matrix type as input Attributes: QI: lower triangular matrix"""
def __init__(self, params):
"""Initialization routine for the custom sweeper Args: params: parameters for the sweeper"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_019077 | 3,929 | permissive | [
{
"docstring": "Initialization routine for the custom sweeper Args: params: parameters for the sweeper",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Integrates the right-hand side Returns: list of dtype_u: containing the integral as values",
"name": "inte... | 4 | stack_v2_sparse_classes_30k_train_012987 | Implement the Python class `generic_implicit` described below.
Class description:
Generic implicit sweeper, expecting lower triangular matrix type as input Attributes: QI: lower triangular matrix
Method signatures and docstrings:
- def __init__(self, params): Initialization routine for the custom sweeper Args: params... | Implement the Python class `generic_implicit` described below.
Class description:
Generic implicit sweeper, expecting lower triangular matrix type as input Attributes: QI: lower triangular matrix
Method signatures and docstrings:
- def __init__(self, params): Initialization routine for the custom sweeper Args: params... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class generic_implicit:
"""Generic implicit sweeper, expecting lower triangular matrix type as input Attributes: QI: lower triangular matrix"""
def __init__(self, params):
"""Initialization routine for the custom sweeper Args: params: parameters for the sweeper"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class generic_implicit:
"""Generic implicit sweeper, expecting lower triangular matrix type as input Attributes: QI: lower triangular matrix"""
def __init__(self, params):
"""Initialization routine for the custom sweeper Args: params: parameters for the sweeper"""
if 'QI' not in params:
... | the_stack_v2_python_sparse | pySDC/implementations/sweeper_classes/generic_implicit.py | Parallel-in-Time/pySDC | train | 30 |
989875b13851df27bc8654709f1cf23c065a5cd3 | [
"print('before init')\nsuper().__init__()\nprint('before get')\nresnet = get_visn_arch(arch)(pretrained=pretrained)\nprint('after get')\nfor param in resnet.parameters():\n param.requires_grad = False\nresnet.fc = nn.Identity()\nself.backbone = resnet",
"x = self.backbone(img)\nx = x.detach()\nreturn x"
] | <|body_start_0|>
print('before init')
super().__init__()
print('before get')
resnet = get_visn_arch(arch)(pretrained=pretrained)
print('after get')
for param in resnet.parameters():
param.requires_grad = False
resnet.fc = nn.Identity()
self.bac... | VisnModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisnModel:
def __init__(self, arch='resnet50', pretrained=True):
""":param dim: dimension of the output :param arch: backbone architecture, :param pretrained: load feature with pre-trained vector :param finetuning: finetune the model"""
<|body_0|>
def forward(self, img):
... | stack_v2_sparse_classes_36k_train_019078 | 11,557 | permissive | [
{
"docstring": ":param dim: dimension of the output :param arch: backbone architecture, :param pretrained: load feature with pre-trained vector :param finetuning: finetune the model",
"name": "__init__",
"signature": "def __init__(self, arch='resnet50', pretrained=True)"
},
{
"docstring": ":para... | 2 | stack_v2_sparse_classes_30k_train_020566 | Implement the Python class `VisnModel` described below.
Class description:
Implement the VisnModel class.
Method signatures and docstrings:
- def __init__(self, arch='resnet50', pretrained=True): :param dim: dimension of the output :param arch: backbone architecture, :param pretrained: load feature with pre-trained v... | Implement the Python class `VisnModel` described below.
Class description:
Implement the VisnModel class.
Method signatures and docstrings:
- def __init__(self, arch='resnet50', pretrained=True): :param dim: dimension of the output :param arch: backbone architecture, :param pretrained: load feature with pre-trained v... | 51ac07d1de564c26fbf038b07031a55660bbcb27 | <|skeleton|>
class VisnModel:
def __init__(self, arch='resnet50', pretrained=True):
""":param dim: dimension of the output :param arch: backbone architecture, :param pretrained: load feature with pre-trained vector :param finetuning: finetune the model"""
<|body_0|>
def forward(self, img):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VisnModel:
def __init__(self, arch='resnet50', pretrained=True):
""":param dim: dimension of the output :param arch: backbone architecture, :param pretrained: load feature with pre-trained vector :param finetuning: finetune the model"""
print('before init')
super().__init__()
p... | the_stack_v2_python_sparse | retrieval_model/vokenization/tmp_extract_vision_keys.py | CJJ2923/Maria | train | 0 | |
129ca51a52d26887e85a1626eabee958aa38a6c5 | [
"x, y = (0, -1)\nn = len(array)\nfor i in range(n):\n for j in range(i, n):\n curr_sum = sum(array[i:j + 1])\n if curr_sum == 0 and j - i + 1 > y - x + 1:\n x, y = (i, j)\nreturn array[x:y + 1]",
"prev_sum = {0: -1}\nx, y = (0, -1)\ncurr = 0\nfor i, num in enumerate(array):\n curr +... | <|body_start_0|>
x, y = (0, -1)
n = len(array)
for i in range(n):
for j in range(i, n):
curr_sum = sum(array[i:j + 1])
if curr_sum == 0 and j - i + 1 > y - x + 1:
x, y = (i, j)
return array[x:y + 1]
<|end_body_0|>
<|body_st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find_largest_brute(self, array):
"""Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array)."""
<|body_0|>
def find_largest(self, array):
"""Algorithm based on hashing already calculated sum. Time ... | stack_v2_sparse_classes_36k_train_019079 | 2,509 | no_license | [
{
"docstring": "Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array).",
"name": "find_largest_brute",
"signature": "def find_largest_brute(self, array)"
},
{
"docstring": "Algorithm based on hashing already calculated sum. Time complexit... | 3 | stack_v2_sparse_classes_30k_train_004571 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_largest_brute(self, array): Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array).
- def find_largest(self, arr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_largest_brute(self, array): Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array).
- def find_largest(self, arr... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def find_largest_brute(self, array):
"""Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array)."""
<|body_0|>
def find_largest(self, array):
"""Algorithm based on hashing already calculated sum. Time ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def find_largest_brute(self, array):
"""Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array)."""
x, y = (0, -1)
n = len(array)
for i in range(n):
for j in range(i, n):
curr_sum = su... | the_stack_v2_python_sparse | Hashing/largest_zero_sum.py | vladn90/Algorithms | train | 0 | |
b7256234838ebc0ff2cb38d2452c03ad780a3213 | [
"account = Account.objects.create(firstname='Test', lastname='Test', email='test@email.com')\npost = Post.objects.create(title='Test Title', content='Test Content', account=account)\nPostImage.objects.create(post=post, image='tesimage.jpg')\nself.factory = RequestFactory()\nself.view = PostCommentView.as_view()\nse... | <|body_start_0|>
account = Account.objects.create(firstname='Test', lastname='Test', email='test@email.com')
post = Post.objects.create(title='Test Title', content='Test Content', account=account)
PostImage.objects.create(post=post, image='tesimage.jpg')
self.factory = RequestFactory()
... | Test class for the PostImageView. | PostImageView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostImageView:
"""Test class for the PostImageView."""
def setUp(self):
"""Set up variables for tests"""
<|body_0|>
def test_retrieve(self):
"""Test the retrieve fucntion in PostImageView"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
account =... | stack_v2_sparse_classes_36k_train_019080 | 15,306 | permissive | [
{
"docstring": "Set up variables for tests",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the retrieve fucntion in PostImageView",
"name": "test_retrieve",
"signature": "def test_retrieve(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018798 | Implement the Python class `PostImageView` described below.
Class description:
Test class for the PostImageView.
Method signatures and docstrings:
- def setUp(self): Set up variables for tests
- def test_retrieve(self): Test the retrieve fucntion in PostImageView | Implement the Python class `PostImageView` described below.
Class description:
Test class for the PostImageView.
Method signatures and docstrings:
- def setUp(self): Set up variables for tests
- def test_retrieve(self): Test the retrieve fucntion in PostImageView
<|skeleton|>
class PostImageView:
"""Test class f... | a364e9997c1c91b09f5db8a004deb4df305fa8cf | <|skeleton|>
class PostImageView:
"""Test class for the PostImageView."""
def setUp(self):
"""Set up variables for tests"""
<|body_0|>
def test_retrieve(self):
"""Test the retrieve fucntion in PostImageView"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostImageView:
"""Test class for the PostImageView."""
def setUp(self):
"""Set up variables for tests"""
account = Account.objects.create(firstname='Test', lastname='Test', email='test@email.com')
post = Post.objects.create(title='Test Title', content='Test Content', account=accou... | the_stack_v2_python_sparse | libStash/blogs/tests.py | Dev-Rem/libStash | train | 0 |
f1595690445b58d8c24c8c40dc353829e05c7775 | [
"res = set()\nif len(nums) < 4:\n return []\nnums.sort()\nfor i in range(len(nums) - 3):\n for j in range(i + 1, len(nums) - 2):\n l, r = (j + 1, len(nums) - 1)\n while l < r:\n s = nums[i] + nums[j] + nums[l] + nums[r]\n if s < target:\n l += 1\n ... | <|body_start_0|>
res = set()
if len(nums) < 4:
return []
nums.sort()
for i in range(len(nums) - 3):
for j in range(i + 1, len(nums) - 2):
l, r = (j + 1, len(nums) - 1)
while l < r:
s = nums[i] + nums[j] + nums[l]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)"""
<|body_0|>
def fourSum1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]] 方法二 O(n^3) 有点问题"""
... | stack_v2_sparse_classes_36k_train_019081 | 2,372 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]] 方法二 O(n^3) 有点问题",
"name": "fourSum1",
"si... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)
- def fourSum1(self, nums, target): :type nums: List[int] :type t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)
- def fourSum1(self, nums, target): :type nums: List[int] :type t... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)"""
<|body_0|>
def fourSum1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]] 方法二 O(n^3) 有点问题"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)"""
res = set()
if len(nums) < 4:
return []
nums.sort()
for i in range(len(nums) - 3):
for j in range(i + 1, len(nums) - ... | the_stack_v2_python_sparse | 算法/学习笔记/四数之和.py | RichieSong/algorithm | train | 0 | |
25ea46673f5cd6641610961618d119b9f708fb5a | [
"test_address = LabAddress(type='Primary', address=Address.objects.get(pk=1))\ntest_address.save()\nself.assertEqual(test_address.pk, 1)",
"test_address = LabAddress(type='Primary', address=Address.objects.get(pk=1))\ntest_address.save()\nself.assertEqual(test_address.pk, 1)\nself.assertEqual(test_address.__unico... | <|body_start_0|>
test_address = LabAddress(type='Primary', address=Address.objects.get(pk=1))
test_address.save()
self.assertEqual(test_address.pk, 1)
<|end_body_0|>
<|body_start_1|>
test_address = LabAddress(type='Primary', address=Address.objects.get(pk=1))
test_address.save()... | This class tests the views associated with models in the :mod:`communication` app. | CommunicationModelTests | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommunicationModelTests:
"""This class tests the views associated with models in the :mod:`communication` app."""
def test_create_new_lab_address(self):
"""This test creates a :class:`~communication.models.LabAddress` with the required information."""
<|body_0|>
def test... | stack_v2_sparse_classes_36k_train_019082 | 14,526 | permissive | [
{
"docstring": "This test creates a :class:`~communication.models.LabAddress` with the required information.",
"name": "test_create_new_lab_address",
"signature": "def test_create_new_lab_address(self)"
},
{
"docstring": "This tests the unicode representation of a :class:`~communication.models.L... | 5 | stack_v2_sparse_classes_30k_train_017701 | Implement the Python class `CommunicationModelTests` described below.
Class description:
This class tests the views associated with models in the :mod:`communication` app.
Method signatures and docstrings:
- def test_create_new_lab_address(self): This test creates a :class:`~communication.models.LabAddress` with the ... | Implement the Python class `CommunicationModelTests` described below.
Class description:
This class tests the views associated with models in the :mod:`communication` app.
Method signatures and docstrings:
- def test_create_new_lab_address(self): This test creates a :class:`~communication.models.LabAddress` with the ... | d6f6c9c068bbf668c253e5943d9514947023e66d | <|skeleton|>
class CommunicationModelTests:
"""This class tests the views associated with models in the :mod:`communication` app."""
def test_create_new_lab_address(self):
"""This test creates a :class:`~communication.models.LabAddress` with the required information."""
<|body_0|>
def test... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommunicationModelTests:
"""This class tests the views associated with models in the :mod:`communication` app."""
def test_create_new_lab_address(self):
"""This test creates a :class:`~communication.models.LabAddress` with the required information."""
test_address = LabAddress(type='Prima... | the_stack_v2_python_sparse | communication/tests.py | BridgesLab/Lab-Website | train | 0 |
2321e7cd83fc05286658ebd29423750790a68b21 | [
"self.tm = tm\nself.alpha = alpha\nself.lam = alpha * q / (1 - tm * q)",
"y = np.random.rand()\nif y >= self.alpha:\n return self.tm\nelse:\n return -math.log(y / self.alpha) / self.lam + self.tm"
] | <|body_start_0|>
self.tm = tm
self.alpha = alpha
self.lam = alpha * q / (1 - tm * q)
<|end_body_0|>
<|body_start_1|>
y = np.random.rand()
if y >= self.alpha:
return self.tm
else:
return -math.log(y / self.alpha) / self.lam + self.tm
<|end_body_1|>... | Generates random arrival times according to the M3 Model (Cowan, 1975). | M3Arrivals | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class M3Arrivals:
"""Generates random arrival times according to the M3 Model (Cowan, 1975)."""
def __init__(self, q, tm, alpha):
"""Inits object whose call method generates arrival times. Args: q (float): the (expected) flow rate q tm (float): the minimum possible time headway alpha (floa... | stack_v2_sparse_classes_36k_train_019083 | 42,486 | permissive | [
{
"docstring": "Inits object whose call method generates arrival times. Args: q (float): the (expected) flow rate q tm (float): the minimum possible time headway alpha (float): (1- alpha) is the probability having tm arrival time",
"name": "__init__",
"signature": "def __init__(self, q, tm, alpha)"
},... | 2 | null | Implement the Python class `M3Arrivals` described below.
Class description:
Generates random arrival times according to the M3 Model (Cowan, 1975).
Method signatures and docstrings:
- def __init__(self, q, tm, alpha): Inits object whose call method generates arrival times. Args: q (float): the (expected) flow rate q ... | Implement the Python class `M3Arrivals` described below.
Class description:
Generates random arrival times according to the M3 Model (Cowan, 1975).
Method signatures and docstrings:
- def __init__(self, q, tm, alpha): Inits object whose call method generates arrival times. Args: q (float): the (expected) flow rate q ... | 0aaf9674e987822ff2dc90c74613d5e68e8ef0ce | <|skeleton|>
class M3Arrivals:
"""Generates random arrival times according to the M3 Model (Cowan, 1975)."""
def __init__(self, q, tm, alpha):
"""Inits object whose call method generates arrival times. Args: q (float): the (expected) flow rate q tm (float): the minimum possible time headway alpha (floa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class M3Arrivals:
"""Generates random arrival times according to the M3 Model (Cowan, 1975)."""
def __init__(self, q, tm, alpha):
"""Inits object whose call method generates arrival times. Args: q (float): the (expected) flow rate q tm (float): the minimum possible time headway alpha (float): (1- alpha... | the_stack_v2_python_sparse | havsim/simulation/road_networks.py | seccode/havsim | train | 0 |
79189fe09c2dbee535542003eec6459614f3ba83 | [
"self.chars = re.findall('\\\\D', compressedString)[::-1]\nself.counts = re.findall('\\\\d+', compressedString)[::-1]\nself.count = 0\nself.char = ''",
"if not self.hasNext():\n return ' '\nif self.count:\n self.count -= 1\n return self.char\nself.count = int(self.counts.pop())\nself.char = self.chars.po... | <|body_start_0|>
self.chars = re.findall('\\D', compressedString)[::-1]
self.counts = re.findall('\\d+', compressedString)[::-1]
self.count = 0
self.char = ''
<|end_body_0|>
<|body_start_1|>
if not self.hasNext():
return ' '
if self.count:
self.co... | StringIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_36k_train_019084 | 1,348 | no_license | [
{
"docstring": ":type compressedString: str",
"name": "__init__",
"signature": "def __init__(self, compressedString)"
},
{
"docstring": ":rtype: str",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasN... | 3 | null | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool
<|skeleton|>
class StringIterator:
... | 11c8fc663888b48b5417256aab1bf872190267ba | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
self.chars = re.findall('\\D', compressedString)[::-1]
self.counts = re.findall('\\d+', compressedString)[::-1]
self.count = 0
self.char = ''
def next(self):
""":rtype: ... | the_stack_v2_python_sparse | Design Compressed String Iterator.py | lfdyf20/Leetcode | train | 1 | |
4511b9f574582a9614dd738414109b8f0154d6e8 | [
"request = pecan.request\ncontext = request.environ['context']\ntransfer_accepts = self.central_api.get_zone_transfer_accept(context, transfer_accept_id)\nLOG.info('Retrieved %(transfer_accepts)s', {'transfer_accepts': transfer_accepts})\nreturn DesignateAdapter.render('API_v2', transfer_accepts, request=request)",... | <|body_start_0|>
request = pecan.request
context = request.environ['context']
transfer_accepts = self.central_api.get_zone_transfer_accept(context, transfer_accept_id)
LOG.info('Retrieved %(transfer_accepts)s', {'transfer_accepts': transfer_accepts})
return DesignateAdapter.rende... | TransferAcceptsController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransferAcceptsController:
def get_one(self, transfer_accept_id):
"""Get transfer_accepts"""
<|body_0|>
def get_all(self, **params):
"""List ZoneTransferAccepts"""
<|body_1|>
def post_all(self):
"""Create ZoneTransferAccept"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_019085 | 3,661 | permissive | [
{
"docstring": "Get transfer_accepts",
"name": "get_one",
"signature": "def get_one(self, transfer_accept_id)"
},
{
"docstring": "List ZoneTransferAccepts",
"name": "get_all",
"signature": "def get_all(self, **params)"
},
{
"docstring": "Create ZoneTransferAccept",
"name": "p... | 3 | stack_v2_sparse_classes_30k_train_016592 | Implement the Python class `TransferAcceptsController` described below.
Class description:
Implement the TransferAcceptsController class.
Method signatures and docstrings:
- def get_one(self, transfer_accept_id): Get transfer_accepts
- def get_all(self, **params): List ZoneTransferAccepts
- def post_all(self): Create... | Implement the Python class `TransferAcceptsController` described below.
Class description:
Implement the TransferAcceptsController class.
Method signatures and docstrings:
- def get_one(self, transfer_accept_id): Get transfer_accepts
- def get_all(self, **params): List ZoneTransferAccepts
- def post_all(self): Create... | 360433b38b449d1c53ab1357fdb0c4608c09efa5 | <|skeleton|>
class TransferAcceptsController:
def get_one(self, transfer_accept_id):
"""Get transfer_accepts"""
<|body_0|>
def get_all(self, **params):
"""List ZoneTransferAccepts"""
<|body_1|>
def post_all(self):
"""Create ZoneTransferAccept"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransferAcceptsController:
def get_one(self, transfer_accept_id):
"""Get transfer_accepts"""
request = pecan.request
context = request.environ['context']
transfer_accepts = self.central_api.get_zone_transfer_accept(context, transfer_accept_id)
LOG.info('Retrieved %(tran... | the_stack_v2_python_sparse | designate/api/v2/controllers/zones/tasks/transfer_accepts.py | openstack/designate | train | 156 | |
079cfa111750e7132792b64391803fe4c2751039 | [
"self.seconds = seconds\nself.on_earth = self.on_planet_gen(1.0)\nself.on_mercury = self.on_planet_gen(0.2408467)\nself.on_venus = self.on_planet_gen(0.61519726)\nself.on_mars = self.on_planet_gen(1.8808158)\nself.on_jupiter = self.on_planet_gen(11.862615)\nself.on_saturn = self.on_planet_gen(29.447498)\nself.on_ur... | <|body_start_0|>
self.seconds = seconds
self.on_earth = self.on_planet_gen(1.0)
self.on_mercury = self.on_planet_gen(0.2408467)
self.on_venus = self.on_planet_gen(0.61519726)
self.on_mars = self.on_planet_gen(1.8808158)
self.on_jupiter = self.on_planet_gen(11.862615)
... | Calculates age on various planets | SpaceAge | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceAge:
"""Calculates age on various planets"""
def __init__(self, seconds):
"""Stores age builds functions"""
<|body_0|>
def on_planet_gen(self, ratio_to_earth):
"""Returns a function that converts seconds into planet years"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_019086 | 1,052 | no_license | [
{
"docstring": "Stores age builds functions",
"name": "__init__",
"signature": "def __init__(self, seconds)"
},
{
"docstring": "Returns a function that converts seconds into planet years",
"name": "on_planet_gen",
"signature": "def on_planet_gen(self, ratio_to_earth)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011254 | Implement the Python class `SpaceAge` described below.
Class description:
Calculates age on various planets
Method signatures and docstrings:
- def __init__(self, seconds): Stores age builds functions
- def on_planet_gen(self, ratio_to_earth): Returns a function that converts seconds into planet years | Implement the Python class `SpaceAge` described below.
Class description:
Calculates age on various planets
Method signatures and docstrings:
- def __init__(self, seconds): Stores age builds functions
- def on_planet_gen(self, ratio_to_earth): Returns a function that converts seconds into planet years
<|skeleton|>
c... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class SpaceAge:
"""Calculates age on various planets"""
def __init__(self, seconds):
"""Stores age builds functions"""
<|body_0|>
def on_planet_gen(self, ratio_to_earth):
"""Returns a function that converts seconds into planet years"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpaceAge:
"""Calculates age on various planets"""
def __init__(self, seconds):
"""Stores age builds functions"""
self.seconds = seconds
self.on_earth = self.on_planet_gen(1.0)
self.on_mercury = self.on_planet_gen(0.2408467)
self.on_venus = self.on_planet_gen(0.6151... | the_stack_v2_python_sparse | _algorithms_challenges/exercism/exercism-python-master/space-age/space_age.py | syurskyi/Algorithms_and_Data_Structure | train | 4 |
ed3c19e8a0e20d19710c4849df0b73d38bef42cf | [
"units = Unit.objects.all()\nserializer = UnitSerializer(units, many=True)\nreturn Response(serializer.data)",
"serializer = UnitSerializer(request.data)\nserializer.save()\nreturn Response(serializer.data)"
] | <|body_start_0|>
units = Unit.objects.all()
serializer = UnitSerializer(units, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = UnitSerializer(request.data)
serializer.save()
return Response(serializer.data)
<|end_body_1|>
| View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. | ListUnits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListUnits:
"""View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view."""
def get(self, request):
"""Return a list of all units."""
<|body_0|>
def post(self, request):
"""Creates a new complex."""
... | stack_v2_sparse_classes_36k_train_019087 | 9,992 | no_license | [
{
"docstring": "Return a list of all units.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Creates a new complex.",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001401 | Implement the Python class `ListUnits` described below.
Class description:
View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view.
Method signatures and docstrings:
- def get(self, request): Return a list of all units.
- def post(self, request): Creates ... | Implement the Python class `ListUnits` described below.
Class description:
View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view.
Method signatures and docstrings:
- def get(self, request): Return a list of all units.
- def post(self, request): Creates ... | f887d41800541e058b2d350ded6f02759d174815 | <|skeleton|>
class ListUnits:
"""View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view."""
def get(self, request):
"""Return a list of all units."""
<|body_0|>
def post(self, request):
"""Creates a new complex."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListUnits:
"""View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view."""
def get(self, request):
"""Return a list of all units."""
units = Unit.objects.all()
serializer = UnitSerializer(units, many=True)
retur... | the_stack_v2_python_sparse | api/govrent/views.py | kamal94/hacka22019 | train | 0 |
c177afd68af0b6515e467dfb6237cb661086ae25 | [
"self.matrix = matrix8x8\nself.index = 0\nself.row = 0\nself.iterations = 0",
"self.index = 0\nself.row = 0\nself.iterations = 0\nself.matrix.set_brightness(BRIGHTNESS)",
"time.sleep(UPDATE_RATE_SECONDS)\nself.matrix.clear()\nself.index += 1\nif self.index >= len(PRIMES):\n self.index = 0\n self.row = 0\n... | <|body_start_0|>
self.matrix = matrix8x8
self.index = 0
self.row = 0
self.iterations = 0
<|end_body_0|>
<|body_start_1|>
self.index = 0
self.row = 0
self.iterations = 0
self.matrix.set_brightness(BRIGHTNESS)
<|end_body_1|>
<|body_start_2|>
time.s... | Prime numbers less than 256 display on an 8x8 matrix | Led8x8Prime | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Led8x8Prime:
"""Prime numbers less than 256 display on an 8x8 matrix"""
def __init__(self, matrix8x8):
"""create the prime object"""
<|body_0|>
def reset(self):
"""initialize and start the prime number display"""
<|body_1|>
def display(self):
... | stack_v2_sparse_classes_36k_train_019088 | 1,786 | permissive | [
{
"docstring": "create the prime object",
"name": "__init__",
"signature": "def __init__(self, matrix8x8)"
},
{
"docstring": "initialize and start the prime number display",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "display primes up to the max for 8 bits... | 3 | stack_v2_sparse_classes_30k_train_005383 | Implement the Python class `Led8x8Prime` described below.
Class description:
Prime numbers less than 256 display on an 8x8 matrix
Method signatures and docstrings:
- def __init__(self, matrix8x8): create the prime object
- def reset(self): initialize and start the prime number display
- def display(self): display pri... | Implement the Python class `Led8x8Prime` described below.
Class description:
Prime numbers less than 256 display on an 8x8 matrix
Method signatures and docstrings:
- def __init__(self, matrix8x8): create the prime object
- def reset(self): initialize and start the prime number display
- def display(self): display pri... | 6937b4f64a1a2526bc9888c119371d72bacbdfaa | <|skeleton|>
class Led8x8Prime:
"""Prime numbers less than 256 display on an 8x8 matrix"""
def __init__(self, matrix8x8):
"""create the prime object"""
<|body_0|>
def reset(self):
"""initialize and start the prime number display"""
<|body_1|>
def display(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Led8x8Prime:
"""Prime numbers less than 256 display on an 8x8 matrix"""
def __init__(self, matrix8x8):
"""create the prime object"""
self.matrix = matrix8x8
self.index = 0
self.row = 0
self.iterations = 0
def reset(self):
"""initialize and start the pr... | the_stack_v2_python_sparse | led8x8prime.py | parttimehacker/diyclock | train | 0 |
894426cfade8094ea3e9dad27e8780ad9481c24f | [
"if properties is None:\n properties = []\nif product_id:\n domain = ['&', ('type', '=', bomType)]\n if not product_tmpl_id:\n product_tmpl_id = self.pool['product.product'].browse(cr, uid, product_id, context=context).product_tmpl_id.id\n domain = domain + ['|', ('product_id', '=', product_id), ... | <|body_start_0|>
if properties is None:
properties = []
if product_id:
domain = ['&', ('type', '=', bomType)]
if not product_tmpl_id:
product_tmpl_id = self.pool['product.product'].browse(cr, uid, product_id, context=context).product_tmpl_id.id
... | plm_relation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class plm_relation:
def _bom_find(self, cr, uid, product_tmpl_id=None, product_id=None, properties=None, bomType='normal', context=None):
"""Finds BoM for particular product and product uom. @param product_tmpl_id: Selected product. @param product_uom: Unit of measure of a product. @param prop... | stack_v2_sparse_classes_36k_train_019089 | 12,135 | no_license | [
{
"docstring": "Finds BoM for particular product and product uom. @param product_tmpl_id: Selected product. @param product_uom: Unit of measure of a product. @param properties: List of related properties. @return: False or BoM id.",
"name": "_bom_find",
"signature": "def _bom_find(self, cr, uid, product... | 2 | null | Implement the Python class `plm_relation` described below.
Class description:
Implement the plm_relation class.
Method signatures and docstrings:
- def _bom_find(self, cr, uid, product_tmpl_id=None, product_id=None, properties=None, bomType='normal', context=None): Finds BoM for particular product and product uom. @p... | Implement the Python class `plm_relation` described below.
Class description:
Implement the plm_relation class.
Method signatures and docstrings:
- def _bom_find(self, cr, uid, product_tmpl_id=None, product_id=None, properties=None, bomType='normal', context=None): Finds BoM for particular product and product uom. @p... | 5a4fd72991c846d5cb7c5082f6bdfef5b2bca572 | <|skeleton|>
class plm_relation:
def _bom_find(self, cr, uid, product_tmpl_id=None, product_id=None, properties=None, bomType='normal', context=None):
"""Finds BoM for particular product and product uom. @param product_tmpl_id: Selected product. @param product_uom: Unit of measure of a product. @param prop... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class plm_relation:
def _bom_find(self, cr, uid, product_tmpl_id=None, product_id=None, properties=None, bomType='normal', context=None):
"""Finds BoM for particular product and product uom. @param product_tmpl_id: Selected product. @param product_uom: Unit of measure of a product. @param properties: List o... | the_stack_v2_python_sparse | yuancloud/plugin/plm/install/plm_extend_entities.py | cash2one/yuancloud | train | 0 | |
d0c5990f14d4a41aa7029c4c8ce0dd99c2e11def | [
"self.multiple_a = multiple_a or 3\nself.multiple_b = multiple_b or 5\nself.multiple_c = multiple_c or None\nself.sum = 0",
"for number in range(1, n):\n if not self.multiple_c:\n if number % self.multiple_a == 0 or number % self.multiple_b == 0:\n self.sum += number\n elif number % self.m... | <|body_start_0|>
self.multiple_a = multiple_a or 3
self.multiple_b = multiple_b or 5
self.multiple_c = multiple_c or None
self.sum = 0
<|end_body_0|>
<|body_start_1|>
for number in range(1, n):
if not self.multiple_c:
if number % self.multiple_a == 0 ... | SumOfMultiples | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SumOfMultiples:
def __init__(self, multiple_a=None, multiple_b=None, multiple_c=None):
"""Takes up to 3 multiples. If first two are not given, they are set as 3 and 5 respectively."""
<|body_0|>
def to(self, n):
"""Takes integer to find sum of multiples up to. Return... | stack_v2_sparse_classes_36k_train_019090 | 745 | no_license | [
{
"docstring": "Takes up to 3 multiples. If first two are not given, they are set as 3 and 5 respectively.",
"name": "__init__",
"signature": "def __init__(self, multiple_a=None, multiple_b=None, multiple_c=None)"
},
{
"docstring": "Takes integer to find sum of multiples up to. Returns sum.",
... | 2 | stack_v2_sparse_classes_30k_train_014770 | Implement the Python class `SumOfMultiples` described below.
Class description:
Implement the SumOfMultiples class.
Method signatures and docstrings:
- def __init__(self, multiple_a=None, multiple_b=None, multiple_c=None): Takes up to 3 multiples. If first two are not given, they are set as 3 and 5 respectively.
- de... | Implement the Python class `SumOfMultiples` described below.
Class description:
Implement the SumOfMultiples class.
Method signatures and docstrings:
- def __init__(self, multiple_a=None, multiple_b=None, multiple_c=None): Takes up to 3 multiples. If first two are not given, they are set as 3 and 5 respectively.
- de... | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | <|skeleton|>
class SumOfMultiples:
def __init__(self, multiple_a=None, multiple_b=None, multiple_c=None):
"""Takes up to 3 multiples. If first two are not given, they are set as 3 and 5 respectively."""
<|body_0|>
def to(self, n):
"""Takes integer to find sum of multiples up to. Return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SumOfMultiples:
def __init__(self, multiple_a=None, multiple_b=None, multiple_c=None):
"""Takes up to 3 multiples. If first two are not given, they are set as 3 and 5 respectively."""
self.multiple_a = multiple_a or 3
self.multiple_b = multiple_b or 5
self.multiple_c = multiple... | the_stack_v2_python_sparse | all_data/exercism_data/python/sum-of-multiples/0e57c01cf56e4d36a5b3ad9942721308.py | itsolutionscorp/AutoStyle-Clustering | train | 4 | |
82662211c6a35edc85fbd4c5cb5e1b9f699d9bff | [
"account = BaseAccount.get(accountId)\nif account:\n return self.make_response({'message': None, 'account': account.to_json(is_admin=True)})\nelse:\n return self.make_response({'message': 'Unable to find account', 'account': None}, HTTP.NOT_FOUND)",
"self.reqparse.add_argument('accountName', type=str, requi... | <|body_start_0|>
account = BaseAccount.get(accountId)
if account:
return self.make_response({'message': None, 'account': account.to_json(is_admin=True)})
else:
return self.make_response({'message': 'Unable to find account', 'account': None}, HTTP.NOT_FOUND)
<|end_body_0|>... | AccountDetail | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountDetail:
def get(self, accountId):
"""Fetch a single account"""
<|body_0|>
def put(self, accountId):
"""Update an account"""
<|body_1|>
def delete(self, accountId):
"""Delete an account"""
<|body_2|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_019091 | 9,518 | permissive | [
{
"docstring": "Fetch a single account",
"name": "get",
"signature": "def get(self, accountId)"
},
{
"docstring": "Update an account",
"name": "put",
"signature": "def put(self, accountId)"
},
{
"docstring": "Delete an account",
"name": "delete",
"signature": "def delete(... | 3 | stack_v2_sparse_classes_30k_train_015288 | Implement the Python class `AccountDetail` described below.
Class description:
Implement the AccountDetail class.
Method signatures and docstrings:
- def get(self, accountId): Fetch a single account
- def put(self, accountId): Update an account
- def delete(self, accountId): Delete an account | Implement the Python class `AccountDetail` described below.
Class description:
Implement the AccountDetail class.
Method signatures and docstrings:
- def get(self, accountId): Fetch a single account
- def put(self, accountId): Update an account
- def delete(self, accountId): Delete an account
<|skeleton|>
class Acco... | 29a26c705381fdba3538b4efedb25b9e09b387ed | <|skeleton|>
class AccountDetail:
def get(self, accountId):
"""Fetch a single account"""
<|body_0|>
def put(self, accountId):
"""Update an account"""
<|body_1|>
def delete(self, accountId):
"""Delete an account"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountDetail:
def get(self, accountId):
"""Fetch a single account"""
account = BaseAccount.get(accountId)
if account:
return self.make_response({'message': None, 'account': account.to_json(is_admin=True)})
else:
return self.make_response({'message': 'Un... | the_stack_v2_python_sparse | backend/cloud_inquisitor/plugins/views/accounts.py | RiotGames/cloud-inquisitor | train | 468 | |
2d1f1f1067da6e69c84ea8f6a9c9fb338d2247d9 | [
"self.setup = setup\nself.merge_fields = merge_fields\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nsetup = idfy_rest_client.models.setup.Setup.from_dictionary(dictionary.get('setup')) if dictionary.get('setup') else None\nmerge_fields = dictionary.get('mergeField... | <|body_start_0|>
self.setup = setup
self.merge_fields = merge_fields
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
setup = idfy_rest_client.models.setup.Setup.from_dictionary(dictionary.get('setu... | Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own notifications texts (See the root object -> Notification), you can create you... | Notifications | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Notifications:
"""Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own notifications texts (See the root objec... | stack_v2_sparse_classes_36k_train_019092 | 2,680 | permissive | [
{
"docstring": "Constructor for the Notifications class",
"name": "__init__",
"signature": "def __init__(self, setup=None, merge_fields=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representati... | 2 | stack_v2_sparse_classes_30k_train_011752 | Implement the Python class `Notifications` described below.
Class description:
Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own ... | Implement the Python class `Notifications` described below.
Class description:
Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own ... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Notifications:
"""Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own notifications texts (See the root objec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Notifications:
"""Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own notifications texts (See the root object -> Notif... | the_stack_v2_python_sparse | idfy_rest_client/models/notifications.py | dealflowteam/Idfy | train | 0 |
a8b13280dfcd80ebba43870b71cb0017f9ccb8e0 | [
"super(ConfigDriveDirectoryTest, cls).setUpClass()\ncls.metadata = {'meta_key_1': 'meta_value_1', 'meta_key_2': 'meta_value_2'}\ncls.file_contents = 'This is a config drive test file.'\nfiles = [{'path': '/test.txt', 'contents': base64.b64encode(cls.file_contents)}]\ncls.key = cls.keypairs_client.create_keypair(ran... | <|body_start_0|>
super(ConfigDriveDirectoryTest, cls).setUpClass()
cls.metadata = {'meta_key_1': 'meta_value_1', 'meta_key_2': 'meta_value_2'}
cls.file_contents = 'This is a config drive test file.'
files = [{'path': '/test.txt', 'contents': base64.b64encode(cls.file_contents)}]
... | ConfigDriveDirectoryTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigDriveDirectoryTest:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing The following data is generated during this set up: - A name value that is a random name starting with the word 'server' - A dictionary of metadata with the values: {'user_key... | stack_v2_sparse_classes_36k_train_019093 | 7,401 | permissive | [
{
"docstring": "Perform actions that setup the necessary resources for testing The following data is generated during this set up: - A name value that is a random name starting with the word 'server' - A dictionary of metadata with the values: {'user_key1': 'value1', 'user_key2': 'value2'} - If default file inj... | 4 | null | Implement the Python class `ConfigDriveDirectoryTest` described below.
Class description:
Implement the ConfigDriveDirectoryTest class.
Method signatures and docstrings:
- def setUpClass(cls): Perform actions that setup the necessary resources for testing The following data is generated during this set up: - A name v... | Implement the Python class `ConfigDriveDirectoryTest` described below.
Class description:
Implement the ConfigDriveDirectoryTest class.
Method signatures and docstrings:
- def setUpClass(cls): Perform actions that setup the necessary resources for testing The following data is generated during this set up: - A name v... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class ConfigDriveDirectoryTest:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing The following data is generated during this set up: - A name value that is a random name starting with the word 'server' - A dictionary of metadata with the values: {'user_key... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigDriveDirectoryTest:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing The following data is generated during this set up: - A name value that is a random name starting with the word 'server' - A dictionary of metadata with the values: {'user_key1': 'value1', ... | the_stack_v2_python_sparse | cloudroast/compute/api/config_drive/test_config_drive_directory_structure.py | RULCSoft/cloudroast | train | 1 | |
7bfd44bc05b51108cde061f51cad1d54b77b4239 | [
"self.ps = PastaSauce()\nself.desired_capabilities['name'] = self.id()\nif not LOCAL_RUN:\n self.admin = Admin(use_env_vars=True, pasta_user=self.ps, capabilities=self.desired_capabilities)\n self.content = ContentQA(existing_driver=self.admin.driver, use_env_vars=True, pasta_user=self.ps, capabilities=self.d... | <|body_start_0|>
self.ps = PastaSauce()
self.desired_capabilities['name'] = self.id()
if not LOCAL_RUN:
self.admin = Admin(use_env_vars=True, pasta_user=self.ps, capabilities=self.desired_capabilities)
self.content = ContentQA(existing_driver=self.admin.driver, use_env_va... | TestManageEcosystems | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestManageEcosystems:
def setUp(self):
"""Pretest settings."""
<|body_0|>
def tearDown(self):
"""Test destructor."""
<|body_1|>
def test_content_tag_search_admin(self):
"""Go to https://tutor-qa.openstax.org/ Login to admin account Open the drop ... | stack_v2_sparse_classes_36k_train_019094 | 4,735 | no_license | [
{
"docstring": "Pretest settings.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test destructor.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "Go to https://tutor-qa.openstax.org/ Login to admin account Open the drop down menu b... | 3 | stack_v2_sparse_classes_30k_train_004510 | Implement the Python class `TestManageEcosystems` described below.
Class description:
Implement the TestManageEcosystems class.
Method signatures and docstrings:
- def setUp(self): Pretest settings.
- def tearDown(self): Test destructor.
- def test_content_tag_search_admin(self): Go to https://tutor-qa.openstax.org/ ... | Implement the Python class `TestManageEcosystems` described below.
Class description:
Implement the TestManageEcosystems class.
Method signatures and docstrings:
- def setUp(self): Pretest settings.
- def tearDown(self): Test destructor.
- def test_content_tag_search_admin(self): Go to https://tutor-qa.openstax.org/ ... | 39751799858ac30df90760b8bb753d338e8edc46 | <|skeleton|>
class TestManageEcosystems:
def setUp(self):
"""Pretest settings."""
<|body_0|>
def tearDown(self):
"""Test destructor."""
<|body_1|>
def test_content_tag_search_admin(self):
"""Go to https://tutor-qa.openstax.org/ Login to admin account Open the drop ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestManageEcosystems:
def setUp(self):
"""Pretest settings."""
self.ps = PastaSauce()
self.desired_capabilities['name'] = self.id()
if not LOCAL_RUN:
self.admin = Admin(use_env_vars=True, pasta_user=self.ps, capabilities=self.desired_capabilities)
self.c... | the_stack_v2_python_sparse | tutor/TestRewrite/Admin/Content/test_content_tag_search_admin.py | openstax/test-automation | train | 4 | |
6b76e47b78c64b0eb94afcd92c3b963b97e223d9 | [
"nums.sort()\nself.k = k\nself.kth_largest_nums = nums[max(-k, -len(nums)):]\nheapify(self.kth_largest_nums)",
"if len(self.kth_largest_nums) < self.k:\n heappush(self.kth_largest_nums, val)\nelif val > self.kth_largest_nums[0]:\n heappush(self.kth_largest_nums, val)\n heappop(self.kth_largest_nums)\nret... | <|body_start_0|>
nums.sort()
self.k = k
self.kth_largest_nums = nums[max(-k, -len(nums)):]
heapify(self.kth_largest_nums)
<|end_body_0|>
<|body_start_1|>
if len(self.kth_largest_nums) < self.k:
heappush(self.kth_largest_nums, val)
elif val > self.kth_largest_... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
self.k = k
self.kth_largest_nu... | stack_v2_sparse_classes_36k_train_019095 | 932 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008296 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 9d394cd2862703cfb7a7b505b35deda7450a692e | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
nums.sort()
self.k = k
self.kth_largest_nums = nums[max(-k, -len(nums)):]
heapify(self.kth_largest_nums)
def add(self, val):
""":type val: int :rtype: int"""
if len(se... | the_stack_v2_python_sparse | 703.数据流中的第-k-大元素.py | Ezi4Zy/leetcode | train | 0 | |
7568bc426bc141d2d8e6b3f8af86511e1602712e | [
"total = 0\nprime = {2, 3, 5, 7, 11, 13, 17, 19}\nfor i in range(L, R + 1):\n sumi = 0\n while i != 0:\n if i & 1 == 1:\n sumi += 1\n i = i >> 1\n if sumi in prime:\n total += 1\nreturn total",
"dic = {}\nfor i in range(len(S)):\n if S[i] in dic:\n dic[S[i]][1] =... | <|body_start_0|>
total = 0
prime = {2, 3, 5, 7, 11, 13, 17, 19}
for i in range(L, R + 1):
sumi = 0
while i != 0:
if i & 1 == 1:
sumi += 1
i = i >> 1
if sumi in prime:
total += 1
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimeSetBits(self, L, R):
""":type L: int :type R: int :rtype: int"""
<|body_0|>
def partitionLabels(self, S):
""":type S: str :rtype: List[int]"""
<|body_1|>
def orderOfLargestPlusSign(self, N, mines):
""":type N: int :type mi... | stack_v2_sparse_classes_36k_train_019096 | 2,461 | no_license | [
{
"docstring": ":type L: int :type R: int :rtype: int",
"name": "countPrimeSetBits",
"signature": "def countPrimeSetBits(self, L, R)"
},
{
"docstring": ":type S: str :rtype: List[int]",
"name": "partitionLabels",
"signature": "def partitionLabels(self, S)"
},
{
"docstring": ":typ... | 3 | stack_v2_sparse_classes_30k_train_002832 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int
- def partitionLabels(self, S): :type S: str :rtype: List[int]
- def orderOfLargestPlusSign(self, N, mine... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int
- def partitionLabels(self, S): :type S: str :rtype: List[int]
- def orderOfLargestPlusSign(self, N, mine... | 8790abadd5289024794cd95529187c96111c2bd6 | <|skeleton|>
class Solution:
def countPrimeSetBits(self, L, R):
""":type L: int :type R: int :rtype: int"""
<|body_0|>
def partitionLabels(self, S):
""":type S: str :rtype: List[int]"""
<|body_1|>
def orderOfLargestPlusSign(self, N, mines):
""":type N: int :type mi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimeSetBits(self, L, R):
""":type L: int :type R: int :rtype: int"""
total = 0
prime = {2, 3, 5, 7, 11, 13, 17, 19}
for i in range(L, R + 1):
sumi = 0
while i != 0:
if i & 1 == 1:
sumi += 1
... | the_stack_v2_python_sparse | contests/contest67.py | minging234/LeetCode_ming | train | 0 | |
ca3b9831c3756ecfbbe3bc4a133b3204d4377c7d | [
"self._num_threads = num_threads\nself._count = 0\nself._cond = threading.Condition()",
"with self._cond:\n self._count += 1\n self._cond.notifyAll()\n while self._count < self._num_threads:\n self._cond.wait()"
] | <|body_start_0|>
self._num_threads = num_threads
self._count = 0
self._cond = threading.Condition()
<|end_body_0|>
<|body_start_1|>
with self._cond:
self._count += 1
self._cond.notifyAll()
while self._count < self._num_threads:
self._c... | Defines a simple barrier class to synchronize on a particular event. | Barrier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Barrier:
"""Defines a simple barrier class to synchronize on a particular event."""
def __init__(self, num_threads):
"""Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier"""
<|body_0|>
def wait(self):
"""Waits on the barri... | stack_v2_sparse_classes_36k_train_019097 | 3,873 | permissive | [
{
"docstring": "Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier",
"name": "__init__",
"signature": "def __init__(self, num_threads)"
},
{
"docstring": "Waits on the barrier until all threads have called this method.",
"name": "wait",
"signature... | 2 | null | Implement the Python class `Barrier` described below.
Class description:
Defines a simple barrier class to synchronize on a particular event.
Method signatures and docstrings:
- def __init__(self, num_threads): Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier
- def wait(self... | Implement the Python class `Barrier` described below.
Class description:
Defines a simple barrier class to synchronize on a particular event.
Method signatures and docstrings:
- def __init__(self, num_threads): Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier
- def wait(self... | 97c50eaa62c039d8f4b9efa3e80c4d80e6f40c4c | <|skeleton|>
class Barrier:
"""Defines a simple barrier class to synchronize on a particular event."""
def __init__(self, num_threads):
"""Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier"""
<|body_0|>
def wait(self):
"""Waits on the barri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Barrier:
"""Defines a simple barrier class to synchronize on a particular event."""
def __init__(self, num_threads):
"""Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier"""
self._num_threads = num_threads
self._count = 0
self._cond... | the_stack_v2_python_sparse | acme/utils/counting_test.py | RaoulDrake/acme | train | 0 |
dc0fe727283fd639cdf2132d9f18a4230a4f7707 | [
"wide_ftrs_sp_idx = tf.cast(wide_ftrs_sp_idx, dtype=tf.float32)\nif wide_ftrs_sp_val is None:\n wide_ftrs_sp_val = tf.ones(tf.shape(wide_ftrs_sp_idx), dtype=tf.float32)\nself._num_wide_sp = num_wide_sp\nself._padding_idx = padding_idx\nwith tf.variable_scope('wide', reuse=tf.AUTO_REUSE):\n self.ftrs_weight = ... | <|body_start_0|>
wide_ftrs_sp_idx = tf.cast(wide_ftrs_sp_idx, dtype=tf.float32)
if wide_ftrs_sp_val is None:
wide_ftrs_sp_val = tf.ones(tf.shape(wide_ftrs_sp_idx), dtype=tf.float32)
self._num_wide_sp = num_wide_sp
self._padding_idx = padding_idx
with tf.variable_scope... | Embedding model that performs embedding lookup and summation on sparse features | SparseEmbModel | [
"BSD-2-Clause",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseEmbModel:
"""Embedding model that performs embedding lookup and summation on sparse features"""
def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padding_idx: int=0, initializer=tf.contrib.layers.xavier_initializer()):... | stack_v2_sparse_classes_36k_train_019098 | 5,383 | permissive | [
{
"docstring": "Computes a embedding given wide feature indices and values If wide_ftrs_sp_val is specified, users should keep consistency between wide_ftrs_sp_idx and wide_ftrs_sp_val -- the value of wide_ftrs_sp_idx[i] should be wide_ftrs_sp_val[i]. CAVEAT: it is required that padding value = 0 for wide_ftrs_... | 2 | stack_v2_sparse_classes_30k_train_011807 | Implement the Python class `SparseEmbModel` described below.
Class description:
Embedding model that performs embedding lookup and summation on sparse features
Method signatures and docstrings:
- def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padd... | Implement the Python class `SparseEmbModel` described below.
Class description:
Embedding model that performs embedding lookup and summation on sparse features
Method signatures and docstrings:
- def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padd... | 38e7b74879debd8ae5f2685367c81cc3a8aa003b | <|skeleton|>
class SparseEmbModel:
"""Embedding model that performs embedding lookup and summation on sparse features"""
def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padding_idx: int=0, initializer=tf.contrib.layers.xavier_initializer()):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseEmbModel:
"""Embedding model that performs embedding lookup and summation on sparse features"""
def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padding_idx: int=0, initializer=tf.contrib.layers.xavier_initializer()):
"""C... | the_stack_v2_python_sparse | src/detext/model/sp_emb_model.py | naimmalek/detext | train | 1 |
f0b8145f2a2b37538ad9cf83f8ae97f99cfc452d | [
"if entity_embedding is not None and relation_embedding is not None:\n config['dim'] = entity_embedding.shape[1]\n config['e_num'] = entity_embedding.shape[0]\n config['r_num'] = relation_embedding.shape[0]\nsuper().__init__(config, device)\nself.e_embedding = nn.Embedding(self.e_num, self.dim)\nself.r_emb... | <|body_start_0|>
if entity_embedding is not None and relation_embedding is not None:
config['dim'] = entity_embedding.shape[1]
config['e_num'] = entity_embedding.shape[0]
config['r_num'] = relation_embedding.shape[0]
super().__init__(config, device)
self.e_emb... | TransE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransE:
def __init__(self, config, device, entity_embedding=None, relation_embedding=None):
"""Initialize model and assign parameters in parent class based on the chosen configurations. Use pre-trained embeddings if provided. :param config: a dictionary that defines the model attributes ... | stack_v2_sparse_classes_36k_train_019099 | 3,883 | no_license | [
{
"docstring": "Initialize model and assign parameters in parent class based on the chosen configurations. Use pre-trained embeddings if provided. :param config: a dictionary that defines the model attributes :param device: the torch device on which the model is executed :param entity_embedding: an optional pre... | 3 | stack_v2_sparse_classes_30k_train_013363 | Implement the Python class `TransE` described below.
Class description:
Implement the TransE class.
Method signatures and docstrings:
- def __init__(self, config, device, entity_embedding=None, relation_embedding=None): Initialize model and assign parameters in parent class based on the chosen configurations. Use pre... | Implement the Python class `TransE` described below.
Class description:
Implement the TransE class.
Method signatures and docstrings:
- def __init__(self, config, device, entity_embedding=None, relation_embedding=None): Initialize model and assign parameters in parent class based on the chosen configurations. Use pre... | f8d43e8bfa6131ed6926fce516df6bec699450af | <|skeleton|>
class TransE:
def __init__(self, config, device, entity_embedding=None, relation_embedding=None):
"""Initialize model and assign parameters in parent class based on the chosen configurations. Use pre-trained embeddings if provided. :param config: a dictionary that defines the model attributes ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransE:
def __init__(self, config, device, entity_embedding=None, relation_embedding=None):
"""Initialize model and assign parameters in parent class based on the chosen configurations. Use pre-trained embeddings if provided. :param config: a dictionary that defines the model attributes :param device:... | the_stack_v2_python_sparse | src/kg_embedding/transE.py | jusch25/mt_kg-fusion | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.