blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
94be4c4b15b517eb227443a215fd19711760b58f | [
"self.firebaseCOM = FirebasePlantCom(piID='123')\nself.imgUpdatePiIDPath = self.firebaseCOM.piPath + '/imgUpdate'\nself.imgPiIDPath = self.firebaseCOM.piPath + '/Image'\nmy_stream = self.firebaseCOM.db.child(self.imgUpdatePiIDPath).stream(self.stream_img_handler)",
"data = self.firebaseCOM.db.child(self.imgPiIDPa... | <|body_start_0|>
self.firebaseCOM = FirebasePlantCom(piID='123')
self.imgUpdatePiIDPath = self.firebaseCOM.piPath + '/imgUpdate'
self.imgPiIDPath = self.firebaseCOM.piPath + '/Image'
my_stream = self.firebaseCOM.db.child(self.imgUpdatePiIDPath).stream(self.stream_img_handler)
<|end_body_... | MainRun | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainRun:
def __init__(self):
"""init."""
<|body_0|>
def stream_img_handler(self, message):
"""monitors the imgs that gets taken and activates a function when there is a change"""
<|body_1|>
def main(self):
"""starting point of the code"""
... | stack_v2_sparse_classes_75kplus_train_073100 | 2,599 | no_license | [
{
"docstring": "init.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "monitors the imgs that gets taken and activates a function when there is a change",
"name": "stream_img_handler",
"signature": "def stream_img_handler(self, message)"
},
{
"docstring"... | 3 | null | Implement the Python class `MainRun` described below.
Class description:
Implement the MainRun class.
Method signatures and docstrings:
- def __init__(self): init.
- def stream_img_handler(self, message): monitors the imgs that gets taken and activates a function when there is a change
- def main(self): starting poin... | Implement the Python class `MainRun` described below.
Class description:
Implement the MainRun class.
Method signatures and docstrings:
- def __init__(self): init.
- def stream_img_handler(self, message): monitors the imgs that gets taken and activates a function when there is a change
- def main(self): starting poin... | 58c0cf3aae48d99b50aed1efeee59ebd1f7e1a4d | <|skeleton|>
class MainRun:
def __init__(self):
"""init."""
<|body_0|>
def stream_img_handler(self, message):
"""monitors the imgs that gets taken and activates a function when there is a change"""
<|body_1|>
def main(self):
"""starting point of the code"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MainRun:
def __init__(self):
"""init."""
self.firebaseCOM = FirebasePlantCom(piID='123')
self.imgUpdatePiIDPath = self.firebaseCOM.piPath + '/imgUpdate'
self.imgPiIDPath = self.firebaseCOM.piPath + '/Image'
my_stream = self.firebaseCOM.db.child(self.imgUpdatePiIDPath).s... | the_stack_v2_python_sparse | main.py | adaamm/PotPy | train | 1 | |
3f33287eecefe78325409a694de6fc6fd0d505a0 | [
"if self.request.version == 'v6':\n return self.list_v6(request, name)\nelif self.request.version == 'v7':\n return self.list_v6(request, name)\nelse:\n raise Http404",
"recipe_type_revs = RecipeTypeRevision.objects.get_revisions(name=name)\npage = self.paginate_queryset(recipe_type_revs)\nserializer = s... | <|body_start_0|>
if self.request.version == 'v6':
return self.list_v6(request, name)
elif self.request.version == 'v7':
return self.list_v6(request, name)
else:
raise Http404
<|end_body_0|>
<|body_start_1|>
recipe_type_revs = RecipeTypeRevision.object... | This view is the endpoint for retrieving the list of all recipe types | RecipeTypeRevisionsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipeTypeRevisionsView:
"""This view is the endpoint for retrieving the list of all recipe types"""
def list(self, request, name):
"""Retrieves the list of all recipe type revisions and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framewor... | stack_v2_sparse_classes_75kplus_train_073101 | 29,952 | permissive | [
{
"docstring": "Retrieves the list of all recipe type revisions and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :param name: The name of the recipe type :type name: string :rtype: :class:`rest_framework.response.Response` :returns: the HTTP... | 2 | stack_v2_sparse_classes_30k_train_031270 | Implement the Python class `RecipeTypeRevisionsView` described below.
Class description:
This view is the endpoint for retrieving the list of all recipe types
Method signatures and docstrings:
- def list(self, request, name): Retrieves the list of all recipe type revisions and returns it in JSON form :param request: ... | Implement the Python class `RecipeTypeRevisionsView` described below.
Class description:
This view is the endpoint for retrieving the list of all recipe types
Method signatures and docstrings:
- def list(self, request, name): Retrieves the list of all recipe type revisions and returns it in JSON form :param request: ... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class RecipeTypeRevisionsView:
"""This view is the endpoint for retrieving the list of all recipe types"""
def list(self, request, name):
"""Retrieves the list of all recipe type revisions and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framewor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecipeTypeRevisionsView:
"""This view is the endpoint for retrieving the list of all recipe types"""
def list(self, request, name):
"""Retrieves the list of all recipe type revisions and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Req... | the_stack_v2_python_sparse | scale/recipe/views.py | kfconsultant/scale | train | 0 |
ac805d02c6376b67f36fb45c03319c709f5cd7da | [
"self._train_op = optimizer.minimize(loss)\nself._loss = loss\nself._predictions = predictions\nself._ds_train = ds_train\nself._ds_validation = ds_validation\nself._stop_patience = stop_patience\nself._evaluation = evaluation\nself._validation_losses = []\nself._model_inputs = inputs\nself._model_labels = labels\n... | <|body_start_0|>
self._train_op = optimizer.minimize(loss)
self._loss = loss
self._predictions = predictions
self._ds_train = ds_train
self._ds_validation = ds_validation
self._stop_patience = stop_patience
self._evaluation = evaluation
self._validation_lo... | Trainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels):
"""Initialize the trainer Args: loss an operation that computes the loss predictions an operation that computes the predictions for the current optimizer optimiz... | stack_v2_sparse_classes_75kplus_train_073102 | 6,508 | permissive | [
{
"docstring": "Initialize the trainer Args: loss an operation that computes the loss predictions an operation that computes the predictions for the current optimizer optimizer to use ds_train instance of Dataset that holds the training data ds_validation instance of Dataset that holds the validation data stop_... | 5 | stack_v2_sparse_classes_30k_train_015448 | Implement the Python class `Trainer` described below.
Class description:
Implement the Trainer class.
Method signatures and docstrings:
- def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels): Initialize the trainer Args: loss an operation that computes t... | Implement the Python class `Trainer` described below.
Class description:
Implement the Trainer class.
Method signatures and docstrings:
- def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels): Initialize the trainer Args: loss an operation that computes t... | e66ca5b33645641426edac4da5aed0cb205a5aeb | <|skeleton|>
class Trainer:
def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels):
"""Initialize the trainer Args: loss an operation that computes the loss predictions an operation that computes the predictions for the current optimizer optimiz... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trainer:
def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels):
"""Initialize the trainer Args: loss an operation that computes the loss predictions an operation that computes the predictions for the current optimizer optimizer to use ds_t... | the_stack_v2_python_sparse | train/trainer.py | snowskysun/Classification-of-solar-cell-defects | train | 0 | |
e616810b04cb4ad7032222d0c7ca68e924b193fe | [
"super(NNBlock, self).__init__()\nself.n_layers = len(arch) - 1\nself.activation = activation\nself.device = 'cuda' if torch.cuda.is_available() else 'cpu'\nfor i in range(self.n_layers):\n self.add_module('Linear_{}'.format(i), torch.nn.Linear(arch[i], arch[i + 1]).to(self.device))",
"for i in range(self.n_la... | <|body_start_0|>
super(NNBlock, self).__init__()
self.n_layers = len(arch) - 1
self.activation = activation
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
for i in range(self.n_layers):
self.add_module('Linear_{}'.format(i), torch.nn.Linear(arch[i], arch... | NNBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NNBlock:
def __init__(self, arch, activation=torch.nn.ReLU()):
""":param arch: architecture of the nn_block :param activation: activation function"""
<|body_0|>
def forward(self, x):
""":param x: input of nn :return: output of nn"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_073103 | 10,752 | permissive | [
{
"docstring": ":param arch: architecture of the nn_block :param activation: activation function",
"name": "__init__",
"signature": "def __init__(self, arch, activation=torch.nn.ReLU())"
},
{
"docstring": ":param x: input of nn :return: output of nn",
"name": "forward",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_041049 | Implement the Python class `NNBlock` described below.
Class description:
Implement the NNBlock class.
Method signatures and docstrings:
- def __init__(self, arch, activation=torch.nn.ReLU()): :param arch: architecture of the nn_block :param activation: activation function
- def forward(self, x): :param x: input of nn... | Implement the Python class `NNBlock` described below.
Class description:
Implement the NNBlock class.
Method signatures and docstrings:
- def __init__(self, arch, activation=torch.nn.ReLU()): :param arch: architecture of the nn_block :param activation: activation function
- def forward(self, x): :param x: input of nn... | cf536bb0d245982b72e4416ea329419e59baf1c9 | <|skeleton|>
class NNBlock:
def __init__(self, arch, activation=torch.nn.ReLU()):
""":param arch: architecture of the nn_block :param activation: activation function"""
<|body_0|>
def forward(self, x):
""":param x: input of nn :return: output of nn"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NNBlock:
def __init__(self, arch, activation=torch.nn.ReLU()):
""":param arch: architecture of the nn_block :param activation: activation function"""
super(NNBlock, self).__init__()
self.n_layers = len(arch) - 1
self.activation = activation
self.device = 'cuda' if torch... | the_stack_v2_python_sparse | multiscale_HiTS-master/src/ResNet.py | msaad1311/PDEs-using-NN | train | 0 | |
d592c134d1f42716119ababe80909bd8d0ec0044 | [
"self._entity_ids = entity_ids\nself._attr_name = name\nself._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_ids}\nself._attr_unique_id = unique_id\nself._attr_event_types = []",
"@callback\ndef async_state_changed_listener(event: EventType[EventStateChangedData]) -> None:\n \"\"\"Handle child updates.\... | <|body_start_0|>
self._entity_ids = entity_ids
self._attr_name = name
self._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_ids}
self._attr_unique_id = unique_id
self._attr_event_types = []
<|end_body_0|>
<|body_start_1|>
@callback
def async_state_changed_l... | Representation of an event group. | EventGroup | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventGroup:
"""Representation of an event group."""
def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None:
"""Initialize an event group."""
<|body_0|>
async def async_added_to_hass(self) -> None:
"""Register callbacks."""
<|b... | stack_v2_sparse_classes_75kplus_train_073104 | 5,729 | permissive | [
{
"docstring": "Initialize an event group.",
"name": "__init__",
"signature": "def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None"
},
{
"docstring": "Register callbacks.",
"name": "async_added_to_hass",
"signature": "async def async_added_to_hass(self) ->... | 3 | stack_v2_sparse_classes_30k_train_017556 | Implement the Python class `EventGroup` described below.
Class description:
Representation of an event group.
Method signatures and docstrings:
- def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: Initialize an event group.
- async def async_added_to_hass(self) -> None: Register call... | Implement the Python class `EventGroup` described below.
Class description:
Representation of an event group.
Method signatures and docstrings:
- def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: Initialize an event group.
- async def async_added_to_hass(self) -> None: Register call... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EventGroup:
"""Representation of an event group."""
def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None:
"""Initialize an event group."""
<|body_0|>
async def async_added_to_hass(self) -> None:
"""Register callbacks."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventGroup:
"""Representation of an event group."""
def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None:
"""Initialize an event group."""
self._entity_ids = entity_ids
self._attr_name = name
self._attr_extra_state_attributes = {ATTR_ENTITY_I... | the_stack_v2_python_sparse | homeassistant/components/group/event.py | home-assistant/core | train | 35,501 |
c3f831e21b3afc2ba0364626e10f86eb08ea51ba | [
"super(TFC_RNN, self).__init__()\nself.skip_connection = skip_connection\nself.tfc = TFC(in_channels, num_layers_tfc, gr, kt, kf, activation)\nself.bn = nn.BatchNorm2d(gr)\nhidden_units_rnn = max(f // bn_factor_rnn, min_bn_units_rnn)\nself.rnn = nn.GRU(f, hidden_units_rnn, num_layers_rnn, bias=bias_rnn, batch_first... | <|body_start_0|>
super(TFC_RNN, self).__init__()
self.skip_connection = skip_connection
self.tfc = TFC(in_channels, num_layers_tfc, gr, kt, kf, activation)
self.bn = nn.BatchNorm2d(gr)
hidden_units_rnn = max(f // bn_factor_rnn, min_bn_units_rnn)
self.rnn = nn.GRU(f, hidde... | [B, in_channels, T, F] => [B, gr, T, F] | TFC_RNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFC_RNN:
"""[B, in_channels, T, F] => [B, gr, T, F]"""
def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, bias_tdf=True, skip_connection=True, activation=nn.ReLU):
"""... | stack_v2_sparse_classes_75kplus_train_073105 | 6,895 | permissive | [
{
"docstring": "in_channels: number of input channels num_layers_tfc: number of densely connected conv layers gr: growth rate kt: kernel size of the temporal axis. kf: kernel size of the freq. axis f: num of frequency bins bn_factor_rnn: bottleneck factor of rnn num_layers_rnn: number of layers of rnn bidirecti... | 2 | stack_v2_sparse_classes_30k_train_011108 | Implement the Python class `TFC_RNN` described below.
Class description:
[B, in_channels, T, F] => [B, gr, T, F]
Method signatures and docstrings:
- def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, b... | Implement the Python class `TFC_RNN` described below.
Class description:
[B, in_channels, T, F] => [B, gr, T, F]
Method signatures and docstrings:
- def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, b... | 366b92b601f324a5937fb902d3cd123a0980c9b8 | <|skeleton|>
class TFC_RNN:
"""[B, in_channels, T, F] => [B, gr, T, F]"""
def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, bias_tdf=True, skip_connection=True, activation=nn.ReLU):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TFC_RNN:
"""[B, in_channels, T, F] => [B, gr, T, F]"""
def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, bias_tdf=True, skip_connection=True, activation=nn.ReLU):
"""in_channels: ... | the_stack_v2_python_sparse | src/lasaft/source_separation/sub_modules/building_blocks.py | loretoparisi/Conditioned-Source-Separation-LaSAFT | train | 3 |
d625925ab1be35baf10415a37328551780a7aa86 | [
"users = User.objects.all()\nserializer = self.serializer_class(users, many=True, context={'request': request})\nreturn Response(serializer.data)",
"serializer = self.serializer_class(data=request.data, many=False, context={'request': request})\nif serializer.is_valid():\n with transaction.atomic():\n s... | <|body_start_0|>
users = User.objects.all()
serializer = self.serializer_class(users, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = self.serializer_class(data=request.data, many=False, context={'request': request})... | UserList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserList:
def get(self, request, format=None):
"""Lista de todos los usuarios"""
<|body_0|>
def post(self, request, format=None):
"""Creacion de un usuario"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
users = User.objects.all()
serializer... | stack_v2_sparse_classes_75kplus_train_073106 | 3,982 | no_license | [
{
"docstring": "Lista de todos los usuarios",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Creacion de un usuario",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038986 | Implement the Python class `UserList` described below.
Class description:
Implement the UserList class.
Method signatures and docstrings:
- def get(self, request, format=None): Lista de todos los usuarios
- def post(self, request, format=None): Creacion de un usuario | Implement the Python class `UserList` described below.
Class description:
Implement the UserList class.
Method signatures and docstrings:
- def get(self, request, format=None): Lista de todos los usuarios
- def post(self, request, format=None): Creacion de un usuario
<|skeleton|>
class UserList:
def get(self, r... | f87ad9cfb331562c381087da54c0e1da906d45ac | <|skeleton|>
class UserList:
def get(self, request, format=None):
"""Lista de todos los usuarios"""
<|body_0|>
def post(self, request, format=None):
"""Creacion de un usuario"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserList:
def get(self, request, format=None):
"""Lista de todos los usuarios"""
users = User.objects.all()
serializer = self.serializer_class(users, many=True, context={'request': request})
return Response(serializer.data)
def post(self, request, format=None):
"""... | the_stack_v2_python_sparse | Users/views.py | C-Mierez/GrAPI | train | 1 | |
505d7d98024e8535c1a3fc317a627ac63030a22b | [
"self._url = url\nself._api_key = api_key\nif not url:\n raise ValueError('Urlscan URL must be set')\nif not api_key:\n raise ValueError('Urlscan API key must be set')",
"resp = requests.get(self._url, headers={'API-key': self._api_key})\nresp.raise_for_status()\nparsed = pydantic.parse_raw_as(UrlscanRespon... | <|body_start_0|>
self._url = url
self._api_key = api_key
if not url:
raise ValueError('Urlscan URL must be set')
if not api_key:
raise ValueError('Urlscan API key must be set')
<|end_body_0|>
<|body_start_1|>
resp = requests.get(self._url, headers={'API-k... | Urlscan.io client | UrlscanClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UrlscanClient:
"""Urlscan.io client"""
def __init__(self, url: str, api_key: str):
"""Initializer. :param url: Urlscan URL :param api_key: Urlscan api key"""
<|body_0|>
def query(self) -> Iterator[str]:
"""Process the feed URL and return any indicators. :return: ... | stack_v2_sparse_classes_75kplus_train_073107 | 1,180 | permissive | [
{
"docstring": "Initializer. :param url: Urlscan URL :param api_key: Urlscan api key",
"name": "__init__",
"signature": "def __init__(self, url: str, api_key: str)"
},
{
"docstring": "Process the feed URL and return any indicators. :return: Feed results.",
"name": "query",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_022613 | Implement the Python class `UrlscanClient` described below.
Class description:
Urlscan.io client
Method signatures and docstrings:
- def __init__(self, url: str, api_key: str): Initializer. :param url: Urlscan URL :param api_key: Urlscan api key
- def query(self) -> Iterator[str]: Process the feed URL and return any ... | Implement the Python class `UrlscanClient` described below.
Class description:
Urlscan.io client
Method signatures and docstrings:
- def __init__(self, url: str, api_key: str): Initializer. :param url: Urlscan URL :param api_key: Urlscan api key
- def query(self) -> Iterator[str]: Process the feed URL and return any ... | d00a0243946ded25b5d06bdefd9b40015dea9b80 | <|skeleton|>
class UrlscanClient:
"""Urlscan.io client"""
def __init__(self, url: str, api_key: str):
"""Initializer. :param url: Urlscan URL :param api_key: Urlscan api key"""
<|body_0|>
def query(self) -> Iterator[str]:
"""Process the feed URL and return any indicators. :return: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UrlscanClient:
"""Urlscan.io client"""
def __init__(self, url: str, api_key: str):
"""Initializer. :param url: Urlscan URL :param api_key: Urlscan api key"""
self._url = url
self._api_key = api_key
if not url:
raise ValueError('Urlscan URL must be set')
... | the_stack_v2_python_sparse | external-import/urlscan/src/urlscan/client.py | OpenCTI-Platform/connectors | train | 254 |
00799fd28ae907d6e261e9b3809e94ccb5ffd88d | [
"super(DDQN, self).__init__()\nself.conv1 = nn.Conv2d(in_channels=num_frames, out_channels=16, kernel_size=8, stride=4)\nself.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=4, stride=2)\nself.fc = nn.Linear(in_features=32 * 9 * 9, out_features=256)\nself.output = nn.Linear(in_features=256, out_featu... | <|body_start_0|>
super(DDQN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=num_frames, out_channels=16, kernel_size=8, stride=4)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=4, stride=2)
self.fc = nn.Linear(in_features=32 * 9 * 9, out_features=256)
se... | DQN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DQN:
def __init__(self, num_frames, num_actions):
"""Initialize neural net. Args: num_frames: number of frames in the stack, equivalant to number of channels num_actions: number of actions for agent, number of ouput neurons"""
<|body_0|>
def forward(self, t):
"""Forw... | stack_v2_sparse_classes_75kplus_train_073108 | 3,262 | permissive | [
{
"docstring": "Initialize neural net. Args: num_frames: number of frames in the stack, equivalant to number of channels num_actions: number of actions for agent, number of ouput neurons",
"name": "__init__",
"signature": "def __init__(self, num_frames, num_actions)"
},
{
"docstring": "Forward p... | 2 | null | Implement the Python class `DQN` described below.
Class description:
Implement the DQN class.
Method signatures and docstrings:
- def __init__(self, num_frames, num_actions): Initialize neural net. Args: num_frames: number of frames in the stack, equivalant to number of channels num_actions: number of actions for age... | Implement the Python class `DQN` described below.
Class description:
Implement the DQN class.
Method signatures and docstrings:
- def __init__(self, num_frames, num_actions): Initialize neural net. Args: num_frames: number of frames in the stack, equivalant to number of channels num_actions: number of actions for age... | 8961235561f7d289bcd479807243fd5be3dae6e5 | <|skeleton|>
class DQN:
def __init__(self, num_frames, num_actions):
"""Initialize neural net. Args: num_frames: number of frames in the stack, equivalant to number of channels num_actions: number of actions for agent, number of ouput neurons"""
<|body_0|>
def forward(self, t):
"""Forw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DQN:
def __init__(self, num_frames, num_actions):
"""Initialize neural net. Args: num_frames: number of frames in the stack, equivalant to number of channels num_actions: number of actions for agent, number of ouput neurons"""
super(DDQN, self).__init__()
self.conv1 = nn.Conv2d(in_chan... | the_stack_v2_python_sparse | src/atari-breakout/ddqn.py | davidmkwon/rl | train | 0 | |
5e9809d1bb25870b5ceb87f6e946ee0685ee3177 | [
"self.validate_parameters(country_code=country_code)\n_query_builder = Configuration.get_base_uri()\n_query_builder += '/information/geodata/countries/{countryCode}/subdivisions'\n_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'countryCode': country_code})\n_query_parameters = {'lan... | <|body_start_0|>
self.validate_parameters(country_code=country_code)
_query_builder = Configuration.get_base_uri()
_query_builder += '/information/geodata/countries/{countryCode}/subdivisions'
_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'countryCode': ... | A Controller to access Endpoints in the idfy_rest_client API. | GeoDataController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoDataController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def list_country_subdivisions(self, country_code, lang=None):
"""Does a GET request to /information/geodata/countries/{countryCode}/subdivisions. Retrieves a list over top level administrative subd... | stack_v2_sparse_classes_75kplus_train_073109 | 6,016 | permissive | [
{
"docstring": "Does a GET request to /information/geodata/countries/{countryCode}/subdivisions. Retrieves a list over top level administrative subdivisions for a country with name and ISO 3166-2 region code Args: country_code (string): ISO 3166-1 country code to look up lang (string, optional): Language for re... | 3 | stack_v2_sparse_classes_30k_train_046135 | Implement the Python class `GeoDataController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def list_country_subdivisions(self, country_code, lang=None): Does a GET request to /information/geodata/countries/{countryCode}/subdivis... | Implement the Python class `GeoDataController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def list_country_subdivisions(self, country_code, lang=None): Does a GET request to /information/geodata/countries/{countryCode}/subdivis... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class GeoDataController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def list_country_subdivisions(self, country_code, lang=None):
"""Does a GET request to /information/geodata/countries/{countryCode}/subdivisions. Retrieves a list over top level administrative subd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeoDataController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def list_country_subdivisions(self, country_code, lang=None):
"""Does a GET request to /information/geodata/countries/{countryCode}/subdivisions. Retrieves a list over top level administrative subdivisions for ... | the_stack_v2_python_sparse | idfy_rest_client/controllers/geo_data_controller.py | dealflowteam/Idfy | train | 0 |
c97fdb45784e33af0557f4c96f8d3d0c53fdfcad | [
"trace_id = None\nspan_id = None\ntrace_options = None\nfor key in carrier:\n key = key.lower()\n if key == _TRACE_ID_KEY:\n trace_id = carrier[key]\n if key == _SPAN_ID_KEY:\n span_id = carrier[key]\n if key == _TRACE_OPTIONS_KEY:\n trace_options = bool(carrier[key])\nif trace_opti... | <|body_start_0|>
trace_id = None
span_id = None
trace_options = None
for key in carrier:
key = key.lower()
if key == _TRACE_ID_KEY:
trace_id = carrier[key]
if key == _SPAN_ID_KEY:
span_id = carrier[key]
if ke... | This class provides the basic utilities for extracting the trace information from a carrier which is a dict to form a SpanContext. And generating a dict using the provided SpanContext. | TextFormatPropagator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextFormatPropagator:
"""This class provides the basic utilities for extracting the trace information from a carrier which is a dict to form a SpanContext. And generating a dict using the provided SpanContext."""
def from_carrier(self, carrier):
"""Generate a SpanContext object using... | stack_v2_sparse_classes_75kplus_train_073110 | 3,089 | permissive | [
{
"docstring": "Generate a SpanContext object using the information in the carrier. :type carrier: dict :param carrier: The carrier which has the trace_id, span_id, options information for creating a SpanContext. :rtype: :class:`~opencensus.trace.span_context.SpanContext` :returns: SpanContext generated from th... | 2 | stack_v2_sparse_classes_30k_train_045603 | Implement the Python class `TextFormatPropagator` described below.
Class description:
This class provides the basic utilities for extracting the trace information from a carrier which is a dict to form a SpanContext. And generating a dict using the provided SpanContext.
Method signatures and docstrings:
- def from_ca... | Implement the Python class `TextFormatPropagator` described below.
Class description:
This class provides the basic utilities for extracting the trace information from a carrier which is a dict to form a SpanContext. And generating a dict using the provided SpanContext.
Method signatures and docstrings:
- def from_ca... | 3a2d8dfe1db4e0129dc691c35901a0d12127afc1 | <|skeleton|>
class TextFormatPropagator:
"""This class provides the basic utilities for extracting the trace information from a carrier which is a dict to form a SpanContext. And generating a dict using the provided SpanContext."""
def from_carrier(self, carrier):
"""Generate a SpanContext object using... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextFormatPropagator:
"""This class provides the basic utilities for extracting the trace information from a carrier which is a dict to form a SpanContext. And generating a dict using the provided SpanContext."""
def from_carrier(self, carrier):
"""Generate a SpanContext object using the informat... | the_stack_v2_python_sparse | opencensus/trace/propagation/text_format.py | census-instrumentation/opencensus-python | train | 701 |
ce738c7acfdd4870df0065cf8a2285f1647c4696 | [
"super().__init__()\nself.client = None\nself.sub_client = None\nself.subscription_ids = None\nself._connected = False\nself._debug = kwargs.get('debug', False)\nself.az_cloud_config = AzureCloudConfig(cloud=kwargs.get('cloud'))",
"auth_methods = kwargs.get('auth_methods')\nauth_methods = auth_methods or self.az_... | <|body_start_0|>
super().__init__()
self.client = None
self.sub_client = None
self.subscription_ids = None
self._connected = False
self._debug = kwargs.get('debug', False)
self.az_cloud_config = AzureCloudConfig(cloud=kwargs.get('cloud'))
<|end_body_0|>
<|body_st... | Driver to connect and query from Azure Resource Graph. | ResourceGraphDriver | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"EPL-1.0",
"GPL-1.0-or-later",
"LGPL-2.1-only",
"MPL-2.0",
"Python-2.0",
"PSF-2.0",
"LicenseRef-scancode-python-cwi",
"GPL-2.0-or-later",
"LGPL-2.1-or-later... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceGraphDriver:
"""Driver to connect and query from Azure Resource Graph."""
def __init__(self, **kwargs):
"""Instantiate Azure Resource Graph Driver."""
<|body_0|>
def connect(self, connection_str: str=None, **kwargs):
"""Connect to Azure Resource Graph via... | stack_v2_sparse_classes_75kplus_train_073111 | 6,202 | permissive | [
{
"docstring": "Instantiate Azure Resource Graph Driver.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Connect to Azure Resource Graph via Azure SDK. Parameters ---------- connection_str : Optional[str], optional Not used. Other Parameters ---------------- ... | 4 | stack_v2_sparse_classes_30k_train_014972 | Implement the Python class `ResourceGraphDriver` described below.
Class description:
Driver to connect and query from Azure Resource Graph.
Method signatures and docstrings:
- def __init__(self, **kwargs): Instantiate Azure Resource Graph Driver.
- def connect(self, connection_str: str=None, **kwargs): Connect to Azu... | Implement the Python class `ResourceGraphDriver` described below.
Class description:
Driver to connect and query from Azure Resource Graph.
Method signatures and docstrings:
- def __init__(self, **kwargs): Instantiate Azure Resource Graph Driver.
- def connect(self, connection_str: str=None, **kwargs): Connect to Azu... | 55c6c1aebb8505a220046705b7c74194f83d62f3 | <|skeleton|>
class ResourceGraphDriver:
"""Driver to connect and query from Azure Resource Graph."""
def __init__(self, **kwargs):
"""Instantiate Azure Resource Graph Driver."""
<|body_0|>
def connect(self, connection_str: str=None, **kwargs):
"""Connect to Azure Resource Graph via... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceGraphDriver:
"""Driver to connect and query from Azure Resource Graph."""
def __init__(self, **kwargs):
"""Instantiate Azure Resource Graph Driver."""
super().__init__()
self.client = None
self.sub_client = None
self.subscription_ids = None
self._co... | the_stack_v2_python_sparse | msticpy/data/drivers/resource_graph_driver.py | rhaug77/msticpy | train | 0 |
5884d76564373e8c592cb06889b9bc8ecce3cccf | [
"helpline = data.get('helpline')\nusername = data.get('username')\nfirst_name = data.get('first_name')\nlast_name = data.get('last_name')\npassword = data.get('password')\nphone_no = data.get('phone_no')\nemail = data.get('email')\ngcm_canonical_id = data.get('gcm_canonical_id')\nhelper = Helper(gcm_canonical_id=gc... | <|body_start_0|>
helpline = data.get('helpline')
username = data.get('username')
first_name = data.get('first_name')
last_name = data.get('last_name')
password = data.get('password')
phone_no = data.get('phone_no')
email = data.get('email')
gcm_canonical_i... | Register call used to handle incoming call requests | RegisterHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterHelper:
"""Register call used to handle incoming call requests"""
def register_call(self, data):
"""Register call handler"""
<|body_0|>
def post(self, request):
"""Post request handler"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
help... | stack_v2_sparse_classes_75kplus_train_073112 | 2,859 | no_license | [
{
"docstring": "Register call handler",
"name": "register_call",
"signature": "def register_call(self, data)"
},
{
"docstring": "Post request handler",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051451 | Implement the Python class `RegisterHelper` described below.
Class description:
Register call used to handle incoming call requests
Method signatures and docstrings:
- def register_call(self, data): Register call handler
- def post(self, request): Post request handler | Implement the Python class `RegisterHelper` described below.
Class description:
Register call used to handle incoming call requests
Method signatures and docstrings:
- def register_call(self, data): Register call handler
- def post(self, request): Post request handler
<|skeleton|>
class RegisterHelper:
"""Regist... | 910ed40940d79f454a02b8553bb2ef76b99c1eaa | <|skeleton|>
class RegisterHelper:
"""Register call used to handle incoming call requests"""
def register_call(self, data):
"""Register call handler"""
<|body_0|>
def post(self, request):
"""Post request handler"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegisterHelper:
"""Register call used to handle incoming call requests"""
def register_call(self, data):
"""Register call handler"""
helpline = data.get('helpline')
username = data.get('username')
first_name = data.get('first_name')
last_name = data.get('last_name'... | the_stack_v2_python_sparse | register_helper/views.py | raj231992/helpline | train | 0 |
cb27955e64a906337ee83c5139735c5833ef1e76 | [
"self.in_nodes = inputNodes\nself.hide_nodes = hiddenNodes\nself.out_nodes = outputNodes\nself.l_rate = learningRate\nself.weight_in_hide = numpy.random.normal(0.0, pow(self.hide_nodes, -0.5), (self.hide_nodes, self.in_nodes))\nself.weight_hide_out = numpy.random.normal(0.0, pow(self.out_nodes, -0.5), (self.out_nod... | <|body_start_0|>
self.in_nodes = inputNodes
self.hide_nodes = hiddenNodes
self.out_nodes = outputNodes
self.l_rate = learningRate
self.weight_in_hide = numpy.random.normal(0.0, pow(self.hide_nodes, -0.5), (self.hide_nodes, self.in_nodes))
self.weight_hide_out = numpy.rand... | neuralNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class neuralNetwork:
def __init__(self, inputNodes, hiddenNodes, outputNodes, learningRate):
"""初始化网络参数, 共三层网络"""
<|body_0|>
def train(self, inputs_list, targets_list):
"""训练数据集"""
<|body_1|>
def test(self, inputs_lists):
"""测试"""
<|body_2|>
<... | stack_v2_sparse_classes_75kplus_train_073113 | 4,505 | no_license | [
{
"docstring": "初始化网络参数, 共三层网络",
"name": "__init__",
"signature": "def __init__(self, inputNodes, hiddenNodes, outputNodes, learningRate)"
},
{
"docstring": "训练数据集",
"name": "train",
"signature": "def train(self, inputs_list, targets_list)"
},
{
"docstring": "测试",
"name": "te... | 3 | stack_v2_sparse_classes_30k_train_050939 | Implement the Python class `neuralNetwork` described below.
Class description:
Implement the neuralNetwork class.
Method signatures and docstrings:
- def __init__(self, inputNodes, hiddenNodes, outputNodes, learningRate): 初始化网络参数, 共三层网络
- def train(self, inputs_list, targets_list): 训练数据集
- def test(self, inputs_lists... | Implement the Python class `neuralNetwork` described below.
Class description:
Implement the neuralNetwork class.
Method signatures and docstrings:
- def __init__(self, inputNodes, hiddenNodes, outputNodes, learningRate): 初始化网络参数, 共三层网络
- def train(self, inputs_list, targets_list): 训练数据集
- def test(self, inputs_lists... | 212f8b83d6ac22db1a777f980075d9e12ce521d2 | <|skeleton|>
class neuralNetwork:
def __init__(self, inputNodes, hiddenNodes, outputNodes, learningRate):
"""初始化网络参数, 共三层网络"""
<|body_0|>
def train(self, inputs_list, targets_list):
"""训练数据集"""
<|body_1|>
def test(self, inputs_lists):
"""测试"""
<|body_2|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class neuralNetwork:
def __init__(self, inputNodes, hiddenNodes, outputNodes, learningRate):
"""初始化网络参数, 共三层网络"""
self.in_nodes = inputNodes
self.hide_nodes = hiddenNodes
self.out_nodes = outputNodes
self.l_rate = learningRate
self.weight_in_hide = numpy.random.normal... | the_stack_v2_python_sparse | MachineLearning/Python-simple-Bp/python简单神经网络.py | FrankieZhen/Lookoop | train | 1 | |
c02668f76b2c3bc579eeb58ee2131b0c436f0cec | [
"if DatabaseApiFactory._db is None:\n DatabaseApiFactory._db = DatabaseApiFactory._implement(orm_type, connection_database)\nreturn DatabaseApiFactory._db",
"if orm_type == 'sqlalchemy':\n return DatabaseSqlAlchemy(connection_database)\nelse:\n raise DatabaseException(ErrorMessages.CONFIGURATION_ERROR)"
... | <|body_start_0|>
if DatabaseApiFactory._db is None:
DatabaseApiFactory._db = DatabaseApiFactory._implement(orm_type, connection_database)
return DatabaseApiFactory._db
<|end_body_0|>
<|body_start_1|>
if orm_type == 'sqlalchemy':
return DatabaseSqlAlchemy(connection_datab... | Class to get any implement | DatabaseApiFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseApiFactory:
"""Class to get any implement"""
def get_connection(orm_type: str, connection_database: str) -> DatabaseApi:
"""Get orm database implementation :param orm_type: name of implementation software :param connection_database: url connection"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_073114 | 1,287 | no_license | [
{
"docstring": "Get orm database implementation :param orm_type: name of implementation software :param connection_database: url connection",
"name": "get_connection",
"signature": "def get_connection(orm_type: str, connection_database: str) -> DatabaseApi"
},
{
"docstring": "Set implementation ... | 2 | stack_v2_sparse_classes_30k_train_041078 | Implement the Python class `DatabaseApiFactory` described below.
Class description:
Class to get any implement
Method signatures and docstrings:
- def get_connection(orm_type: str, connection_database: str) -> DatabaseApi: Get orm database implementation :param orm_type: name of implementation software :param connect... | Implement the Python class `DatabaseApiFactory` described below.
Class description:
Class to get any implement
Method signatures and docstrings:
- def get_connection(orm_type: str, connection_database: str) -> DatabaseApi: Get orm database implementation :param orm_type: name of implementation software :param connect... | d838937cf92262176faec6a6a833a602dbcd868e | <|skeleton|>
class DatabaseApiFactory:
"""Class to get any implement"""
def get_connection(orm_type: str, connection_database: str) -> DatabaseApi:
"""Get orm database implementation :param orm_type: name of implementation software :param connection_database: url connection"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatabaseApiFactory:
"""Class to get any implement"""
def get_connection(orm_type: str, connection_database: str) -> DatabaseApi:
"""Get orm database implementation :param orm_type: name of implementation software :param connection_database: url connection"""
if DatabaseApiFactory._db is N... | the_stack_v2_python_sparse | common/infra_modules/database_module/impl/database_api_factory.py | jsmoyam/zserver | train | 0 |
6dc73ac419af04ad6391e1311e6c806d618231bb | [
"self.sumsMatrix = matrix\nlengI = len(matrix)\nif not lengI:\n return\nlengJ = len(matrix[0])\nfor i in xrange(1, lengI):\n self.sumsMatrix[i][0] += self.sumsMatrix[i - 1][0]\nfor j in xrange(1, lengJ):\n self.sumsMatrix[0][j] += self.sumsMatrix[0][j - 1]\nfor i in xrange(1, lengI):\n for j in xrange(1... | <|body_start_0|>
self.sumsMatrix = matrix
lengI = len(matrix)
if not lengI:
return
lengJ = len(matrix[0])
for i in xrange(1, lengI):
self.sumsMatrix[i][0] += self.sumsMatrix[i - 1][0]
for j in xrange(1, lengJ):
self.sumsMatrix[0][j] += ... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_75kplus_train_073115 | 1,378 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | 608770f2eec4bd5110110a950a813dcc225bc23d | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
self.sumsMatrix = matrix
lengI = len(matrix)
if not lengI:
return
lengJ = len(matrix[0])
for i in xrange(1, lengI):
self.sumsM... | the_stack_v2_python_sparse | python/304.py | madgd/leetcode | train | 0 | |
c00f0983bfc283e4f7cd65de110fbf6e0be78264 | [
"if len(nums) < 1:\n return 0\nmax_num, min_num = (nums[0], nums[0])\nresult = nums[0]\nfor i in range(1, len(nums)):\n temp = max_num\n max_num = max(max(max_num * nums[i], min_num * nums[i]), nums[i])\n min_num = min(min(temp * nums[i], min_num * nums[i]), nums[i])\n if max_num > result:\n r... | <|body_start_0|>
if len(nums) < 1:
return 0
max_num, min_num = (nums[0], nums[0])
result = nums[0]
for i in range(1, len(nums)):
temp = max_num
max_num = max(max(max_num * nums[i], min_num * nums[i]), nums[i])
min_num = min(min(temp * nums[... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_product(self, nums: List[int]) -> int:
"""数组乘积最大值 Args: arrs: 数组 Returns: 乘积"""
<|body_0|>
def max_product2(self, nums: List[int]) -> int:
"""数组乘积最大值 Args: nums: 数组 Returns: 乘积"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len... | stack_v2_sparse_classes_75kplus_train_073116 | 2,270 | permissive | [
{
"docstring": "数组乘积最大值 Args: arrs: 数组 Returns: 乘积",
"name": "max_product",
"signature": "def max_product(self, nums: List[int]) -> int"
},
{
"docstring": "数组乘积最大值 Args: nums: 数组 Returns: 乘积",
"name": "max_product2",
"signature": "def max_product2(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 max_product(self, nums: List[int]) -> int: 数组乘积最大值 Args: arrs: 数组 Returns: 乘积
- def max_product2(self, nums: List[int]) -> int: 数组乘积最大值 Args: nums: 数组 Returns: 乘积 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_product(self, nums: List[int]) -> int: 数组乘积最大值 Args: arrs: 数组 Returns: 乘积
- def max_product2(self, nums: List[int]) -> int: 数组乘积最大值 Args: nums: 数组 Returns: 乘积
<|skeleton... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def max_product(self, nums: List[int]) -> int:
"""数组乘积最大值 Args: arrs: 数组 Returns: 乘积"""
<|body_0|>
def max_product2(self, nums: List[int]) -> int:
"""数组乘积最大值 Args: nums: 数组 Returns: 乘积"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def max_product(self, nums: List[int]) -> int:
"""数组乘积最大值 Args: arrs: 数组 Returns: 乘积"""
if len(nums) < 1:
return 0
max_num, min_num = (nums[0], nums[0])
result = nums[0]
for i in range(1, len(nums)):
temp = max_num
max_num =... | the_stack_v2_python_sparse | src/leetcodepython/array/maximum_product_subarray_152.py | zhangyu345293721/leetcode | train | 101 | |
e9344b06ef250b4c62c7b61d823cea2600f87fc0 | [
"meeting_user = MeetingUser()\nmeeting_user.is_accepted = is_accepted\nmeeting_user.is_response = may_join\nmeeting_user.is_coordinator = is_coordinator\nmeeting_user.user_id = user_id\nreturn meeting_user",
"meeting_user = MeetingUser()\nmeeting_user.is_coordinator = True\nmeeting_user.is_accepted = 1\nmeeting_u... | <|body_start_0|>
meeting_user = MeetingUser()
meeting_user.is_accepted = is_accepted
meeting_user.is_response = may_join
meeting_user.is_coordinator = is_coordinator
meeting_user.user_id = user_id
return meeting_user
<|end_body_0|>
<|body_start_1|>
meeting_user =... | CreateMeetingAttendees | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateMeetingAttendees:
def _form_attendee(self, user_id: int, is_accepted=False, may_join=False, is_coordinator=False):
"""For create Meeting, create MeetingUser models. :param user_id: :param is_accepted: :param may_join: :param is_coordinator: :return: List of MeetingUser models."""
... | stack_v2_sparse_classes_75kplus_train_073117 | 1,133 | no_license | [
{
"docstring": "For create Meeting, create MeetingUser models. :param user_id: :param is_accepted: :param may_join: :param is_coordinator: :return: List of MeetingUser models.",
"name": "_form_attendee",
"signature": "def _form_attendee(self, user_id: int, is_accepted=False, may_join=False, is_coordinat... | 2 | stack_v2_sparse_classes_30k_train_034387 | Implement the Python class `CreateMeetingAttendees` described below.
Class description:
Implement the CreateMeetingAttendees class.
Method signatures and docstrings:
- def _form_attendee(self, user_id: int, is_accepted=False, may_join=False, is_coordinator=False): For create Meeting, create MeetingUser models. :param... | Implement the Python class `CreateMeetingAttendees` described below.
Class description:
Implement the CreateMeetingAttendees class.
Method signatures and docstrings:
- def _form_attendee(self, user_id: int, is_accepted=False, may_join=False, is_coordinator=False): For create Meeting, create MeetingUser models. :param... | 214cb14eb23f3aa1e32616d666c14d041a2c7dc7 | <|skeleton|>
class CreateMeetingAttendees:
def _form_attendee(self, user_id: int, is_accepted=False, may_join=False, is_coordinator=False):
"""For create Meeting, create MeetingUser models. :param user_id: :param is_accepted: :param may_join: :param is_coordinator: :return: List of MeetingUser models."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateMeetingAttendees:
def _form_attendee(self, user_id: int, is_accepted=False, may_join=False, is_coordinator=False):
"""For create Meeting, create MeetingUser models. :param user_id: :param is_accepted: :param may_join: :param is_coordinator: :return: List of MeetingUser models."""
meeting... | the_stack_v2_python_sparse | backend/src/api/pool/decorators/meeting_decorators/libs_meeting_decorator/meeting_attendee_libs/attendee_create.py | enixdark/meeting-training-app | train | 0 | |
d1565af10a938cb36ddf7b6ec5b43224700f01f2 | [
"if isinstance(reference, pd.DataFrame):\n reference = reference.values\nself.reference = reference\nself.scalers = {}",
"if not (log, scale) in self.scalers.keys():\n scaler = None\n ref = self.reference.copy()\n if log:\n ref = np.log2(ref + 1)\n if scale == 'minmax':\n scaler = pp.... | <|body_start_0|>
if isinstance(reference, pd.DataFrame):
reference = reference.values
self.reference = reference
self.scalers = {}
<|end_body_0|>
<|body_start_1|>
if not (log, scale) in self.scalers.keys():
scaler = None
ref = self.reference.copy()
... | CustomScaler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomScaler:
def __init__(self, reference):
""":param reference:"""
<|body_0|>
def transform(self, data, log, scale: str):
""":param data: :param log: log2(data+1) :param scale: 'minmax','m0s1','divide_mean' :return:"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_073118 | 45,930 | no_license | [
{
"docstring": ":param reference:",
"name": "__init__",
"signature": "def __init__(self, reference)"
},
{
"docstring": ":param data: :param log: log2(data+1) :param scale: 'minmax','m0s1','divide_mean' :return:",
"name": "transform",
"signature": "def transform(self, data, log, scale: st... | 2 | stack_v2_sparse_classes_30k_train_014936 | Implement the Python class `CustomScaler` described below.
Class description:
Implement the CustomScaler class.
Method signatures and docstrings:
- def __init__(self, reference): :param reference:
- def transform(self, data, log, scale: str): :param data: :param log: log2(data+1) :param scale: 'minmax','m0s1','divide... | Implement the Python class `CustomScaler` described below.
Class description:
Implement the CustomScaler class.
Method signatures and docstrings:
- def __init__(self, reference): :param reference:
- def transform(self, data, log, scale: str): :param data: :param log: log2(data+1) :param scale: 'minmax','m0s1','divide... | 6d11df5e8ca37e53e048d261ac287f859ba6e9b9 | <|skeleton|>
class CustomScaler:
def __init__(self, reference):
""":param reference:"""
<|body_0|>
def transform(self, data, log, scale: str):
""":param data: :param log: log2(data+1) :param scale: 'minmax','m0s1','divide_mean' :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomScaler:
def __init__(self, reference):
""":param reference:"""
if isinstance(reference, pd.DataFrame):
reference = reference.values
self.reference = reference
self.scalers = {}
def transform(self, data, log, scale: str):
""":param data: :param log... | the_stack_v2_python_sparse | stages_DE/stages_library.py | biolab/baylor-dicty | train | 0 | |
c258acbae6ae508f22572c91473380ead503130e | [
"vowels = 'aeiou'\nlst = list(s)\nl, r = (0, len(s) - 1)\nwhile l <= r:\n if lst[l].lower() not in vowels:\n l += 1\n elif lst[r].lower() not in vowels:\n r -= 1\n else:\n lst[l], lst[r] = (lst[r], lst[l])\n l += 1\n r -= 1\nreturn ''.join(lst)",
"vowels = re.findall('[... | <|body_start_0|>
vowels = 'aeiou'
lst = list(s)
l, r = (0, len(s) - 1)
while l <= r:
if lst[l].lower() not in vowels:
l += 1
elif lst[r].lower() not in vowels:
r -= 1
else:
lst[l], lst[r] = (lst[r], lst[l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
vowels = 'aeiou'
lst = list(s)
l, r = (0, len(s)... | stack_v2_sparse_classes_75kplus_train_073119 | 861 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels2",
"signature": "def reverseVowels2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002166 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels2(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels2(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseVowels(self, s):
... | 0ac672a1582707fcaa6b6ad1f2a1d927034447df | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
vowels = 'aeiou'
lst = list(s)
l, r = (0, len(s) - 1)
while l <= r:
if lst[l].lower() not in vowels:
l += 1
elif lst[r].lower() not in vowels:
r ... | the_stack_v2_python_sparse | Chapter01_ArrayProblem/leetcode345.py | HuichuanLI/alogritme-interview | train | 1 | |
340b35c005342ce3072f0e15a354806c6f6eeb93 | [
"inputs = common_layers.flatten4d3d(inputs)\nencoder_input, self_attention_bias, encoder_decoder_attention_bias = transformer_prepare_encoder(inputs, target_space, hparams, features=features)\nencoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.layer_prepostprocess_dropout)\nencoder_output = transformer_enco... | <|body_start_0|>
inputs = common_layers.flatten4d3d(inputs)
encoder_input, self_attention_bias, encoder_decoder_attention_bias = transformer_prepare_encoder(inputs, target_space, hparams, features=features)
encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.layer_prepostprocess_dropout)
... | Attention net. See file docstring. | TransformerExt2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerExt2:
"""Attention net. See file docstring."""
def encode(self, inputs, target_space, hparams, features=None):
"""Encode transformer inputs. Args: inputs: Transformer inputs [batch_size, input_length, hidden_dim] target_space: scalar, target space ID. hparams: hyperparmete... | stack_v2_sparse_classes_75kplus_train_073120 | 36,593 | permissive | [
{
"docstring": "Encode transformer inputs. Args: inputs: Transformer inputs [batch_size, input_length, hidden_dim] target_space: scalar, target space ID. hparams: hyperparmeters for model. features: optionally pass the entire features dictionary as well. This is needed now for \"packed\" datasets. Returns: Tupl... | 3 | stack_v2_sparse_classes_30k_train_025830 | Implement the Python class `TransformerExt2` described below.
Class description:
Attention net. See file docstring.
Method signatures and docstrings:
- def encode(self, inputs, target_space, hparams, features=None): Encode transformer inputs. Args: inputs: Transformer inputs [batch_size, input_length, hidden_dim] tar... | Implement the Python class `TransformerExt2` described below.
Class description:
Attention net. See file docstring.
Method signatures and docstrings:
- def encode(self, inputs, target_space, hparams, features=None): Encode transformer inputs. Args: inputs: Transformer inputs [batch_size, input_length, hidden_dim] tar... | f6e1b78c4b831c09149265edfd2873aa7fc29f55 | <|skeleton|>
class TransformerExt2:
"""Attention net. See file docstring."""
def encode(self, inputs, target_space, hparams, features=None):
"""Encode transformer inputs. Args: inputs: Transformer inputs [batch_size, input_length, hidden_dim] target_space: scalar, target space ID. hparams: hyperparmete... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformerExt2:
"""Attention net. See file docstring."""
def encode(self, inputs, target_space, hparams, features=None):
"""Encode transformer inputs. Args: inputs: Transformer inputs [batch_size, input_length, hidden_dim] target_space: scalar, target space ID. hparams: hyperparmeters for model.... | the_stack_v2_python_sparse | usr/models/transformer_ext2/model.py | fstahlberg/tensor2tensor-usr | train | 5 |
eb9a8cf46e986e429392775fb513b43e27880d56 | [
"self.root = Node()\nself.root.children = [Node('5'), Node('10'), Node('20'), Node('50'), Node('100')]\nself.validator = re.compile('^[A-M][A-L](?!00000000)\\\\d{8}(?!O)(?!Z)[A-Z]$')\nif fname:\n with open(fname, 'r') as file:\n text = file.read().splitlines()\n for line in text:\n line ... | <|body_start_0|>
self.root = Node()
self.root.children = [Node('5'), Node('10'), Node('20'), Node('50'), Node('100')]
self.validator = re.compile('^[A-M][A-L](?!00000000)\\d{8}(?!O)(?!Z)[A-Z]$')
if fname:
with open(fname, 'r') as file:
text = file.read().split... | WatchListLinked | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WatchListLinked:
def __init__(self, fname=''):
"""This magic method sets an instance variable root to a node of 5 children with each denomination being a child and if the file name is given, then inserts each bill number to the watchlistlinked class."""
<|body_0|>
def insert... | stack_v2_sparse_classes_75kplus_train_073121 | 4,827 | no_license | [
{
"docstring": "This magic method sets an instance variable root to a node of 5 children with each denomination being a child and if the file name is given, then inserts each bill number to the watchlistlinked class.",
"name": "__init__",
"signature": "def __init__(self, fname='')"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_042727 | Implement the Python class `WatchListLinked` described below.
Class description:
Implement the WatchListLinked class.
Method signatures and docstrings:
- def __init__(self, fname=''): This magic method sets an instance variable root to a node of 5 children with each denomination being a child and if the file name is ... | Implement the Python class `WatchListLinked` described below.
Class description:
Implement the WatchListLinked class.
Method signatures and docstrings:
- def __init__(self, fname=''): This magic method sets an instance variable root to a node of 5 children with each denomination being a child and if the file name is ... | e773e87668af057c8adb1e012aa5d81f42c70f2a | <|skeleton|>
class WatchListLinked:
def __init__(self, fname=''):
"""This magic method sets an instance variable root to a node of 5 children with each denomination being a child and if the file name is given, then inserts each bill number to the watchlistlinked class."""
<|body_0|>
def insert... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WatchListLinked:
def __init__(self, fname=''):
"""This magic method sets an instance variable root to a node of 5 children with each denomination being a child and if the file name is given, then inserts each bill number to the watchlistlinked class."""
self.root = Node()
self.root.chi... | the_stack_v2_python_sparse | HW/HW2/hw2.py | SiddhantBhardwaj2018/ISTA-350 | train | 0 | |
33463450a2f3e02e9b94cd8155c27db424ffe7f2 | [
"self.min = np.array([0.0, 0.0])\nself.value = 0.0\nself.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])\nself.n = 2\nself.smooth = True\nself.info = [True, True, True]\nself.latex_name = 'Three Hump Camel Function'\nself.latex_type = 'Valley Shaped'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = 2x_0^{2} - 1.05x_0^{4}... | <|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])
self.n = 2
self.smooth = True
self.info = [True, True, True]
self.latex_name = 'Three Hump Camel Function'
self.latex_type = 'Valley Shaped... | Three Hump Camel Function. | ThreeHumpCamel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeHumpCamel:
"""Three Hump Camel Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
def grad(self, x):
"""Grad function."""
<|body_2|>
def hess(self, x):
"... | stack_v2_sparse_classes_75kplus_train_073122 | 1,572 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
},
{
"docstring": "Grad function.",
"name": "grad",
"signature": "def grad(self, x)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_047945 | Implement the Python class `ThreeHumpCamel` described below.
Class description:
Three Hump Camel Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
- def grad(self, x): Grad function.
- def hess(self, x): Hess function. | Implement the Python class `ThreeHumpCamel` described below.
Class description:
Three Hump Camel Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
- def grad(self, x): Grad function.
- def hess(self, x): Hess function.
<|skeleton|>
class ThreeHumpCamel... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class ThreeHumpCamel:
"""Three Hump Camel Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
def grad(self, x):
"""Grad function."""
<|body_2|>
def hess(self, x):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreeHumpCamel:
"""Three Hump Camel Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])
self.n = 2
self.smooth = True
self.info = [True, True, True]
... | the_stack_v2_python_sparse | ctf/functions2d/three_hump_camel.py | cntaylor/ctf | train | 1 |
58a09615f47b9b1fddaff0e54420a20c3c147f7d | [
"super().__init__()\nif upsample == 'nontrainable' and pre_conv is None:\n up_chns = in_chns\nelse:\n up_chns = in_chns // 2 if halves else in_chns\nself.upsample = UpSample(spatial_dims, in_chns, up_chns, 2, mode=upsample, pre_conv=pre_conv, interp_mode=interp_mode, align_corners=align_corners)\nself.convs =... | <|body_start_0|>
super().__init__()
if upsample == 'nontrainable' and pre_conv is None:
up_chns = in_chns
else:
up_chns = in_chns // 2 if halves else in_chns
self.upsample = UpSample(spatial_dims, in_chns, up_chns, 2, mode=upsample, pre_conv=pre_conv, interp_mode=... | upsampling, concatenation with the encoder feature map, two convolutions | UpCat | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpCat:
"""upsampling, concatenation with the encoder feature map, two convolutions"""
def __init__(self, spatial_dims: int, in_chns: int, cat_chns: int, out_chns: int, act: str | tuple, norm: str | tuple, bias: bool, dropout: float | tuple=0.0, upsample: str='deconv', pre_conv: nn.Module | s... | stack_v2_sparse_classes_75kplus_train_073123 | 10,950 | permissive | [
{
"docstring": "Args: spatial_dims: number of spatial dimensions. in_chns: number of input channels to be upsampled. cat_chns: number of channels from the encoder. out_chns: number of output channels. act: activation type and arguments. norm: feature normalization type and arguments. bias: whether to have a bia... | 2 | stack_v2_sparse_classes_30k_train_024505 | Implement the Python class `UpCat` described below.
Class description:
upsampling, concatenation with the encoder feature map, two convolutions
Method signatures and docstrings:
- def __init__(self, spatial_dims: int, in_chns: int, cat_chns: int, out_chns: int, act: str | tuple, norm: str | tuple, bias: bool, dropout... | Implement the Python class `UpCat` described below.
Class description:
upsampling, concatenation with the encoder feature map, two convolutions
Method signatures and docstrings:
- def __init__(self, spatial_dims: int, in_chns: int, cat_chns: int, out_chns: int, act: str | tuple, norm: str | tuple, bias: bool, dropout... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class UpCat:
"""upsampling, concatenation with the encoder feature map, two convolutions"""
def __init__(self, spatial_dims: int, in_chns: int, cat_chns: int, out_chns: int, act: str | tuple, norm: str | tuple, bias: bool, dropout: float | tuple=0.0, upsample: str='deconv', pre_conv: nn.Module | s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpCat:
"""upsampling, concatenation with the encoder feature map, two convolutions"""
def __init__(self, spatial_dims: int, in_chns: int, cat_chns: int, out_chns: int, act: str | tuple, norm: str | tuple, bias: bool, dropout: float | tuple=0.0, upsample: str='deconv', pre_conv: nn.Module | str | None='de... | the_stack_v2_python_sparse | monai/networks/nets/basic_unet.py | Project-MONAI/MONAI | train | 4,805 |
f44e278619e216730e09f33788f909077dc5f8b1 | [
"data = df.Dataframe(self.array_dict)\nnew_row = {'a': 2, 'b': 3}\ndata.append(new_row)\nfor key, value in data.data.items():\n self.assertEqual(data[key][-1], new_row[key])",
"a = np.arange(10)\nb = np.arange(10)\narray_dict = {'a': a, 'b': b}\ndata = df.Dataframe(array_dict)\nnew_row = {'a': 2, 'b': 3}\ndata... | <|body_start_0|>
data = df.Dataframe(self.array_dict)
new_row = {'a': 2, 'b': 3}
data.append(new_row)
for key, value in data.data.items():
self.assertEqual(data[key][-1], new_row[key])
<|end_body_0|>
<|body_start_1|>
a = np.arange(10)
b = np.arange(10)
... | AppendRowTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppendRowTests:
def testAppendedRowCorrect(self):
"""The appended row must match the row that was passed to Dataframe.append()"""
<|body_0|>
def testNewRowNumber(self):
"""After append, the dataframe must have the right number of rows"""
<|body_1|>
def t... | stack_v2_sparse_classes_75kplus_train_073124 | 6,558 | no_license | [
{
"docstring": "The appended row must match the row that was passed to Dataframe.append()",
"name": "testAppendedRowCorrect",
"signature": "def testAppendedRowCorrect(self)"
},
{
"docstring": "After append, the dataframe must have the right number of rows",
"name": "testNewRowNumber",
"s... | 5 | null | Implement the Python class `AppendRowTests` described below.
Class description:
Implement the AppendRowTests class.
Method signatures and docstrings:
- def testAppendedRowCorrect(self): The appended row must match the row that was passed to Dataframe.append()
- def testNewRowNumber(self): After append, the dataframe ... | Implement the Python class `AppendRowTests` described below.
Class description:
Implement the AppendRowTests class.
Method signatures and docstrings:
- def testAppendedRowCorrect(self): The appended row must match the row that was passed to Dataframe.append()
- def testNewRowNumber(self): After append, the dataframe ... | 3648c72b76d1f2fc03f6a177d093920359f0a5a0 | <|skeleton|>
class AppendRowTests:
def testAppendedRowCorrect(self):
"""The appended row must match the row that was passed to Dataframe.append()"""
<|body_0|>
def testNewRowNumber(self):
"""After append, the dataframe must have the right number of rows"""
<|body_1|>
def t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppendRowTests:
def testAppendedRowCorrect(self):
"""The appended row must match the row that was passed to Dataframe.append()"""
data = df.Dataframe(self.array_dict)
new_row = {'a': 2, 'b': 3}
data.append(new_row)
for key, value in data.data.items():
self.a... | the_stack_v2_python_sparse | DataFrame_test.py | SundropFuels/gasifier_analysis | train | 1 | |
908ae0cce406613bce50900852e08db64640528c | [
"self.product_range = get_object_or_404(models.ProductRange, pk=self.kwargs.get('range_pk'))\ncontext = super().get_context_data(*args, **kwargs)\ncontext['product_range'] = self.product_range\ncontext['variations'] = self.get_variation_matrix(self.product_range)\nreturn context",
"variations = {}\nproducts = pro... | <|body_start_0|>
self.product_range = get_object_or_404(models.ProductRange, pk=self.kwargs.get('range_pk'))
context = super().get_context_data(*args, **kwargs)
context['product_range'] = self.product_range
context['variations'] = self.get_variation_matrix(self.product_range)
ret... | Base view for product range edits. | EditNewProduct | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditNewProduct:
"""Base view for product range edits."""
def get_context_data(self, *args, **kwargs):
"""Get template context data."""
<|body_0|>
def get_variation_matrix(self, product_range):
"""Return a dict of all possible variations for the range."""
... | stack_v2_sparse_classes_75kplus_train_073125 | 11,012 | no_license | [
{
"docstring": "Get template context data.",
"name": "get_context_data",
"signature": "def get_context_data(self, *args, **kwargs)"
},
{
"docstring": "Return a dict of all possible variations for the range.",
"name": "get_variation_matrix",
"signature": "def get_variation_matrix(self, pr... | 2 | stack_v2_sparse_classes_30k_train_013336 | Implement the Python class `EditNewProduct` described below.
Class description:
Base view for product range edits.
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Get template context data.
- def get_variation_matrix(self, product_range): Return a dict of all possible variations for t... | Implement the Python class `EditNewProduct` described below.
Class description:
Base view for product range edits.
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Get template context data.
- def get_variation_matrix(self, product_range): Return a dict of all possible variations for t... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class EditNewProduct:
"""Base view for product range edits."""
def get_context_data(self, *args, **kwargs):
"""Get template context data."""
<|body_0|>
def get_variation_matrix(self, product_range):
"""Return a dict of all possible variations for the range."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditNewProduct:
"""Base view for product range edits."""
def get_context_data(self, *args, **kwargs):
"""Get template context data."""
self.product_range = get_object_or_404(models.ProductRange, pk=self.kwargs.get('range_pk'))
context = super().get_context_data(*args, **kwargs)
... | the_stack_v2_python_sparse | inventory/views/product_editor.py | stcstores/stcadmin | train | 0 |
5f7d4a5e2d4f8845654a2f0219ca238240741a50 | [
"credentials = pika.PlainCredentials(config.rabbitmq_server_user, config.rabbitmq_server_passwd)\nself.connection = pika.BlockingConnection(pika.ConnectionParameters(config.rabbitmq_server_ip, credentials=credentials))\nself.channel = self.connection.channel()\nself.channel.queue_declare(queue='rpc_queue')\nself.ch... | <|body_start_0|>
credentials = pika.PlainCredentials(config.rabbitmq_server_user, config.rabbitmq_server_passwd)
self.connection = pika.BlockingConnection(pika.ConnectionParameters(config.rabbitmq_server_ip, credentials=credentials))
self.channel = self.connection.channel()
self.channel.... | RpcServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RpcServer:
def __init__(self):
"""初始化接收命令的队列"""
<|body_0|>
def run_command(self, command):
"""在本服务器上执行任务,返回结果 :param command: :return:"""
<|body_1|>
def on_request(self, ch, method, props, body):
"""收到命令后,调用的函数,返回结果到客户端指定的队列中"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_073126 | 2,278 | no_license | [
{
"docstring": "初始化接收命令的队列",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "在本服务器上执行任务,返回结果 :param command: :return:",
"name": "run_command",
"signature": "def run_command(self, command)"
},
{
"docstring": "收到命令后,调用的函数,返回结果到客户端指定的队列中",
"name": "on_re... | 4 | stack_v2_sparse_classes_30k_train_008200 | Implement the Python class `RpcServer` described below.
Class description:
Implement the RpcServer class.
Method signatures and docstrings:
- def __init__(self): 初始化接收命令的队列
- def run_command(self, command): 在本服务器上执行任务,返回结果 :param command: :return:
- def on_request(self, ch, method, props, body): 收到命令后,调用的函数,返回结果到客户端指... | Implement the Python class `RpcServer` described below.
Class description:
Implement the RpcServer class.
Method signatures and docstrings:
- def __init__(self): 初始化接收命令的队列
- def run_command(self, command): 在本服务器上执行任务,返回结果 :param command: :return:
- def on_request(self, ch, method, props, body): 收到命令后,调用的函数,返回结果到客户端指... | 8e4dfaaeae782a37f6baca4c024b1c2a1dc83cba | <|skeleton|>
class RpcServer:
def __init__(self):
"""初始化接收命令的队列"""
<|body_0|>
def run_command(self, command):
"""在本服务器上执行任务,返回结果 :param command: :return:"""
<|body_1|>
def on_request(self, ch, method, props, body):
"""收到命令后,调用的函数,返回结果到客户端指定的队列中"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RpcServer:
def __init__(self):
"""初始化接收命令的队列"""
credentials = pika.PlainCredentials(config.rabbitmq_server_user, config.rabbitmq_server_passwd)
self.connection = pika.BlockingConnection(pika.ConnectionParameters(config.rabbitmq_server_ip, credentials=credentials))
self.channel ... | the_stack_v2_python_sparse | rabbitmq/rpc_server.py | PeterZhangxing/codewars | train | 0 | |
94239537bd6c69e1b6ee9abcdb4f8b5907df5e21 | [
"flag = 1 if x > -1 else -1\npositiveX = flag * x\nstrX = str(positiveX)\nrevsedX = strX[::-1]\nrevsedIntX = int(revsedX) * flag\nif revsedIntX < -2 ** 31 or revsedIntX > 2 ** 31 - 1:\n revsedIntX = 0\nreturn revsedIntX",
"flag = 1 if x > -1 else -1\npositiveX = flag * x\nres = 0\nwhile positiveX > 0:\n res... | <|body_start_0|>
flag = 1 if x > -1 else -1
positiveX = flag * x
strX = str(positiveX)
revsedX = strX[::-1]
revsedIntX = int(revsedX) * flag
if revsedIntX < -2 ** 31 or revsedIntX > 2 ** 31 - 1:
revsedIntX = 0
return revsedIntX
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
flag = 1 if x > -1 else -1
positiveX = flag * x
strX = str(p... | stack_v2_sparse_classes_75kplus_train_073127 | 790 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse2",
"signature": "def reverse2(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036483 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse2(self, x): :type x: int :rtype: int
- def reverse(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse2(self, x): :type x: int :rtype: int
- def reverse(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse2(self, x):
""":type x: int... | 238995bd23c8a6c40c6035890e94baa2473d4bbc | <|skeleton|>
class Solution:
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverse2(self, x):
""":type x: int :rtype: int"""
flag = 1 if x > -1 else -1
positiveX = flag * x
strX = str(positiveX)
revsedX = strX[::-1]
revsedIntX = int(revsedX) * flag
if revsedIntX < -2 ** 31 or revsedIntX > 2 ** 31 - 1:
... | the_stack_v2_python_sparse | problems/ReverseInteger.py | wan-catherine/Leetcode | train | 5 | |
31101687d35e8fe89ce8460a6901ccbd315bb198 | [
"connection = os.environ.get('DB_CONNECTION')\nusername = os.getenv('DB_USERNAME')\npassword = os.getenv('DB_PASSWORD')\nhost = os.getenv('DB_HOST')\nport = os.environ.get('DB_PORT')\ndatabase = os.getenv('DB_DATABASE')\nSQLALCHEMY_DATABASE_URI = connection + '://' + username + ':' + password + '@' + host + ':' + p... | <|body_start_0|>
connection = os.environ.get('DB_CONNECTION')
username = os.getenv('DB_USERNAME')
password = os.getenv('DB_PASSWORD')
host = os.getenv('DB_HOST')
port = os.environ.get('DB_PORT')
database = os.getenv('DB_DATABASE')
SQLALCHEMY_DATABASE_URI = connect... | Config | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def database():
"""Configuration For Database :return string:"""
<|body_0|>
def database_analytic():
"""Configuration For Database Analytics :return string:"""
<|body_1|>
def per_page():
"""this function for create default data perpage :r... | stack_v2_sparse_classes_75kplus_train_073128 | 1,655 | no_license | [
{
"docstring": "Configuration For Database :return string:",
"name": "database",
"signature": "def database()"
},
{
"docstring": "Configuration For Database Analytics :return string:",
"name": "database_analytic",
"signature": "def database_analytic()"
},
{
"docstring": "this fun... | 3 | stack_v2_sparse_classes_30k_train_026972 | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def database(): Configuration For Database :return string:
- def database_analytic(): Configuration For Database Analytics :return string:
- def per_page(): this function for create ... | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def database(): Configuration For Database :return string:
- def database_analytic(): Configuration For Database Analytics :return string:
- def per_page(): this function for create ... | 4af89bd110ca305b952df15febe749bc9d0f6fe8 | <|skeleton|>
class Config:
def database():
"""Configuration For Database :return string:"""
<|body_0|>
def database_analytic():
"""Configuration For Database Analytics :return string:"""
<|body_1|>
def per_page():
"""this function for create default data perpage :r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
def database():
"""Configuration For Database :return string:"""
connection = os.environ.get('DB_CONNECTION')
username = os.getenv('DB_USERNAME')
password = os.getenv('DB_PASSWORD')
host = os.getenv('DB_HOST')
port = os.environ.get('DB_PORT')
dat... | the_stack_v2_python_sparse | config/app.py | arywidiantara/Flask-Sqlalchemy | train | 0 | |
7d2fce56982c6d54a4ede5b681be380be64e8019 | [
"self.proof_type = proof_type\nself.proof_purpose = proof_purpose\nself.created = created\nself.domain = domain\nself.challenge = challenge\nself.credential_status = credential_status",
"if isinstance(o, LDProofVCDetailOptions):\n return self.proof_type == o.proof_type and self.proof_purpose == o.proof_purpose... | <|body_start_0|>
self.proof_type = proof_type
self.proof_purpose = proof_purpose
self.created = created
self.domain = domain
self.challenge = challenge
self.credential_status = credential_status
<|end_body_0|>
<|body_start_1|>
if isinstance(o, LDProofVCDetailOpti... | Linked Data Proof verifiable credential options model. | LDProofVCDetailOptions | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LDProofVCDetailOptions:
"""Linked Data Proof verifiable credential options model."""
def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=None, challenge: Optional[str]=None, credential_status: Optional[dict]... | stack_v2_sparse_classes_75kplus_train_073129 | 4,481 | permissive | [
{
"docstring": "Initialize the LDProofVCDetailOptions instance.",
"name": "__init__",
"signature": "def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=None, challenge: Optional[str]=None, credential_status: Optional[di... | 2 | stack_v2_sparse_classes_30k_train_028153 | Implement the Python class `LDProofVCDetailOptions` described below.
Class description:
Linked Data Proof verifiable credential options model.
Method signatures and docstrings:
- def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=No... | Implement the Python class `LDProofVCDetailOptions` described below.
Class description:
Linked Data Proof verifiable credential options model.
Method signatures and docstrings:
- def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=No... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class LDProofVCDetailOptions:
"""Linked Data Proof verifiable credential options model."""
def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=None, challenge: Optional[str]=None, credential_status: Optional[dict]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LDProofVCDetailOptions:
"""Linked Data Proof verifiable credential options model."""
def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=None, challenge: Optional[str]=None, credential_status: Optional[dict]=None) -> Non... | the_stack_v2_python_sparse | aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/models/cred_detail_options.py | hyperledger/aries-cloudagent-python | train | 370 |
096c4fb9852ac26daeaa1554c4013b1c96328f54 | [
"gtest_output = 'TestSuite.\\n TestFixture\\n'\nexpected_test_list = ['TestSuite.TestFixture']\nself.assertEquals(_gtest_list_tests(gtest_output), expected_test_list)",
"gtest_output = 'TestSuite.\\r\\n TestFixture1\\r\\n'\nexpected_test_list = ['TestSuite.TestFixture1']\nself.assertEquals(_gtest_list_tests(gte... | <|body_start_0|>
gtest_output = 'TestSuite.\n TestFixture\n'
expected_test_list = ['TestSuite.TestFixture']
self.assertEquals(_gtest_list_tests(gtest_output), expected_test_list)
<|end_body_0|>
<|body_start_1|>
gtest_output = 'TestSuite.\r\n TestFixture1\r\n'
expected_test_lis... | Tests |_gtest_list_tests()| handling of --gtest_list_tests output. | GTestListTestsTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GTestListTestsTest:
"""Tests |_gtest_list_tests()| handling of --gtest_list_tests output."""
def testSingleSuiteAndFixture(self):
"""Tests a single suite with a single fixture."""
<|body_0|>
def testWindowsNewlines(self):
"""Tests handling of newlines."""
... | stack_v2_sparse_classes_75kplus_train_073130 | 2,417 | permissive | [
{
"docstring": "Tests a single suite with a single fixture.",
"name": "testSingleSuiteAndFixture",
"signature": "def testSingleSuiteAndFixture(self)"
},
{
"docstring": "Tests handling of newlines.",
"name": "testWindowsNewlines",
"signature": "def testWindowsNewlines(self)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_000583 | Implement the Python class `GTestListTestsTest` described below.
Class description:
Tests |_gtest_list_tests()| handling of --gtest_list_tests output.
Method signatures and docstrings:
- def testSingleSuiteAndFixture(self): Tests a single suite with a single fixture.
- def testWindowsNewlines(self): Tests handling of... | Implement the Python class `GTestListTestsTest` described below.
Class description:
Tests |_gtest_list_tests()| handling of --gtest_list_tests output.
Method signatures and docstrings:
- def testSingleSuiteAndFixture(self): Tests a single suite with a single fixture.
- def testWindowsNewlines(self): Tests handling of... | 89a278ec589d98bcbc7e57e0b80d055667cca62f | <|skeleton|>
class GTestListTestsTest:
"""Tests |_gtest_list_tests()| handling of --gtest_list_tests output."""
def testSingleSuiteAndFixture(self):
"""Tests a single suite with a single fixture."""
<|body_0|>
def testWindowsNewlines(self):
"""Tests handling of newlines."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GTestListTestsTest:
"""Tests |_gtest_list_tests()| handling of --gtest_list_tests output."""
def testSingleSuiteAndFixture(self):
"""Tests a single suite with a single fixture."""
gtest_output = 'TestSuite.\n TestFixture\n'
expected_test_list = ['TestSuite.TestFixture']
s... | the_stack_v2_python_sparse | src/mojo/devtools/common/devtoolslib/apptest_gtest_unittest.py | amplab/ray-core | train | 4 |
b155a3433740c166e0aad6729d7e0bfdc53b7ded | [
"self.tmp_dir = tmp_dir\nself.update_stats = update_stats\nself.model_loaded = False\npackage_zip_path = download_if_needed(prediction_package_uri, tmp_dir)\npackage_dir = os.path.join(tmp_dir, 'package')\nmake_dir(package_dir)\nwith zipfile.ZipFile(package_zip_path, 'r') as package_zip:\n package_zip.extractall... | <|body_start_0|>
self.tmp_dir = tmp_dir
self.update_stats = update_stats
self.model_loaded = False
package_zip_path = download_if_needed(prediction_package_uri, tmp_dir)
package_dir = os.path.join(tmp_dir, 'package')
make_dir(package_dir)
with zipfile.ZipFile(pack... | Class for making predictions based off of a prediction package. | Predictor | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
"""Class for making predictions based off of a prediction package."""
def __init__(self, prediction_package_uri, tmp_dir, update_stats=False, channel_order=None):
"""Creates a new Predictor. Args: prediction_package_uri: The URI of the prediction package to use. Can be any... | stack_v2_sparse_classes_75kplus_train_073131 | 7,520 | permissive | [
{
"docstring": "Creates a new Predictor. Args: prediction_package_uri: The URI of the prediction package to use. Can be any type of URI that Raster Vision can read. tmp_dir: Temporary directory in which to store files that are used by the Predictor. This directory is not cleaned up by this class. update_stats: ... | 3 | stack_v2_sparse_classes_30k_train_050965 | Implement the Python class `Predictor` described below.
Class description:
Class for making predictions based off of a prediction package.
Method signatures and docstrings:
- def __init__(self, prediction_package_uri, tmp_dir, update_stats=False, channel_order=None): Creates a new Predictor. Args: prediction_package_... | Implement the Python class `Predictor` described below.
Class description:
Class for making predictions based off of a prediction package.
Method signatures and docstrings:
- def __init__(self, prediction_package_uri, tmp_dir, update_stats=False, channel_order=None): Creates a new Predictor. Args: prediction_package_... | fe74bef30daa5821023946576b00c584ddc56de8 | <|skeleton|>
class Predictor:
"""Class for making predictions based off of a prediction package."""
def __init__(self, prediction_package_uri, tmp_dir, update_stats=False, channel_order=None):
"""Creates a new Predictor. Args: prediction_package_uri: The URI of the prediction package to use. Can be any... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Predictor:
"""Class for making predictions based off of a prediction package."""
def __init__(self, prediction_package_uri, tmp_dir, update_stats=False, channel_order=None):
"""Creates a new Predictor. Args: prediction_package_uri: The URI of the prediction package to use. Can be any type of URI ... | the_stack_v2_python_sparse | rastervision/predictor.py | dgketchum/raster-vision | train | 3 |
99f6b8338f9990d97be47923bae154e1bdd79abf | [
"self.__vc = virtual_coach.VirtualCoach('local', storage_username='demo', storage_password='demo')\nself.__experiments_list = {}\nself.__last_status = [None]\nself.__launched = False\nself.__sim = None\nexperiments_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'experiments_list.json')\nif not os.... | <|body_start_0|>
self.__vc = virtual_coach.VirtualCoach('local', storage_username='demo', storage_password='demo')
self.__experiments_list = {}
self.__last_status = [None]
self.__launched = False
self.__sim = None
experiments_path = os.path.join(os.path.dirname(os.path.re... | This class contains an instance of the virtual coach, and exposes a single function to run continuously the list of experiments contained in the experiments_list.json | ExperimentsLauncher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExperimentsLauncher:
"""This class contains an instance of the virtual coach, and exposes a single function to run continuously the list of experiments contained in the experiments_list.json"""
def __init__(self):
"""In the constructor we instantiate a VC, and read the list of experi... | stack_v2_sparse_classes_75kplus_train_073132 | 5,296 | no_license | [
{
"docstring": "In the constructor we instantiate a VC, and read the list of experiments from the experiments_list.json",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "\" Helper method that is specified as the callback function whenever we have a status change. By defa... | 4 | stack_v2_sparse_classes_30k_val_001538 | Implement the Python class `ExperimentsLauncher` described below.
Class description:
This class contains an instance of the virtual coach, and exposes a single function to run continuously the list of experiments contained in the experiments_list.json
Method signatures and docstrings:
- def __init__(self): In the con... | Implement the Python class `ExperimentsLauncher` described below.
Class description:
This class contains an instance of the virtual coach, and exposes a single function to run continuously the list of experiments contained in the experiments_list.json
Method signatures and docstrings:
- def __init__(self): In the con... | e4d22da4488aacd727d9f520b40fba2230bea113 | <|skeleton|>
class ExperimentsLauncher:
"""This class contains an instance of the virtual coach, and exposes a single function to run continuously the list of experiments contained in the experiments_list.json"""
def __init__(self):
"""In the constructor we instantiate a VC, and read the list of experi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExperimentsLauncher:
"""This class contains an instance of the virtual coach, and exposes a single function to run continuously the list of experiments contained in the experiments_list.json"""
def __init__(self):
"""In the constructor we instantiate a VC, and read the list of experiments from th... | the_stack_v2_python_sparse | demo_carousel/experiments_launcher.py | HBPNeurorobotics/Experiments | train | 1 |
ff69e28ec1026d8f674e40c20b99767c3280573f | [
"try:\n assert _is_valid_user(user_id)\nexcept AssertionError:\n message = 'invalid user id:{}'.format(user_id)\n logger.error(message)\n raise HTTPBadRequest(message, payload={'message': message})\nuser = Users.get(user_id)\nratings = user.get_ratings()\nreturn {'ratings': ratings}",
"try:\n asser... | <|body_start_0|>
try:
assert _is_valid_user(user_id)
except AssertionError:
message = 'invalid user id:{}'.format(user_id)
logger.error(message)
raise HTTPBadRequest(message, payload={'message': message})
user = Users.get(user_id)
ratings =... | Exposes the ratings associated with a user id as a resource for REST. | RatingsResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RatingsResource:
"""Exposes the ratings associated with a user id as a resource for REST."""
def get(self, user_id: int):
"""fetches the ratings submitted by a user. Args: user_id: the id of the user. Returns: a response object (either directly or implicitly done by Flask)"""
... | stack_v2_sparse_classes_75kplus_train_073133 | 10,758 | permissive | [
{
"docstring": "fetches the ratings submitted by a user. Args: user_id: the id of the user. Returns: a response object (either directly or implicitly done by Flask)",
"name": "get",
"signature": "def get(self, user_id: int)"
},
{
"docstring": "submits the ratings by a user to the system. Args: u... | 3 | stack_v2_sparse_classes_30k_test_001120 | Implement the Python class `RatingsResource` described below.
Class description:
Exposes the ratings associated with a user id as a resource for REST.
Method signatures and docstrings:
- def get(self, user_id: int): fetches the ratings submitted by a user. Args: user_id: the id of the user. Returns: a response object... | Implement the Python class `RatingsResource` described below.
Class description:
Exposes the ratings associated with a user id as a resource for REST.
Method signatures and docstrings:
- def get(self, user_id: int): fetches the ratings submitted by a user. Args: user_id: the id of the user. Returns: a response object... | b91961f2baa2ab70626aaadad2f90f609c92a449 | <|skeleton|>
class RatingsResource:
"""Exposes the ratings associated with a user id as a resource for REST."""
def get(self, user_id: int):
"""fetches the ratings submitted by a user. Args: user_id: the id of the user. Returns: a response object (either directly or implicitly done by Flask)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RatingsResource:
"""Exposes the ratings associated with a user id as a resource for REST."""
def get(self, user_id: int):
"""fetches the ratings submitted by a user. Args: user_id: the id of the user. Returns: a response object (either directly or implicitly done by Flask)"""
try:
... | the_stack_v2_python_sparse | product/server/resources.py | abhishekpathak/recommender | train | 0 |
bab346dbdb547045bd0cbe189f12d4a36ded41c6 | [
"curr = 0\ntotal = 1\nfor page in books:\n if curr + page > min_pages:\n total += 1\n curr = 0\n curr += page\nreturn total",
"if m > len(books) or not m:\n return -1\nlow = max(books)\nhigh = sum(books)\nwhile low < high:\n mid = (low + high) // 2\n result = self.count_students(books... | <|body_start_0|>
curr = 0
total = 1
for page in books:
if curr + page > min_pages:
total += 1
curr = 0
curr += page
return total
<|end_body_0|>
<|body_start_1|>
if m > len(books) or not m:
return -1
low ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def count_students(self, books, min_pages):
"""Returns number of students needed if you assign to each student min_pages. Time complexity: O(n). Space complexity: O(1), n is len(books)."""
<|body_0|>
def min_pages(self, books, m):
"""Returns minimum number ... | stack_v2_sparse_classes_75kplus_train_073134 | 2,089 | no_license | [
{
"docstring": "Returns number of students needed if you assign to each student min_pages. Time complexity: O(n). Space complexity: O(1), n is len(books).",
"name": "count_students",
"signature": "def count_students(self, books, min_pages)"
},
{
"docstring": "Returns minimum number of pages per ... | 2 | stack_v2_sparse_classes_30k_train_025863 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def count_students(self, books, min_pages): Returns number of students needed if you assign to each student min_pages. Time complexity: O(n). Space complexity: O(1), n is len(boo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def count_students(self, books, min_pages): Returns number of students needed if you assign to each student min_pages. Time complexity: O(n). Space complexity: O(1), n is len(boo... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def count_students(self, books, min_pages):
"""Returns number of students needed if you assign to each student min_pages. Time complexity: O(n). Space complexity: O(1), n is len(books)."""
<|body_0|>
def min_pages(self, books, m):
"""Returns minimum number ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def count_students(self, books, min_pages):
"""Returns number of students needed if you assign to each student min_pages. Time complexity: O(n). Space complexity: O(1), n is len(books)."""
curr = 0
total = 1
for page in books:
if curr + page > min_pages:
... | the_stack_v2_python_sparse | Binary_Search/allocate_books.py | vladn90/Algorithms | train | 0 | |
358813d77d8554d81c78611dbf6f1ed3ff92e515 | [
"super(HStoreField, self).__init__(*args, **kwargs)\nself.uniqueness = uniqueness\nself.required = required",
"value = Field.get_prep_value(self, value)\nif isinstance(value, dict):\n prep_value = {}\n for key, val in value.items():\n if isinstance(val, Expression):\n prep_value[key] = val... | <|body_start_0|>
super(HStoreField, self).__init__(*args, **kwargs)
self.uniqueness = uniqueness
self.required = required
<|end_body_0|>
<|body_start_1|>
value = Field.get_prep_value(self, value)
if isinstance(value, dict):
prep_value = {}
for key, val in... | Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end. | HStoreField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HStoreField:
"""Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end."""
def __init__(self, *args, uniqueness: Optional[List[Union[str, Tuple[str, ...]]]]=None, required... | stack_v2_sparse_classes_75kplus_train_073135 | 2,324 | permissive | [
{
"docstring": "Initializes a new instance of :see:HStoreField. Arguments: uniqueness: List of keys to enforce as unique. Use tuples to enforce multiple keys together to be unique. required: List of keys that should be enforced as required.",
"name": "__init__",
"signature": "def __init__(self, *args, u... | 3 | stack_v2_sparse_classes_30k_train_003826 | Implement the Python class `HStoreField` described below.
Class description:
Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end.
Method signatures and docstrings:
- def __init__(self, *args, un... | Implement the Python class `HStoreField` described below.
Class description:
Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end.
Method signatures and docstrings:
- def __init__(self, *args, un... | e5503cb3f3c1b7959bd55253d3a79296f4c8f0ef | <|skeleton|>
class HStoreField:
"""Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end."""
def __init__(self, *args, uniqueness: Optional[List[Union[str, Tuple[str, ...]]]]=None, required... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HStoreField:
"""Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end."""
def __init__(self, *args, uniqueness: Optional[List[Union[str, Tuple[str, ...]]]]=None, required: Optional[Li... | the_stack_v2_python_sparse | psqlextra/fields/hstore_field.py | SectorLabs/django-postgres-extra | train | 645 |
92a816f44fd2dad753cb6ecef7408a40ba9f0591 | [
"pypy = exec_call(*'-n 0 -q -- mpirun uname -a'.split())\nself.assertEqual(pypy.returncode, EXIT_OK)\nself.assertEqual(pypy.command[0], 'uname')",
"pypy = exec_call(*'-n1 -q -- mpirun uname -a'.split())\nself.assertEqual(pypy.returncode, EXIT_OK)\nself.assertEqual(pypy.command[0], 'mpirun')\nself.assertEqual(pypy... | <|body_start_0|>
pypy = exec_call(*'-n 0 -q -- mpirun uname -a'.split())
self.assertEqual(pypy.returncode, EXIT_OK)
self.assertEqual(pypy.command[0], 'uname')
<|end_body_0|>
<|body_start_1|>
pypy = exec_call(*'-n1 -q -- mpirun uname -a'.split())
self.assertEqual(pypy.returncode,... | Class TestDoWork tests interface for script runtest.py and backend runtest_module | TestDoWork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDoWork:
"""Class TestDoWork tests interface for script runtest.py and backend runtest_module"""
def test_single_job(self):
"""Run exec parallel with CPU = 0 meaning no MPI should be used"""
<|body_0|>
def test_single_job(self):
"""Run exec parallel with CPU =... | stack_v2_sparse_classes_75kplus_train_073136 | 3,219 | no_license | [
{
"docstring": "Run exec parallel with CPU = 0 meaning no MPI should be used",
"name": "test_single_job",
"signature": "def test_single_job(self)"
},
{
"docstring": "Run exec parallel with CPU = 1",
"name": "test_single_job",
"signature": "def test_single_job(self)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_051849 | Implement the Python class `TestDoWork` described below.
Class description:
Class TestDoWork tests interface for script runtest.py and backend runtest_module
Method signatures and docstrings:
- def test_single_job(self): Run exec parallel with CPU = 0 meaning no MPI should be used
- def test_single_job(self): Run exe... | Implement the Python class `TestDoWork` described below.
Class description:
Class TestDoWork tests interface for script runtest.py and backend runtest_module
Method signatures and docstrings:
- def test_single_job(self): Run exec parallel with CPU = 0 meaning no MPI should be used
- def test_single_job(self): Run exe... | 1f02b2c851f0e6ec2f93321b623000381b558a0b | <|skeleton|>
class TestDoWork:
"""Class TestDoWork tests interface for script runtest.py and backend runtest_module"""
def test_single_job(self):
"""Run exec parallel with CPU = 0 meaning no MPI should be used"""
<|body_0|>
def test_single_job(self):
"""Run exec parallel with CPU =... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDoWork:
"""Class TestDoWork tests interface for script runtest.py and backend runtest_module"""
def test_single_job(self):
"""Run exec parallel with CPU = 0 meaning no MPI should be used"""
pypy = exec_call(*'-n 0 -q -- mpirun uname -a'.split())
self.assertEqual(pypy.returncod... | the_stack_v2_python_sparse | unit_tests/test_scripts/test_pbs.py | flow123d/flow123d | train | 17 |
7b96d74e4a927b8f9d62078d8796131a3efa8fad | [
"test_map = dict(working_map)\nabs_rooms = []\nfor i in range(100):\n generator_pos = GeneratorUtil.random_pos(map_size, False)\n room = RoomGenerator.__generate_room(map_size)\n abs_room = GeneratorUtil.offset(generator_pos, room)\n room_clear = GeneratorUtil.check_clearance(test_map, abs_room)\n if... | <|body_start_0|>
test_map = dict(working_map)
abs_rooms = []
for i in range(100):
generator_pos = GeneratorUtil.random_pos(map_size, False)
room = RoomGenerator.__generate_room(map_size)
abs_room = GeneratorUtil.offset(generator_pos, room)
room_cle... | RoomGenerator | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoomGenerator:
def generate_rooms(working_map, map_size):
"""Generate a list of absoulte-positioned rooms"""
<|body_0|>
def __generate_room(map_size):
"""Generate a room, and return it. A room is defined as a 2D list with MapTileTypes.Floor."""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_073137 | 1,518 | permissive | [
{
"docstring": "Generate a list of absoulte-positioned rooms",
"name": "generate_rooms",
"signature": "def generate_rooms(working_map, map_size)"
},
{
"docstring": "Generate a room, and return it. A room is defined as a 2D list with MapTileTypes.Floor.",
"name": "__generate_room",
"signa... | 2 | stack_v2_sparse_classes_30k_val_001876 | Implement the Python class `RoomGenerator` described below.
Class description:
Implement the RoomGenerator class.
Method signatures and docstrings:
- def generate_rooms(working_map, map_size): Generate a list of absoulte-positioned rooms
- def __generate_room(map_size): Generate a room, and return it. A room is defin... | Implement the Python class `RoomGenerator` described below.
Class description:
Implement the RoomGenerator class.
Method signatures and docstrings:
- def generate_rooms(working_map, map_size): Generate a list of absoulte-positioned rooms
- def __generate_room(map_size): Generate a room, and return it. A room is defin... | bce8c262bc80912045a9e5394447b937f9b08f83 | <|skeleton|>
class RoomGenerator:
def generate_rooms(working_map, map_size):
"""Generate a list of absoulte-positioned rooms"""
<|body_0|>
def __generate_room(map_size):
"""Generate a room, and return it. A room is defined as a 2D list with MapTileTypes.Floor."""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoomGenerator:
def generate_rooms(working_map, map_size):
"""Generate a list of absoulte-positioned rooms"""
test_map = dict(working_map)
abs_rooms = []
for i in range(100):
generator_pos = GeneratorUtil.random_pos(map_size, False)
room = RoomGenerator._... | the_stack_v2_python_sparse | ageofwinds/map/mapGenerator/roomGenerator.py | pbrn46/ageofwinds | train | 0 | |
549a62c3978d203bf422081bad0566a6af0bd3bc | [
"results = []\n\ndef strSerialize(node):\n if node:\n results.append(str(node.val))\n strSerialize(node.left)\n strSerialize(node.right)\n else:\n results.append('None')\nstrSerialize(root)\nresultStr = ' '.join(results)\nreturn resultStr",
"def strDeserialize(nodes):\n if nod... | <|body_start_0|>
results = []
def strSerialize(node):
if node:
results.append(str(node.val))
strSerialize(node.left)
strSerialize(node.right)
else:
results.append('None')
strSerialize(root)
resultStr... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_073138 | 2,652 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_024430 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 453e92109494c962c36280cd0d32fb28aa771615 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
results = []
def strSerialize(node):
if node:
results.append(str(node.val))
strSerialize(node.left)
strSerialize(node... | the_stack_v2_python_sparse | Python/leetcode_297_serialize_and_deserialize_binary_tree.py | bakker4444/Algorithms | train | 1 | |
2f291941efe9b119387deafecb46828520bfeef5 | [
"reader = staticconf.NamespaceReaders(config_namespace)\ntry:\n signal_name = reader.read_string('autoscale_signal.name')\nexcept ConfigurationError as e:\n raise NoSignalConfiguredException from e\nsuper().__init__(signal_name, cluster, pool, scheduler, app, config_namespace)\nself.required_metrics: list = r... | <|body_start_0|>
reader = staticconf.NamespaceReaders(config_namespace)
try:
signal_name = reader.read_string('autoscale_signal.name')
except ConfigurationError as e:
raise NoSignalConfiguredException from e
super().__init__(signal_name, cluster, pool, scheduler, ... | ExternalSignal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalSignal:
def __init__(self, cluster: str, pool: str, scheduler: str, app: str, config_namespace: str, metrics_client: ClustermanMetricsBotoClient, signal_namespace: str) -> None:
"""Create an encapsulation of the Unix sockets via which we communicate with signals :param cluster: t... | stack_v2_sparse_classes_75kplus_train_073139 | 8,912 | permissive | [
{
"docstring": "Create an encapsulation of the Unix sockets via which we communicate with signals :param cluster: the name of the cluster this signal is for :param pool: the name of the pool this signal is for :param app: the name of the application this signal is for :param config_namespace: the staticconf nam... | 3 | stack_v2_sparse_classes_30k_train_024176 | Implement the Python class `ExternalSignal` described below.
Class description:
Implement the ExternalSignal class.
Method signatures and docstrings:
- def __init__(self, cluster: str, pool: str, scheduler: str, app: str, config_namespace: str, metrics_client: ClustermanMetricsBotoClient, signal_namespace: str) -> No... | Implement the Python class `ExternalSignal` described below.
Class description:
Implement the ExternalSignal class.
Method signatures and docstrings:
- def __init__(self, cluster: str, pool: str, scheduler: str, app: str, config_namespace: str, metrics_client: ClustermanMetricsBotoClient, signal_namespace: str) -> No... | 6c4b8bb424fd84f1087552fb19d992180cf17834 | <|skeleton|>
class ExternalSignal:
def __init__(self, cluster: str, pool: str, scheduler: str, app: str, config_namespace: str, metrics_client: ClustermanMetricsBotoClient, signal_namespace: str) -> None:
"""Create an encapsulation of the Unix sockets via which we communicate with signals :param cluster: t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExternalSignal:
def __init__(self, cluster: str, pool: str, scheduler: str, app: str, config_namespace: str, metrics_client: ClustermanMetricsBotoClient, signal_namespace: str) -> None:
"""Create an encapsulation of the Unix sockets via which we communicate with signals :param cluster: the name of the... | the_stack_v2_python_sparse | clusterman/signals/external_signal.py | Yelp/clusterman | train | 310 | |
d8cf7f5d3406b7d43cca572e5dc04731fa3065d0 | [
"assert len(input_data.shape) == 2\nassert len(output_data.shape) == 2\nassert input_data.shape[0] == output_data.shape[0]\nregressor = linear_model.LinearRegression(copy_X=True, fit_intercept=bias)\nregressor.fit(X=input_data, y=output_data)\nlogger.info('finished linear regression fit ')\nnew_weight = regressor.c... | <|body_start_0|>
assert len(input_data.shape) == 2
assert len(output_data.shape) == 2
assert input_data.shape[0] == output_data.shape[0]
regressor = linear_model.LinearRegression(copy_X=True, fit_intercept=bias)
regressor.fit(X=input_data, y=output_data)
logger.info('fini... | Class enables weights to be reconstructed for a channel-pruned layer | WeightReconstructor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightReconstructor:
"""Class enables weights to be reconstructed for a channel-pruned layer"""
def _linear_regression(input_data: np.ndarray, output_data: np.ndarray, bias: bool) -> (np.ndarray, np.ndarray):
"""least square linear regression Given a matrix of input_data (X) and outp... | stack_v2_sparse_classes_75kplus_train_073140 | 7,317 | permissive | [
{
"docstring": "least square linear regression Given a matrix of input_data (X) and output_data (y), linear regression attempts to find solution vector (W) that will approximate y = W * X + b. :param input_data: input_data, in the shape of [n_samples, n_features] :param output_data: output_data, in the shape of... | 3 | stack_v2_sparse_classes_30k_train_053090 | Implement the Python class `WeightReconstructor` described below.
Class description:
Class enables weights to be reconstructed for a channel-pruned layer
Method signatures and docstrings:
- def _linear_regression(input_data: np.ndarray, output_data: np.ndarray, bias: bool) -> (np.ndarray, np.ndarray): least square li... | Implement the Python class `WeightReconstructor` described below.
Class description:
Class enables weights to be reconstructed for a channel-pruned layer
Method signatures and docstrings:
- def _linear_regression(input_data: np.ndarray, output_data: np.ndarray, bias: bool) -> (np.ndarray, np.ndarray): least square li... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class WeightReconstructor:
"""Class enables weights to be reconstructed for a channel-pruned layer"""
def _linear_regression(input_data: np.ndarray, output_data: np.ndarray, bias: bool) -> (np.ndarray, np.ndarray):
"""least square linear regression Given a matrix of input_data (X) and outp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeightReconstructor:
"""Class enables weights to be reconstructed for a channel-pruned layer"""
def _linear_regression(input_data: np.ndarray, output_data: np.ndarray, bias: bool) -> (np.ndarray, np.ndarray):
"""least square linear regression Given a matrix of input_data (X) and output_data (y), ... | the_stack_v2_python_sparse | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/channel_pruning/weight_reconstruction.py | quic/aimet | train | 1,676 |
821e95cf964c53f08451db7f37bd424697266c96 | [
"stack = []\nresult = set()\nfor index, item in enumerate(s):\n if item == '(':\n stack.append(index)\n elif len(stack) > 0:\n result.add(stack.pop())\n result.add(index)\nreturn frozenset(result)",
"s = s.lstrip(')').rstrip('(')\nlength = len(s)\nif length < 2:\n return 0\nlast_valu... | <|body_start_0|>
stack = []
result = set()
for index, item in enumerate(s):
if item == '(':
stack.append(index)
elif len(stack) > 0:
result.add(stack.pop())
result.add(index)
return frozenset(result)
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def valid(self, s):
""">>> s = Solution() >>> text = "(()(()" >>> result = s.valid(text) >>> result [1, 2, 4, 5] >>> text = "((((()(()))))" >>> result = s.valid(text) >>> result.sort() >>> result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]"""
<|body_0|>
def longestVali... | stack_v2_sparse_classes_75kplus_train_073141 | 3,108 | no_license | [
{
"docstring": ">>> s = Solution() >>> text = \"(()(()\" >>> result = s.valid(text) >>> result [1, 2, 4, 5] >>> text = \"((((()(()))))\" >>> result = s.valid(text) >>> result.sort() >>> result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]",
"name": "valid",
"signature": "def valid(self, s)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_030389 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def valid(self, s): >>> s = Solution() >>> text = "(()(()" >>> result = s.valid(text) >>> result [1, 2, 4, 5] >>> text = "((((()(()))))" >>> result = s.valid(text) >>> result.sor... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def valid(self, s): >>> s = Solution() >>> text = "(()(()" >>> result = s.valid(text) >>> result [1, 2, 4, 5] >>> text = "((((()(()))))" >>> result = s.valid(text) >>> result.sor... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def valid(self, s):
""">>> s = Solution() >>> text = "(()(()" >>> result = s.valid(text) >>> result [1, 2, 4, 5] >>> text = "((((()(()))))" >>> result = s.valid(text) >>> result.sort() >>> result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]"""
<|body_0|>
def longestVali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def valid(self, s):
""">>> s = Solution() >>> text = "(()(()" >>> result = s.valid(text) >>> result [1, 2, 4, 5] >>> text = "((((()(()))))" >>> result = s.valid(text) >>> result.sort() >>> result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]"""
stack = []
result = set()
for... | the_stack_v2_python_sparse | longest_valid_parentheses.py | gsy/leetcode | train | 1 | |
0aca9c6495fbeea9f85a0da8b67ca4af4231ff7a | [
"ver = state.pop('version')\nassert ver == cls.VERSION\nreturn cls(**state)",
"state = attr.asdict(self)\nstate['version'] = self.VERSION\nreturn state"
] | <|body_start_0|>
ver = state.pop('version')
assert ver == cls.VERSION
return cls(**state)
<|end_body_0|>
<|body_start_1|>
state = attr.asdict(self)
state['version'] = self.VERSION
return state
<|end_body_1|>
| Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled. | Serializable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serializable:
"""Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled."""
def deserialize(cls, state):
"""Deseriali... | stack_v2_sparse_classes_75kplus_train_073142 | 1,206 | permissive | [
{
"docstring": "Deserialize the object from the dict of basic types. :param state dict: dict (serialized) representation of the object :return Serializable: the deserialized object",
"name": "deserialize",
"signature": "def deserialize(cls, state)"
},
{
"docstring": "Serialize object to dict of ... | 2 | stack_v2_sparse_classes_30k_test_002756 | Implement the Python class `Serializable` described below.
Class description:
Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled.
Method signatures... | Implement the Python class `Serializable` described below.
Class description:
Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled.
Method signatures... | e2864d88eb971e327d7e886e75d00140673006ef | <|skeleton|>
class Serializable:
"""Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled."""
def deserialize(cls, state):
"""Deseriali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Serializable:
"""Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled."""
def deserialize(cls, state):
"""Deserialize the object... | the_stack_v2_python_sparse | bc_gym_planning_env/utilities/serialize.py | braincorp/bc-gym-planning-env | train | 2 |
2cc205a901e0c383ba6bb36a23b4d199f67b5be6 | [
"assert isinstance(a, agent.Agent)\nself.a = a\nself.a.tc_h1('TRAFFIC TESTS')\nself.host = host.Host(a, STA)\nself.ap = accesspoint.AccessPoint(a, AP)\nself.host.reset(False)\nself.host.dbg_macaddr()\nself.ap.start()\nself.host.scan_passive(200)\nself.host.sta_connect(self.ap.macaddr)\nmpdu = self.ap.rx_mpdu(wifi.A... | <|body_start_0|>
assert isinstance(a, agent.Agent)
self.a = a
self.a.tc_h1('TRAFFIC TESTS')
self.host = host.Host(a, STA)
self.ap = accesspoint.AccessPoint(a, AP)
self.host.reset(False)
self.host.dbg_macaddr()
self.ap.start()
self.host.scan_passive... | Traffic condition test cases. | TcTraffic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TcTraffic:
"""Traffic condition test cases."""
def __init__(self, a):
"""Initializes the traffic tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT"""
<|body_0|>
def run_bidi(self):
"""Perform bidirectional transfer tests."""
... | stack_v2_sparse_classes_75kplus_train_073143 | 3,639 | no_license | [
{
"docstring": "Initializes the traffic tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT",
"name": "__init__",
"signature": "def __init__(self, a)"
},
{
"docstring": "Perform bidirectional transfer tests.",
"name": "run_bidi",
"signature": "def run_bi... | 2 | stack_v2_sparse_classes_30k_val_001121 | Implement the Python class `TcTraffic` described below.
Class description:
Traffic condition test cases.
Method signatures and docstrings:
- def __init__(self, a): Initializes the traffic tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT
- def run_bidi(self): Perform bidirectional ... | Implement the Python class `TcTraffic` described below.
Class description:
Traffic condition test cases.
Method signatures and docstrings:
- def __init__(self, a): Initializes the traffic tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT
- def run_bidi(self): Perform bidirectional ... | 83464d87d767c383e4eb599a096a999f0095a613 | <|skeleton|>
class TcTraffic:
"""Traffic condition test cases."""
def __init__(self, a):
"""Initializes the traffic tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT"""
<|body_0|>
def run_bidi(self):
"""Perform bidirectional transfer tests."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TcTraffic:
"""Traffic condition test cases."""
def __init__(self, a):
"""Initializes the traffic tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT"""
assert isinstance(a, agent.Agent)
self.a = a
self.a.tc_h1('TRAFFIC TESTS')
self... | the_stack_v2_python_sparse | tools/test_agent/tc_traffic.py | louiscaron/open-socemu | train | 0 |
09ff35c7a52d235f4cc3e7356379c929f2be0567 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AuditLogRoot()",
"from .directory_audit import DirectoryAudit\nfrom .entity import Entity\nfrom .provisioning_object_summary import ProvisioningObjectSummary\nfrom .sign_in import SignIn\nfrom .directory_audit import DirectoryAudit\nfr... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AuditLogRoot()
<|end_body_0|>
<|body_start_1|>
from .directory_audit import DirectoryAudit
from .entity import Entity
from .provisioning_object_summary import ProvisioningObjectS... | AuditLogRoot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditLogRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot:
"""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_75kplus_train_073144 | 3,089 | 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: AuditLogRoot",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | stack_v2_sparse_classes_30k_train_043383 | Implement the Python class `AuditLogRoot` described below.
Class description:
Implement the AuditLogRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `AuditLogRoot` described below.
Class description:
Implement the AuditLogRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AuditLogRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot:
"""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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuditLogRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot:
"""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: AuditLogRoot""... | the_stack_v2_python_sparse | msgraph/generated/models/audit_log_root.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ef580e40184ad0f2d5177a7e51c42e327b97c61b | [
"layers = []\nif first_layer == 'discrete':\n layers.extend([DiscreteFeature(num_embeddings, hidden_size, **kwargs)])\nif first_layer == 'continuous':\n layers.extend([ContinuousFeature(num_embeddings, hidden_size, **kwargs)])\nif first_layer == 'region':\n layers.extend([RegionFeature(num_embeddings, hidd... | <|body_start_0|>
layers = []
if first_layer == 'discrete':
layers.extend([DiscreteFeature(num_embeddings, hidden_size, **kwargs)])
if first_layer == 'continuous':
layers.extend([ContinuousFeature(num_embeddings, hidden_size, **kwargs)])
if first_layer == 'region':... | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
def __init__(self, num_embeddings, hidden_size, heads, num_layers, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, logits_per_slot=1, first_layer='region', final_layer='logits', **kwargs):
"""Creates a Transformer Keras model for processing sequences ... | stack_v2_sparse_classes_75kplus_train_073145 | 6,652 | no_license | [
{
"docstring": "Creates a Transformer Keras model for processing sequences and uses the tf.layers.Sequential as backend Arguments: num_embeddings: int the number of elements in the vocabulary which input sequences contain elements of hidden_size: int the number of units in the hidden variables used in each mult... | 2 | stack_v2_sparse_classes_30k_train_020989 | Implement the Python class `Transformer` described below.
Class description:
Implement the Transformer class.
Method signatures and docstrings:
- def __init__(self, num_embeddings, hidden_size, heads, num_layers, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, logits_per_slot=1, first_layer='r... | Implement the Python class `Transformer` described below.
Class description:
Implement the Transformer class.
Method signatures and docstrings:
- def __init__(self, num_embeddings, hidden_size, heads, num_layers, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, logits_per_slot=1, first_layer='r... | c155b16265f13d87be0108fcf815517491b93a74 | <|skeleton|>
class Transformer:
def __init__(self, num_embeddings, hidden_size, heads, num_layers, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, logits_per_slot=1, first_layer='region', final_layer='logits', **kwargs):
"""Creates a Transformer Keras model for processing sequences ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transformer:
def __init__(self, num_embeddings, hidden_size, heads, num_layers, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, logits_per_slot=1, first_layer='region', final_layer='logits', **kwargs):
"""Creates a Transformer Keras model for processing sequences and uses the t... | the_stack_v2_python_sparse | indigo/nn/transformer.py | mlberkeley/indigo | train | 4 | |
ad7b6440d72a5fa608a89039811ac975266697a2 | [
"self.pos_tag = 'SPAM'\nself.neg_tag = 'OK'\nself.spam_sender_counter = Counter()\nself.spam_subject_word_counter = Counter()",
"self.train_corpus_dir = corpus_dir\ntruth_file = os.path.join(corpus_dir, '!truth.txt')\nif os.path.exists(truth_file) == False:\n self.trained = False\n return\nCorpus = Training... | <|body_start_0|>
self.pos_tag = 'SPAM'
self.neg_tag = 'OK'
self.spam_sender_counter = Counter()
self.spam_subject_word_counter = Counter()
<|end_body_0|>
<|body_start_1|>
self.train_corpus_dir = corpus_dir
truth_file = os.path.join(corpus_dir, '!truth.txt')
if os... | MyFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyFilter:
def __init__(self):
"""Classificates e-mails dependig of their's headers."""
<|body_0|>
def train(self, corpus_dir):
"""Train method the filter uses to teach according to !truth.txt file."""
<|body_1|>
def save_ham_header(self, sender, subject)... | stack_v2_sparse_classes_75kplus_train_073146 | 3,341 | no_license | [
{
"docstring": "Classificates e-mails dependig of their's headers.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Train method the filter uses to teach according to !truth.txt file.",
"name": "train",
"signature": "def train(self, corpus_dir)"
},
{
"do... | 6 | null | Implement the Python class `MyFilter` described below.
Class description:
Implement the MyFilter class.
Method signatures and docstrings:
- def __init__(self): Classificates e-mails dependig of their's headers.
- def train(self, corpus_dir): Train method the filter uses to teach according to !truth.txt file.
- def sa... | Implement the Python class `MyFilter` described below.
Class description:
Implement the MyFilter class.
Method signatures and docstrings:
- def __init__(self): Classificates e-mails dependig of their's headers.
- def train(self, corpus_dir): Train method the filter uses to teach according to !truth.txt file.
- def sa... | a50b6abbc5aae7334ac76bb081fe438d94880744 | <|skeleton|>
class MyFilter:
def __init__(self):
"""Classificates e-mails dependig of their's headers."""
<|body_0|>
def train(self, corpus_dir):
"""Train method the filter uses to teach according to !truth.txt file."""
<|body_1|>
def save_ham_header(self, sender, subject)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyFilter:
def __init__(self):
"""Classificates e-mails dependig of their's headers."""
self.pos_tag = 'SPAM'
self.neg_tag = 'OK'
self.spam_sender_counter = Counter()
self.spam_subject_word_counter = Counter()
def train(self, corpus_dir):
"""Train method the... | the_stack_v2_python_sparse | RPH/SPAM/filter.py | stankmic/OI-BC | train | 0 | |
57613186c6af322077a41f18ddac713fa9001569 | [
"self.mobile = mobile()\nself.url = 'http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel={}'.format(self.mobile)\nself.k780_url = 'http://api.k780.com:88/?app=phone.get&phone={}&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json'.format(self.mobile)",
"data = request(self.url, None)[1].text.split... | <|body_start_0|>
self.mobile = mobile()
self.url = 'http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel={}'.format(self.mobile)
self.k780_url = 'http://api.k780.com:88/?app=phone.get&phone={}&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json'.format(self.mobile)
<|end_body_0|>
... | test user mobile | TestUserMobile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUserMobile:
"""test user mobile"""
def setUp(self):
"""setUp function"""
<|body_0|>
def test_request_api(self):
"""request api and get response"""
<|body_1|>
def test_request_k780_api(self):
"""get api data and assert response"""
... | stack_v2_sparse_classes_75kplus_train_073147 | 1,635 | no_license | [
{
"docstring": "setUp function",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "request api and get response",
"name": "test_request_api",
"signature": "def test_request_api(self)"
},
{
"docstring": "get api data and assert response",
"name": "test_request... | 3 | stack_v2_sparse_classes_30k_train_022865 | Implement the Python class `TestUserMobile` described below.
Class description:
test user mobile
Method signatures and docstrings:
- def setUp(self): setUp function
- def test_request_api(self): request api and get response
- def test_request_k780_api(self): get api data and assert response | Implement the Python class `TestUserMobile` described below.
Class description:
test user mobile
Method signatures and docstrings:
- def setUp(self): setUp function
- def test_request_api(self): request api and get response
- def test_request_k780_api(self): get api data and assert response
<|skeleton|>
class TestUs... | b8dd4dd6dafaf9899e97bbb75a3ef80246ec427b | <|skeleton|>
class TestUserMobile:
"""test user mobile"""
def setUp(self):
"""setUp function"""
<|body_0|>
def test_request_api(self):
"""request api and get response"""
<|body_1|>
def test_request_k780_api(self):
"""get api data and assert response"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestUserMobile:
"""test user mobile"""
def setUp(self):
"""setUp function"""
self.mobile = mobile()
self.url = 'http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel={}'.format(self.mobile)
self.k780_url = 'http://api.k780.com:88/?app=phone.get&phone={}&appkey=10003&sig... | the_stack_v2_python_sparse | sixth_week/second_day/test_user_mobile.py | czkun1986/Let-s-go-python- | train | 0 |
721ee4a642230c11516505b16b2b7b319975b37e | [
"super().__init__()\nself.max_delta_freq = +200\nself.min_delta_freq = -200\nself.meas_nrsteps = 8\nself.npoints = 5\nself.wait_tune = 5\nself.timeout_wait_sofb = 3\nself.sofb_nrpoints = 10",
"ftmp = '{0:24s} = {1:9.3f} {2:s}\\n'.format\ndtmp = '{0:24s} = {1:9d} {2:s}\\n'.format\nstg = ftmp('max_delta_freq [Hz]... | <|body_start_0|>
super().__init__()
self.max_delta_freq = +200
self.min_delta_freq = -200
self.meas_nrsteps = 8
self.npoints = 5
self.wait_tune = 5
self.timeout_wait_sofb = 3
self.sofb_nrpoints = 10
<|end_body_0|>
<|body_start_1|>
ftmp = '{0:24s} ... | . | MeasParams | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.max_delta_freq = +200
self.min_delta_freq = -200
self.meas_nrsteps... | stack_v2_sparse_classes_75kplus_train_073148 | 13,058 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ".",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `MeasParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): . | Implement the Python class `MeasParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): .
<|skeleton|>
class MeasParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_... | 39644161d98964a3a3d80d63269201f0a1712e82 | <|skeleton|>
class MeasParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MeasParams:
"""."""
def __init__(self):
"""."""
super().__init__()
self.max_delta_freq = +200
self.min_delta_freq = -200
self.meas_nrsteps = 8
self.npoints = 5
self.wait_tune = 5
self.timeout_wait_sofb = 3
self.sofb_nrpoints = 10
... | the_stack_v2_python_sparse | apsuite/commisslib/measure_chromdisp.py | lnls-fac/apsuite | train | 1 |
194cdbbee0b4a77826161e6fcc423a12d5b82d40 | [
"x = 9\nn = 2\nresult = ReturnsNthRoot(x, n)\nroot = 3\nself.assertEqual(result, root)",
"x = 9\nn = 3\nresult = ReturnsNthRoot(x, n)\nroot = None\nself.assertEqual(result, root)"
] | <|body_start_0|>
x = 9
n = 2
result = ReturnsNthRoot(x, n)
root = 3
self.assertEqual(result, root)
<|end_body_0|>
<|body_start_1|>
x = 9
n = 3
result = ReturnsNthRoot(x, n)
root = None
self.assertEqual(result, root)
<|end_body_1|>
| TestRootPower | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRootPower:
def test_ReturnsNthRoot_Existent(self):
"""Test ReturnsNthRoot if it exists as an Integer"""
<|body_0|>
def test_ReturnsNthRoot_NonExistent(self):
"""Test ReturnsNthRoot if it exists as an Integer"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_073149 | 1,474 | no_license | [
{
"docstring": "Test ReturnsNthRoot if it exists as an Integer",
"name": "test_ReturnsNthRoot_Existent",
"signature": "def test_ReturnsNthRoot_Existent(self)"
},
{
"docstring": "Test ReturnsNthRoot if it exists as an Integer",
"name": "test_ReturnsNthRoot_NonExistent",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_031970 | Implement the Python class `TestRootPower` described below.
Class description:
Implement the TestRootPower class.
Method signatures and docstrings:
- def test_ReturnsNthRoot_Existent(self): Test ReturnsNthRoot if it exists as an Integer
- def test_ReturnsNthRoot_NonExistent(self): Test ReturnsNthRoot if it exists as ... | Implement the Python class `TestRootPower` described below.
Class description:
Implement the TestRootPower class.
Method signatures and docstrings:
- def test_ReturnsNthRoot_Existent(self): Test ReturnsNthRoot if it exists as an Integer
- def test_ReturnsNthRoot_NonExistent(self): Test ReturnsNthRoot if it exists as ... | cd85abea9d91ed8b17334f744ab150e790044da6 | <|skeleton|>
class TestRootPower:
def test_ReturnsNthRoot_Existent(self):
"""Test ReturnsNthRoot if it exists as an Integer"""
<|body_0|>
def test_ReturnsNthRoot_NonExistent(self):
"""Test ReturnsNthRoot if it exists as an Integer"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestRootPower:
def test_ReturnsNthRoot_Existent(self):
"""Test ReturnsNthRoot if it exists as an Integer"""
x = 9
n = 2
result = ReturnsNthRoot(x, n)
root = 3
self.assertEqual(result, root)
def test_ReturnsNthRoot_NonExistent(self):
"""Test ReturnsN... | the_stack_v2_python_sparse | Chapters/Chapter3/FingerExercises/RootPower/testRootPower.py | ppysjp93/Introduction-to-Computation-and-Programming-Using-Python- | train | 0 | |
681903f274afaab32adb0585cbfa022c82ab5e8e | [
"pk = self.kwargs['pk']\nif self.kwargs['model'] == 'userprofile':\n return Userprofile.objects.get(pk=pk)\nelse:\n return Annotation.objects.get(pk=pk)",
"model = kwargs['model']\nif model == 'userprofile':\n userprofile = self.get_queryset()\n userprofile_serialize = UserprofileSerializer(userprofil... | <|body_start_0|>
pk = self.kwargs['pk']
if self.kwargs['model'] == 'userprofile':
return Userprofile.objects.get(pk=pk)
else:
return Annotation.objects.get(pk=pk)
<|end_body_0|>
<|body_start_1|>
model = kwargs['model']
if model == 'userprofile':
... | Updates or deletes the desired model with the desired updates :request verb: GET, PATCH, DELETE :endpoint : http://localhost:8000/model/object_change/pk :parameter : The class that is used to generate the viewsets :return : status 201, the updated model | ObjectChange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectChange:
"""Updates or deletes the desired model with the desired updates :request verb: GET, PATCH, DELETE :endpoint : http://localhost:8000/model/object_change/pk :parameter : The class that is used to generate the viewsets :return : status 201, the updated model"""
def get_queryset(s... | stack_v2_sparse_classes_75kplus_train_073150 | 24,034 | no_license | [
{
"docstring": "Method to get the selected object from the correct model objects :return: the object(through pk) of the desired model",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Overrides the default functionality to manage different models :param request: ... | 4 | stack_v2_sparse_classes_30k_train_021542 | Implement the Python class `ObjectChange` described below.
Class description:
Updates or deletes the desired model with the desired updates :request verb: GET, PATCH, DELETE :endpoint : http://localhost:8000/model/object_change/pk :parameter : The class that is used to generate the viewsets :return : status 201, the u... | Implement the Python class `ObjectChange` described below.
Class description:
Updates or deletes the desired model with the desired updates :request verb: GET, PATCH, DELETE :endpoint : http://localhost:8000/model/object_change/pk :parameter : The class that is used to generate the viewsets :return : status 201, the u... | a80e288af21eddc6d64d0079d7e17708b2c365fb | <|skeleton|>
class ObjectChange:
"""Updates or deletes the desired model with the desired updates :request verb: GET, PATCH, DELETE :endpoint : http://localhost:8000/model/object_change/pk :parameter : The class that is used to generate the viewsets :return : status 201, the updated model"""
def get_queryset(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObjectChange:
"""Updates or deletes the desired model with the desired updates :request verb: GET, PATCH, DELETE :endpoint : http://localhost:8000/model/object_change/pk :parameter : The class that is used to generate the viewsets :return : status 201, the updated model"""
def get_queryset(self):
... | the_stack_v2_python_sparse | userprofile/views.py | Errrnesto/MapSuite | train | 0 |
c053bf43c5e6d659a1a42a45b2352e74fd4e1fb7 | [
"args = parser.parse_args()\nif request.query_string:\n abort(400)\npost_data = request.get_json()\nif post_data.has_key('creator_id') and post_data.has_key('target1_id') and post_data.has_key('target2_id'):\n creator_id = post_data.get('creator_id')\n target1_id = post_data.get('target1_id')\n target2_... | <|body_start_0|>
args = parser.parse_args()
if request.query_string:
abort(400)
post_data = request.get_json()
if post_data.has_key('creator_id') and post_data.has_key('target1_id') and post_data.has_key('target2_id'):
creator_id = post_data.get('creator_id')
... | Matches | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matches:
def post(self):
"""Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_id 'target2_id' = target2_id } } Response: HTTP 200 OK { 'status': 'success', 'data': { 'match_id... | stack_v2_sparse_classes_75kplus_train_073151 | 6,658 | no_license | [
{
"docstring": "Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_id 'target2_id' = target2_id } } Response: HTTP 200 OK { 'status': 'success', 'data': { 'match_id': match_id } }",
"name": "post"... | 2 | stack_v2_sparse_classes_30k_train_014334 | Implement the Python class `Matches` described below.
Class description:
Implement the Matches class.
Method signatures and docstrings:
- def post(self): Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_i... | Implement the Python class `Matches` described below.
Class description:
Implement the Matches class.
Method signatures and docstrings:
- def post(self): Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_i... | 6998dd53493e463c487f4dfb2a637dbcfe25593d | <|skeleton|>
class Matches:
def post(self):
"""Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_id 'target2_id' = target2_id } } Response: HTTP 200 OK { 'status': 'success', 'data': { 'match_id... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Matches:
def post(self):
"""Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_id 'target2_id' = target2_id } } Response: HTTP 200 OK { 'status': 'success', 'data': { 'match_id': match_id } ... | the_stack_v2_python_sparse | app/mod_api/resources/matches.py | I-C-Karakozis/HackPrinceton2017_Matchr | train | 1 | |
b8a25f273a443393eb9bd26b32bdfd435d286574 | [
"super(GCSToSFTPOperator, self).__init__(**kwargs)\nself._gcs_hook = gcs_hook\nself._gcs_bucket = gcs_bucket\nself._gcs_filename = gcs_filename\nself._ssh_hook = ssh_hook\nself._sftp_destination_path = sftp_destination_path\nself._header = header",
"file_data = self._gcs_hook.download(self._gcs_bucket, self._gcs_... | <|body_start_0|>
super(GCSToSFTPOperator, self).__init__(**kwargs)
self._gcs_hook = gcs_hook
self._gcs_bucket = gcs_bucket
self._gcs_filename = gcs_filename
self._ssh_hook = ssh_hook
self._sftp_destination_path = sftp_destination_path
self._header = header
<|end_b... | Operator to upload a GCS file to an sFTP location. | GCSToSFTPOperator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCSToSFTPOperator:
"""Operator to upload a GCS file to an sFTP location."""
def __init__(self, gcs_hook, ssh_hook, gcs_bucket, gcs_filename, sftp_destination_path, header=None, **kwargs):
"""Constructor. Args: gcs_hook: GCS Hook for connecting to Google Cloud Storage. ssh_hook: sFTP ... | stack_v2_sparse_classes_75kplus_train_073152 | 2,720 | permissive | [
{
"docstring": "Constructor. Args: gcs_hook: GCS Hook for connecting to Google Cloud Storage. ssh_hook: sFTP Hook for connecting to sFTP server. gcs_bucket: GCS bucket where source file is stored. gcs_filename: File name in GCS of source file. sftp_destination_path: Destination path in the sFTP server. header: ... | 2 | stack_v2_sparse_classes_30k_train_044967 | Implement the Python class `GCSToSFTPOperator` described below.
Class description:
Operator to upload a GCS file to an sFTP location.
Method signatures and docstrings:
- def __init__(self, gcs_hook, ssh_hook, gcs_bucket, gcs_filename, sftp_destination_path, header=None, **kwargs): Constructor. Args: gcs_hook: GCS Hoo... | Implement the Python class `GCSToSFTPOperator` described below.
Class description:
Operator to upload a GCS file to an sFTP location.
Method signatures and docstrings:
- def __init__(self, gcs_hook, ssh_hook, gcs_bucket, gcs_filename, sftp_destination_path, header=None, **kwargs): Constructor. Args: gcs_hook: GCS Hoo... | 21cdfef70a8acb8814d17575f458c53285f7f51a | <|skeleton|>
class GCSToSFTPOperator:
"""Operator to upload a GCS file to an sFTP location."""
def __init__(self, gcs_hook, ssh_hook, gcs_bucket, gcs_filename, sftp_destination_path, header=None, **kwargs):
"""Constructor. Args: gcs_hook: GCS Hook for connecting to Google Cloud Storage. ssh_hook: sFTP ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GCSToSFTPOperator:
"""Operator to upload a GCS file to an sFTP location."""
def __init__(self, gcs_hook, ssh_hook, gcs_bucket, gcs_filename, sftp_destination_path, header=None, **kwargs):
"""Constructor. Args: gcs_hook: GCS Hook for connecting to Google Cloud Storage. ssh_hook: sFTP Hook for conn... | the_stack_v2_python_sparse | composer/gcs_to_sftp_operator.py | NeoTim/mozart | train | 0 |
57c970e2a82aaaaff91bf95c5fd01279f12e18fe | [
"res = []\nfor each in A:\n tem = []\n for each_char in each[::-1]:\n if each_char == 1:\n tem.append(0)\n else:\n tem.append(1)\n res.append(tem)\nreturn res",
"res = []\nfor each in A:\n tem = []\n for each_char in each[::-1]:\n tem.append(1 - each_char)... | <|body_start_0|>
res = []
for each in A:
tem = []
for each_char in each[::-1]:
if each_char == 1:
tem.append(0)
else:
tem.append(1)
res.append(tem)
return res
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flipAndInvertImage(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def flipAndInvertImage2(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = ... | stack_v2_sparse_classes_75kplus_train_073153 | 804 | no_license | [
{
"docstring": ":type A: List[List[int]] :rtype: List[List[int]]",
"name": "flipAndInvertImage",
"signature": "def flipAndInvertImage(self, A)"
},
{
"docstring": ":type A: List[List[int]] :rtype: List[List[int]]",
"name": "flipAndInvertImage2",
"signature": "def flipAndInvertImage2(self,... | 2 | stack_v2_sparse_classes_30k_train_002960 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flipAndInvertImage(self, A): :type A: List[List[int]] :rtype: List[List[int]]
- def flipAndInvertImage2(self, A): :type A: List[List[int]] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flipAndInvertImage(self, A): :type A: List[List[int]] :rtype: List[List[int]]
- def flipAndInvertImage2(self, A): :type A: List[List[int]] :rtype: List[List[int]]
<|skeleton... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def flipAndInvertImage(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def flipAndInvertImage2(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def flipAndInvertImage(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
res = []
for each in A:
tem = []
for each_char in each[::-1]:
if each_char == 1:
tem.append(0)
else:
... | the_stack_v2_python_sparse | flipAndInvertImage.py | NeilWangziyu/Leetcode_py | train | 2 | |
4422acca830f4a9655593caba658adf316d3a8c7 | [
"image_file = StringIO.StringIO(temp_image.read())\nimage = Image.open(image_file)\nreturn image",
"try:\n for orientation in ExifTags.TAGS.keys():\n if ExifTags.TAGS[orientation] == 'Orientation':\n exif = dict(image._getexif().items())\n if exif[orientation] == 3:\n ... | <|body_start_0|>
image_file = StringIO.StringIO(temp_image.read())
image = Image.open(image_file)
return image
<|end_body_0|>
<|body_start_1|>
try:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
ex... | Assisting methods to help with file upload processes. | PhotoUpload | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhotoUpload:
"""Assisting methods to help with file upload processes."""
def open_image(temp_image):
"""Open a this image using StringIO."""
<|body_0|>
def check_image_orientation(image):
"""Digital photo devices attach EXIF data to an image when a photo is taken... | stack_v2_sparse_classes_75kplus_train_073154 | 3,690 | no_license | [
{
"docstring": "Open a this image using StringIO.",
"name": "open_image",
"signature": "def open_image(temp_image)"
},
{
"docstring": "Digital photo devices attach EXIF data to an image when a photo is taken. In order to display an image appropriately without it getting rotated, we need to check... | 6 | stack_v2_sparse_classes_30k_train_015084 | Implement the Python class `PhotoUpload` described below.
Class description:
Assisting methods to help with file upload processes.
Method signatures and docstrings:
- def open_image(temp_image): Open a this image using StringIO.
- def check_image_orientation(image): Digital photo devices attach EXIF data to an image ... | Implement the Python class `PhotoUpload` described below.
Class description:
Assisting methods to help with file upload processes.
Method signatures and docstrings:
- def open_image(temp_image): Open a this image using StringIO.
- def check_image_orientation(image): Digital photo devices attach EXIF data to an image ... | a780ccdc3350d4b5c7990c65d1af8d71060c62cc | <|skeleton|>
class PhotoUpload:
"""Assisting methods to help with file upload processes."""
def open_image(temp_image):
"""Open a this image using StringIO."""
<|body_0|>
def check_image_orientation(image):
"""Digital photo devices attach EXIF data to an image when a photo is taken... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhotoUpload:
"""Assisting methods to help with file upload processes."""
def open_image(temp_image):
"""Open a this image using StringIO."""
image_file = StringIO.StringIO(temp_image.read())
image = Image.open(image_file)
return image
def check_image_orientation(image... | the_stack_v2_python_sparse | common/service/photo_upload.py | wcirillo/ten | train | 0 |
c9e7e3d5e8f606eb66e7deb9bbb78af1be35a30a | [
"super().__init__()\nself.input_table = input_table\nself.output_gmt = output_gmt\nself.name_col = name_col\nself.group_col = group_col\nself.descriptor = descriptor\nif self.input_table.endswith('.csv'):\n self.table = rc.ReadCsv(self.input_table, use_cols=[self.name_col, self.group_col]).get_data()\nelif self.... | <|body_start_0|>
super().__init__()
self.input_table = input_table
self.output_gmt = output_gmt
self.name_col = name_col
self.group_col = group_col
self.descriptor = descriptor
if self.input_table.endswith('.csv'):
self.table = rc.ReadCsv(self.input_ta... | This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs | GroupGmt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupGmt:
"""This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs"""
def __init__(self, input_table, outpu... | stack_v2_sparse_classes_75kplus_train_073155 | 13,420 | permissive | [
{
"docstring": ":param input_table: str, the filename path :param output_gmt: str, the output gmt file path :param name_col: str, the name of the column to write the genes :param group_col: str, the name of the column to group :param descriptor: str, the descriptor to use",
"name": "__init__",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_005856 | Implement the Python class `GroupGmt` described below.
Class description:
This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs
Metho... | Implement the Python class `GroupGmt` described below.
Class description:
This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs
Metho... | 62307f90af4c72c50aca4cbf8c61e924e69467be | <|skeleton|>
class GroupGmt:
"""This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs"""
def __init__(self, input_table, outpu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupGmt:
"""This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs"""
def __init__(self, input_table, output_gmt, name_c... | the_stack_v2_python_sparse | pygna/converters.py | science4fun/pygna | train | 0 |
d5b28fa0ce9d0f2297d846023c5854c74505707b | [
"super(LeNet, self).__init__()\nself.relu = nn.ReLU()\nself.pool = nn.AvgPool2d(kernel_size=(2, 2), stride=(2, 2))\nself.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=(5, 5), stride=1, padding=0)\nself.conv2 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=(5, 5), stride=1, padding=0)\nself.co... | <|body_start_0|>
super(LeNet, self).__init__()
self.relu = nn.ReLU()
self.pool = nn.AvgPool2d(kernel_size=(2, 2), stride=(2, 2))
self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=(5, 5), stride=1, padding=0)
self.conv2 = nn.Conv2d(in_channels=6, out_channels=16, k... | LeNet implementation. | LeNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeNet:
"""LeNet implementation."""
def __init__(self):
"""Lenet architecture. 1x32x32 -> ((5x5), s=1, p=0 -> avg pool s=2, p=0 -> (5x5), s=1,p=0) x2 -> Conv 5x5 to 120 channels -> linear 84 -> linear 10"""
<|body_0|>
def forward(self, x):
"""Forward method."""
... | stack_v2_sparse_classes_75kplus_train_073156 | 1,599 | no_license | [
{
"docstring": "Lenet architecture. 1x32x32 -> ((5x5), s=1, p=0 -> avg pool s=2, p=0 -> (5x5), s=1,p=0) x2 -> Conv 5x5 to 120 channels -> linear 84 -> linear 10",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Forward method.",
"name": "forward",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_039356 | Implement the Python class `LeNet` described below.
Class description:
LeNet implementation.
Method signatures and docstrings:
- def __init__(self): Lenet architecture. 1x32x32 -> ((5x5), s=1, p=0 -> avg pool s=2, p=0 -> (5x5), s=1,p=0) x2 -> Conv 5x5 to 120 channels -> linear 84 -> linear 10
- def forward(self, x): ... | Implement the Python class `LeNet` described below.
Class description:
LeNet implementation.
Method signatures and docstrings:
- def __init__(self): Lenet architecture. 1x32x32 -> ((5x5), s=1, p=0 -> avg pool s=2, p=0 -> (5x5), s=1,p=0) x2 -> Conv 5x5 to 120 channels -> linear 84 -> linear 10
- def forward(self, x): ... | c43aa363f7ad5c5fd3979119cef6761e93ffdd48 | <|skeleton|>
class LeNet:
"""LeNet implementation."""
def __init__(self):
"""Lenet architecture. 1x32x32 -> ((5x5), s=1, p=0 -> avg pool s=2, p=0 -> (5x5), s=1,p=0) x2 -> Conv 5x5 to 120 channels -> linear 84 -> linear 10"""
<|body_0|>
def forward(self, x):
"""Forward method."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LeNet:
"""LeNet implementation."""
def __init__(self):
"""Lenet architecture. 1x32x32 -> ((5x5), s=1, p=0 -> avg pool s=2, p=0 -> (5x5), s=1,p=0) x2 -> Conv 5x5 to 120 channels -> linear 84 -> linear 10"""
super(LeNet, self).__init__()
self.relu = nn.ReLU()
self.pool = nn.... | the_stack_v2_python_sparse | LeNet_1998/driver.py | nsbits/ML_Papers | train | 0 |
af41a3efdab4c32e5ff1e3a692541ca87f1a6ba9 | [
"if 'xd' not in kwargs:\n kwargs['xd'] = 20\nsuper(DownUpTrend, self)._init_self(**kwargs)\nself.past_factor = kwargs.pop('past_factor', 4)\nself.down_deg_threshold = kwargs.pop('down_deg_threshold', -3)",
"long_kl = self.past_today_kl(today, self.past_factor * self.xd)\ntl_long = TLine(long_kl.close, 'long')\... | <|body_start_0|>
if 'xd' not in kwargs:
kwargs['xd'] = 20
super(DownUpTrend, self)._init_self(**kwargs)
self.past_factor = kwargs.pop('past_factor', 4)
self.down_deg_threshold = kwargs.pop('down_deg_threshold', -3)
<|end_body_0|>
<|body_start_1|>
long_kl = self.past_... | 示例长线下跌中寻找短线突破反转买入择时因子,混入BuyCallMixin,即向上突破触发买入event | DownUpTrend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownUpTrend:
"""示例长线下跌中寻找短线突破反转买入择时因子,混入BuyCallMixin,即向上突破触发买入event"""
def _init_self(self, **kwargs):
"""kwargs中可以包含xd: 比如20,30,40天...突破,默认20 kwargs中可以包含past_factor: 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4 kwargs中可以包含down_deg_threshold: 代表判断下跌趋势拟合角度阀值,即长线拟合角度值多少决策... | stack_v2_sparse_classes_75kplus_train_073157 | 9,460 | no_license | [
{
"docstring": "kwargs中可以包含xd: 比如20,30,40天...突破,默认20 kwargs中可以包含past_factor: 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4 kwargs中可以包含down_deg_threshold: 代表判断下跌趋势拟合角度阀值,即长线拟合角度值多少决策为下跌,默认-3",
"name": "_init_self",
"signature": "def _init_self(self, **kwargs)"
},
{
"docstring": "长线下跌... | 2 | stack_v2_sparse_classes_30k_train_008804 | Implement the Python class `DownUpTrend` described below.
Class description:
示例长线下跌中寻找短线突破反转买入择时因子,混入BuyCallMixin,即向上突破触发买入event
Method signatures and docstrings:
- def _init_self(self, **kwargs): kwargs中可以包含xd: 比如20,30,40天...突破,默认20 kwargs中可以包含past_factor: 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4 k... | Implement the Python class `DownUpTrend` described below.
Class description:
示例长线下跌中寻找短线突破反转买入择时因子,混入BuyCallMixin,即向上突破触发买入event
Method signatures and docstrings:
- def _init_self(self, **kwargs): kwargs中可以包含xd: 比如20,30,40天...突破,默认20 kwargs中可以包含past_factor: 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4 k... | 822d97afd0ed0987723b574c22d15cc1325c36ed | <|skeleton|>
class DownUpTrend:
"""示例长线下跌中寻找短线突破反转买入择时因子,混入BuyCallMixin,即向上突破触发买入event"""
def _init_self(self, **kwargs):
"""kwargs中可以包含xd: 比如20,30,40天...突破,默认20 kwargs中可以包含past_factor: 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4 kwargs中可以包含down_deg_threshold: 代表判断下跌趋势拟合角度阀值,即长线拟合角度值多少决策... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DownUpTrend:
"""示例长线下跌中寻找短线突破反转买入择时因子,混入BuyCallMixin,即向上突破触发买入event"""
def _init_self(self, **kwargs):
"""kwargs中可以包含xd: 比如20,30,40天...突破,默认20 kwargs中可以包含past_factor: 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4 kwargs中可以包含down_deg_threshold: 代表判断下跌趋势拟合角度阀值,即长线拟合角度值多少决策为下跌,默认-3"""
... | the_stack_v2_python_sparse | common/FactorBuy/FactorBuyTrend.py | xiaoshitoucoding/Quantitative_Trading | train | 0 |
a7c8d15e32fde66bf2e3ae7aee7ccc2f750d0a0c | [
"serializer = MoveSecretLinkSerializer(data=request.data, context=self.get_serializer_context())\nif not serializer.is_valid():\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\nlink_id = serializer.validated_data['link_id']\nnew_parent_share_id = serializer.validated_data['new_parent_sha... | <|body_start_0|>
serializer = MoveSecretLinkSerializer(data=request.data, context=self.get_serializer_context())
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
link_id = serializer.validated_data['link_id']
new_parent_shar... | Secret Link View: Accepted Methods: POST, DELETE | SecretLinkView | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecretLinkView:
"""Secret Link View: Accepted Methods: POST, DELETE"""
def post(self, request, *args, **kwargs):
"""Move Secret_Link obj Necessary Rights: - write on old_parent_share - write on old_datastore - write on new_parent_share - write on new_datastore :param request: :param ... | stack_v2_sparse_classes_75kplus_train_073158 | 3,495 | permissive | [
{
"docstring": "Move Secret_Link obj Necessary Rights: - write on old_parent_share - write on old_datastore - write on new_parent_share - write on new_datastore :param request: :param uuid: :param args: :param kwargs: :return: 200 / 400",
"name": "post",
"signature": "def post(self, request, *args, **kw... | 2 | stack_v2_sparse_classes_30k_train_041800 | Implement the Python class `SecretLinkView` described below.
Class description:
Secret Link View: Accepted Methods: POST, DELETE
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Move Secret_Link obj Necessary Rights: - write on old_parent_share - write on old_datastore - write on new_pare... | Implement the Python class `SecretLinkView` described below.
Class description:
Secret Link View: Accepted Methods: POST, DELETE
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Move Secret_Link obj Necessary Rights: - write on old_parent_share - write on old_datastore - write on new_pare... | 8936aa8ccdee8b9617ef7d894cb9a9a9f6f473cf | <|skeleton|>
class SecretLinkView:
"""Secret Link View: Accepted Methods: POST, DELETE"""
def post(self, request, *args, **kwargs):
"""Move Secret_Link obj Necessary Rights: - write on old_parent_share - write on old_datastore - write on new_parent_share - write on new_datastore :param request: :param ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SecretLinkView:
"""Secret Link View: Accepted Methods: POST, DELETE"""
def post(self, request, *args, **kwargs):
"""Move Secret_Link obj Necessary Rights: - write on old_parent_share - write on old_datastore - write on new_parent_share - write on new_datastore :param request: :param uuid: :param ... | the_stack_v2_python_sparse | psono/restapi/views/secret_link.py | psono/psono-server | train | 76 |
13d9a093bbb7a6e16868010e58ce4bf331145e70 | [
"self.addr = (host_ip, port)\nself.UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nself.send_message_queue = send_message_queue\nwarnings.warn(DeprecationWarning('Use TCP instead'))",
"while True:\n message = str(self.send_message_queue.get())\n self.UDPSock.sendto(message, self.addr)"
] | <|body_start_0|>
self.addr = (host_ip, port)
self.UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.send_message_queue = send_message_queue
warnings.warn(DeprecationWarning('Use TCP instead'))
<|end_body_0|>
<|body_start_1|>
while True:
message = str(se... | Send | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Send:
def __init__(self, host_ip, port, send_message_queue):
"""Sends messages to the specified host and port for computers on the same network. :param host_ip: (string) Set to the ip address (host) of the target computer (example: 173.250.XXX.XX) :param port: (int) Set to desired port. ... | stack_v2_sparse_classes_75kplus_train_073159 | 1,874 | no_license | [
{
"docstring": "Sends messages to the specified host and port for computers on the same network. :param host_ip: (string) Set to the ip address (host) of the target computer (example: 173.250.XXX.XX) :param port: (int) Set to desired port. Only one Send object can be opened on a given port. Example: 13000 :para... | 2 | stack_v2_sparse_classes_30k_test_001497 | Implement the Python class `Send` described below.
Class description:
Implement the Send class.
Method signatures and docstrings:
- def __init__(self, host_ip, port, send_message_queue): Sends messages to the specified host and port for computers on the same network. :param host_ip: (string) Set to the ip address (ho... | Implement the Python class `Send` described below.
Class description:
Implement the Send class.
Method signatures and docstrings:
- def __init__(self, host_ip, port, send_message_queue): Sends messages to the specified host and port for computers on the same network. :param host_ip: (string) Set to the ip address (ho... | 4eec0ea2eb3dc287d475f9ab4e0b75259c51b309 | <|skeleton|>
class Send:
def __init__(self, host_ip, port, send_message_queue):
"""Sends messages to the specified host and port for computers on the same network. :param host_ip: (string) Set to the ip address (host) of the target computer (example: 173.250.XXX.XX) :param port: (int) Set to desired port. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Send:
def __init__(self, host_ip, port, send_message_queue):
"""Sends messages to the specified host and port for computers on the same network. :param host_ip: (string) Set to the ip address (host) of the target computer (example: 173.250.XXX.XX) :param port: (int) Set to desired port. Only one Send ... | the_stack_v2_python_sparse | Communications/DepreciatedCommunications/Send.py | heathzhang35/CCDLUtil | train | 0 | |
695c41c7f778557a88479bfc71625ef260bbb207 | [
"jsonconfig.JsonConfig.__init__(self)\nself.hostname = b'esp%05d' % Hostname.getNumber()\nself.activated = True\nself.fallback = True\nself.default = b''",
"result = '%s:\\n' % self.__class__.__name__\nresult += ' Activated :%s\\n' % useful.tostrings(self.activated)\nresult = ' Hostname :%s\\n' % useful.to... | <|body_start_0|>
jsonconfig.JsonConfig.__init__(self)
self.hostname = b'esp%05d' % Hostname.getNumber()
self.activated = True
self.fallback = True
self.default = b''
<|end_body_0|>
<|body_start_1|>
result = '%s:\n' % self.__class__.__name__
result += ' Activate... | Wifi station configuration class | StationConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __repr__(self):
"""Display the content of wifi station"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
jsonconfig.JsonConfig.__init__(self... | stack_v2_sparse_classes_75kplus_train_073160 | 8,871 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display the content of wifi station",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002667 | Implement the Python class `StationConfig` described below.
Class description:
Wifi station configuration class
Method signatures and docstrings:
- def __init__(self): Constructor
- def __repr__(self): Display the content of wifi station | Implement the Python class `StationConfig` described below.
Class description:
Wifi station configuration class
Method signatures and docstrings:
- def __init__(self): Constructor
- def __repr__(self): Display the content of wifi station
<|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
... | d86814625a7cd2f7e5fa01b8e1652efc811cef3a | <|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __repr__(self):
"""Display the content of wifi station"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
jsonconfig.JsonConfig.__init__(self)
self.hostname = b'esp%05d' % Hostname.getNumber()
self.activated = True
self.fallback = True
self.default = b''
def __repr_... | the_stack_v2_python_sparse | modules/lib/wifi/station.py | antiquefu/pycameresp | train | 0 |
62cadba52319831c7d29cf0e345dad1244cba96d | [
"client = get_client_by_request(request)\ninfo = client.cmsi.get_msg_type()\nalls = info['data']\nfor app in alls:\n print(app['is_active'])\n print(app['label'])\n print(app['type'])\n print('*' * 30)\nreturn JsonResponse(info)",
"receiver = request.GET.get('receiver')\ntitle = request.GET.get('title... | <|body_start_0|>
client = get_client_by_request(request)
info = client.cmsi.get_msg_type()
alls = info['data']
for app in alls:
print(app['is_active'])
print(app['label'])
print(app['type'])
print('*' * 30)
return JsonResponse(info)... | PaasCmsi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaasCmsi:
def get_msg_type(cls, request):
"""查询消息发送类型"""
<|body_0|>
def send_mail(cls, request):
"""发送邮件"""
<|body_1|>
def send_sms(cls, request):
"""发送短信"""
<|body_2|>
def send_weixin(cls, request):
"""发送微信"""
<|body... | stack_v2_sparse_classes_75kplus_train_073161 | 5,818 | no_license | [
{
"docstring": "查询消息发送类型",
"name": "get_msg_type",
"signature": "def get_msg_type(cls, request)"
},
{
"docstring": "发送邮件",
"name": "send_mail",
"signature": "def send_mail(cls, request)"
},
{
"docstring": "发送短信",
"name": "send_sms",
"signature": "def send_sms(cls, request... | 4 | stack_v2_sparse_classes_30k_train_012795 | Implement the Python class `PaasCmsi` described below.
Class description:
Implement the PaasCmsi class.
Method signatures and docstrings:
- def get_msg_type(cls, request): 查询消息发送类型
- def send_mail(cls, request): 发送邮件
- def send_sms(cls, request): 发送短信
- def send_weixin(cls, request): 发送微信 | Implement the Python class `PaasCmsi` described below.
Class description:
Implement the PaasCmsi class.
Method signatures and docstrings:
- def get_msg_type(cls, request): 查询消息发送类型
- def send_mail(cls, request): 发送邮件
- def send_sms(cls, request): 发送短信
- def send_weixin(cls, request): 发送微信
<|skeleton|>
class PaasCmsi... | 1911aadda75fc25c78f6fb37852111deb50052c0 | <|skeleton|>
class PaasCmsi:
def get_msg_type(cls, request):
"""查询消息发送类型"""
<|body_0|>
def send_mail(cls, request):
"""发送邮件"""
<|body_1|>
def send_sms(cls, request):
"""发送短信"""
<|body_2|>
def send_weixin(cls, request):
"""发送微信"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PaasCmsi:
def get_msg_type(cls, request):
"""查询消息发送类型"""
client = get_client_by_request(request)
info = client.cmsi.get_msg_type()
alls = info['data']
for app in alls:
print(app['is_active'])
print(app['label'])
print(app['type'])
... | the_stack_v2_python_sparse | BK/exam_api_test/home_application/api_views.py | Louis-King123/projects | train | 0 | |
6dab7b5d515022427238d113de4e9a776dddab5e | [
"super(AnalysisReport, self).__init__()\nself.analysis_counter = None\nself.event_filter = None\nself.plugin_name = plugin_name\nself.text = text\nself.time_compiled = None",
"dictionary = {}\nfor attribute_name, attribute_value in self.GetAttributes():\n if attribute_value is None:\n continue\n dict... | <|body_start_0|>
super(AnalysisReport, self).__init__()
self.analysis_counter = None
self.event_filter = None
self.plugin_name = plugin_name
self.text = text
self.time_compiled = None
<|end_body_0|>
<|body_start_1|>
dictionary = {}
for attribute_name, att... | Analysis report attribute container. Attributes: analysis_counter (collections.Counter): counter of analysis results, for example number of events analyzed and tagged. event_filter (str): event filter expression that was used when the analysis plugin was run. plugin_name (str): name of the analysis plugin that generate... | AnalysisReport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisReport:
"""Analysis report attribute container. Attributes: analysis_counter (collections.Counter): counter of analysis results, for example number of events analyzed and tagged. event_filter (str): event filter expression that was used when the analysis plugin was run. plugin_name (str):... | stack_v2_sparse_classes_75kplus_train_073162 | 1,671 | permissive | [
{
"docstring": "Initializes the analysis report. Args: plugin_name (Optional[str]): name of the analysis plugin that generated the report. text (Optional[str]): report text.",
"name": "__init__",
"signature": "def __init__(self, plugin_name=None, text=None)"
},
{
"docstring": "Copies the attribu... | 2 | null | Implement the Python class `AnalysisReport` described below.
Class description:
Analysis report attribute container. Attributes: analysis_counter (collections.Counter): counter of analysis results, for example number of events analyzed and tagged. event_filter (str): event filter expression that was used when the anal... | Implement the Python class `AnalysisReport` described below.
Class description:
Analysis report attribute container. Attributes: analysis_counter (collections.Counter): counter of analysis results, for example number of events analyzed and tagged. event_filter (str): event filter expression that was used when the anal... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class AnalysisReport:
"""Analysis report attribute container. Attributes: analysis_counter (collections.Counter): counter of analysis results, for example number of events analyzed and tagged. event_filter (str): event filter expression that was used when the analysis plugin was run. plugin_name (str):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnalysisReport:
"""Analysis report attribute container. Attributes: analysis_counter (collections.Counter): counter of analysis results, for example number of events analyzed and tagged. event_filter (str): event filter expression that was used when the analysis plugin was run. plugin_name (str): name of the ... | the_stack_v2_python_sparse | plaso/containers/reports.py | log2timeline/plaso | train | 1,506 |
f068a05ac79b3e12972bc2787e57ff4255d0ea92 | [
"self.mm = slt()\nself.urla = ParamsTest().selenium_url_sempreprod()\nself.url = f'{self.urla}scp/inventory/optlist'",
"driver = self.mm.sem_login()\nsleep(2)\ndriver.get(self.url)\nreturn driver"
] | <|body_start_0|>
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url = f'{self.urla}scp/inventory/optlist'
<|end_body_0|>
<|body_start_1|>
driver = self.mm.sem_login()
sleep(2)
driver.get(self.url)
return driver
<|end_body_1|>
| SemOptList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
<|body_0|>
def optlist(self):
"""定义driver"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url... | stack_v2_sparse_classes_75kplus_train_073163 | 850 | no_license | [
{
"docstring": "运营管理系统 供应链管理 库存管理 ----- 拣货单页面",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "定义driver",
"name": "optlist",
"signature": "def optlist(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045652 | Implement the Python class `SemOptList` described below.
Class description:
Implement the SemOptList class.
Method signatures and docstrings:
- def __init__(self): 运营管理系统 供应链管理 库存管理 ----- 拣货单页面
- def optlist(self): 定义driver | Implement the Python class `SemOptList` described below.
Class description:
Implement the SemOptList class.
Method signatures and docstrings:
- def __init__(self): 运营管理系统 供应链管理 库存管理 ----- 拣货单页面
- def optlist(self): 定义driver
<|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货... | 97f9e4f286d017ee39ceeae0c730f1c4971499e7 | <|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
<|body_0|>
def optlist(self):
"""定义driver"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url = f'{self.urla}scp/inventory/optlist'
def optlist(self):
"""定义driver"""
driver = self.mm.sem_login()
slee... | the_stack_v2_python_sparse | setting/optlist/optlist.py | qq183727918/selenium_ui | train | 0 | |
c8a10c69f249277b8adbb56ab23bf60cb4df09be | [
"def traverse(node, cur, k):\n if not node:\n return\n self.cache.add(node.val)\n traverse(node.left, cur, k)\n traverse(node.right, cur, k)\nself.cache = set()\ntraverse(root, 0, set())\nfor x in self.cache:\n req = k - x\n if req in self.cache and x != req:\n return True\nreturn Fa... | <|body_start_0|>
def traverse(node, cur, k):
if not node:
return
self.cache.add(node.val)
traverse(node.left, cur, k)
traverse(node.right, cur, k)
self.cache = set()
traverse(root, 0, set())
for x in self.cache:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTarget(self, root, k):
"""Purpose: Returns bool. indicating whether there exist two elements in a BST such that their sum is equal to the given target. Time complexity: O(n), where n is no. of nodes in BST. Space complexity: O(n), same as above."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_073164 | 1,585 | no_license | [
{
"docstring": "Purpose: Returns bool. indicating whether there exist two elements in a BST such that their sum is equal to the given target. Time complexity: O(n), where n is no. of nodes in BST. Space complexity: O(n), same as above.",
"name": "findTarget",
"signature": "def findTarget(self, root, k)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget(self, root, k): Purpose: Returns bool. indicating whether there exist two elements in a BST such that their sum is equal to the given target. Time complexity: O(n)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget(self, root, k): Purpose: Returns bool. indicating whether there exist two elements in a BST such that their sum is equal to the given target. Time complexity: O(n)... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def findTarget(self, root, k):
"""Purpose: Returns bool. indicating whether there exist two elements in a BST such that their sum is equal to the given target. Time complexity: O(n), where n is no. of nodes in BST. Space complexity: O(n), same as above."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findTarget(self, root, k):
"""Purpose: Returns bool. indicating whether there exist two elements in a BST such that their sum is equal to the given target. Time complexity: O(n), where n is no. of nodes in BST. Space complexity: O(n), same as above."""
def traverse(node, cur, k):... | the_stack_v2_python_sparse | twoSumBinSearchTree.py | tashakim/puzzles_python | train | 8 | |
c4834fa7bf9f3d377884416f0a8965d2cf9724fe | [
"self.driver = driver\nself.ProjectFilePath = GetProjectFilePath()\nself.Page_object_data_file = open(self.ProjectFilePath + '\\\\Page_object\\\\Data\\\\DistributionlineFlowDayCalcResult.yaml')\nself.Page_Data = yaml.load(self.Page_object_data_file)\nself.Page_object_data_file.close()\nself.Data = self.Page_Data['D... | <|body_start_0|>
self.driver = driver
self.ProjectFilePath = GetProjectFilePath()
self.Page_object_data_file = open(self.ProjectFilePath + '\\Page_object\\Data\\DistributionlineFlowDayCalcResult.yaml')
self.Page_Data = yaml.load(self.Page_object_data_file)
self.Page_object_data_f... | DistributionlineFlowDayCalcResult | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistributionlineFlowDayCalcResult:
def __init__(self, driver):
"""潮流精确算法配电线路线损表结果验证"""
<|body_0|>
def DistributionlineFlowDayCalcResult_Fun(self):
"""潮流精确算法配电线路线损表结果验证"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.driver = driver
self... | stack_v2_sparse_classes_75kplus_train_073165 | 3,402 | no_license | [
{
"docstring": "潮流精确算法配电线路线损表结果验证",
"name": "__init__",
"signature": "def __init__(self, driver)"
},
{
"docstring": "潮流精确算法配电线路线损表结果验证",
"name": "DistributionlineFlowDayCalcResult_Fun",
"signature": "def DistributionlineFlowDayCalcResult_Fun(self)"
}
] | 2 | null | Implement the Python class `DistributionlineFlowDayCalcResult` described below.
Class description:
Implement the DistributionlineFlowDayCalcResult class.
Method signatures and docstrings:
- def __init__(self, driver): 潮流精确算法配电线路线损表结果验证
- def DistributionlineFlowDayCalcResult_Fun(self): 潮流精确算法配电线路线损表结果验证 | Implement the Python class `DistributionlineFlowDayCalcResult` described below.
Class description:
Implement the DistributionlineFlowDayCalcResult class.
Method signatures and docstrings:
- def __init__(self, driver): 潮流精确算法配电线路线损表结果验证
- def DistributionlineFlowDayCalcResult_Fun(self): 潮流精确算法配电线路线损表结果验证
<|skeleton|>... | 190796e380df1e28770f73a392ac92f482eb9809 | <|skeleton|>
class DistributionlineFlowDayCalcResult:
def __init__(self, driver):
"""潮流精确算法配电线路线损表结果验证"""
<|body_0|>
def DistributionlineFlowDayCalcResult_Fun(self):
"""潮流精确算法配电线路线损表结果验证"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DistributionlineFlowDayCalcResult:
def __init__(self, driver):
"""潮流精确算法配电线路线损表结果验证"""
self.driver = driver
self.ProjectFilePath = GetProjectFilePath()
self.Page_object_data_file = open(self.ProjectFilePath + '\\Page_object\\Data\\DistributionlineFlowDayCalcResult.yaml')
... | the_stack_v2_python_sparse | Project/Page_object/Page_object/DistributionlineFlowDayCalcResult.py | RainsWang/Python2.7-Selenium | train | 1 | |
6fb2ece6be6ac1a6c283bdf60335d3d224b9075b | [
"for endpoint in ['api-stock-count', 'api-stock-add', 'api-stock-remove']:\n url = reverse(endpoint)\n data = {}\n response = self.doPost(url, data)\n self.assertContains(response, 'must contain list', status_code=status.HTTP_400_BAD_REQUEST)\n data['items'] = [{'no': 'aa'}]\n response = self.doPo... | <|body_start_0|>
for endpoint in ['api-stock-count', 'api-stock-add', 'api-stock-remove']:
url = reverse(endpoint)
data = {}
response = self.doPost(url, data)
self.assertContains(response, 'must contain list', status_code=status.HTTP_400_BAD_REQUEST)
d... | Series of tests for the Stocktake API | StocktakeTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StocktakeTest:
"""Series of tests for the Stocktake API"""
def test_action(self):
"""Test each stocktake action endpoint, for validation"""
<|body_0|>
def test_transfer(self):
"""Test stock transfers"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_073166 | 7,555 | permissive | [
{
"docstring": "Test each stocktake action endpoint, for validation",
"name": "test_action",
"signature": "def test_action(self)"
},
{
"docstring": "Test stock transfers",
"name": "test_transfer",
"signature": "def test_transfer(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027114 | Implement the Python class `StocktakeTest` described below.
Class description:
Series of tests for the Stocktake API
Method signatures and docstrings:
- def test_action(self): Test each stocktake action endpoint, for validation
- def test_transfer(self): Test stock transfers | Implement the Python class `StocktakeTest` described below.
Class description:
Series of tests for the Stocktake API
Method signatures and docstrings:
- def test_action(self): Test each stocktake action endpoint, for validation
- def test_transfer(self): Test stock transfers
<|skeleton|>
class StocktakeTest:
"""... | daab81fa2cf6f3ce1760e31d8cd94951c6dffdd2 | <|skeleton|>
class StocktakeTest:
"""Series of tests for the Stocktake API"""
def test_action(self):
"""Test each stocktake action endpoint, for validation"""
<|body_0|>
def test_transfer(self):
"""Test stock transfers"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StocktakeTest:
"""Series of tests for the Stocktake API"""
def test_action(self):
"""Test each stocktake action endpoint, for validation"""
for endpoint in ['api-stock-count', 'api-stock-add', 'api-stock-remove']:
url = reverse(endpoint)
data = {}
respo... | the_stack_v2_python_sparse | InvenTree/stock/test_api.py | fritzlim/InvenTree | train | 1 |
4f72c82577b47bb8b61cf2924d7eeb2685756292 | [
"article = get_object_or_404(Article, slug=slug)\nif article.author == self.request.user:\n raise PermissionDenied({'error': 'You cannot rate an article you created'})\nif Rating.objects.filter(reader=user.pk).filter(article=article.id).exists():\n raise ParseError({'error': 'You already rated this article'})... | <|body_start_0|>
article = get_object_or_404(Article, slug=slug)
if article.author == self.request.user:
raise PermissionDenied({'error': 'You cannot rate an article you created'})
if Rating.objects.filter(reader=user.pk).filter(article=article.id).exists():
raise ParseEr... | Class to handle the rating of articles | CreateRatingsView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateRatingsView:
"""Class to handle the rating of articles"""
def get_queryset(self, data, user, slug):
"""Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissions in relation to rating an article"""
<|body_0|>... | stack_v2_sparse_classes_75kplus_train_073167 | 17,142 | permissive | [
{
"docstring": "Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissions in relation to rating an article",
"name": "get_queryset",
"signature": "def get_queryset(self, data, user, slug)"
},
{
"docstring": "Method that edit a rating... | 2 | stack_v2_sparse_classes_30k_test_001875 | Implement the Python class `CreateRatingsView` described below.
Class description:
Class to handle the rating of articles
Method signatures and docstrings:
- def get_queryset(self, data, user, slug): Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissio... | Implement the Python class `CreateRatingsView` described below.
Class description:
Class to handle the rating of articles
Method signatures and docstrings:
- def get_queryset(self, data, user, slug): Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissio... | cc84c18f7c222bc69cf4a263a1c2296b6d335c8b | <|skeleton|>
class CreateRatingsView:
"""Class to handle the rating of articles"""
def get_queryset(self, data, user, slug):
"""Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissions in relation to rating an article"""
<|body_0|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateRatingsView:
"""Class to handle the rating of articles"""
def get_queryset(self, data, user, slug):
"""Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissions in relation to rating an article"""
article = get_object_or... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/Ah-backend-guardians | train | 0 |
017e7ef76e4fbea13e57957939f64ce97da18344 | [
"if num == 0:\n from random import randint\n self.num = randint(1, 100)\n self.count = 0\nelse:\n self.num = int(num)\n self.count = int(count)",
"if guess < 1 or guess > 100:\n return (False, '')\nself.count += 1\nif self.num < guess:\n return (False, 'Die gesuchte Zahl ist kleiner als %d.' ... | <|body_start_0|>
if num == 0:
from random import randint
self.num = randint(1, 100)
self.count = 0
else:
self.num = int(num)
self.count = int(count)
<|end_body_0|>
<|body_start_1|>
if guess < 1 or guess > 100:
return (False... | Chooses a random number to guess, maintains counter and compares guesses to random number. | GuessNumberModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuessNumberModel:
"""Chooses a random number to guess, maintains counter and compares guesses to random number."""
def __init__(self, num=0, count=0):
"""Constructs Model from scratch or from known values."""
<|body_0|>
def guess(self, guess):
"""Compares guess a... | stack_v2_sparse_classes_75kplus_train_073168 | 6,929 | no_license | [
{
"docstring": "Constructs Model from scratch or from known values.",
"name": "__init__",
"signature": "def __init__(self, num=0, count=0)"
},
{
"docstring": "Compares guess and stored number to guess. Increases counter. Returns tuple of (Found?, Message to display).",
"name": "guess",
"... | 2 | stack_v2_sparse_classes_30k_train_044966 | Implement the Python class `GuessNumberModel` described below.
Class description:
Chooses a random number to guess, maintains counter and compares guesses to random number.
Method signatures and docstrings:
- def __init__(self, num=0, count=0): Constructs Model from scratch or from known values.
- def guess(self, gue... | Implement the Python class `GuessNumberModel` described below.
Class description:
Chooses a random number to guess, maintains counter and compares guesses to random number.
Method signatures and docstrings:
- def __init__(self, num=0, count=0): Constructs Model from scratch or from known values.
- def guess(self, gue... | 0ba91f4d8e8f036f0d47baa3bd761f9394347e60 | <|skeleton|>
class GuessNumberModel:
"""Chooses a random number to guess, maintains counter and compares guesses to random number."""
def __init__(self, num=0, count=0):
"""Constructs Model from scratch or from known values."""
<|body_0|>
def guess(self, guess):
"""Compares guess a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GuessNumberModel:
"""Chooses a random number to guess, maintains counter and compares guesses to random number."""
def __init__(self, num=0, count=0):
"""Constructs Model from scratch or from known values."""
if num == 0:
from random import randint
self.num = randi... | the_stack_v2_python_sparse | woche06/numberguess.py | tthelen/webtech16-public | train | 7 |
028d80b24867f09946d11df436e66ed39985cbb7 | [
"super(DiceLossV1, self).__init__()\nself.smooth = smooth\nif weight is not None:\n weight = torch.tensor(weight).float()\nself.weight = weight",
"num_classes = logits.shape[1]\ngt = gt.long()\nif num_classes == 1:\n gt_1_hot = torch.eye(num_classes + 1)[gt.squeeze(1)]\n gt_1_hot = gt_1_hot.permute(0, 3,... | <|body_start_0|>
super(DiceLossV1, self).__init__()
self.smooth = smooth
if weight is not None:
weight = torch.tensor(weight).float()
self.weight = weight
<|end_body_0|>
<|body_start_1|>
num_classes = logits.shape[1]
gt = gt.long()
if num_classes == 1... | different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel | DiceLossV1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiceLossV1:
"""different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel"""
def __init__(self, smooth=1e-07, weight=None):
"""Diceloss for segmentation :param smooth: smooth value for fraction... | stack_v2_sparse_classes_75kplus_train_073169 | 12,362 | no_license | [
{
"docstring": "Diceloss for segmentation :param smooth: smooth value for fraction :param weight: class weight",
"name": "__init__",
"signature": "def __init__(self, smooth=1e-07, weight=None)"
},
{
"docstring": "code from https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py Note ... | 2 | stack_v2_sparse_classes_30k_train_040880 | Implement the Python class `DiceLossV1` described below.
Class description:
different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel
Method signatures and docstrings:
- def __init__(self, smooth=1e-07, weight=None): Diceloss ... | Implement the Python class `DiceLossV1` described below.
Class description:
different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel
Method signatures and docstrings:
- def __init__(self, smooth=1e-07, weight=None): Diceloss ... | 8e6f42e3a0cbc87c66b148fb61fcb44af287619e | <|skeleton|>
class DiceLossV1:
"""different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel"""
def __init__(self, smooth=1e-07, weight=None):
"""Diceloss for segmentation :param smooth: smooth value for fraction... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiceLossV1:
"""different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel"""
def __init__(self, smooth=1e-07, weight=None):
"""Diceloss for segmentation :param smooth: smooth value for fraction :param weigh... | the_stack_v2_python_sparse | lib/loss/loss.py | yangsenwxy/colonoscopy_tissue_screen_and_segmentation | train | 0 |
46374d5cf6cdb34273e2da52296245507d921c4a | [
"data: dict = {}\ndata = LogStock.query.all()\ndata_list = []\nfor res in data:\n data = {'id': res.id, 'product_id': res.product_id, 'stock': res.stock, 'remark': data.remark, 'date_created': str(res.date_created)}\n data_list.append(data)\nreturn data_list",
"result: dict = {}\ntry:\n data = LogStock(s... | <|body_start_0|>
data: dict = {}
data = LogStock.query.all()
data_list = []
for res in data:
data = {'id': res.id, 'product_id': res.product_id, 'stock': res.stock, 'remark': data.remark, 'date_created': str(res.date_created)}
data_list.append(data)
return... | LogStockRepository | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogStockRepository:
def findAll() -> dict:
"""Get All LogStock"""
<|body_0|>
def create(stock, product_id, remark) -> dict:
"""Create LogStock"""
<|body_1|>
def findByProductId(product_id) -> dict:
"""Query a LogStock by name"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_073170 | 1,948 | permissive | [
{
"docstring": "Get All LogStock",
"name": "findAll",
"signature": "def findAll() -> dict"
},
{
"docstring": "Create LogStock",
"name": "create",
"signature": "def create(stock, product_id, remark) -> dict"
},
{
"docstring": "Query a LogStock by name",
"name": "findByProductI... | 4 | stack_v2_sparse_classes_30k_train_045656 | Implement the Python class `LogStockRepository` described below.
Class description:
Implement the LogStockRepository class.
Method signatures and docstrings:
- def findAll() -> dict: Get All LogStock
- def create(stock, product_id, remark) -> dict: Create LogStock
- def findByProductId(product_id) -> dict: Query a Lo... | Implement the Python class `LogStockRepository` described below.
Class description:
Implement the LogStockRepository class.
Method signatures and docstrings:
- def findAll() -> dict: Get All LogStock
- def create(stock, product_id, remark) -> dict: Create LogStock
- def findByProductId(product_id) -> dict: Query a Lo... | 09f0a7d4c919e3dfb0a101a55f2f97b5861066fa | <|skeleton|>
class LogStockRepository:
def findAll() -> dict:
"""Get All LogStock"""
<|body_0|>
def create(stock, product_id, remark) -> dict:
"""Create LogStock"""
<|body_1|>
def findByProductId(product_id) -> dict:
"""Query a LogStock by name"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogStockRepository:
def findAll() -> dict:
"""Get All LogStock"""
data: dict = {}
data = LogStock.query.all()
data_list = []
for res in data:
data = {'id': res.id, 'product_id': res.product_id, 'stock': res.stock, 'remark': data.remark, 'date_created': str(r... | the_stack_v2_python_sparse | Task-1/online_store/src/repositories/log_stock.py | gilangkhasani/be-assesment | train | 0 | |
91a58dc135ee6af12f4ad8231f8847e82d95ab21 | [
"parser.description = 'view or modify DF variables as JSON documents. Strings are encoded/decoded from their internal byte representation using latin1 encoding.'\nparser.add_argument('object')\nparser.add_argument('new_data', nargs='?')\nparser.add_argument('--header', default='', required=False, help='write file f... | <|body_start_0|>
parser.description = 'view or modify DF variables as JSON documents. Strings are encoded/decoded from their internal byte representation using latin1 encoding.'
parser.add_argument('object')
parser.add_argument('new_data', nargs='?')
parser.add_argument('--header', defau... | CLI utility for viewing and modifying level variables | Variables | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Variables:
"""CLI utility for viewing and modifying level variables"""
def setup_parser(self, parser: argparse.ArgumentParser) -> None:
"""Read CLI arguments"""
<|body_0|>
def main(self, args) -> int:
"""thumbnail CLI entrypoint"""
<|body_1|>
def upd... | stack_v2_sparse_classes_75kplus_train_073171 | 7,974 | permissive | [
{
"docstring": "Read CLI arguments",
"name": "setup_parser",
"signature": "def setup_parser(self, parser: argparse.ArgumentParser) -> None"
},
{
"docstring": "thumbnail CLI entrypoint",
"name": "main",
"signature": "def main(self, args) -> int"
},
{
"docstring": "Update the varia... | 4 | stack_v2_sparse_classes_30k_train_018569 | Implement the Python class `Variables` described below.
Class description:
CLI utility for viewing and modifying level variables
Method signatures and docstrings:
- def setup_parser(self, parser: argparse.ArgumentParser) -> None: Read CLI arguments
- def main(self, args) -> int: thumbnail CLI entrypoint
- def update_... | Implement the Python class `Variables` described below.
Class description:
CLI utility for viewing and modifying level variables
Method signatures and docstrings:
- def setup_parser(self, parser: argparse.ArgumentParser) -> None: Read CLI arguments
- def main(self, args) -> int: thumbnail CLI entrypoint
- def update_... | fcbcf1a5e2afe70be8a57eca08bb957cff54c420 | <|skeleton|>
class Variables:
"""CLI utility for viewing and modifying level variables"""
def setup_parser(self, parser: argparse.ArgumentParser) -> None:
"""Read CLI arguments"""
<|body_0|>
def main(self, args) -> int:
"""thumbnail CLI entrypoint"""
<|body_1|>
def upd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Variables:
"""CLI utility for viewing and modifying level variables"""
def setup_parser(self, parser: argparse.ArgumentParser) -> None:
"""Read CLI arguments"""
parser.description = 'view or modify DF variables as JSON documents. Strings are encoded/decoded from their internal byte repres... | the_stack_v2_python_sparse | dustmaker/cmd/variables.py | msg555/dustmaker | train | 11 |
ad2fa7fe4ea3b3ed5ffb5242fb5a6655fdd738f1 | [
"nlp = spacy.load('en')\ndoc = nlp(text)\nkeywords = doc.ents\nline_loc()\nhighlight_fore(str(keywords))\nhighlight_fore(other_list_of_keywords)\nline_loc()\nfinal_keywords = []\nfor word in keywords:\n for item in other_list_of_keywords:\n if str(word) in item or item in str(word):\n if len(st... | <|body_start_0|>
nlp = spacy.load('en')
doc = nlp(text)
keywords = doc.ents
line_loc()
highlight_fore(str(keywords))
highlight_fore(other_list_of_keywords)
line_loc()
final_keywords = []
for word in keywords:
for item in other_list_of_k... | This class contains methods to process keyword before it is applied to the api | KeyWordCheck | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyWordCheck:
"""This class contains methods to process keyword before it is applied to the api"""
def eir_intersection_reduction(self, text, other_list_of_keywords):
"""This method uses spacys entity recogintion to recognize entities and applies intersection between the meta keyword... | stack_v2_sparse_classes_75kplus_train_073172 | 5,426 | permissive | [
{
"docstring": "This method uses spacys entity recogintion to recognize entities and applies intersection between the meta keywords to get most relevant keywords it returns a list of possible keywords :type text: string :param string: The text from which the keywords must be extracted :type other_list_of_keywor... | 5 | stack_v2_sparse_classes_30k_train_015213 | Implement the Python class `KeyWordCheck` described below.
Class description:
This class contains methods to process keyword before it is applied to the api
Method signatures and docstrings:
- def eir_intersection_reduction(self, text, other_list_of_keywords): This method uses spacys entity recogintion to recognize e... | Implement the Python class `KeyWordCheck` described below.
Class description:
This class contains methods to process keyword before it is applied to the api
Method signatures and docstrings:
- def eir_intersection_reduction(self, text, other_list_of_keywords): This method uses spacys entity recogintion to recognize e... | 0688c97fc46d2304944935b589c0c61f7d7dbb8c | <|skeleton|>
class KeyWordCheck:
"""This class contains methods to process keyword before it is applied to the api"""
def eir_intersection_reduction(self, text, other_list_of_keywords):
"""This method uses spacys entity recogintion to recognize entities and applies intersection between the meta keyword... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeyWordCheck:
"""This class contains methods to process keyword before it is applied to the api"""
def eir_intersection_reduction(self, text, other_list_of_keywords):
"""This method uses spacys entity recogintion to recognize entities and applies intersection between the meta keywords to get most... | the_stack_v2_python_sparse | fake_news/preprocessor/keywords_check.py | ncrypt96/Fake-news | train | 2 |
ce24f7bcc30664ff103f6ab5a00e3c88a6982157 | [
"api_version = '2019-06-01'\nurl = self.check_dns_name_availability.metadata['url']\npath_format_arguments = {'location': self._serialize.url('location', location, 'str'), 'subscriptionId': self._serialize.url('self.config.subscription_id', self.config.subscription_id, 'str')}\nurl = self._client.format_url(url, **... | <|body_start_0|>
api_version = '2019-06-01'
url = self.check_dns_name_availability.metadata['url']
path_format_arguments = {'location': self._serialize.url('location', location, 'str'), 'subscriptionId': self._serialize.url('self.config.subscription_id', self.config.subscription_id, 'str')}
... | NetworkManagementClientOperationsMixin | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkManagementClientOperationsMixin:
def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config):
"""Checks whether a domain name in the cloudapp.azure.com zone is available for use. :param location: The location of the domain... | stack_v2_sparse_classes_75kplus_train_073173 | 7,118 | permissive | [
{
"docstring": "Checks whether a domain name in the cloudapp.azure.com zone is available for use. :param location: The location of the domain name. :type location: str :param domain_name_label: The domain name to be verified. It must conform to the following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. :... | 2 | stack_v2_sparse_classes_30k_train_011253 | Implement the Python class `NetworkManagementClientOperationsMixin` described below.
Class description:
Implement the NetworkManagementClientOperationsMixin class.
Method signatures and docstrings:
- def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config)... | Implement the Python class `NetworkManagementClientOperationsMixin` described below.
Class description:
Implement the NetworkManagementClientOperationsMixin class.
Method signatures and docstrings:
- def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config)... | b8c2cf97e991adf0c0a207d810316b8f4686dc29 | <|skeleton|>
class NetworkManagementClientOperationsMixin:
def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config):
"""Checks whether a domain name in the cloudapp.azure.com zone is available for use. :param location: The location of the domain... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetworkManagementClientOperationsMixin:
def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config):
"""Checks whether a domain name in the cloudapp.azure.com zone is available for use. :param location: The location of the domain name. :type l... | the_stack_v2_python_sparse | src/connection-monitor-preview/azext_connection_monitor_preview/vendored_sdks/v2019_06_01/v2019_06_01/operations/_network_management_client_operations.py | Azure/azure-cli-extensions | train | 336 | |
ac2c663028da2b2c85c43146546642cad817c895 | [
"url = utils.urljoin(Cluster.base_path, self.id, 'actions', 'resize')\nheaders = {'Accept': ''}\nbody = {'node_count': node_count, 'nodes_to_remove': nodes_to_remove}\nresponse = session.post(url, json=body, headers=headers)\nexceptions.raise_from_response(response)\nreturn response['uuid']",
"url = utils.urljoin... | <|body_start_0|>
url = utils.urljoin(Cluster.base_path, self.id, 'actions', 'resize')
headers = {'Accept': ''}
body = {'node_count': node_count, 'nodes_to_remove': nodes_to_remove}
response = session.post(url, json=body, headers=headers)
exceptions.raise_from_response(response)
... | Cluster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cluster:
def resize(self, session, *, node_count, nodes_to_remove=None):
"""Resize the cluster. :param node_count: The number of servers that will serve as node in the bay/cluster. The default is 1. :param nodes_to_remove: The server ID list will be removed if downsizing the cluster. :re... | stack_v2_sparse_classes_75kplus_train_073174 | 8,130 | permissive | [
{
"docstring": "Resize the cluster. :param node_count: The number of servers that will serve as node in the bay/cluster. The default is 1. :param nodes_to_remove: The server ID list will be removed if downsizing the cluster. :returns: The UUID of the resized cluster. :raises: :exc:`~openstack.exceptions.Resourc... | 2 | stack_v2_sparse_classes_30k_train_054522 | Implement the Python class `Cluster` described below.
Class description:
Implement the Cluster class.
Method signatures and docstrings:
- def resize(self, session, *, node_count, nodes_to_remove=None): Resize the cluster. :param node_count: The number of servers that will serve as node in the bay/cluster. The default... | Implement the Python class `Cluster` described below.
Class description:
Implement the Cluster class.
Method signatures and docstrings:
- def resize(self, session, *, node_count, nodes_to_remove=None): Resize the cluster. :param node_count: The number of servers that will serve as node in the bay/cluster. The default... | d474eb84c605c429bb9cccb166cabbdd1654d73c | <|skeleton|>
class Cluster:
def resize(self, session, *, node_count, nodes_to_remove=None):
"""Resize the cluster. :param node_count: The number of servers that will serve as node in the bay/cluster. The default is 1. :param nodes_to_remove: The server ID list will be removed if downsizing the cluster. :re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cluster:
def resize(self, session, *, node_count, nodes_to_remove=None):
"""Resize the cluster. :param node_count: The number of servers that will serve as node in the bay/cluster. The default is 1. :param nodes_to_remove: The server ID list will be removed if downsizing the cluster. :returns: The UUI... | the_stack_v2_python_sparse | openstack/container_infrastructure_management/v1/cluster.py | openstack/openstacksdk | train | 124 | |
ebd97ebd746ed1ef6cb3ff84d7de2cda7cbfbcfd | [
"user = self.model(email=self.normalize_email(email), username=username)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(username=username, password=password, email=email)\nuser.is_admin = True\nuser.save(using=self._db)\nreturn user"
] | <|body_start_0|>
user = self.model(email=self.normalize_email(email), username=username)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.create_user(username=username, password=password, email=email)
user.is_a... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, username, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, username, email, password):
"""Creates and saves a superuser with the given em... | stack_v2_sparse_classes_75kplus_train_073175 | 2,334 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, username, email, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_038722 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, username, email, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, username,... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, username, email, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, username,... | 933d6c9c54d4a50b2ff67b78f45ee5a5a6d741c6 | <|skeleton|>
class MyUserManager:
def create_user(self, username, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, username, email, password):
"""Creates and saves a superuser with the given em... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyUserManager:
def create_user(self, username, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
user = self.model(email=self.normalize_email(email), username=username)
user.set_password(password)
user.save(using=self._db)
... | the_stack_v2_python_sparse | django/mysite/book/models.py | morefreeze/python | train | 0 | |
940e8c453141dd0b351311626c8584225e5258d3 | [
"l1, l2 = (len(s) + 1, len(t) + 1)\ncur = [0] * l2\ncur[0] = 1\nfor i in xrange(1, l1):\n pre = cur[:]\n for j in xrange(1, l2):\n cur[j] = pre[j] + pre[j - 1] * (s[i - 1] == t[j - 1])\nreturn cur[-1]",
"l1, l2 = (len(s) + 1, len(t) + 1)\ndp = [[1] * l2 for _ in xrange(l1)]\nfor j in xrange(1, l2):\n... | <|body_start_0|>
l1, l2 = (len(s) + 1, len(t) + 1)
cur = [0] * l2
cur[0] = 1
for i in xrange(1, l1):
pre = cur[:]
for j in xrange(1, l2):
cur[j] = pre[j] + pre[j - 1] * (s[i - 1] == t[j - 1])
return cur[-1]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int O(n) space beats 70.80%"""
<|body_0|>
def numDistinct1(self, s, t):
""":type s: str :type t: str :rtype: int O(m*n) space beats 4.40%"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_073176 | 922 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: int O(n) space beats 70.80%",
"name": "numDistinct",
"signature": "def numDistinct(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: int O(m*n) space beats 4.40%",
"name": "numDistinct1",
"signature": "def numDistinct1(sel... | 2 | stack_v2_sparse_classes_30k_train_013703 | 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 O(n) space beats 70.80%
- def numDistinct1(self, s, t): :type s: str :type t: str :rtype: int O(m*n) space beat... | 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 O(n) space beats 70.80%
- def numDistinct1(self, s, t): :type s: str :type t: str :rtype: int O(m*n) space beat... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int O(n) space beats 70.80%"""
<|body_0|>
def numDistinct1(self, s, t):
""":type s: str :type t: str :rtype: int O(m*n) space beats 4.40%"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int O(n) space beats 70.80%"""
l1, l2 = (len(s) + 1, len(t) + 1)
cur = [0] * l2
cur[0] = 1
for i in xrange(1, l1):
pre = cur[:]
for j in xrange(1, l2):
cu... | the_stack_v2_python_sparse | LeetCode/115_distinct_subsequences.py | yao23/Machine_Learning_Playground | train | 12 | |
e6338ad3c71ea2274391597b1004ae0674993893 | [
"id = args['id']\ncorp = args['corp']\norder_repository = corp.order_repository\ndelivery_fill_options = {'with_products': True, 'with_refunding_info': True, 'with_express_details': True, 'with_supplier': True, 'with_operation_logs': True}\nfill_options = {'with_refunding_info': True, 'with_group_buy_info': True, '... | <|body_start_0|>
id = args['id']
corp = args['corp']
order_repository = corp.order_repository
delivery_fill_options = {'with_products': True, 'with_refunding_info': True, 'with_express_details': True, 'with_supplier': True, 'with_operation_logs': True}
fill_options = {'with_refun... | 订单 | AOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AOrder:
"""订单"""
def get(args):
"""相对于订单列表的增量信息:状态日志、操作日志、物流信息、完整的促销信息、优惠券信息 @return:"""
<|body_0|>
def post(args):
"""修改订单信息,目前会修改的只有价格 @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
id = args['id']
corp = args['corp']
... | stack_v2_sparse_classes_75kplus_train_073177 | 2,703 | no_license | [
{
"docstring": "相对于订单列表的增量信息:状态日志、操作日志、物流信息、完整的促销信息、优惠券信息 @return:",
"name": "get",
"signature": "def get(args)"
},
{
"docstring": "修改订单信息,目前会修改的只有价格 @return:",
"name": "post",
"signature": "def post(args)"
}
] | 2 | null | Implement the Python class `AOrder` described below.
Class description:
订单
Method signatures and docstrings:
- def get(args): 相对于订单列表的增量信息:状态日志、操作日志、物流信息、完整的促销信息、优惠券信息 @return:
- def post(args): 修改订单信息,目前会修改的只有价格 @return: | Implement the Python class `AOrder` described below.
Class description:
订单
Method signatures and docstrings:
- def get(args): 相对于订单列表的增量信息:状态日志、操作日志、物流信息、完整的促销信息、优惠券信息 @return:
- def post(args): 修改订单信息,目前会修改的只有价格 @return:
<|skeleton|>
class AOrder:
"""订单"""
def get(args):
"""相对于订单列表的增量信息:状态日志、操作日志、物... | 39860a451678ab50ad93ce8ebe2ef8490af65d62 | <|skeleton|>
class AOrder:
"""订单"""
def get(args):
"""相对于订单列表的增量信息:状态日志、操作日志、物流信息、完整的促销信息、优惠券信息 @return:"""
<|body_0|>
def post(args):
"""修改订单信息,目前会修改的只有价格 @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AOrder:
"""订单"""
def get(args):
"""相对于订单列表的增量信息:状态日志、操作日志、物流信息、完整的促销信息、优惠券信息 @return:"""
id = args['id']
corp = args['corp']
order_repository = corp.order_repository
delivery_fill_options = {'with_products': True, 'with_refunding_info': True, 'with_express_details'... | the_stack_v2_python_sparse | api/order/a_order.py | chengdg/gaia | train | 0 |
c4760e00db28f407d5f100b2da99b75dc424c3b0 | [
"self.x = x\nself.y = y\nself.width = w\nself.height = h",
"x = ponto[0]\ny = ponto[1]\nif x < self.x or x > self.x + self.width:\n return False\nif y < self.y or y > self.y + self.height:\n return False\nreturn True"
] | <|body_start_0|>
self.x = x
self.y = y
self.width = w
self.height = h
<|end_body_0|>
<|body_start_1|>
x = ponto[0]
y = ponto[1]
if x < self.x or x > self.x + self.width:
return False
if y < self.y or y > self.y + self.height:
retur... | Define objetos do tipo retangulo. | Retangulo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Retangulo:
"""Define objetos do tipo retangulo."""
def __init__(self, x, y, w, h):
"""Inicializa objeto retangulo."""
<|body_0|>
def colide(self, ponto):
"""Testa se um ponto colide com este retangulo."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_073178 | 591 | no_license | [
{
"docstring": "Inicializa objeto retangulo.",
"name": "__init__",
"signature": "def __init__(self, x, y, w, h)"
},
{
"docstring": "Testa se um ponto colide com este retangulo.",
"name": "colide",
"signature": "def colide(self, ponto)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003219 | Implement the Python class `Retangulo` described below.
Class description:
Define objetos do tipo retangulo.
Method signatures and docstrings:
- def __init__(self, x, y, w, h): Inicializa objeto retangulo.
- def colide(self, ponto): Testa se um ponto colide com este retangulo. | Implement the Python class `Retangulo` described below.
Class description:
Define objetos do tipo retangulo.
Method signatures and docstrings:
- def __init__(self, x, y, w, h): Inicializa objeto retangulo.
- def colide(self, ponto): Testa se um ponto colide com este retangulo.
<|skeleton|>
class Retangulo:
"""De... | 19516ef61c07758fc3befedab82fd3fdcf23d531 | <|skeleton|>
class Retangulo:
"""Define objetos do tipo retangulo."""
def __init__(self, x, y, w, h):
"""Inicializa objeto retangulo."""
<|body_0|>
def colide(self, ponto):
"""Testa se um ponto colide com este retangulo."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Retangulo:
"""Define objetos do tipo retangulo."""
def __init__(self, x, y, w, h):
"""Inicializa objeto retangulo."""
self.x = x
self.y = y
self.width = w
self.height = h
def colide(self, ponto):
"""Testa se um ponto colide com este retangulo."""
... | the_stack_v2_python_sparse | Algoritmos II/Exercicio01/BehaveExemploProf/features/steps/retangulo.py | willcgoulart/algoritmos_programacao2 | train | 0 |
dc747c3ea0d7e878c729caab43931b04eb24fe66 | [
"coins = models.Historical.objects.all()\nfor coin in coins:\n if coin.name in self.historical_data:\n self.historical_data[coin.name].append([str(coin.name), coin.datetime.strftime('%s'), float(coin.historical_price), float(coin.circulating_supply), float(coin.market_cap), float(coin.volume)])\n else:... | <|body_start_0|>
coins = models.Historical.objects.all()
for coin in coins:
if coin.name in self.historical_data:
self.historical_data[coin.name].append([str(coin.name), coin.datetime.strftime('%s'), float(coin.historical_price), float(coin.circulating_supply), float(coin.mar... | ML Fetcher fetches historical data and stores into a python data structure and then triggers the ML Manager | MLFetcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLFetcher:
"""ML Fetcher fetches historical data and stores into a python data structure and then triggers the ML Manager"""
def collect_data(self):
"""Capture all coin historical data that is in the database and store in a local data structure"""
<|body_0|>
def run(self... | stack_v2_sparse_classes_75kplus_train_073179 | 1,533 | permissive | [
{
"docstring": "Capture all coin historical data that is in the database and store in a local data structure",
"name": "collect_data",
"signature": "def collect_data(self)"
},
{
"docstring": "Pass the stored data to the manager to run the machine learning",
"name": "run",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_045215 | Implement the Python class `MLFetcher` described below.
Class description:
ML Fetcher fetches historical data and stores into a python data structure and then triggers the ML Manager
Method signatures and docstrings:
- def collect_data(self): Capture all coin historical data that is in the database and store in a loc... | Implement the Python class `MLFetcher` described below.
Class description:
ML Fetcher fetches historical data and stores into a python data structure and then triggers the ML Manager
Method signatures and docstrings:
- def collect_data(self): Capture all coin historical data that is in the database and store in a loc... | 59e6c5380950a92fcce841642d1cdc31f85618ed | <|skeleton|>
class MLFetcher:
"""ML Fetcher fetches historical data and stores into a python data structure and then triggers the ML Manager"""
def collect_data(self):
"""Capture all coin historical data that is in the database and store in a local data structure"""
<|body_0|>
def run(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLFetcher:
"""ML Fetcher fetches historical data and stores into a python data structure and then triggers the ML Manager"""
def collect_data(self):
"""Capture all coin historical data that is in the database and store in a local data structure"""
coins = models.Historical.objects.all()
... | the_stack_v2_python_sparse | prophet/mlFetcher.py | andywu9/Prophet | train | 0 |
ff63a8032ba6acdc6c44c738382e4f480ba0c684 | [
"if filestream is None:\n self.Blue = 0\n self.Green = 0\n self.Red = 0\n self.Reserved = 0\nelse:\n self.PopulateFromFileStream(filestream)",
"if fs is None:\n raise Exception('Invalid File stream')\noffset = fs.tell()\nfs.seek(0, 2)\nend = fs.tell()\nfs.seek(offset)\nif end - offset < BmpColor... | <|body_start_0|>
if filestream is None:
self.Blue = 0
self.Green = 0
self.Red = 0
self.Reserved = 0
else:
self.PopulateFromFileStream(filestream)
<|end_body_0|>
<|body_start_1|>
if fs is None:
raise Exception('Invalid File ... | An object representing a BMP_COLOR_MAP. Attributes: Blue (int): blue Green (int): green Red (int): red ``` typedef struct { UINT8 Blue; UINT8 Green; UINT8 Red; UINT8 Reserved; } BMP_COLOR_MAP; ``` | BmpColorMap | [
"BSD-2-Clause-Patent"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BmpColorMap:
"""An object representing a BMP_COLOR_MAP. Attributes: Blue (int): blue Green (int): green Red (int): red ``` typedef struct { UINT8 Blue; UINT8 Green; UINT8 Red; UINT8 Reserved; } BMP_COLOR_MAP; ```"""
def __init__(self, filestream=None):
"""Inits an empty object or loa... | stack_v2_sparse_classes_75kplus_train_073180 | 13,139 | permissive | [
{
"docstring": "Inits an empty object or loads from an fs.",
"name": "__init__",
"signature": "def __init__(self, filestream=None)"
},
{
"docstring": "Loads a bmp from a filestream. Args: fs (obj): A loaded filestream. Raises: (Exception): Invalid filestream",
"name": "PopulateFromFileStream... | 4 | stack_v2_sparse_classes_30k_train_019758 | Implement the Python class `BmpColorMap` described below.
Class description:
An object representing a BMP_COLOR_MAP. Attributes: Blue (int): blue Green (int): green Red (int): red ``` typedef struct { UINT8 Blue; UINT8 Green; UINT8 Red; UINT8 Reserved; } BMP_COLOR_MAP; ```
Method signatures and docstrings:
- def __in... | Implement the Python class `BmpColorMap` described below.
Class description:
An object representing a BMP_COLOR_MAP. Attributes: Blue (int): blue Green (int): green Red (int): red ``` typedef struct { UINT8 Blue; UINT8 Green; UINT8 Red; UINT8 Reserved; } BMP_COLOR_MAP; ```
Method signatures and docstrings:
- def __in... | 78295929b37af62a8cfc4c28eab72ed0c468f350 | <|skeleton|>
class BmpColorMap:
"""An object representing a BMP_COLOR_MAP. Attributes: Blue (int): blue Green (int): green Red (int): red ``` typedef struct { UINT8 Blue; UINT8 Green; UINT8 Red; UINT8 Reserved; } BMP_COLOR_MAP; ```"""
def __init__(self, filestream=None):
"""Inits an empty object or loa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BmpColorMap:
"""An object representing a BMP_COLOR_MAP. Attributes: Blue (int): blue Green (int): green Red (int): red ``` typedef struct { UINT8 Blue; UINT8 Green; UINT8 Red; UINT8 Reserved; } BMP_COLOR_MAP; ```"""
def __init__(self, filestream=None):
"""Inits an empty object or loads from an fs... | the_stack_v2_python_sparse | edk2toollib/uefi/bmp_object.py | tianocore/edk2-pytool-library | train | 47 |
37b029713a318804b60335e8ed43632e83e99a12 | [
"initial = super(ArticleCreate, self).get_initial()\nresult = source_page(self.request)\ncategory_id = self.category_post_model.objects.filter(slug=result).values_list('id', flat=True).first()\nif category_id:\n initial['category_id'] = category_id\nreturn initial",
"context = super(ArticleCreate, self).get_co... | <|body_start_0|>
initial = super(ArticleCreate, self).get_initial()
result = source_page(self.request)
category_id = self.category_post_model.objects.filter(slug=result).values_list('id', flat=True).first()
if category_id:
initial['category_id'] = category_id
return i... | Класс контроллера обрабоки запросов на создание новой статьи. Класс наследуется от встроенного класса CreateView Задается связанная модель - Post Определяются отображаемые поляЖ 'title', 'text', 'category_id' Задается url для перехода в случае успешного создания статьи | ArticleCreate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleCreate:
"""Класс контроллера обрабоки запросов на создание новой статьи. Класс наследуется от встроенного класса CreateView Задается связанная модель - Post Определяются отображаемые поляЖ 'title', 'text', 'category_id' Задается url для перехода в случае успешного создания статьи"""
d... | stack_v2_sparse_classes_75kplus_train_073181 | 25,390 | no_license | [
{
"docstring": "Функция задает исходные параметры полей формы создания статьи :return: функуия возвращает словарь initial, содержащий исходные (присутствующие по умолчанию) параметры",
"name": "get_initial",
"signature": "def get_initial(self)"
},
{
"docstring": "Переопределение встроенного мето... | 3 | null | Implement the Python class `ArticleCreate` described below.
Class description:
Класс контроллера обрабоки запросов на создание новой статьи. Класс наследуется от встроенного класса CreateView Задается связанная модель - Post Определяются отображаемые поляЖ 'title', 'text', 'category_id' Задается url для перехода в слу... | Implement the Python class `ArticleCreate` described below.
Class description:
Класс контроллера обрабоки запросов на создание новой статьи. Класс наследуется от встроенного класса CreateView Задается связанная модель - Post Определяются отображаемые поляЖ 'title', 'text', 'category_id' Задается url для перехода в слу... | 9ba862f9b5f86829b5e014db2e7fed367d508a74 | <|skeleton|>
class ArticleCreate:
"""Класс контроллера обрабоки запросов на создание новой статьи. Класс наследуется от встроенного класса CreateView Задается связанная модель - Post Определяются отображаемые поляЖ 'title', 'text', 'category_id' Задается url для перехода в случае успешного создания статьи"""
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArticleCreate:
"""Класс контроллера обрабоки запросов на создание новой статьи. Класс наследуется от встроенного класса CreateView Задается связанная модель - Post Определяются отображаемые поляЖ 'title', 'text', 'category_id' Задается url для перехода в случае успешного создания статьи"""
def get_initia... | the_stack_v2_python_sparse | TeamHabr/mainapp/views.py | Ximaxis/Aglie_teamwork | train | 0 |
6ae3afdf0b05cf4aeb13be7c54efdef3679cd8d3 | [
"self.ir_c = cv2.imread(str(ir_path), cv2.IMREAD_GRAYSCALE)\nself.vi_c = cv2.imread(str(vi_path), cv2.IMREAD_COLOR)\nself.ir_t = kornia.utils.image_to_tensor(self.ir_c / 255.0).float()\nself.vi_t = kornia.utils.image_to_tensor(cv2.cvtColor(self.vi_c, cv2.COLOR_BGR2GRAY) / 255.0).float()",
"fus = kornia.utils.tens... | <|body_start_0|>
self.ir_c = cv2.imread(str(ir_path), cv2.IMREAD_GRAYSCALE)
self.vi_c = cv2.imread(str(vi_path), cv2.IMREAD_COLOR)
self.ir_t = kornia.utils.image_to_tensor(self.ir_c / 255.0).float()
self.vi_t = kornia.utils.image_to_tensor(cv2.cvtColor(self.vi_c, cv2.COLOR_BGR2GRAY) / 25... | ImagePair | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePair:
def __init__(self, ir_path: Path, vi_path: Path):
"""Load infrared and visible image pair. Args: ir_path: infrared image path vi_path: visible image path"""
<|body_0|>
def save_fus(self, path: Path, fus: Tensor, color: bool=False):
"""Colorize fusion image... | stack_v2_sparse_classes_75kplus_train_073182 | 1,494 | permissive | [
{
"docstring": "Load infrared and visible image pair. Args: ir_path: infrared image path vi_path: visible image path",
"name": "__init__",
"signature": "def __init__(self, ir_path: Path, vi_path: Path)"
},
{
"docstring": "Colorize fusion image with visible color channels. Args: path: save fused ... | 2 | stack_v2_sparse_classes_30k_test_002888 | Implement the Python class `ImagePair` described below.
Class description:
Implement the ImagePair class.
Method signatures and docstrings:
- def __init__(self, ir_path: Path, vi_path: Path): Load infrared and visible image pair. Args: ir_path: infrared image path vi_path: visible image path
- def save_fus(self, path... | Implement the Python class `ImagePair` described below.
Class description:
Implement the ImagePair class.
Method signatures and docstrings:
- def __init__(self, ir_path: Path, vi_path: Path): Load infrared and visible image pair. Args: ir_path: infrared image path vi_path: visible image path
- def save_fus(self, path... | ae368ea39b4049afb4b54cb3447d26107c3a8ab1 | <|skeleton|>
class ImagePair:
def __init__(self, ir_path: Path, vi_path: Path):
"""Load infrared and visible image pair. Args: ir_path: infrared image path vi_path: visible image path"""
<|body_0|>
def save_fus(self, path: Path, fus: Tensor, color: bool=False):
"""Colorize fusion image... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImagePair:
def __init__(self, ir_path: Path, vi_path: Path):
"""Load infrared and visible image pair. Args: ir_path: infrared image path vi_path: visible image path"""
self.ir_c = cv2.imread(str(ir_path), cv2.IMREAD_GRAYSCALE)
self.vi_c = cv2.imread(str(vi_path), cv2.IMREAD_COLOR)
... | the_stack_v2_python_sparse | TarDAL/utils/image_pair.py | Linfeng-Tang/VIF-Benchmark | train | 29 | |
5826b018b9ac8ae864a49adf88ee7914c69d040d | [
"res = Simulation.objects.all()\nif scenario_id:\n rs = RoadSegment.objects.filter(scenario__id__exact=scenario_id)\n res = res.filter(Q(simulation_scenes__simulation_scene_events__road_segment__in=rs)).distinct()\nif simulation_id:\n res = res.filter(Q(id__exact=simulation_id))\nif name:\n res = res.fi... | <|body_start_0|>
res = Simulation.objects.all()
if scenario_id:
rs = RoadSegment.objects.filter(scenario__id__exact=scenario_id)
res = res.filter(Q(simulation_scenes__simulation_scene_events__road_segment__in=rs)).distinct()
if simulation_id:
res = res.filter(... | Query | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Query:
def resolve_simulations(self, info, simulation_id=None, name=None, desc=None, scene_id=None, scenario_id=None, **kwargs):
"""Queries simulations from the database :param info: :param simulation_id: The simulation ID to filter on :param name: The (part of the) name to filter on :pa... | stack_v2_sparse_classes_75kplus_train_073183 | 13,405 | no_license | [
{
"docstring": "Queries simulations from the database :param info: :param simulation_id: The simulation ID to filter on :param name: The (part of the) name to filter on :param desc: The (part of the) description to filter on :param scene_id: The scene ID to filter on :param kwargs: :return: All (filtered) simul... | 3 | stack_v2_sparse_classes_30k_train_051266 | Implement the Python class `Query` described below.
Class description:
Implement the Query class.
Method signatures and docstrings:
- def resolve_simulations(self, info, simulation_id=None, name=None, desc=None, scene_id=None, scenario_id=None, **kwargs): Queries simulations from the database :param info: :param simu... | Implement the Python class `Query` described below.
Class description:
Implement the Query class.
Method signatures and docstrings:
- def resolve_simulations(self, info, simulation_id=None, name=None, desc=None, scene_id=None, scenario_id=None, **kwargs): Queries simulations from the database :param info: :param simu... | 618440303dcbf819cd61aa5e593b4b50483f0070 | <|skeleton|>
class Query:
def resolve_simulations(self, info, simulation_id=None, name=None, desc=None, scene_id=None, scenario_id=None, **kwargs):
"""Queries simulations from the database :param info: :param simulation_id: The simulation ID to filter on :param name: The (part of the) name to filter on :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Query:
def resolve_simulations(self, info, simulation_id=None, name=None, desc=None, scene_id=None, scenario_id=None, **kwargs):
"""Queries simulations from the database :param info: :param simulation_id: The simulation ID to filter on :param name: The (part of the) name to filter on :param desc: The ... | the_stack_v2_python_sparse | backend/api/simulations/schema.py | Rohan-Deshamudre/Smart-traffic-management-system | train | 0 | |
aa048432e488aab88a7c267226a94c313e54dc3c | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('aoconno8_dmak1112', 'aoconno8_dmak1112')\nurl = 'https://data.boston.gov/api/3/action/datastore_search?resource_id=bd8dd4bb-867e-4ca2-b6c7-6c3bd9e6c290&limit=176'\nresponse = urllib.request.urlopen(url).... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aoconno8_dmak1112', 'aoconno8_dmak1112')
url = 'https://data.boston.gov/api/3/action/datastore_search?resource_id=bd8dd4bb-867e-4ca2-b6c7-6c3bd9e6c290&lim... | yearlyEmissions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class yearlyEmissions:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_75kplus_train_073184 | 3,717 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_049036 | Implement the Python class `yearlyEmissions` described below.
Class description:
Implement the yearlyEmissions class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | Implement the Python class `yearlyEmissions` described below.
Class description:
Implement the yearlyEmissions class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | b5ccaad97f6e35f9580e645ca764f36eb3406f43 | <|skeleton|>
class yearlyEmissions:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class yearlyEmissions:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aoconno8_dmak1112', 'aoconno8_dmak1... | the_stack_v2_python_sparse | aoconno8_dmak1112/yearlyEmissions.py | dwang1995/course-2018-spr-proj | train | 1 | |
5dcb8fa19c9334af8bc7a662f8dfb830bc3a684f | [
"self.browser.get(self.live_server_url)\ninput_box = self.get_item_input_box()\ninput_box.send_keys(Keys.ENTER)\nself.wait_for(lambda: self.browser.find_element_by_css_selector('#id_text:invalid'))\ninput_box = self.get_item_input_box()\ninput_box.send_keys('买一盒牛奶')\nself.wait_for(lambda: self.browser.find_element_... | <|body_start_0|>
self.browser.get(self.live_server_url)
input_box = self.get_item_input_box()
input_box.send_keys(Keys.ENTER)
self.wait_for(lambda: self.browser.find_element_by_css_selector('#id_text:invalid'))
input_box = self.get_item_input_box()
input_box.send_keys('买一... | 输入框效验测试 | ListItemValidationTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListItemValidationTest:
"""输入框效验测试"""
def test_001(self):
"""首页和清单页面都不能提交空的待办事项"""
<|body_0|>
def test_002(self):
"""不能提交重复的待办事项"""
<|body_1|>
def test_003(self):
"""新建清单时,提交空白文字会报错 但是,我的清单能正常表示"""
<|body_2|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_073185 | 4,240 | no_license | [
{
"docstring": "首页和清单页面都不能提交空的待办事项",
"name": "test_001",
"signature": "def test_001(self)"
},
{
"docstring": "不能提交重复的待办事项",
"name": "test_002",
"signature": "def test_002(self)"
},
{
"docstring": "新建清单时,提交空白文字会报错 但是,我的清单能正常表示",
"name": "test_003",
"signature": "def test_0... | 3 | stack_v2_sparse_classes_30k_test_000623 | Implement the Python class `ListItemValidationTest` described below.
Class description:
输入框效验测试
Method signatures and docstrings:
- def test_001(self): 首页和清单页面都不能提交空的待办事项
- def test_002(self): 不能提交重复的待办事项
- def test_003(self): 新建清单时,提交空白文字会报错 但是,我的清单能正常表示 | Implement the Python class `ListItemValidationTest` described below.
Class description:
输入框效验测试
Method signatures and docstrings:
- def test_001(self): 首页和清单页面都不能提交空的待办事项
- def test_002(self): 不能提交重复的待办事项
- def test_003(self): 新建清单时,提交空白文字会报错 但是,我的清单能正常表示
<|skeleton|>
class ListItemValidationTest:
"""输入框效验测试"""
... | 973b3afb239db5f55cb52897e7a8a241a459349f | <|skeleton|>
class ListItemValidationTest:
"""输入框效验测试"""
def test_001(self):
"""首页和清单页面都不能提交空的待办事项"""
<|body_0|>
def test_002(self):
"""不能提交重复的待办事项"""
<|body_1|>
def test_003(self):
"""新建清单时,提交空白文字会报错 但是,我的清单能正常表示"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListItemValidationTest:
"""输入框效验测试"""
def test_001(self):
"""首页和清单页面都不能提交空的待办事项"""
self.browser.get(self.live_server_url)
input_box = self.get_item_input_box()
input_box.send_keys(Keys.ENTER)
self.wait_for(lambda: self.browser.find_element_by_css_selector('#id_text... | the_stack_v2_python_sparse | functional_tests/test_lists/test_list_item_validation.py | aaluo001/superlists | train | 0 |
e09eca9387b3fae4b74f7f48c362b8b3d40da401 | [
"if not a1 or not a2:\n return list()\nif len(a1) < len(a2):\n u = list(set(a1))\n v = list(set(a2))\nelse:\n u = list(set(a2))\n v = list(set(a1))\nu.sort()\nr = [x for x in v if self.is_present(x, u)]\nreturn r",
"l = 0\nr = len(u) - 1\nwhile l <= r:\n m = l + (r - l) // 2\n if u[m] == x:\n... | <|body_start_0|>
if not a1 or not a2:
return list()
if len(a1) < len(a2):
u = list(set(a1))
v = list(set(a2))
else:
u = list(set(a2))
v = list(set(a1))
u.sort()
r = [x for x in v if self.is_present(x, u)]
return ... | Iteration over all elements of smaller input array with binary search. Time complexity: O(min(len(n), len(m))) - Traverse all elements of smaller input array Space complexity: O(min(len(n), len(m))) - Amortized collect all elements of smaller input array | Solution2 | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
"""Iteration over all elements of smaller input array with binary search. Time complexity: O(min(len(n), len(m))) - Traverse all elements of smaller input array Space complexity: O(min(len(n), len(m))) - Amortized collect all elements of smaller input array"""
def find_intersectio... | stack_v2_sparse_classes_75kplus_train_073186 | 3,821 | permissive | [
{
"docstring": "Determines common elements in both input arrays. :param list[int] a1: first input array :param list[int] a2: second input array :return: array of elements common to both input arrays :rtype: list[int]",
"name": "find_intersection",
"signature": "def find_intersection(self, a1, a2)"
},
... | 2 | stack_v2_sparse_classes_30k_train_028971 | Implement the Python class `Solution2` described below.
Class description:
Iteration over all elements of smaller input array with binary search. Time complexity: O(min(len(n), len(m))) - Traverse all elements of smaller input array Space complexity: O(min(len(n), len(m))) - Amortized collect all elements of smaller i... | Implement the Python class `Solution2` described below.
Class description:
Iteration over all elements of smaller input array with binary search. Time complexity: O(min(len(n), len(m))) - Traverse all elements of smaller input array Space complexity: O(min(len(n), len(m))) - Amortized collect all elements of smaller i... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution2:
"""Iteration over all elements of smaller input array with binary search. Time complexity: O(min(len(n), len(m))) - Traverse all elements of smaller input array Space complexity: O(min(len(n), len(m))) - Amortized collect all elements of smaller input array"""
def find_intersectio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution2:
"""Iteration over all elements of smaller input array with binary search. Time complexity: O(min(len(n), len(m))) - Traverse all elements of smaller input array Space complexity: O(min(len(n), len(m))) - Amortized collect all elements of smaller input array"""
def find_intersection(self, a1, a... | the_stack_v2_python_sparse | 0349_intersection_two_arrays/python_source.py | arthurdysart/LeetCode | train | 0 |
5e58a4e93f08bc3b8bc44e655c13f4449474a56a | [
"super(ShuffleUnitV2, self).__init__()\nself._channel_split_factor = channel_split\nif downsample is None:\n self._width = int(inplanes * self._channel_split_factor)\nelse:\n self._width = inplanes\nif norm_layer is None:\n norm_layer = nn.BatchNorm2d\nself._groups = 2\nself.conv1 = conv1x1(self._width, se... | <|body_start_0|>
super(ShuffleUnitV2, self).__init__()
self._channel_split_factor = channel_split
if downsample is None:
self._width = int(inplanes * self._channel_split_factor)
else:
self._width = inplanes
if norm_layer is None:
norm_layer = n... | Basic unit for ShuffleNetV2 structure: > stride=1 - channel split operator > 1x1-conv > bn > relu > 3x3-conv-dw > bn > 1x1-conv > bn > relu > skip connect concat > channel shuffle operator > stride=2 - bottleneck path: 1x1-conv > bn > relu > 3x3-conv-dw s=2 > bn > 1x1-conv > bn > relu > concat > channel shuffle operato... | ShuffleUnitV2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShuffleUnitV2:
"""Basic unit for ShuffleNetV2 structure: > stride=1 - channel split operator > 1x1-conv > bn > relu > 3x3-conv-dw > bn > 1x1-conv > bn > relu > skip connect concat > channel shuffle operator > stride=2 - bottleneck path: 1x1-conv > bn > relu > 3x3-conv-dw s=2 > bn > 1x1-conv > bn ... | stack_v2_sparse_classes_75kplus_train_073187 | 13,400 | no_license | [
{
"docstring": "Constructor Args: inplanes: (int) number of input channels to the block channel_split: (float) channel split factor; number of channels going through the bottleneck path = channel_split * inplanes stride: (int) stride; applied to 3x3-conv-dw if stride > 1 dropout: (float) p=dropout; if dropout=0... | 4 | null | Implement the Python class `ShuffleUnitV2` described below.
Class description:
Basic unit for ShuffleNetV2 structure: > stride=1 - channel split operator > 1x1-conv > bn > relu > 3x3-conv-dw > bn > 1x1-conv > bn > relu > skip connect concat > channel shuffle operator > stride=2 - bottleneck path: 1x1-conv > bn > relu ... | Implement the Python class `ShuffleUnitV2` described below.
Class description:
Basic unit for ShuffleNetV2 structure: > stride=1 - channel split operator > 1x1-conv > bn > relu > 3x3-conv-dw > bn > 1x1-conv > bn > relu > skip connect concat > channel shuffle operator > stride=2 - bottleneck path: 1x1-conv > bn > relu ... | a0c51824b9c4c458918ef9a40a925cd576137d75 | <|skeleton|>
class ShuffleUnitV2:
"""Basic unit for ShuffleNetV2 structure: > stride=1 - channel split operator > 1x1-conv > bn > relu > 3x3-conv-dw > bn > 1x1-conv > bn > relu > skip connect concat > channel shuffle operator > stride=2 - bottleneck path: 1x1-conv > bn > relu > 3x3-conv-dw s=2 > bn > 1x1-conv > bn ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShuffleUnitV2:
"""Basic unit for ShuffleNetV2 structure: > stride=1 - channel split operator > 1x1-conv > bn > relu > 3x3-conv-dw > bn > 1x1-conv > bn > relu > skip connect concat > channel shuffle operator > stride=2 - bottleneck path: 1x1-conv > bn > relu > 3x3-conv-dw s=2 > bn > 1x1-conv > bn > relu > conc... | the_stack_v2_python_sparse | model/shufflenetv2.py | baihuaxie/ConvLab | train | 0 |
886aed965411c0e8469b0e4f9161e8ad0411d3d6 | [
"super(RelationNetwork, self).__init__(**kwargs)\nif not isinstance(self.embedding_fn, reparameterizable_backbones.RelationNetConvNet):\n raise ValueError('`embedding_fn` for `RelationNetwork` must be a `reparameterizable_backbones.RelationNetConvNet`, as this backbone omits dimensionality reductions.')\nself.re... | <|body_start_0|>
super(RelationNetwork, self).__init__(**kwargs)
if not isinstance(self.embedding_fn, reparameterizable_backbones.RelationNetConvNet):
raise ValueError('`embedding_fn` for `RelationNetwork` must be a `reparameterizable_backbones.RelationNetConvNet`, as this backbone omits dim... | A Relation Network. | RelationNetwork | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelationNetwork:
"""A Relation Network."""
def __init__(self, relation_module_cls=reparameterizable_backbones.RelationModule, **kwargs):
"""Initializes a RelationNetwork instance. Args: relation_module_cls: The class of a Module that computes relations from pairs. **kwargs: Arguments... | stack_v2_sparse_classes_75kplus_train_073188 | 9,986 | permissive | [
{
"docstring": "Initializes a RelationNetwork instance. Args: relation_module_cls: The class of a Module that computes relations from pairs. **kwargs: Arguments common to all `MetricLearner`s. Raises: `ValueError` if `RelationNetwork.embedding_fn` is not an instance of `reparameterizable_backbones.RelationNetCo... | 3 | null | Implement the Python class `RelationNetwork` described below.
Class description:
A Relation Network.
Method signatures and docstrings:
- def __init__(self, relation_module_cls=reparameterizable_backbones.RelationModule, **kwargs): Initializes a RelationNetwork instance. Args: relation_module_cls: The class of a Modul... | Implement the Python class `RelationNetwork` described below.
Class description:
A Relation Network.
Method signatures and docstrings:
- def __init__(self, relation_module_cls=reparameterizable_backbones.RelationModule, **kwargs): Initializes a RelationNetwork instance. Args: relation_module_cls: The class of a Modul... | 13ca9ed2533056909f232168c759c096ae291740 | <|skeleton|>
class RelationNetwork:
"""A Relation Network."""
def __init__(self, relation_module_cls=reparameterizable_backbones.RelationModule, **kwargs):
"""Initializes a RelationNetwork instance. Args: relation_module_cls: The class of a Module that computes relations from pairs. **kwargs: Arguments... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelationNetwork:
"""A Relation Network."""
def __init__(self, relation_module_cls=reparameterizable_backbones.RelationModule, **kwargs):
"""Initializes a RelationNetwork instance. Args: relation_module_cls: The class of a Module that computes relations from pairs. **kwargs: Arguments common to al... | the_stack_v2_python_sparse | meta_dataset/learners/experimental/metric_learners.py | google-research/meta-dataset | train | 753 |
7a559b2ce0570b2d027b0b5611da621ea01a2a27 | [
"length = len(nums)\ndp = [[] for _ in range(length)]\ndp[0] = [[nums[0]]]\nfor i in range(1, length):\n for sub in dp[i - 1]:\n compatible = True\n for num in sub:\n if nums[i] % num != 0 and num % nums[i] != 0:\n dp[i].append(sub)\n dp[i].append([nums[i]])... | <|body_start_0|>
length = len(nums)
dp = [[] for _ in range(length)]
dp[0] = [[nums[0]]]
for i in range(1, length):
for sub in dp[i - 1]:
compatible = True
for num in sub:
if nums[i] % num != 0 and num % nums[i] != 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestDivisibleSubset(self, nums):
"""Time Limit Exceeded. each cell in dp list stores the matched sublists for all previous nums plus current num. :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def largestDivisibleSubset2(self, nums):
"""dp is ... | stack_v2_sparse_classes_75kplus_train_073189 | 1,460 | no_license | [
{
"docstring": "Time Limit Exceeded. each cell in dp list stores the matched sublists for all previous nums plus current num. :type nums: List[int] :rtype: List[int]",
"name": "largestDivisibleSubset",
"signature": "def largestDivisibleSubset(self, nums)"
},
{
"docstring": "dp is a dict maps cur... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestDivisibleSubset(self, nums): Time Limit Exceeded. each cell in dp list stores the matched sublists for all previous nums plus current num. :type nums: List[int] :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestDivisibleSubset(self, nums): Time Limit Exceeded. each cell in dp list stores the matched sublists for all previous nums plus current num. :type nums: List[int] :rtype... | 49d0831387227e69ae4067c1f5b7e828976377b4 | <|skeleton|>
class Solution:
def largestDivisibleSubset(self, nums):
"""Time Limit Exceeded. each cell in dp list stores the matched sublists for all previous nums plus current num. :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def largestDivisibleSubset2(self, nums):
"""dp is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def largestDivisibleSubset(self, nums):
"""Time Limit Exceeded. each cell in dp list stores the matched sublists for all previous nums plus current num. :type nums: List[int] :rtype: List[int]"""
length = len(nums)
dp = [[] for _ in range(length)]
dp[0] = [[nums[0]]]
... | the_stack_v2_python_sparse | dp/368_largest_divisible_subset.py | libinjungle/LeetCode_Python | train | 0 | |
4d0009d949d754816d61d31782da11b8b1344c53 | [
"@lru_cache(None)\ndef dfs(cur: int) -> int:\n res = 0\n for next in adjList[cur]:\n res = max(res, dfs(next))\n return res + 1\nreturn max((dfs(i) for i in range(len(adjList)))) - 1",
"n = len(adjList)\ndeg = [0] * n\nfor i in range(n):\n for j in adjList[i]:\n deg[j] += 1\nqueue = dequ... | <|body_start_0|>
@lru_cache(None)
def dfs(cur: int) -> int:
res = 0
for next in adjList[cur]:
res = max(res, dfs(next))
return res + 1
return max((dfs(i) for i in range(len(adjList)))) - 1
<|end_body_0|>
<|body_start_1|>
n = len(adjLis... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_0|>
def solve2(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
@lru_cache(None)
def dfs(cur... | stack_v2_sparse_classes_75kplus_train_073190 | 1,503 | no_license | [
{
"docstring": "DAG中最长路径只和当前位置有关",
"name": "solve",
"signature": "def solve(self, adjList: List[List[int]]) -> int"
},
{
"docstring": "DAG中最长路径只和当前位置有关",
"name": "solve2",
"signature": "def solve2(self, adjList: List[List[int]]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_029098 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
- def solve2(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
- def solve2(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
<|skeleton|>
class Solution:
def so... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_0|>
def solve2(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
@lru_cache(None)
def dfs(cur: int) -> int:
res = 0
for next in adjList[cur]:
res = max(res, dfs(next))
return res + 1
return max((dfs(i) for i ... | the_stack_v2_python_sparse | 7_graph/拓扑排序/DAG最长路/DAG中的最长路径.py | 981377660LMT/algorithm-study | train | 225 | |
8fe70f778074ee2ce032fe11375889317f383c57 | [
"super(HyperOptNoTraining, self).__init__(params, data)\nself.objective = None\nself.trial_losses = None\nself.best_trial = None\nself.trial_list = None",
"self.trial_list = trial_list\nif self.trial_list is None:\n raise Exception('Sorry, Hyperparameter optimization without training currently only works if a ... | <|body_start_0|>
super(HyperOptNoTraining, self).__init__(params, data)
self.objective = None
self.trial_losses = None
self.best_trial = None
self.trial_list = None
<|end_body_0|>
<|body_start_1|>
self.trial_list = trial_list
if self.trial_list is None:
... | Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian. | HyperOptNoTraining | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HyperOptNoTraining:
"""Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian."""
def __init__(self, params, data):
"""Create a HyperOptNoTraining object. Parameters ---------- params : mala.common.parametes.Parameters Parameters us... | stack_v2_sparse_classes_75kplus_train_073191 | 2,999 | permissive | [
{
"docstring": "Create a HyperOptNoTraining object. Parameters ---------- params : mala.common.parametes.Parameters Parameters used to create this hyperparameter optimizer. data : mala.datahandling.data_handler.DataHandler DataHandler holding the data for the hyperparameter optimization.",
"name": "__init__... | 3 | stack_v2_sparse_classes_30k_train_033913 | Implement the Python class `HyperOptNoTraining` described below.
Class description:
Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian.
Method signatures and docstrings:
- def __init__(self, params, data): Create a HyperOptNoTraining object. Parameters ---------... | Implement the Python class `HyperOptNoTraining` described below.
Class description:
Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian.
Method signatures and docstrings:
- def __init__(self, params, data): Create a HyperOptNoTraining object. Parameters ---------... | 9cc771b0cdc4178c7f66fd717684658abbb0d95c | <|skeleton|>
class HyperOptNoTraining:
"""Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian."""
def __init__(self, params, data):
"""Create a HyperOptNoTraining object. Parameters ---------- params : mala.common.parametes.Parameters Parameters us... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HyperOptNoTraining:
"""Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian."""
def __init__(self, params, data):
"""Create a HyperOptNoTraining object. Parameters ---------- params : mala.common.parametes.Parameters Parameters used to create ... | the_stack_v2_python_sparse | mala/network/hyper_opt_notraining.py | icamps/mala | train | 0 |
1ea120aff3cdffec93453948f8ec71f4ae095a43 | [
"super().__init__(name, cuisinetype)\nself.flavors = []\nself.name = name",
"print('My ice cream stand serves the following ice cream flavors.')\nfor flavor in self.flavors:\n print('- ' + flavor.title())"
] | <|body_start_0|>
super().__init__(name, cuisinetype)
self.flavors = []
self.name = name
<|end_body_0|>
<|body_start_1|>
print('My ice cream stand serves the following ice cream flavors.')
for flavor in self.flavors:
print('- ' + flavor.title())
<|end_body_1|>
| Represent aspects of a restaurant, specific to and icecream stand. | Icecream | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Icecream:
"""Represent aspects of a restaurant, specific to and icecream stand."""
def __init__(self, name, cuisinetype='ice cream'):
"""Initialize attributes of the parent class. Then initialize attributes specific to an icecream stand."""
<|body_0|>
def listflavors(sel... | stack_v2_sparse_classes_75kplus_train_073192 | 1,164 | no_license | [
{
"docstring": "Initialize attributes of the parent class. Then initialize attributes specific to an icecream stand.",
"name": "__init__",
"signature": "def __init__(self, name, cuisinetype='ice cream')"
},
{
"docstring": "Provide customers a description of the ice cream flavors.",
"name": "... | 2 | null | Implement the Python class `Icecream` described below.
Class description:
Represent aspects of a restaurant, specific to and icecream stand.
Method signatures and docstrings:
- def __init__(self, name, cuisinetype='ice cream'): Initialize attributes of the parent class. Then initialize attributes specific to an icecr... | Implement the Python class `Icecream` described below.
Class description:
Represent aspects of a restaurant, specific to and icecream stand.
Method signatures and docstrings:
- def __init__(self, name, cuisinetype='ice cream'): Initialize attributes of the parent class. Then initialize attributes specific to an icecr... | bacbda303a99654f78fa1f30b1588c1c1f04e281 | <|skeleton|>
class Icecream:
"""Represent aspects of a restaurant, specific to and icecream stand."""
def __init__(self, name, cuisinetype='ice cream'):
"""Initialize attributes of the parent class. Then initialize attributes specific to an icecream stand."""
<|body_0|>
def listflavors(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Icecream:
"""Represent aspects of a restaurant, specific to and icecream stand."""
def __init__(self, name, cuisinetype='ice cream'):
"""Initialize attributes of the parent class. Then initialize attributes specific to an icecream stand."""
super().__init__(name, cuisinetype)
self... | the_stack_v2_python_sparse | icecream.py | huffmp2/python | train | 0 |
a107a6043152b947d43c2b0557236ddb86dcb289 | [
"[numSwaps, first, last] = countSwaps([6, 4, 1])\nself.assertEqual(numSwaps, 3)\nself.assertEqual(first, 1)\nself.assertEqual(last, 6)",
"[numSwaps, first, last] = countSwaps([0, 1, 2, 3, 4, 5])\nself.assertEqual(numSwaps, 0)\nself.assertEqual(first, 0)\nself.assertEqual(last, 5)"
] | <|body_start_0|>
[numSwaps, first, last] = countSwaps([6, 4, 1])
self.assertEqual(numSwaps, 3)
self.assertEqual(first, 1)
self.assertEqual(last, 6)
<|end_body_0|>
<|body_start_1|>
[numSwaps, first, last] = countSwaps([0, 1, 2, 3, 4, 5])
self.assertEqual(numSwaps, 0)
... | TestCountSwaps | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCountSwaps:
def test_sorts_and_counts(self):
"""Sorts and counts the number of swaps"""
<|body_0|>
def test_returns_zero(self):
"""Prints 0 if no swaps are required"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
[numSwaps, first, last] = countS... | stack_v2_sparse_classes_75kplus_train_073193 | 673 | permissive | [
{
"docstring": "Sorts and counts the number of swaps",
"name": "test_sorts_and_counts",
"signature": "def test_sorts_and_counts(self)"
},
{
"docstring": "Prints 0 if no swaps are required",
"name": "test_returns_zero",
"signature": "def test_returns_zero(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001382 | Implement the Python class `TestCountSwaps` described below.
Class description:
Implement the TestCountSwaps class.
Method signatures and docstrings:
- def test_sorts_and_counts(self): Sorts and counts the number of swaps
- def test_returns_zero(self): Prints 0 if no swaps are required | Implement the Python class `TestCountSwaps` described below.
Class description:
Implement the TestCountSwaps class.
Method signatures and docstrings:
- def test_sorts_and_counts(self): Sorts and counts the number of swaps
- def test_returns_zero(self): Prints 0 if no swaps are required
<|skeleton|>
class TestCountSw... | 27ffb6b32d6d18d279c51cfa45bf305a409be5c2 | <|skeleton|>
class TestCountSwaps:
def test_sorts_and_counts(self):
"""Sorts and counts the number of swaps"""
<|body_0|>
def test_returns_zero(self):
"""Prints 0 if no swaps are required"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCountSwaps:
def test_sorts_and_counts(self):
"""Sorts and counts the number of swaps"""
[numSwaps, first, last] = countSwaps([6, 4, 1])
self.assertEqual(numSwaps, 3)
self.assertEqual(first, 1)
self.assertEqual(last, 6)
def test_returns_zero(self):
"""Pr... | the_stack_v2_python_sparse | src/hacker-rank/easy/bubble-sort/test_bubble_sort.py | nwthomas/code-challenges | train | 2 | |
1036f3aabd2cefc815aa001a846acc5a4764edb8 | [
"user = super(UpdateUserForm, self).save(commit=False)\nuser.set_password(self.cleaned_data['password'])\nif commit:\n user.save()\n self.save_m2m()\nreturn user",
"super(UpdateUserForm, self).__init__(*args, **kwargs)\ninstance = getattr(self, 'instance', None)\nif instance and instance.pk:\n self.field... | <|body_start_0|>
user = super(UpdateUserForm, self).save(commit=False)
user.set_password(self.cleaned_data['password'])
if commit:
user.save()
self.save_m2m()
return user
<|end_body_0|>
<|body_start_1|>
super(UpdateUserForm, self).__init__(*args, **kwargs... | Formulario para la modificacion de un Usuario | UpdateUserForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateUserForm:
"""Formulario para la modificacion de un Usuario"""
def save(self, commit=True):
"""Metodo para guardar el formulario :param commit: indicador de guardado en la base de datos, True: se debe guardar, False: No guardar. :return: El objeto creado por el formulario luego ... | stack_v2_sparse_classes_75kplus_train_073194 | 4,021 | no_license | [
{
"docstring": "Metodo para guardar el formulario :param commit: indicador de guardado en la base de datos, True: se debe guardar, False: No guardar. :return: El objeto creado por el formulario luego de ejecutar el metodo en el formulario",
"name": "save",
"signature": "def save(self, commit=True)"
},... | 2 | stack_v2_sparse_classes_30k_train_013886 | Implement the Python class `UpdateUserForm` described below.
Class description:
Formulario para la modificacion de un Usuario
Method signatures and docstrings:
- def save(self, commit=True): Metodo para guardar el formulario :param commit: indicador de guardado en la base de datos, True: se debe guardar, False: No gu... | Implement the Python class `UpdateUserForm` described below.
Class description:
Formulario para la modificacion de un Usuario
Method signatures and docstrings:
- def save(self, commit=True): Metodo para guardar el formulario :param commit: indicador de guardado en la base de datos, True: se debe guardar, False: No gu... | 467be7bd8babccf4e1af89c956efc8e53abc4122 | <|skeleton|>
class UpdateUserForm:
"""Formulario para la modificacion de un Usuario"""
def save(self, commit=True):
"""Metodo para guardar el formulario :param commit: indicador de guardado en la base de datos, True: se debe guardar, False: No guardar. :return: El objeto creado por el formulario luego ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateUserForm:
"""Formulario para la modificacion de un Usuario"""
def save(self, commit=True):
"""Metodo para guardar el formulario :param commit: indicador de guardado en la base de datos, True: se debe guardar, False: No guardar. :return: El objeto creado por el formulario luego de ejecutar e... | the_stack_v2_python_sparse | usuarios/forms.py | vgarcete98/IS2 | train | 0 |
9440ef7a4d897f203ef22095553f1de6a996c606 | [
"order = get_object_or_404(Order, orderNum=kwargs['orderNum'])\nserializer = OrderDetailSerializer(order)\nreturn Response(serializer.data)",
"data = request.data\ninsertData = {}\nif 'trackingNumber' in data.keys():\n insertData['trackingNumber'] = data['trackingNumber']\nif 'remarks' in data.keys():\n ins... | <|body_start_0|>
order = get_object_or_404(Order, orderNum=kwargs['orderNum'])
serializer = OrderDetailSerializer(order)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
data = request.data
insertData = {}
if 'trackingNumber' in data.keys():
i... | OrderDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderDetailView:
def get(self, request, *args, **kwargs):
"""根据订单号查询订单详情 :param request: :param args: :param kwargs: orderNum:订单号 :return:"""
<|body_0|>
def patch(self, request, *args, **kwargs):
"""管理员更新订单 :param request: trackingNumber:物流单号 shortName:快递公司简称 remarks... | stack_v2_sparse_classes_75kplus_train_073195 | 7,104 | no_license | [
{
"docstring": "根据订单号查询订单详情 :param request: :param args: :param kwargs: orderNum:订单号 :return:",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "管理员更新订单 :param request: trackingNumber:物流单号 shortName:快递公司简称 remarks:卖家备注 status:订单状态(0, '已失效'), (1, '待支付'), (2... | 2 | stack_v2_sparse_classes_30k_val_001656 | Implement the Python class `OrderDetailView` described below.
Class description:
Implement the OrderDetailView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 根据订单号查询订单详情 :param request: :param args: :param kwargs: orderNum:订单号 :return:
- def patch(self, request, *args, **kwargs): ... | Implement the Python class `OrderDetailView` described below.
Class description:
Implement the OrderDetailView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 根据订单号查询订单详情 :param request: :param args: :param kwargs: orderNum:订单号 :return:
- def patch(self, request, *args, **kwargs): ... | 4510c5bb5b1a936dc881412b92518d01b5d5be13 | <|skeleton|>
class OrderDetailView:
def get(self, request, *args, **kwargs):
"""根据订单号查询订单详情 :param request: :param args: :param kwargs: orderNum:订单号 :return:"""
<|body_0|>
def patch(self, request, *args, **kwargs):
"""管理员更新订单 :param request: trackingNumber:物流单号 shortName:快递公司简称 remarks... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderDetailView:
def get(self, request, *args, **kwargs):
"""根据订单号查询订单详情 :param request: :param args: :param kwargs: orderNum:订单号 :return:"""
order = get_object_or_404(Order, orderNum=kwargs['orderNum'])
serializer = OrderDetailSerializer(order)
return Response(serializer.data)... | the_stack_v2_python_sparse | WebAdmin/views/order.py | liuyucomeon/WeChatMall | train | 1 | |
e08fc300f5c6ef15d1b63915d67d24e57955a788 | [
"flags.AddRegion(parser)\nflags.AddCluster(parser, False)\nparser.display_info.AddFormat(_USER_FORMAT)",
"client = api_util.AlloyDBClient(self.ReleaseTrack())\nalloydb_client = client.alloydb_client\nalloydb_messages = client.alloydb_messages\ncluster_ref = client.resource_parser.Create('alloydb.projects.location... | <|body_start_0|>
flags.AddRegion(parser)
flags.AddCluster(parser, False)
parser.display_info.AddFormat(_USER_FORMAT)
<|end_body_0|>
<|body_start_1|>
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.allo... | Lists AlloyDB users in a given cluster. | List | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class List:
"""Lists AlloyDB users in a given cluster."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser, Parser object for command line inputs"""
<|body_0|>
def Run(self, args):
"""Constructs and sends request. Args: args: argpa... | stack_v2_sparse_classes_75kplus_train_073196 | 2,743 | permissive | [
{
"docstring": "Specifies additional command flags. Args: parser: argparse.Parser, Parser object for command line inputs",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Constructs and sends request. Args: args: argparse.Namespace, An object that contains the values for the a... | 2 | stack_v2_sparse_classes_30k_train_043463 | Implement the Python class `List` described below.
Class description:
Lists AlloyDB users in a given cluster.
Method signatures and docstrings:
- def Args(parser): Specifies additional command flags. Args: parser: argparse.Parser, Parser object for command line inputs
- def Run(self, args): Constructs and sends reque... | Implement the Python class `List` described below.
Class description:
Lists AlloyDB users in a given cluster.
Method signatures and docstrings:
- def Args(parser): Specifies additional command flags. Args: parser: argparse.Parser, Parser object for command line inputs
- def Run(self, args): Constructs and sends reque... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class List:
"""Lists AlloyDB users in a given cluster."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser, Parser object for command line inputs"""
<|body_0|>
def Run(self, args):
"""Constructs and sends request. Args: args: argpa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class List:
"""Lists AlloyDB users in a given cluster."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser, Parser object for command line inputs"""
flags.AddRegion(parser)
flags.AddCluster(parser, False)
parser.display_info.AddFormat(_USER_... | the_stack_v2_python_sparse | lib/surface/alloydb/users/list.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
c3e45acad087ed28cd648d637fb225c4e8709c60 | [
"user = User.objects.create(username='testuser', password='qwerty12345Q!')\nrecruiter = User.objects.create(username='recruiter2', first_name='first_recruiter', last_name='last_recruiter', email='recruiter@mail.com')\ncandidate = User.objects.create(username='candidate2', first_name='first_candidate', last_name='la... | <|body_start_0|>
user = User.objects.create(username='testuser', password='qwerty12345Q!')
recruiter = User.objects.create(username='recruiter2', first_name='first_recruiter', last_name='last_recruiter', email='recruiter@mail.com')
candidate = User.objects.create(username='candidate2', first_nam... | Test POST request Interviews app | InterviewsPostTestCases | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterviewsPostTestCases:
"""Test POST request Interviews app"""
def setUp(self):
"""Create new data in in linked tables"""
<|body_0|>
def test_post_create_interviews(self):
"""Test for POST Interviews"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_073197 | 6,694 | no_license | [
{
"docstring": "Create new data in in linked tables",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test for POST Interviews",
"name": "test_post_create_interviews",
"signature": "def test_post_create_interviews(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052378 | Implement the Python class `InterviewsPostTestCases` described below.
Class description:
Test POST request Interviews app
Method signatures and docstrings:
- def setUp(self): Create new data in in linked tables
- def test_post_create_interviews(self): Test for POST Interviews | Implement the Python class `InterviewsPostTestCases` described below.
Class description:
Test POST request Interviews app
Method signatures and docstrings:
- def setUp(self): Create new data in in linked tables
- def test_post_create_interviews(self): Test for POST Interviews
<|skeleton|>
class InterviewsPostTestCas... | f448ec0453818d55c5c9d30aaa4f19e1d7ca5867 | <|skeleton|>
class InterviewsPostTestCases:
"""Test POST request Interviews app"""
def setUp(self):
"""Create new data in in linked tables"""
<|body_0|>
def test_post_create_interviews(self):
"""Test for POST Interviews"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterviewsPostTestCases:
"""Test POST request Interviews app"""
def setUp(self):
"""Create new data in in linked tables"""
user = User.objects.create(username='testuser', password='qwerty12345Q!')
recruiter = User.objects.create(username='recruiter2', first_name='first_recruiter',... | the_stack_v2_python_sparse | Portfolio/tech-interview/techinterview/interviews/test_interviews.py | HeCToR74/Python | train | 1 |
cd782c0bcc1da02ac3629bd9b0822570d58210d8 | [
"with patch('search.tasks._index_program_enrolled_users', autospec=True) as mocked:\n enrollment = ProgramEnrollment.objects.create(user=self.user, program=self.program)\nmocked.assert_called_once_with([enrollment])",
"with mute_signals(post_save):\n enrollment = ProgramEnrollment.objects.create(user=self.u... | <|body_start_0|>
with patch('search.tasks._index_program_enrolled_users', autospec=True) as mocked:
enrollment = ProgramEnrollment.objects.create(user=self.user, program=self.program)
mocked.assert_called_once_with([enrollment])
<|end_body_0|>
<|body_start_1|>
with mute_signals(post... | Test indexing on program enrollment | ProgramEnrollmentTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgramEnrollmentTests:
"""Test indexing on program enrollment"""
def test_create(self):
"""Tests that the database is reindexed when a ProgramEnrollment is created"""
<|body_0|>
def test_update(self):
"""Tests that the database is reindexed when a ProgramEnrollm... | stack_v2_sparse_classes_75kplus_train_073198 | 2,316 | no_license | [
{
"docstring": "Tests that the database is reindexed when a ProgramEnrollment is created",
"name": "test_create",
"signature": "def test_create(self)"
},
{
"docstring": "Tests that the database is reindexed when a ProgramEnrollment is created",
"name": "test_update",
"signature": "def te... | 3 | stack_v2_sparse_classes_30k_train_005806 | Implement the Python class `ProgramEnrollmentTests` described below.
Class description:
Test indexing on program enrollment
Method signatures and docstrings:
- def test_create(self): Tests that the database is reindexed when a ProgramEnrollment is created
- def test_update(self): Tests that the database is reindexed ... | Implement the Python class `ProgramEnrollmentTests` described below.
Class description:
Test indexing on program enrollment
Method signatures and docstrings:
- def test_create(self): Tests that the database is reindexed when a ProgramEnrollment is created
- def test_update(self): Tests that the database is reindexed ... | 3c166bc52dfe8d7aa04f922134f4f6deeff49eb6 | <|skeleton|>
class ProgramEnrollmentTests:
"""Test indexing on program enrollment"""
def test_create(self):
"""Tests that the database is reindexed when a ProgramEnrollment is created"""
<|body_0|>
def test_update(self):
"""Tests that the database is reindexed when a ProgramEnrollm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProgramEnrollmentTests:
"""Test indexing on program enrollment"""
def test_create(self):
"""Tests that the database is reindexed when a ProgramEnrollment is created"""
with patch('search.tasks._index_program_enrolled_users', autospec=True) as mocked:
enrollment = ProgramEnroll... | the_stack_v2_python_sparse | dashboard/signals_test.py | avontd2868/micromasters | train | 0 |
9c6c9a111726157737c42211a2eb3d0f35e4471d | [
"self.deque = deque([])\nself.dic = {}\nself.cap = capacity",
"if key not in self.dic:\n return -1\nself.deque.remove(key)\nself.deque.append(key)\nreturn self.dic[key]",
"if key in self.dic:\n self.deque.remove(key)\nelif len(self.dic) == self.cap:\n v = self.deque.popleft()\n self.dic.pop(v)\nself... | <|body_start_0|>
self.deque = deque([])
self.dic = {}
self.cap = capacity
<|end_body_0|>
<|body_start_1|>
if key not in self.dic:
return -1
self.deque.remove(key)
self.deque.append(key)
return self.dic[key]
<|end_body_1|>
<|body_start_2|>
if ... | LRUCache_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache_1:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus_train_073199 | 4,476 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_021802 | Implement the Python class `LRUCache_1` described below.
Class description:
Implement the LRUCache_1 class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache_1` described below.
Class description:
Implement the LRUCache_1 class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class LRUCache_1:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache_1:
def __init__(self, capacity):
""":type capacity: int"""
self.deque = deque([])
self.dic = {}
self.cap = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.dic:
return -1
self.deque.remove(key)
... | the_stack_v2_python_sparse | Solutions/0146_LRUCache.py | YoupengLi/leetcode-sorting | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.