blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
99c8c384b081271c6a6599b17906b01e1fa62678
[ "actor_ids = Infraction.objects.order_by().values_list('actor').distinct()\nactors = User.objects.filter(id__in=actor_ids)\nreturn ((a.id, a.username) for a in actors)", "if not self.value():\n return None\nreturn queryset.filter(actor__id=self.value())" ]
<|body_start_0|> actor_ids = Infraction.objects.order_by().values_list('actor').distinct() actors = User.objects.filter(id__in=actor_ids) return ((a.id, a.username) for a in actors) <|end_body_0|> <|body_start_1|> if not self.value(): return None return queryset.filt...
Actor Filter for Infraction Admin list page.
InfractionActorFilter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InfractionActorFilter: """Actor Filter for Infraction Admin list page.""" def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]: """Selectable values for viewer to filter by.""" <|body_0|> def queryset(self, request: HttpRequest, qu...
stack_v2_sparse_classes_36k_train_010300
14,240
permissive
[ { "docstring": "Selectable values for viewer to filter by.", "name": "lookups", "signature": "def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]" }, { "docstring": "Query to filter the list of Users against.", "name": "queryset", "signature": "de...
2
null
Implement the Python class `InfractionActorFilter` described below. Class description: Actor Filter for Infraction Admin list page. Method signatures and docstrings: - def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]: Selectable values for viewer to filter by. - def queryse...
Implement the Python class `InfractionActorFilter` described below. Class description: Actor Filter for Infraction Admin list page. Method signatures and docstrings: - def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]: Selectable values for viewer to filter by. - def queryse...
cb6326cabee6570a5725702cb2893ae39f752279
<|skeleton|> class InfractionActorFilter: """Actor Filter for Infraction Admin list page.""" def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]: """Selectable values for viewer to filter by.""" <|body_0|> def queryset(self, request: HttpRequest, qu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InfractionActorFilter: """Actor Filter for Infraction Admin list page.""" def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]: """Selectable values for viewer to filter by.""" actor_ids = Infraction.objects.order_by().values_list('actor').distinct(...
the_stack_v2_python_sparse
pydis_site/apps/api/admin.py
python-discord/site
train
746
ba75b39a7eab16a2f69e24dacad66033d6c364ee
[ "tipocontato = get_a_contacttype(id)\nif not tipocontato:\n api.abort(404)\nelse:\n return tipocontato", "tipocontato = get_a_contacttype(id)\nif not tipocontato:\n api.abort(404)\nelse:\n data = request.json\n return update_contacttype(tipocontato, data=data)" ]
<|body_start_0|> tipocontato = get_a_contacttype(id) if not tipocontato: api.abort(404) else: return tipocontato <|end_body_0|> <|body_start_1|> tipocontato = get_a_contacttype(id) if not tipocontato: api.abort(404) else: d...
Contato
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Contato: def get(self, id): """Obtem informações de um tipo contato com base no seu id""" <|body_0|> def patch(self, id): """Atualiza um tipo contato Obs: para inativar, coloque 'ativo': false""" <|body_1|> <|end_skeleton|> <|body_start_0|> tipocont...
stack_v2_sparse_classes_36k_train_010301
2,623
no_license
[ { "docstring": "Obtem informações de um tipo contato com base no seu id", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Atualiza um tipo contato Obs: para inativar, coloque 'ativo': false", "name": "patch", "signature": "def patch(self, id)" } ]
2
stack_v2_sparse_classes_30k_train_002285
Implement the Python class `Contato` described below. Class description: Implement the Contato class. Method signatures and docstrings: - def get(self, id): Obtem informações de um tipo contato com base no seu id - def patch(self, id): Atualiza um tipo contato Obs: para inativar, coloque 'ativo': false
Implement the Python class `Contato` described below. Class description: Implement the Contato class. Method signatures and docstrings: - def get(self, id): Obtem informações de um tipo contato com base no seu id - def patch(self, id): Atualiza um tipo contato Obs: para inativar, coloque 'ativo': false <|skeleton|> ...
a86fcb085af8567a661d47876f8b9f13d7b062a9
<|skeleton|> class Contato: def get(self, id): """Obtem informações de um tipo contato com base no seu id""" <|body_0|> def patch(self, id): """Atualiza um tipo contato Obs: para inativar, coloque 'ativo': false""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Contato: def get(self, id): """Obtem informações de um tipo contato com base no seu id""" tipocontato = get_a_contacttype(id) if not tipocontato: api.abort(404) else: return tipocontato def patch(self, id): """Atualiza um tipo contato Obs: p...
the_stack_v2_python_sparse
backend/app/main/controller/tipocontato_controller.py
AnderSilva/ozomali
train
1
1436eeb94d071103defcddc3abdb7610236b3b02
[ "if obj.sender:\n serializer = UserSerializer(obj.sender, context=self.context, fields=['id', 'username', 'email', 'name', 'last_name', 'second_last_name', 'photo'])\n return serializer.data", "if obj.target:\n serializer = NotificationTargetSerializer(obj, context=self.context)\n return serializer.da...
<|body_start_0|> if obj.sender: serializer = UserSerializer(obj.sender, context=self.context, fields=['id', 'username', 'email', 'name', 'last_name', 'second_last_name', 'photo']) return serializer.data <|end_body_0|> <|body_start_1|> if obj.target: serializer = Noti...
Serializer class for the ```tandlr.notifications.models.Notification``` model.
NotificationSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NotificationSerializer: """Serializer class for the ```tandlr.notifications.models.Notification``` model.""" def get_sender(self, obj): """Returns the notification's sender serialized with the minimal required fields.""" <|body_0|> def get_target(self, obj): """R...
stack_v2_sparse_classes_36k_train_010302
3,769
permissive
[ { "docstring": "Returns the notification's sender serialized with the minimal required fields.", "name": "get_sender", "signature": "def get_sender(self, obj)" }, { "docstring": "Returns the notification's target serialized with the minimal required fields.", "name": "get_target", "signa...
2
null
Implement the Python class `NotificationSerializer` described below. Class description: Serializer class for the ```tandlr.notifications.models.Notification``` model. Method signatures and docstrings: - def get_sender(self, obj): Returns the notification's sender serialized with the minimal required fields. - def get...
Implement the Python class `NotificationSerializer` described below. Class description: Serializer class for the ```tandlr.notifications.models.Notification``` model. Method signatures and docstrings: - def get_sender(self, obj): Returns the notification's sender serialized with the minimal required fields. - def get...
7349ce18f56658d67daedf5e1abb352b5c15a029
<|skeleton|> class NotificationSerializer: """Serializer class for the ```tandlr.notifications.models.Notification``` model.""" def get_sender(self, obj): """Returns the notification's sender serialized with the minimal required fields.""" <|body_0|> def get_target(self, obj): """R...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NotificationSerializer: """Serializer class for the ```tandlr.notifications.models.Notification``` model.""" def get_sender(self, obj): """Returns the notification's sender serialized with the minimal required fields.""" if obj.sender: serializer = UserSerializer(obj.sender, c...
the_stack_v2_python_sparse
src/tandlr/notifications/serializers.py
shrmoud/schoolapp
train
0
a269b48ae28189a78ab5a3872f5a97437aa33052
[ "self.act = eval(act)\nself.actstr = act\nself.n_inpl = n_inpl\nself.n_inpr = n_inpr\nself.n_out = n_out\nwbound = np.sqrt(9.0 / (n_inpl + n_inpr + n_out))\nW_values = rng.uniform(low=-wbound, high=wbound, size=(n_inpl, n_inpr, n_out))\nW_values = np.asarray(W_values, dtype=theano.config.floatX)\nself.W = theano.sh...
<|body_start_0|> self.act = eval(act) self.actstr = act self.n_inpl = n_inpl self.n_inpr = n_inpr self.n_out = n_out wbound = np.sqrt(9.0 / (n_inpl + n_inpr + n_out)) W_values = rng.uniform(low=-wbound, high=wbound, size=(n_inpl, n_inpr, n_out)) W_values =...
Class for a layer with bilinear interaction (n-mode vector-tensor product) on two input vectors with a tensor of parameters.
LayerBilinear
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LayerBilinear: """Class for a layer with bilinear interaction (n-mode vector-tensor product) on two input vectors with a tensor of parameters.""" def __init__(self, rng, act, n_inpl, n_inpr, n_out, tag=''): """Constructor. :param rng: numpy.random module for number generation. :param...
stack_v2_sparse_classes_36k_train_010303
46,645
permissive
[ { "docstring": "Constructor. :param rng: numpy.random module for number generation. :param act: name of the activation function ('lin', 'rect', 'tanh' or 'sigm'). :param n_inpl: dimension of the 'left' input. :param n_inpr: dimension of the 'right' input. :param n_out: output dimension. :param tag: name of the ...
3
stack_v2_sparse_classes_30k_train_001551
Implement the Python class `LayerBilinear` described below. Class description: Class for a layer with bilinear interaction (n-mode vector-tensor product) on two input vectors with a tensor of parameters. Method signatures and docstrings: - def __init__(self, rng, act, n_inpl, n_inpr, n_out, tag=''): Constructor. :par...
Implement the Python class `LayerBilinear` described below. Class description: Class for a layer with bilinear interaction (n-mode vector-tensor product) on two input vectors with a tensor of parameters. Method signatures and docstrings: - def __init__(self, rng, act, n_inpl, n_inpr, n_out, tag=''): Constructor. :par...
54b4c07fb9cf39a0fc84f5e384a9fc855f9d016f
<|skeleton|> class LayerBilinear: """Class for a layer with bilinear interaction (n-mode vector-tensor product) on two input vectors with a tensor of parameters.""" def __init__(self, rng, act, n_inpl, n_inpr, n_out, tag=''): """Constructor. :param rng: numpy.random module for number generation. :param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LayerBilinear: """Class for a layer with bilinear interaction (n-mode vector-tensor product) on two input vectors with a tensor of parameters.""" def __init__(self, rng, act, n_inpl, n_inpr, n_out, tag=''): """Constructor. :param rng: numpy.random module for number generation. :param act: name of...
the_stack_v2_python_sparse
SME/model.py
thjashin/kblearn
train
3
19a9ba593a2291e326679f61412abae28c0f07cc
[ "super().__init__(nup, ndown, cuda)\nself.cusp_weights = None\nself.fc1 = nn.Linear(1, size1, bias=False)\nself.fc2 = nn.Linear(size1, size2, bias=False)\nself.fc3 = nn.Linear(size2, 1, bias=False)\neps = 1e-06\nself.fc1.weight.data *= eps\nself.fc2.weight.data *= eps\nself.fc3.weight.data *= eps\nself.nl_func = ac...
<|body_start_0|> super().__init__(nup, ndown, cuda) self.cusp_weights = None self.fc1 = nn.Linear(1, size1, bias=False) self.fc2 = nn.Linear(size1, size2, bias=False) self.fc3 = nn.Linear(size2, 1, bias=False) eps = 1e-06 self.fc1.weight.data *= eps self.f...
FullyConnectedJastrowKernel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FullyConnectedJastrowKernel: def __init__(self, nup, ndown, cuda, size1=16, size2=8, activation=torch.nn.Sigmoid(), include_cusp_weight=True): """Defines a fully connected jastrow factors.""" <|body_0|> def get_var_weight(self): """define the variational weight.""" ...
stack_v2_sparse_classes_36k_train_010304
3,241
permissive
[ { "docstring": "Defines a fully connected jastrow factors.", "name": "__init__", "signature": "def __init__(self, nup, ndown, cuda, size1=16, size2=8, activation=torch.nn.Sigmoid(), include_cusp_weight=True)" }, { "docstring": "define the variational weight.", "name": "get_var_weight", "...
4
stack_v2_sparse_classes_30k_train_019225
Implement the Python class `FullyConnectedJastrowKernel` described below. Class description: Implement the FullyConnectedJastrowKernel class. Method signatures and docstrings: - def __init__(self, nup, ndown, cuda, size1=16, size2=8, activation=torch.nn.Sigmoid(), include_cusp_weight=True): Defines a fully connected ...
Implement the Python class `FullyConnectedJastrowKernel` described below. Class description: Implement the FullyConnectedJastrowKernel class. Method signatures and docstrings: - def __init__(self, nup, ndown, cuda, size1=16, size2=8, activation=torch.nn.Sigmoid(), include_cusp_weight=True): Defines a fully connected ...
439a79e97ee63057e3032d28a1a5ebafd2d5b5e4
<|skeleton|> class FullyConnectedJastrowKernel: def __init__(self, nup, ndown, cuda, size1=16, size2=8, activation=torch.nn.Sigmoid(), include_cusp_weight=True): """Defines a fully connected jastrow factors.""" <|body_0|> def get_var_weight(self): """define the variational weight.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FullyConnectedJastrowKernel: def __init__(self, nup, ndown, cuda, size1=16, size2=8, activation=torch.nn.Sigmoid(), include_cusp_weight=True): """Defines a fully connected jastrow factors.""" super().__init__(nup, ndown, cuda) self.cusp_weights = None self.fc1 = nn.Linear(1, si...
the_stack_v2_python_sparse
qmctorch/wavefunction/jastrows/elec_elec/kernels/fully_connected_jastrow_kernel.py
NLESC-JCER/QMCTorch
train
22
eb2c22f454df340957439f442f9b6e0ba02e3157
[ "super().__init__()\nself.generator = generator_cls(latent_dim, num_channels, img_size, n_residual_blocks, num_filts)\nself.discriminator = discriminator_cls(num_channels)\nself.classifier = clf_cls(num_channels, img_size, n_classes)\nself.generator.apply(weights_init_normal)\nself.discriminator.apply(weights_init_...
<|body_start_0|> super().__init__() self.generator = generator_cls(latent_dim, num_channels, img_size, n_residual_blocks, num_filts) self.discriminator = discriminator_cls(num_channels) self.classifier = clf_cls(num_channels, img_size, n_classes) self.generator.apply(weights_init...
Class implementing the Unsupervised Pixel-Level Domain Adaptation with Generative Adversarial Networks References ---------- `Paper <https://arxiv.org/abs/1612.05424>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this n...
PixelDomainAdaptation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PixelDomainAdaptation: """Class implementing the Unsupervised Pixel-Level Domain Adaptation with Generative Adversarial Networks References ---------- `Paper <https://arxiv.org/abs/1612.05424>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already t...
stack_v2_sparse_classes_36k_train_010305
6,091
permissive
[ { "docstring": "Parameters ---------- img_size : int number of pixels per image side num_channels : int number of image channels latent_dim : int size of latent dimension n_classes : int number of classes n_residual_blocks : int number of residual blocks to include num_filts : int number of filters per convolut...
2
null
Implement the Python class `PixelDomainAdaptation` described below. Class description: Class implementing the Unsupervised Pixel-Level Domain Adaptation with Generative Adversarial Networks References ---------- `Paper <https://arxiv.org/abs/1612.05424>`_ Warnings -------- This Network is designed for training only; i...
Implement the Python class `PixelDomainAdaptation` described below. Class description: Class implementing the Unsupervised Pixel-Level Domain Adaptation with Generative Adversarial Networks References ---------- `Paper <https://arxiv.org/abs/1612.05424>`_ Warnings -------- This Network is designed for training only; i...
1078f5030b8aac2bf022daf5fa14d66f74c3c893
<|skeleton|> class PixelDomainAdaptation: """Class implementing the Unsupervised Pixel-Level Domain Adaptation with Generative Adversarial Networks References ---------- `Paper <https://arxiv.org/abs/1612.05424>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PixelDomainAdaptation: """Class implementing the Unsupervised Pixel-Level Domain Adaptation with Generative Adversarial Networks References ---------- `Paper <https://arxiv.org/abs/1612.05424>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained networ...
the_stack_v2_python_sparse
dlutils/models/gans/pixel_da/pixel_da.py
justusschock/dl-utils
train
15
b1ce921dea63c8dbb9ebbc5a2bb43e0112deb5b3
[ "if hasattr(self, 'order'):\n order = self.order\n pivot, pvar = ((1,) + (0,) * (self.number_of_variables - 1), 0)\n for var in range(1, self.number_of_variables):\n vindex = (0,) * var + (1,) + (0,) * (self.number_of_variables - var - 1)\n if order.cmp(pivot, vindex) < 0:\n pivot,...
<|body_start_0|> if hasattr(self, 'order'): order = self.order pivot, pvar = ((1,) + (0,) * (self.number_of_variables - 1), 0) for var in range(1, self.number_of_variables): vindex = (0,) * var + (1,) + (0,) * (self.number_of_variables - var - 1) ...
Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction.
NestProvider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NestProvider: """Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction.""" def leading_variable(self): """Return the position of the leading variable (the leading term among all total degree one terms). The l...
stack_v2_sparse_classes_36k_train_010306
24,835
no_license
[ { "docstring": "Return the position of the leading variable (the leading term among all total degree one terms). The leading term varies with term orders, so does the result. The term order can be specified via the attribute 'order'.", "name": "leading_variable", "signature": "def leading_variable(self)...
3
null
Implement the Python class `NestProvider` described below. Class description: Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction. Method signatures and docstrings: - def leading_variable(self): Return the position of the leading variable (...
Implement the Python class `NestProvider` described below. Class description: Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction. Method signatures and docstrings: - def leading_variable(self): Return the position of the leading variable (...
a48ae9efcf0d9ad1485c2e9863c948a7f1b20311
<|skeleton|> class NestProvider: """Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction.""" def leading_variable(self): """Return the position of the leading variable (the leading term among all total degree one terms). The l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NestProvider: """Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction.""" def leading_variable(self): """Return the position of the leading variable (the leading term among all total degree one terms). The leading term v...
the_stack_v2_python_sparse
nzmath/poly/multiutil.py
turkeydonkey/nzmath3
train
2
15ed22f7fffd066270fb8d0534cc859287a9c769
[ "super().__init__(x, y)\nself.fill_color = QtCore.Qt.lightGray\nself.line_color = QtCore.Qt.darkGray\nself.dx = random.randint(1, 3) * random.choice([-1, 1])\nself.dy = random.randint(1, 3) * random.choice([-1, 1])", "self.x += self.dx\nself.y += self.dy\nif self.x < 0 or self.x > w:\n self.dx *= -1\nif self.y...
<|body_start_0|> super().__init__(x, y) self.fill_color = QtCore.Qt.lightGray self.line_color = QtCore.Qt.darkGray self.dx = random.randint(1, 3) * random.choice([-1, 1]) self.dy = random.randint(1, 3) * random.choice([-1, 1]) <|end_body_0|> <|body_start_1|> self.x += se...
Class to represent a Dodo bird.
Dodo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dodo: """Class to represent a Dodo bird.""" def __init__(self, x, y): """Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.""" <|body_0|> def move(self, w, h): """A Do...
stack_v2_sparse_classes_36k_train_010307
13,878
no_license
[ { "docstring": "Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.", "name": "__init__", "signature": "def __init__(self, x, y)" }, { "docstring": "A Dodo bird flies in straight lines and bounces off ...
2
stack_v2_sparse_classes_30k_train_004827
Implement the Python class `Dodo` described below. Class description: Class to represent a Dodo bird. Method signatures and docstrings: - def __init__(self, x, y): Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero. - def m...
Implement the Python class `Dodo` described below. Class description: Class to represent a Dodo bird. Method signatures and docstrings: - def __init__(self, x, y): Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero. - def m...
0e3470085083012f893adb22aa46d46039016965
<|skeleton|> class Dodo: """Class to represent a Dodo bird.""" def __init__(self, x, y): """Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.""" <|body_0|> def move(self, w, h): """A Do...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dodo: """Class to represent a Dodo bird.""" def __init__(self, x, y): """Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.""" super().__init__(x, y) self.fill_color = QtCore.Qt.lightGr...
the_stack_v2_python_sparse
CS_210 (Introduction to Programming)/Labs/Lab34_AviaryApp.py
JacobOrner/USAFA
train
0
ca809099a2db6f2598cc95337667951ef8095c00
[ "now_time = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')\nmylogs.log_info('-----------------------test_7operate_monitor---------------------------')\nmylogs.log_info('Start to execute test set env and launch ota at {}'.format(now_time))", "user.click_connect_btn()\nsp(2)\nuser.click_download_and_install_...
<|body_start_0|> now_time = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S') mylogs.log_info('-----------------------test_7operate_monitor---------------------------') mylogs.log_info('Start to execute test set env and launch ota at {}'.format(now_time)) <|end_body_0|> <|body_start_1|> ...
TestOtaSmokeClass
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestOtaSmokeClass: def setup_class(self): """Execute one time before run all cases""" <|body_0|> def test_operate_monitor(self): """Todo://1.connet,download,install 2.take screen shot""" <|body_1|> def teardown_class(self): """Execute one time af...
stack_v2_sparse_classes_36k_train_010308
3,731
permissive
[ { "docstring": "Execute one time before run all cases", "name": "setup_class", "signature": "def setup_class(self)" }, { "docstring": "Todo://1.connet,download,install 2.take screen shot", "name": "test_operate_monitor", "signature": "def test_operate_monitor(self)" }, { "docstri...
3
stack_v2_sparse_classes_30k_train_000137
Implement the Python class `TestOtaSmokeClass` described below. Class description: Implement the TestOtaSmokeClass class. Method signatures and docstrings: - def setup_class(self): Execute one time before run all cases - def test_operate_monitor(self): Todo://1.connet,download,install 2.take screen shot - def teardow...
Implement the Python class `TestOtaSmokeClass` described below. Class description: Implement the TestOtaSmokeClass class. Method signatures and docstrings: - def setup_class(self): Execute one time before run all cases - def test_operate_monitor(self): Todo://1.connet,download,install 2.take screen shot - def teardow...
e4afa8944785c1dc1dc80550073858d03a77d629
<|skeleton|> class TestOtaSmokeClass: def setup_class(self): """Execute one time before run all cases""" <|body_0|> def test_operate_monitor(self): """Todo://1.connet,download,install 2.take screen shot""" <|body_1|> def teardown_class(self): """Execute one time af...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestOtaSmokeClass: def setup_class(self): """Execute one time before run all cases""" now_time = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S') mylogs.log_info('-----------------------test_7operate_monitor---------------------------') mylogs.log_info('Start to execute te...
the_stack_v2_python_sparse
testcases/smoke/dongfeng/test_dongfeng_smoke/test_7operate_monitor.py
uniquelover/ota_smoke_auto
train
0
d4ba1cd917884ee1503fe147fe6bb3ed9493e61f
[ "if not root:\n return 'n'\ns = ''\nstack = [root]\nwhile stack:\n root = stack.pop(0)\n if root:\n s += str(root.val)\n stack.append(root.left)\n stack.append(root.right)\n else:\n s += 'n'\n s += ' '\nreturn s", "if not data:\n return None\ntree = data.split()\nif t...
<|body_start_0|> if not root: return 'n' s = '' stack = [root] while stack: root = stack.pop(0) if root: s += str(root.val) stack.append(root.left) stack.append(root.right) else: ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_010309
2,353
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_019055
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:...
ce29ea836bd20841d69972180273e4d4ec11514d
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return 'n' s = '' stack = [root] while stack: root = stack.pop(0) if root: s += str(root.val) ...
the_stack_v2_python_sparse
37.py
NeilWangziyu/JZOffer
train
1
6fd479b4ad064a3851a7abe08fe12bea95a3690a
[ "if logger is None:\n logger = InferLogger(args.log_path)\noutput_data_dir = None\nmodel_path = args.model_file\nparam_path = args.params_file\ncfg = CommonFunc.get_framework_config(model_path, args)\nif args.input_data_file is not None:\n input_data_map = np.load(args.input_data_file, allow_pickle=True).item...
<|body_start_0|> if logger is None: logger = InferLogger(args.log_path) output_data_dir = None model_path = args.model_file param_path = args.params_file cfg = CommonFunc.get_framework_config(model_path, args) if args.input_data_file is not None: i...
functions for model easy infer
EasyInfer
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "MPL-1.0", "OpenSSL", "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause-Open-MPI", "MIT", "MPL-2.0-no-copyleft-exception", "NTP", "BSD-3-Clause", "GPL-1.0-or-later", "0BSD", "MPL-2.0", "LicenseRef-scancode-f...
stack_v2_sparse_python_classes_v1
<|skeleton|> class EasyInfer: """functions for model easy infer""" def easy_infer(args, logger=None): """model easy infer""" <|body_0|> def ms_dynamic_input_infer(args, logger=None): """conduct dynamic shape mindspore lite model infer""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_36k_train_010310
3,725
permissive
[ { "docstring": "model easy infer", "name": "easy_infer", "signature": "def easy_infer(args, logger=None)" }, { "docstring": "conduct dynamic shape mindspore lite model infer", "name": "ms_dynamic_input_infer", "signature": "def ms_dynamic_input_infer(args, logger=None)" } ]
2
null
Implement the Python class `EasyInfer` described below. Class description: functions for model easy infer Method signatures and docstrings: - def easy_infer(args, logger=None): model easy infer - def ms_dynamic_input_infer(args, logger=None): conduct dynamic shape mindspore lite model infer
Implement the Python class `EasyInfer` described below. Class description: functions for model easy infer Method signatures and docstrings: - def easy_infer(args, logger=None): model easy infer - def ms_dynamic_input_infer(args, logger=None): conduct dynamic shape mindspore lite model infer <|skeleton|> class EasyIn...
54acb15d435533c815ee1bd9f6dc0b56b4d4cf83
<|skeleton|> class EasyInfer: """functions for model easy infer""" def easy_infer(args, logger=None): """model easy infer""" <|body_0|> def ms_dynamic_input_infer(args, logger=None): """conduct dynamic shape mindspore lite model infer""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EasyInfer: """functions for model easy infer""" def easy_infer(args, logger=None): """model easy infer""" if logger is None: logger = InferLogger(args.log_path) output_data_dir = None model_path = args.model_file param_path = args.params_file cf...
the_stack_v2_python_sparse
mindspore/lite/tools/mslite_bench/mslite_bench/tools/easy_infer.py
mindspore-ai/mindspore
train
4,178
0c60df827ef68aa87cf300f137aaa9d9d6725dcc
[ "self.disk_to_overwrite = disk_to_overwrite\nself.src_disk = src_disk\nself.target_location = target_location", "if dictionary is None:\n return None\ndisk_to_overwrite = cohesity_management_sdk.models.virtual_disk_id.VirtualDiskId.from_dictionary(dictionary.get('diskToOverwrite')) if dictionary.get('diskToOve...
<|body_start_0|> self.disk_to_overwrite = disk_to_overwrite self.src_disk = src_disk self.target_location = target_location <|end_body_0|> <|body_start_1|> if dictionary is None: return None disk_to_overwrite = cohesity_management_sdk.models.virtual_disk_id.VirtualDi...
Implementation of the 'RecoverVirtualDiskParams_VirtualDiskMapping' model. TODO: type description here. Attributes: disk_to_overwrite (VirtualDiskId): If the user is overwriting a destination disk, then this will capture the target disk info. NOTE: If this is specified, then power_off_vm_before_recovery must be true. s...
RecoverVirtualDiskParams_VirtualDiskMapping
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RecoverVirtualDiskParams_VirtualDiskMapping: """Implementation of the 'RecoverVirtualDiskParams_VirtualDiskMapping' model. TODO: type description here. Attributes: disk_to_overwrite (VirtualDiskId): If the user is overwriting a destination disk, then this will capture the target disk info. NOTE: ...
stack_v2_sparse_classes_36k_train_010311
2,838
permissive
[ { "docstring": "Constructor for the RecoverVirtualDiskParams_VirtualDiskMapping class", "name": "__init__", "signature": "def __init__(self, disk_to_overwrite=None, src_disk=None, target_location=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dict...
2
stack_v2_sparse_classes_30k_val_000173
Implement the Python class `RecoverVirtualDiskParams_VirtualDiskMapping` described below. Class description: Implementation of the 'RecoverVirtualDiskParams_VirtualDiskMapping' model. TODO: type description here. Attributes: disk_to_overwrite (VirtualDiskId): If the user is overwriting a destination disk, then this wi...
Implement the Python class `RecoverVirtualDiskParams_VirtualDiskMapping` described below. Class description: Implementation of the 'RecoverVirtualDiskParams_VirtualDiskMapping' model. TODO: type description here. Attributes: disk_to_overwrite (VirtualDiskId): If the user is overwriting a destination disk, then this wi...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RecoverVirtualDiskParams_VirtualDiskMapping: """Implementation of the 'RecoverVirtualDiskParams_VirtualDiskMapping' model. TODO: type description here. Attributes: disk_to_overwrite (VirtualDiskId): If the user is overwriting a destination disk, then this will capture the target disk info. NOTE: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RecoverVirtualDiskParams_VirtualDiskMapping: """Implementation of the 'RecoverVirtualDiskParams_VirtualDiskMapping' model. TODO: type description here. Attributes: disk_to_overwrite (VirtualDiskId): If the user is overwriting a destination disk, then this will capture the target disk info. NOTE: If this is sp...
the_stack_v2_python_sparse
cohesity_management_sdk/models/recover_virtual_disk_params_virtual_disk_mapping.py
cohesity/management-sdk-python
train
24
1dcb1be470b8860874d5189c7bc3e8f42a43472a
[ "super().__init__(**kwargs)\nself._index = idx\nself.setTitle(f'ROI{idx}')", "image = data.image.masked_mean\nx, y, w, h = getattr(getattr(data.roi, f'geom{self._index}'), 'geometry')\nif w < 0 or h < 0:\n return\nself.setImage(image[y:y + h, x:x + w])" ]
<|body_start_0|> super().__init__(**kwargs) self._index = idx self.setTitle(f'ROI{idx}') <|end_body_0|> <|body_start_1|> image = data.image.masked_mean x, y, w, h = getattr(getattr(data.roi, f'geom{self._index}'), 'geometry') if w < 0 or h < 0: return ...
RoiImageView class. Widget for displaying the ROI for the assembled image.
RoiImageView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoiImageView: """RoiImageView class. Widget for displaying the ROI for the assembled image.""" def __init__(self, idx, **kwargs): """Initialization.""" <|body_0|> def updateF(self, data): """Override.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_010312
7,391
permissive
[ { "docstring": "Initialization.", "name": "__init__", "signature": "def __init__(self, idx, **kwargs)" }, { "docstring": "Override.", "name": "updateF", "signature": "def updateF(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_011300
Implement the Python class `RoiImageView` described below. Class description: RoiImageView class. Widget for displaying the ROI for the assembled image. Method signatures and docstrings: - def __init__(self, idx, **kwargs): Initialization. - def updateF(self, data): Override.
Implement the Python class `RoiImageView` described below. Class description: RoiImageView class. Widget for displaying the ROI for the assembled image. Method signatures and docstrings: - def __init__(self, idx, **kwargs): Initialization. - def updateF(self, data): Override. <|skeleton|> class RoiImageView: """...
a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0
<|skeleton|> class RoiImageView: """RoiImageView class. Widget for displaying the ROI for the assembled image.""" def __init__(self, idx, **kwargs): """Initialization.""" <|body_0|> def updateF(self, data): """Override.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RoiImageView: """RoiImageView class. Widget for displaying the ROI for the assembled image.""" def __init__(self, idx, **kwargs): """Initialization.""" super().__init__(**kwargs) self._index = idx self.setTitle(f'ROI{idx}') def updateF(self, data): """Override...
the_stack_v2_python_sparse
extra_foam/gui/plot_widgets/image_views.py
European-XFEL/EXtra-foam
train
8
9990115b8e8732f451610a6d64d92f93b7725dab
[ "ndict = {}\nfor i in range(len(nums)):\n dif = target - nums[i]\n if dif in ndict.values():\n return [i, ndict.keys()[ndict.values().index(dif)]]\n ndict[i] = nums[i]\nreturn []", "hasht = {k: v for v, k in enumerate(nums)}\nfor i, el in enumerate(nums):\n res = target - el\n if hasht.get(r...
<|body_start_0|> ndict = {} for i in range(len(nums)): dif = target - nums[i] if dif in ndict.values(): return [i, ndict.keys()[ndict.values().index(dif)]] ndict[i] = nums[i] return [] <|end_body_0|> <|body_start_1|> hasht = {k: v for ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def twoSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def twoSumDictv2(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_1|> def twoSumBruteF(self, n...
stack_v2_sparse_classes_36k_train_010313
1,571
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: List[int]", "name": "twoSum", "signature": "def twoSum(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: List[int]", "name": "twoSumDictv2", "signature": "def twoSumDictv2(self, nums, ta...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] - def twoSumDictv2(self, nums, target): :type nums: List[int] :type target: int :rtype: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] - def twoSumDictv2(self, nums, target): :type nums: List[int] :type target: int :rtype: ...
b3a2013d1c3c7a5a16727dbc2ecbc934a01a3979
<|skeleton|> class Solution: def twoSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def twoSumDictv2(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_1|> def twoSumBruteF(self, n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def twoSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" ndict = {} for i in range(len(nums)): dif = target - nums[i] if dif in ndict.values(): return [i, ndict.keys()[ndict.values().index(dif)]] ...
the_stack_v2_python_sparse
LeetcodePython/TwoSum1.py
DianaLuca/Algorithms
train
1
e3f2162dc73b1e34d958149db47aef6156d983a0
[ "try:\n name = cls(value).name\nexcept ValueError:\n return '{}({:#x} = ?)'.format(cls.__name__, value)\nelse:\n assert name.startswith('TPM_ALG_')\n return name[8:]", "if self == TpmAlgId.TPM_ALG_SHA1:\n return hashlib.sha1(data).digest()\nif self == TpmAlgId.TPM_ALG_SHA256:\n return hashlib.sh...
<|body_start_0|> try: name = cls(value).name except ValueError: return '{}({:#x} = ?)'.format(cls.__name__, value) else: assert name.startswith('TPM_ALG_') return name[8:] <|end_body_0|> <|body_start_1|> if self == TpmAlgId.TPM_ALG_SHA1: ...
TPM_ALG_ID constants
TpmAlgId
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TpmAlgId: """TPM_ALG_ID constants""" def get_name(cls, value): """Get the algorithm from the ID value""" <|body_0|> def digest(self, data): """Compute the digest of the data""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: name =...
stack_v2_sparse_classes_36k_train_010314
27,705
permissive
[ { "docstring": "Get the algorithm from the ID value", "name": "get_name", "signature": "def get_name(cls, value)" }, { "docstring": "Compute the digest of the data", "name": "digest", "signature": "def digest(self, data)" } ]
2
null
Implement the Python class `TpmAlgId` described below. Class description: TPM_ALG_ID constants Method signatures and docstrings: - def get_name(cls, value): Get the algorithm from the ID value - def digest(self, data): Compute the digest of the data
Implement the Python class `TpmAlgId` described below. Class description: TPM_ALG_ID constants Method signatures and docstrings: - def get_name(cls, value): Get the algorithm from the ID value - def digest(self, data): Compute the digest of the data <|skeleton|> class TpmAlgId: """TPM_ALG_ID constants""" de...
a846ce38894f749082405d9a86fcf13d0bf5b992
<|skeleton|> class TpmAlgId: """TPM_ALG_ID constants""" def get_name(cls, value): """Get the algorithm from the ID value""" <|body_0|> def digest(self, data): """Compute the digest of the data""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TpmAlgId: """TPM_ALG_ID constants""" def get_name(cls, value): """Get the algorithm from the ID value""" try: name = cls(value).name except ValueError: return '{}({:#x} = ?)'.format(cls.__name__, value) else: assert name.startswith('TPM_...
the_stack_v2_python_sparse
python/crypto/tpm_decode_bios_measurements.py
fishilico/shared
train
35
47136e7f2cefb379a4bce939d371d98ccf55f6c5
[ "self.terms = GetText(node.getElementsByTagName('Q')[0])\nparams = node.getElementsByTagName('PARAM')\nfor param in params:\n name = param.getAttribute('name')\n if name == 'num':\n self.size = param.getAttribute('value')\n elif name == 'start':\n self.start = param.getAttribute('value')\nele...
<|body_start_0|> self.terms = GetText(node.getElementsByTagName('Q')[0]) params = node.getElementsByTagName('PARAM') for param in params: name = param.getAttribute('name') if name == 'num': self.size = param.getAttribute('value') elif name == '...
A wrapper around the XML of a search response
Response
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Response: """A wrapper around the XML of a search response""" def __init__(self, node): """Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the requested number of search results start: the requested start i...
stack_v2_sparse_classes_36k_train_010315
20,975
no_license
[ { "docstring": "Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the requested number of search results start: the requested start index (offset 0) first: the index (offset 1) of the first result in the response last: the index (offset...
2
null
Implement the Python class `Response` described below. Class description: A wrapper around the XML of a search response Method signatures and docstrings: - def __init__(self, node): Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the reques...
Implement the Python class `Response` described below. Class description: A wrapper around the XML of a search response Method signatures and docstrings: - def __init__(self, node): Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the reques...
99ad033be03779e9680ce8024cdd7a4bdc5a58bd
<|skeleton|> class Response: """A wrapper around the XML of a search response""" def __init__(self, node): """Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the requested number of search results start: the requested start i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Response: """A wrapper around the XML of a search response""" def __init__(self, node): """Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the requested number of search results start: the requested start index (offset ...
the_stack_v2_python_sparse
pubConvGoogle
maximilianh/pubMunch
train
43
698d2ccebcaf0dd43f5dc301eafefd5b2bb6dcb2
[ "res = ''\ns = longUrl\nfor i in range(len(s)):\n res += str(ord(s[i]) + 1) + '*'\nreturn res", "s = shortUrl\ntemp = ''\ns = s.split('*')\nfor i in range(len(s)):\n if len(s[i]) != 0:\n temp += str(chr(int(s[i]) - 1))\nreturn temp" ]
<|body_start_0|> res = '' s = longUrl for i in range(len(s)): res += str(ord(s[i]) + 1) + '*' return res <|end_body_0|> <|body_start_1|> s = shortUrl temp = '' s = s.split('*') for i in range(len(s)): if len(s[i]) != 0: ...
Codec
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, longUrl: str) -> str: """Encodes a URL to a shortened URL.""" <|body_0|> def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to its original URL.""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = '' ...
stack_v2_sparse_classes_36k_train_010316
1,433
permissive
[ { "docstring": "Encodes a URL to a shortened URL.", "name": "encode", "signature": "def encode(self, longUrl: str) -> str" }, { "docstring": "Decodes a shortened URL to its original URL.", "name": "decode", "signature": "def decode(self, shortUrl: str) -> str" } ]
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL. - def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL. - def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL. <|skeleton|> class Code...
68dac358a6d4dabd41d47dbd4addb2ec50e0ca11
<|skeleton|> class Codec: def encode(self, longUrl: str) -> str: """Encodes a URL to a shortened URL.""" <|body_0|> def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to its original URL.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def encode(self, longUrl: str) -> str: """Encodes a URL to a shortened URL.""" res = '' s = longUrl for i in range(len(s)): res += str(ord(s[i]) + 1) + '*' return res def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to i...
the_stack_v2_python_sparse
encode_and_decode_tiny_url.py
erjan/coding_exercises
train
5
f6fc5676c7d9015c28ead1d3ba4348b2cc19fd59
[ "self.name = name\nself.parameters = parameters\nself.annotations = annotations\nself.provisioner = provisioner\nself.api_version = api_version\nself.default_storage_class = str(default_storage_class).lower()\nself.kubeconfig = kubeconfig\nself.mount_options = mount_options\nself.reclaim_policy = reclaim_policy\nse...
<|body_start_0|> self.name = name self.parameters = parameters self.annotations = annotations self.provisioner = provisioner self.api_version = api_version self.default_storage_class = str(default_storage_class).lower() self.kubeconfig = kubeconfig self.mo...
Handle service options
StorageClassConfig
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StorageClassConfig: """Handle service options""" def __init__(self, name, provisioner, parameters=None, annotations=None, default_storage_class='false', api_version='v1', kubeconfig='/etc/origin/master/admin.kubeconfig', mount_options=None, reclaim_policy=None): """constructor for ha...
stack_v2_sparse_classes_36k_train_010317
3,122
permissive
[ { "docstring": "constructor for handling storageclass options", "name": "__init__", "signature": "def __init__(self, name, provisioner, parameters=None, annotations=None, default_storage_class='false', api_version='v1', kubeconfig='/etc/origin/master/admin.kubeconfig', mount_options=None, reclaim_policy...
2
null
Implement the Python class `StorageClassConfig` described below. Class description: Handle service options Method signatures and docstrings: - def __init__(self, name, provisioner, parameters=None, annotations=None, default_storage_class='false', api_version='v1', kubeconfig='/etc/origin/master/admin.kubeconfig', mou...
Implement the Python class `StorageClassConfig` described below. Class description: Handle service options Method signatures and docstrings: - def __init__(self, name, provisioner, parameters=None, annotations=None, default_storage_class='false', api_version='v1', kubeconfig='/etc/origin/master/admin.kubeconfig', mou...
e342f6659a4ef1a188ff403e2fc6b06ac6d119c7
<|skeleton|> class StorageClassConfig: """Handle service options""" def __init__(self, name, provisioner, parameters=None, annotations=None, default_storage_class='false', api_version='v1', kubeconfig='/etc/origin/master/admin.kubeconfig', mount_options=None, reclaim_policy=None): """constructor for ha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StorageClassConfig: """Handle service options""" def __init__(self, name, provisioner, parameters=None, annotations=None, default_storage_class='false', api_version='v1', kubeconfig='/etc/origin/master/admin.kubeconfig', mount_options=None, reclaim_policy=None): """constructor for handling storag...
the_stack_v2_python_sparse
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/src/lib/storageclass.py
openshift/openshift-tools
train
170
6ccaa1fbba33f9a0bbcb608307505b1b45f8a05f
[ "N = len(nums) - 1\ndp = [sys.maxsize] * N\nif N <= 0:\n return 0\nfor i in range(N - 1, -1, -1):\n cur = nums[i]\n if cur == 0:\n continue\n if cur + i < N:\n for j in range(cur, 0, -1):\n if dp[i + j] != sys.maxsize:\n dp[i] = min(dp[i], dp[i + j] + 1)\n else...
<|body_start_0|> N = len(nums) - 1 dp = [sys.maxsize] * N if N <= 0: return 0 for i in range(N - 1, -1, -1): cur = nums[i] if cur == 0: continue if cur + i < N: for j in range(cur, 0, -1): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def jump(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def jump2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> N = len(nums) - 1 dp = [sys.maxsize] * N i...
stack_v2_sparse_classes_36k_train_010318
1,613
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "jump", "signature": "def jump(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "jump2", "signature": "def jump2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_020370
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jump(self, nums): :type nums: List[int] :rtype: int - def jump2(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jump(self, nums): :type nums: List[int] :rtype: int - def jump2(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def jump(self, nums): ...
b77130a0133cd40990c4d7096db5e388de67cbf2
<|skeleton|> class Solution: def jump(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def jump2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def jump(self, nums): """:type nums: List[int] :rtype: int""" N = len(nums) - 1 dp = [sys.maxsize] * N if N <= 0: return 0 for i in range(N - 1, -1, -1): cur = nums[i] if cur == 0: continue if cur...
the_stack_v2_python_sparse
45.JumpGame.py
flavorfan/MyLeetCode
train
0
b145369efa61701f6f9138a9519b412ff67d40a0
[ "number_of_nodes = 4\nflights = [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]]\nsource = 0\ndestination = 3\nallowed_stops = 1\nresult = find_cheapest_price(number_of_nodes, flights, source, destination, allowed_stops)\nself.assertEqual(result, 700)", "number_of_nodes = 4\nflights = [[0, 1, 100...
<|body_start_0|> number_of_nodes = 4 flights = [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]] source = 0 destination = 3 allowed_stops = 1 result = find_cheapest_price(number_of_nodes, flights, source, destination, allowed_stops) self.assertEqua...
TestFindCheapestPrice
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFindCheapestPrice: def test_finds_cheapest_flight_in_list_of_flights(self): """Finds the cheapest flight within allowed stops using a list of flights and prices""" <|body_0|> def test_returns_negative_one_if_no_route_is_found(self): """Returns -1 if no flight rou...
stack_v2_sparse_classes_36k_train_010319
1,067
permissive
[ { "docstring": "Finds the cheapest flight within allowed stops using a list of flights and prices", "name": "test_finds_cheapest_flight_in_list_of_flights", "signature": "def test_finds_cheapest_flight_in_list_of_flights(self)" }, { "docstring": "Returns -1 if no flight route can be found in lis...
2
null
Implement the Python class `TestFindCheapestPrice` described below. Class description: Implement the TestFindCheapestPrice class. Method signatures and docstrings: - def test_finds_cheapest_flight_in_list_of_flights(self): Finds the cheapest flight within allowed stops using a list of flights and prices - def test_re...
Implement the Python class `TestFindCheapestPrice` described below. Class description: Implement the TestFindCheapestPrice class. Method signatures and docstrings: - def test_finds_cheapest_flight_in_list_of_flights(self): Finds the cheapest flight within allowed stops using a list of flights and prices - def test_re...
27ffb6b32d6d18d279c51cfa45bf305a409be5c2
<|skeleton|> class TestFindCheapestPrice: def test_finds_cheapest_flight_in_list_of_flights(self): """Finds the cheapest flight within allowed stops using a list of flights and prices""" <|body_0|> def test_returns_negative_one_if_no_route_is_found(self): """Returns -1 if no flight rou...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestFindCheapestPrice: def test_finds_cheapest_flight_in_list_of_flights(self): """Finds the cheapest flight within allowed stops using a list of flights and prices""" number_of_nodes = 4 flights = [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]] source = 0 ...
the_stack_v2_python_sparse
src/leetcode/medium/find-cheapest-flight-within-k-flights/test_find_cheapest_flight_within_k_flights.py
nwthomas/code-challenges
train
2
4114bb93515e6adbe8553b56ed93467b547d65aa
[ "try:\n code = settings.API_ERROR_CODE[message]\nexcept KeyError:\n logger.error('API: System error when get the code of message \"%(message)s\"' % {'message': message})\n code = -1\nreturn code", "errors = self.errors\nnew_errors = {'errors': []}\nfor key, value in errors.items():\n if key == 'non_fi...
<|body_start_0|> try: code = settings.API_ERROR_CODE[message] except KeyError: logger.error('API: System error when get the code of message "%(message)s"' % {'message': message}) code = -1 return code <|end_body_0|> <|body_start_1|> errors = self.erro...
CustomSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomSerializer: def get_api_code(message): """根据 message 获得相应的 API 错误代码""" <|body_0|> def process_errors(self): """对 API 错误信息进行处理后输出, 主要为整理格式""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: code = settings.API_ERROR_CODE[message] ...
stack_v2_sparse_classes_36k_train_010320
1,467
no_license
[ { "docstring": "根据 message 获得相应的 API 错误代码", "name": "get_api_code", "signature": "def get_api_code(message)" }, { "docstring": "对 API 错误信息进行处理后输出, 主要为整理格式", "name": "process_errors", "signature": "def process_errors(self)" } ]
2
null
Implement the Python class `CustomSerializer` described below. Class description: Implement the CustomSerializer class. Method signatures and docstrings: - def get_api_code(message): 根据 message 获得相应的 API 错误代码 - def process_errors(self): 对 API 错误信息进行处理后输出, 主要为整理格式
Implement the Python class `CustomSerializer` described below. Class description: Implement the CustomSerializer class. Method signatures and docstrings: - def get_api_code(message): 根据 message 获得相应的 API 错误代码 - def process_errors(self): 对 API 错误信息进行处理后输出, 主要为整理格式 <|skeleton|> class CustomSerializer: def get_api...
d52681a84bc75615dcfd7a373e579833e1ebece8
<|skeleton|> class CustomSerializer: def get_api_code(message): """根据 message 获得相应的 API 错误代码""" <|body_0|> def process_errors(self): """对 API 错误信息进行处理后输出, 主要为整理格式""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomSerializer: def get_api_code(message): """根据 message 获得相应的 API 错误代码""" try: code = settings.API_ERROR_CODE[message] except KeyError: logger.error('API: System error when get the code of message "%(message)s"' % {'message': message}) code = -1 ...
the_stack_v2_python_sparse
citi/libs/api/serializers.py
doraemonext/citi
train
0
b6093be8a755231bb6ddcbdd6dd0d520a00da5be
[ "table = {}\nbatch_size = start_batch_size\nfor _ in Notifier(pbar)(range(max_iters)):\n info = self.get_memory_utilization(batch_size, method=method, inputs=inputs, targets=targets, n=n, frequency=frequency, time_threshold=time_threshold, tail_size=tail_size, std_threshold=std_threshold)\n table[batch_size] ...
<|body_start_0|> table = {} batch_size = start_batch_size for _ in Notifier(pbar)(range(max_iters)): info = self.get_memory_utilization(batch_size, method=method, inputs=inputs, targets=targets, n=n, frequency=frequency, time_threshold=time_threshold, tail_size=tail_size, std_thresho...
Compute optimal batch size for training/inference to maximize GPU memory usage. Works by using `train`/`predict` with different batch sizes, and measuring how much memory is taken. Then, we solve the system of `measured_memory = batch_size * item_size + model_size + eps` equations for both `item_size` and `model_size`....
OptimalBatchSizeMixin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptimalBatchSizeMixin: """Compute optimal batch size for training/inference to maximize GPU memory usage. Works by using `train`/`predict` with different batch sizes, and measuring how much memory is taken. Then, we solve the system of `measured_memory = batch_size * item_size + model_size + eps`...
stack_v2_sparse_classes_36k_train_010321
26,643
permissive
[ { "docstring": "Compute memory usage for multiple batch sizes.", "name": "compute_optimal_batch_size", "signature": "def compute_optimal_batch_size(self, method='train', max_memory=90, inputs=None, targets=None, pbar='n', start_batch_size=4, delta_batch_size=4, max_batch_size=128, max_iters=16, n=20, fr...
3
null
Implement the Python class `OptimalBatchSizeMixin` described below. Class description: Compute optimal batch size for training/inference to maximize GPU memory usage. Works by using `train`/`predict` with different batch sizes, and measuring how much memory is taken. Then, we solve the system of `measured_memory = bat...
Implement the Python class `OptimalBatchSizeMixin` described below. Class description: Compute optimal batch size for training/inference to maximize GPU memory usage. Works by using `train`/`predict` with different batch sizes, and measuring how much memory is taken. Then, we solve the system of `measured_memory = bat...
bcc2c723976cb5780d7b2876f2c2df74c186d343
<|skeleton|> class OptimalBatchSizeMixin: """Compute optimal batch size for training/inference to maximize GPU memory usage. Works by using `train`/`predict` with different batch sizes, and measuring how much memory is taken. Then, we solve the system of `measured_memory = batch_size * item_size + model_size + eps`...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OptimalBatchSizeMixin: """Compute optimal batch size for training/inference to maximize GPU memory usage. Works by using `train`/`predict` with different batch sizes, and measuring how much memory is taken. Then, we solve the system of `measured_memory = batch_size * item_size + model_size + eps` equations fo...
the_stack_v2_python_sparse
batchflow/models/torch/base_mixins.py
analysiscenter/batchflow
train
110
5109d6ebed0e8b17a1640b293a7dd4b9a065b036
[ "datafile_empty = self.get_file('empty.csv')\nschema_empty = [('col_A', int), ('col_B', int), ('col_C', str), ('col_D', float), ('col_E', float), ('col_F', str)]\nframe = self.context.frame.import_csv(datafile_empty, schema=schema_empty)\nself.assertEqual(frame.count(), 0)\nnull2 = frame.copy()\nself.assertEqual(nu...
<|body_start_0|> datafile_empty = self.get_file('empty.csv') schema_empty = [('col_A', int), ('col_B', int), ('col_C', str), ('col_D', float), ('col_E', float), ('col_F', str)] frame = self.context.frame.import_csv(datafile_empty, schema=schema_empty) self.assertEqual(frame.count(), 0) ...
FileLoadTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileLoadTest: def test_import_empty(self): """Import an empty file.""" <|body_0|> def test_import_whitespace(self): """Build frame with complex quoting and whitespace""" <|body_1|> <|end_skeleton|> <|body_start_0|> datafile_empty = self.get_file('em...
stack_v2_sparse_classes_36k_train_010322
2,116
permissive
[ { "docstring": "Import an empty file.", "name": "test_import_empty", "signature": "def test_import_empty(self)" }, { "docstring": "Build frame with complex quoting and whitespace", "name": "test_import_whitespace", "signature": "def test_import_whitespace(self)" } ]
2
stack_v2_sparse_classes_30k_train_004293
Implement the Python class `FileLoadTest` described below. Class description: Implement the FileLoadTest class. Method signatures and docstrings: - def test_import_empty(self): Import an empty file. - def test_import_whitespace(self): Build frame with complex quoting and whitespace
Implement the Python class `FileLoadTest` described below. Class description: Implement the FileLoadTest class. Method signatures and docstrings: - def test_import_empty(self): Import an empty file. - def test_import_whitespace(self): Build frame with complex quoting and whitespace <|skeleton|> class FileLoadTest: ...
5548fc925b5c278263cbdebbd9e8c7593320c2f4
<|skeleton|> class FileLoadTest: def test_import_empty(self): """Import an empty file.""" <|body_0|> def test_import_whitespace(self): """Build frame with complex quoting and whitespace""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FileLoadTest: def test_import_empty(self): """Import an empty file.""" datafile_empty = self.get_file('empty.csv') schema_empty = [('col_A', int), ('col_B', int), ('col_C', str), ('col_D', float), ('col_E', float), ('col_F', str)] frame = self.context.frame.import_csv(datafile_...
the_stack_v2_python_sparse
regression-tests/sparktkregtests/testcases/frames/file_load_test.py
trustedanalytics/spark-tk
train
35
8cdd55ac5fb149ae51e040031990baa69caceb4f
[ "A.sort()\nmn = min(A)\nmx = max(A)\nret = mx - mn\nfor i in range(len(A) - 1):\n cur_mx = max(mx - K, A[i] + K)\n cur_mn = min(mn + K, A[i + 1] - K)\n ret = min(ret, cur_mx - cur_mn)\nreturn ret", "mini = min(A)\nmaxa = max(A)\nB = []\nmax_upper_diff = 0\nmax_lower_diff = 0\nupper = max(mini + K, maxa -...
<|body_start_0|> A.sort() mn = min(A) mx = max(A) ret = mx - mn for i in range(len(A) - 1): cur_mx = max(mx - K, A[i] + K) cur_mn = min(mn + K, A[i + 1] - K) ret = min(ret, cur_mx - cur_mn) return ret <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: """Say A[i] is the largest i that goes up. A[i+1] would be the smallest goes down Then A[0] + K, A[i] + K, A[i+1] - K, A[A.length - 1] - K""" <|body_0|> def smallestRangeII_error(self, A: List[int], K: int) ->...
stack_v2_sparse_classes_36k_train_010323
1,926
no_license
[ { "docstring": "Say A[i] is the largest i that goes up. A[i+1] would be the smallest goes down Then A[0] + K, A[i] + K, A[i+1] - K, A[A.length - 1] - K", "name": "smallestRangeII", "signature": "def smallestRangeII(self, A: List[int], K: int) -> int" }, { "docstring": "find the min max is not en...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def smallestRangeII(self, A: List[int], K: int) -> int: Say A[i] is the largest i that goes up. A[i+1] would be the smallest goes down Then A[0] + K, A[i] + K, A[i+1] - K, A[A.le...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def smallestRangeII(self, A: List[int], K: int) -> int: Say A[i] is the largest i that goes up. A[i+1] would be the smallest goes down Then A[0] + K, A[i] + K, A[i+1] - K, A[A.le...
929dde1723fb2f54870c8a9badc80fc23e8400d3
<|skeleton|> class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: """Say A[i] is the largest i that goes up. A[i+1] would be the smallest goes down Then A[0] + K, A[i] + K, A[i+1] - K, A[A.length - 1] - K""" <|body_0|> def smallestRangeII_error(self, A: List[int], K: int) ->...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: """Say A[i] is the largest i that goes up. A[i+1] would be the smallest goes down Then A[0] + K, A[i] + K, A[i+1] - K, A[A.length - 1] - K""" A.sort() mn = min(A) mx = max(A) ret = mx - mn for i i...
the_stack_v2_python_sparse
_algorithms_challenges/leetcode/LeetCode/910 Smallest Range II.py
syurskyi/Algorithms_and_Data_Structure
train
4
5234a2e733c2b76f6f965f4182d2c06044eb665e
[ "super(SELayer, self).__init__()\nself.avg_pool = ops.AdaptiveAvgPool2d(1)\nhidden_dim = _make_divisible(channel // reduction, 8)\nself.fc = Sequential(ops.Linear(channel, hidden_dim, use_bias=False), ops.Relu(inplace=True), ops.Linear(hidden_dim, channel, use_bias=False), ops.Hsigmoid())", "b, c, _, _ = x.shape\...
<|body_start_0|> super(SELayer, self).__init__() self.avg_pool = ops.AdaptiveAvgPool2d(1) hidden_dim = _make_divisible(channel // reduction, 8) self.fc = Sequential(ops.Linear(channel, hidden_dim, use_bias=False), ops.Relu(inplace=True), ops.Linear(hidden_dim, channel, use_bias=False), o...
This is the class of Squeeze-and-Excite layer for MobileNetV3.
SELayer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SELayer: """This is the class of Squeeze-and-Excite layer for MobileNetV3.""" def __init__(self, channel, reduction=4): """Init SELayer.""" <|body_0|> def __call__(self, x): """Forward compute of SELayer.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_010324
9,288
permissive
[ { "docstring": "Init SELayer.", "name": "__init__", "signature": "def __init__(self, channel, reduction=4)" }, { "docstring": "Forward compute of SELayer.", "name": "__call__", "signature": "def __call__(self, x)" } ]
2
null
Implement the Python class `SELayer` described below. Class description: This is the class of Squeeze-and-Excite layer for MobileNetV3. Method signatures and docstrings: - def __init__(self, channel, reduction=4): Init SELayer. - def __call__(self, x): Forward compute of SELayer.
Implement the Python class `SELayer` described below. Class description: This is the class of Squeeze-and-Excite layer for MobileNetV3. Method signatures and docstrings: - def __init__(self, channel, reduction=4): Init SELayer. - def __call__(self, x): Forward compute of SELayer. <|skeleton|> class SELayer: """T...
e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04
<|skeleton|> class SELayer: """This is the class of Squeeze-and-Excite layer for MobileNetV3.""" def __init__(self, channel, reduction=4): """Init SELayer.""" <|body_0|> def __call__(self, x): """Forward compute of SELayer.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SELayer: """This is the class of Squeeze-and-Excite layer for MobileNetV3.""" def __init__(self, channel, reduction=4): """Init SELayer.""" super(SELayer, self).__init__() self.avg_pool = ops.AdaptiveAvgPool2d(1) hidden_dim = _make_divisible(channel // reduction, 8) ...
the_stack_v2_python_sparse
zeus/networks/mobilenetv3.py
huawei-noah/xingtian
train
308
5f59f185f20f6372044506753631cdd6adc94a27
[ "for num in nums:\n num = abs(num)\n if nums[num] < 0:\n return num\n else:\n nums[num] = -nums[num]", "store = [0] * len(nums)\nfor i, num in enumerate(nums):\n if store[num] == num:\n return num\n else:\n store[num] = num" ]
<|body_start_0|> for num in nums: num = abs(num) if nums[num] < 0: return num else: nums[num] = -nums[num] <|end_body_0|> <|body_start_1|> store = [0] * len(nums) for i, num in enumerate(nums): if store[num] == num:...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> for num in nums: num = abs(nu...
stack_v2_sparse_classes_36k_train_010325
1,159
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "findDuplicate", "signature": "def findDuplicate(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "findDuplicate", "signature": "def findDuplicate(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums): :type nums: List[int] :rtype: int - def findDuplicate(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums): :type nums: List[int] :rtype: int - def findDuplicate(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def findDup...
844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4
<|skeleton|> class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" for num in nums: num = abs(num) if nums[num] < 0: return num else: nums[num] = -nums[num] def findDuplicate(self, nums): """:type nu...
the_stack_v2_python_sparse
287-find_the_duplicate_num.py
stevestar888/leetcode-problems
train
2
dc9242ee420a6691b8c50ddae8286278cdeb2eab
[ "if file_format[0] != '.':\n file_format = '.' + file_format\nurl = 'http://www.uniprot.org/uniprot/'\nreq = ''.join([url, accession, file_format])\ntry:\n data = urlopen(req)\n return data.read().decode()\nexcept HTTPError:\n print('Entry :', accession, 'not found.')\n return None", "result = cls....
<|body_start_0|> if file_format[0] != '.': file_format = '.' + file_format url = 'http://www.uniprot.org/uniprot/' req = ''.join([url, accession, file_format]) try: data = urlopen(req) return data.read().decode() except HTTPError: p...
Tools for querying the UniProt database.
UniProtTools
[ "LicenseRef-scancode-other-permissive" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UniProtTools: """Tools for querying the UniProt database.""" def get_uniprot(cls, accession, file_format='.fasta'): """Retrieve UniProt data for a given accession.""" <|body_0|> def get_gene_id(cls, accession): """Retrieve the gene id for a given accession.""" ...
stack_v2_sparse_classes_36k_train_010326
9,507
permissive
[ { "docstring": "Retrieve UniProt data for a given accession.", "name": "get_uniprot", "signature": "def get_uniprot(cls, accession, file_format='.fasta')" }, { "docstring": "Retrieve the gene id for a given accession.", "name": "get_gene_id", "signature": "def get_gene_id(cls, accession)...
3
stack_v2_sparse_classes_30k_train_020486
Implement the Python class `UniProtTools` described below. Class description: Tools for querying the UniProt database. Method signatures and docstrings: - def get_uniprot(cls, accession, file_format='.fasta'): Retrieve UniProt data for a given accession. - def get_gene_id(cls, accession): Retrieve the gene id for a g...
Implement the Python class `UniProtTools` described below. Class description: Tools for querying the UniProt database. Method signatures and docstrings: - def get_uniprot(cls, accession, file_format='.fasta'): Retrieve UniProt data for a given accession. - def get_gene_id(cls, accession): Retrieve the gene id for a g...
bedb36eafe681401c11d562f8d7117aad3d758d7
<|skeleton|> class UniProtTools: """Tools for querying the UniProt database.""" def get_uniprot(cls, accession, file_format='.fasta'): """Retrieve UniProt data for a given accession.""" <|body_0|> def get_gene_id(cls, accession): """Retrieve the gene id for a given accession.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UniProtTools: """Tools for querying the UniProt database.""" def get_uniprot(cls, accession, file_format='.fasta'): """Retrieve UniProt data for a given accession.""" if file_format[0] != '.': file_format = '.' + file_format url = 'http://www.uniprot.org/uniprot/' ...
the_stack_v2_python_sparse
omin/utils/network_tools.py
dmpio/omin
train
0
d0e7540c4b72a7e0197f5ff8bacc0abc628e30b6
[ "self.master_config = master_config\nself.data_dict = data_dict\nself.base_path = base_path\nself.logger = logger", "candidate_util = CandidateUtil()\ncandidate_id = candidate_util.get_candidate_id(candidate)\nexperiment_config = self.master_config.get('experiment_config', {})\nvis_value = experiment_config.get('...
<|body_start_0|> self.master_config = master_config self.data_dict = data_dict self.base_path = base_path self.logger = logger <|end_body_0|> <|body_start_1|> candidate_util = CandidateUtil() candidate_id = candidate_util.get_candidate_id(candidate) experiment_co...
Class to aid in handling the configuration and visualize() calling for potentially multiple Network Visualizers. While this class is itself a NetworkVisualizer, we do not enter this in the NetworkVisualizerFactory to avoid a dependency tangle.
NetworkMultiVisualizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetworkMultiVisualizer: """Class to aid in handling the configuration and visualize() calling for potentially multiple Network Visualizers. While this class is itself a NetworkVisualizer, we do not enter this in the NetworkVisualizerFactory to avoid a dependency tangle.""" def __init__(self,...
stack_v2_sparse_classes_36k_train_010327
3,719
no_license
[ { "docstring": "Constructor. :param master_config: The master config for the experiment from which all other sub-configs can be obtained. :param data_dict: The data dictionary used in the evaluator. This is often needed by domains in order that the model is built with the correct dimensionality :param base_path...
2
stack_v2_sparse_classes_30k_train_013116
Implement the Python class `NetworkMultiVisualizer` described below. Class description: Class to aid in handling the configuration and visualize() calling for potentially multiple Network Visualizers. While this class is itself a NetworkVisualizer, we do not enter this in the NetworkVisualizerFactory to avoid a depend...
Implement the Python class `NetworkMultiVisualizer` described below. Class description: Class to aid in handling the configuration and visualize() calling for potentially multiple Network Visualizers. While this class is itself a NetworkVisualizer, we do not enter this in the NetworkVisualizerFactory to avoid a depend...
99c2f401d6c4b203ee439ed607985a918d0c3c7e
<|skeleton|> class NetworkMultiVisualizer: """Class to aid in handling the configuration and visualize() calling for potentially multiple Network Visualizers. While this class is itself a NetworkVisualizer, we do not enter this in the NetworkVisualizerFactory to avoid a dependency tangle.""" def __init__(self,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetworkMultiVisualizer: """Class to aid in handling the configuration and visualize() calling for potentially multiple Network Visualizers. While this class is itself a NetworkVisualizer, we do not enter this in the NetworkVisualizerFactory to avoid a dependency tangle.""" def __init__(self, master_confi...
the_stack_v2_python_sparse
experimenthost/networkvisualization/network_multi_visualizer.py
Cognizant-CDB-AIA-BAI-AI-OI/LEAF-ENN-Training-V2
train
0
dd776d138b4b885ab9550fe7ff3008b7bf7836da
[ "ExterQual_Mapping = {'NaN': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}\nfeature_df = train[['ExterQual']]\ntrain['ExterQual'] = feature_df.fillna('NaN').applymap(lambda x: ExterQual_Mapping[x])", "ExterCond_Mapping = {'NaN': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}\nfeature_df = train[['ExterCond']]\...
<|body_start_0|> ExterQual_Mapping = {'NaN': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5} feature_df = train[['ExterQual']] train['ExterQual'] = feature_df.fillna('NaN').applymap(lambda x: ExterQual_Mapping[x]) <|end_body_0|> <|body_start_1|> ExterCond_Mapping = {'NaN': 0, 'Po': 1, '...
Exterior feature exploration
ExteriorFeatures
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExteriorFeatures: """Exterior feature exploration""" def relabel_exterQual(self, train): """Re-label ExterQual""" <|body_0|> def relabel_exterCond(self, train): """Re-label ExterCond""" <|body_1|> <|end_skeleton|> <|body_start_0|> ExterQual_Mapp...
stack_v2_sparse_classes_36k_train_010328
1,007
no_license
[ { "docstring": "Re-label ExterQual", "name": "relabel_exterQual", "signature": "def relabel_exterQual(self, train)" }, { "docstring": "Re-label ExterCond", "name": "relabel_exterCond", "signature": "def relabel_exterCond(self, train)" } ]
2
stack_v2_sparse_classes_30k_test_000274
Implement the Python class `ExteriorFeatures` described below. Class description: Exterior feature exploration Method signatures and docstrings: - def relabel_exterQual(self, train): Re-label ExterQual - def relabel_exterCond(self, train): Re-label ExterCond
Implement the Python class `ExteriorFeatures` described below. Class description: Exterior feature exploration Method signatures and docstrings: - def relabel_exterQual(self, train): Re-label ExterQual - def relabel_exterCond(self, train): Re-label ExterCond <|skeleton|> class ExteriorFeatures: """Exterior featu...
4fc530d790d359c1a47fad3f8c49ee581cd3656a
<|skeleton|> class ExteriorFeatures: """Exterior feature exploration""" def relabel_exterQual(self, train): """Re-label ExterQual""" <|body_0|> def relabel_exterCond(self, train): """Re-label ExterCond""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExteriorFeatures: """Exterior feature exploration""" def relabel_exterQual(self, train): """Re-label ExterQual""" ExterQual_Mapping = {'NaN': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5} feature_df = train[['ExterQual']] train['ExterQual'] = feature_df.fillna('NaN').app...
the_stack_v2_python_sparse
preprocess/exploringData/missingValues/exterior_features.py
aaaYaaa2/ds_house_price
train
0
7d8bcc90da196daed4347703bb92eaf7eb87ca4c
[ "try:\n print_file = io.StringIO()\n python_vinfo = sys.version_info\n if python_vinfo.major == 3 and python_vinfo.minor < 10:\n traceback.print_exception(etype=type(e), value=e, tb=tb, file=print_file)\n else:\n traceback.print_exception(type(e), value=e, tb=tb, file=print_file)\n prin...
<|body_start_0|> try: print_file = io.StringIO() python_vinfo = sys.version_info if python_vinfo.major == 3 and python_vinfo.minor < 10: traceback.print_exception(etype=type(e), value=e, tb=tb, file=print_file) else: traceback.print...
SerializedException
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SerializedException: def from_exception(e: Exception, tb: types.TracebackType) -> 'SerializedException': """Best effort attempt to serialize Exception. Because this will be used to communicate from a subprocess to its parent, we want to surface as much information as possible. It is not ...
stack_v2_sparse_classes_36k_train_010329
19,762
permissive
[ { "docstring": "Best effort attempt to serialize Exception. Because this will be used to communicate from a subprocess to its parent, we want to surface as much information as possible. It is not possible to serialize a traceback because it is too intertwined with the runtime; however what we really want is the...
2
null
Implement the Python class `SerializedException` described below. Class description: Implement the SerializedException class. Method signatures and docstrings: - def from_exception(e: Exception, tb: types.TracebackType) -> 'SerializedException': Best effort attempt to serialize Exception. Because this will be used to...
Implement the Python class `SerializedException` described below. Class description: Implement the SerializedException class. Method signatures and docstrings: - def from_exception(e: Exception, tb: types.TracebackType) -> 'SerializedException': Best effort attempt to serialize Exception. Because this will be used to...
df4da9bdff11a2f948d5bd4ac83da7922e6f44f4
<|skeleton|> class SerializedException: def from_exception(e: Exception, tb: types.TracebackType) -> 'SerializedException': """Best effort attempt to serialize Exception. Because this will be used to communicate from a subprocess to its parent, we want to surface as much information as possible. It is not ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SerializedException: def from_exception(e: Exception, tb: types.TracebackType) -> 'SerializedException': """Best effort attempt to serialize Exception. Because this will be used to communicate from a subprocess to its parent, we want to surface as much information as possible. It is not possible to se...
the_stack_v2_python_sparse
components/_impl/workers/subprocess_rpc.py
pytorch/benchmark
train
685
8786429ced04caeb1476ce424aa4a2a514574b10
[ "bboxW = bbox[2] - bbox[0]\nbboxH = bbox[3] - bbox[1]\nbboxA = bboxW * bboxH\nlog.debug('bbox area %s' % bboxA)\npoint = Image.open(icon)\ntileImg = Image.new('RGBA', (width, height), (0, 0, 0, 0))\nfor station in stations:\n if station.checkDates('2006-01-01', '2006-12-31'):\n point = Image.open(icon + '...
<|body_start_0|> bboxW = bbox[2] - bbox[0] bboxH = bbox[3] - bbox[1] bboxA = bboxW * bboxH log.debug('bbox area %s' % bboxA) point = Image.open(icon) tileImg = Image.new('RGBA', (width, height), (0, 0, 0, 0)) for station in stations: if station.checkDa...
PointRenderer
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PointRenderer: def renderPoint(self, bbox, stations, width, height, cmap, icon): """Creates an RGBA PNG with each station within given BBox represented by an icon.""" <|body_0|> def txt2img(self, label, fontname='courB08.pil', imgformat='PNG', fgcolor=(0, 0, 0), bgcolor=(255...
stack_v2_sparse_classes_36k_train_010330
2,968
permissive
[ { "docstring": "Creates an RGBA PNG with each station within given BBox represented by an icon.", "name": "renderPoint", "signature": "def renderPoint(self, bbox, stations, width, height, cmap, icon)" }, { "docstring": "Render text as image.", "name": "txt2img", "signature": "def txt2img...
2
stack_v2_sparse_classes_30k_train_006407
Implement the Python class `PointRenderer` described below. Class description: Implement the PointRenderer class. Method signatures and docstrings: - def renderPoint(self, bbox, stations, width, height, cmap, icon): Creates an RGBA PNG with each station within given BBox represented by an icon. - def txt2img(self, la...
Implement the Python class `PointRenderer` described below. Class description: Implement the PointRenderer class. Method signatures and docstrings: - def renderPoint(self, bbox, stations, width, height, cmap, icon): Creates an RGBA PNG with each station within given BBox represented by an icon. - def txt2img(self, la...
db9ed729c886b271ce85355b97e39243081e8246
<|skeleton|> class PointRenderer: def renderPoint(self, bbox, stations, width, height, cmap, icon): """Creates an RGBA PNG with each station within given BBox represented by an icon.""" <|body_0|> def txt2img(self, label, fontname='courB08.pil', imgformat='PNG', fgcolor=(0, 0, 0), bgcolor=(255...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PointRenderer: def renderPoint(self, bbox, stations, width, height, cmap, icon): """Creates an RGBA PNG with each station within given BBox represented by an icon.""" bboxW = bbox[2] - bbox[0] bboxH = bbox[3] - bbox[1] bboxA = bboxW * bboxH log.debug('bbox area %s' % bb...
the_stack_v2_python_sparse
cows/service/imps/pointrenderer.py
cedadev/cows
train
2
046d76758e1b005faef5dcfa3d772c11ab50a958
[ "self.horizontal_line = [ShapePoint(start_end_points[0]), ShapePoint(start_end_points[1])]\nself.colors = colors or list()\nself.bins = bins\ncolumn_count = 2\ncolumns_width = (0.8, 0.2)\nself.text = text\nself.text_scale = 0.6\nself.start_dots_values = start_dots_values\nself.default_color = 'red'\nself.customers,...
<|body_start_0|> self.horizontal_line = [ShapePoint(start_end_points[0]), ShapePoint(start_end_points[1])] self.colors = colors or list() self.bins = bins column_count = 2 columns_width = (0.8, 0.2) self.text = text self.text_scale = 0.6 self.start_dots_va...
Overridden Table class. Custom text and dots were added.
CustomersTable
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomersTable: """Overridden Table class. Custom text and dots were added.""" def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.5, visible_row_count: int=0, colors: list=None, bins: Union[int, float]=0, text: str='', start_dots_value...
stack_v2_sparse_classes_36k_train_010331
9,066
no_license
[ { "docstring": "Class initialization. Args: start_end_points (Tuple[tuple, tuple]): Left top and right top points. ((x1,y1), (x2,y2)). row_count (int, optional): Table row count. Defaults to 0. row_height (Union[int, float], optional): Table row height. Defaults to 0.2. visible_row_count (int, optional): Table ...
2
stack_v2_sparse_classes_30k_train_013844
Implement the Python class `CustomersTable` described below. Class description: Overridden Table class. Custom text and dots were added. Method signatures and docstrings: - def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.5, visible_row_count: int=0, colors: ...
Implement the Python class `CustomersTable` described below. Class description: Overridden Table class. Custom text and dots were added. Method signatures and docstrings: - def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.5, visible_row_count: int=0, colors: ...
290bf56ef888283a0225939ed8b1f87445e506d0
<|skeleton|> class CustomersTable: """Overridden Table class. Custom text and dots were added.""" def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.5, visible_row_count: int=0, colors: list=None, bins: Union[int, float]=0, text: str='', start_dots_value...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomersTable: """Overridden Table class. Custom text and dots were added.""" def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.5, visible_row_count: int=0, colors: list=None, bins: Union[int, float]=0, text: str='', start_dots_values: list=None)...
the_stack_v2_python_sparse
classes/table.py
mohovkm/habr_manim
train
0
abd8a666d60903ee2bd83234adbe3c032cf415d8
[ "self.app_name = app\nself.env = env\nself.region = region\nself.prop_path = prop_path\nself.properties = get_properties(properties_file=prop_path, env=env, region=region)", "remove_all_lambda_permissions(app_name=self.app_name, env=self.env, region=self.region)\ntriggers = self.properties['lambda_triggers']\nLOG...
<|body_start_0|> self.app_name = app self.env = env self.region = region self.prop_path = prop_path self.properties = get_properties(properties_file=prop_path, env=env, region=region) <|end_body_0|> <|body_start_1|> remove_all_lambda_permissions(app_name=self.app_name, e...
Manipulate Lambda events.
LambdaEvent
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LambdaEvent: """Manipulate Lambda events.""" def __init__(self, app=None, env=None, region=None, prop_path=None): """Lambda event object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region prop_path (str): Path of environment property file""" ...
stack_v2_sparse_classes_36k_train_010332
3,903
permissive
[ { "docstring": "Lambda event object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region prop_path (str): Path of environment property file", "name": "__init__", "signature": "def __init__(self, app=None, env=None, region=None, prop_path=None)" }, { "docstri...
2
null
Implement the Python class `LambdaEvent` described below. Class description: Manipulate Lambda events. Method signatures and docstrings: - def __init__(self, app=None, env=None, region=None, prop_path=None): Lambda event object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region...
Implement the Python class `LambdaEvent` described below. Class description: Manipulate Lambda events. Method signatures and docstrings: - def __init__(self, app=None, env=None, region=None, prop_path=None): Lambda event object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region...
d88001ea0e33fcd09707b81b5c4ed40e5e21fb59
<|skeleton|> class LambdaEvent: """Manipulate Lambda events.""" def __init__(self, app=None, env=None, region=None, prop_path=None): """Lambda event object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region prop_path (str): Path of environment property file""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LambdaEvent: """Manipulate Lambda events.""" def __init__(self, app=None, env=None, region=None, prop_path=None): """Lambda event object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region prop_path (str): Path of environment property file""" self.ap...
the_stack_v2_python_sparse
src/foremast/awslambda/awslambdaevent.py
foremast/foremast
train
151
7a20a1e69fcd84fea4ff95beff0f39bc000358f9
[ "super(QCOWFile, self).__init__(resolver_context, path_spec)\nself._parent_qcow_files = []\nself._sub_file_objects = []", "super(QCOWFile, self)._Close()\nfor qcow_file in self._parent_qcow_files:\n qcow_file.close()\nself._parent_qcow_files = []\nself._sub_file_objects = []", "if not path_spec.HasParent():\...
<|body_start_0|> super(QCOWFile, self).__init__(resolver_context, path_spec) self._parent_qcow_files = [] self._sub_file_objects = [] <|end_body_0|> <|body_start_1|> super(QCOWFile, self)._Close() for qcow_file in self._parent_qcow_files: qcow_file.close() se...
File input/output (IO) object using pyqcow.
QCOWFile
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QCOWFile: """File input/output (IO) object using pyqcow.""" def __init__(self, resolver_context, path_spec): """Initializes a file input/output (IO) object. Args: resolver_context (Context): resolver context. path_spec (PathSpec): a path specification.""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_010333
4,074
permissive
[ { "docstring": "Initializes a file input/output (IO) object. Args: resolver_context (Context): resolver context. path_spec (PathSpec): a path specification.", "name": "__init__", "signature": "def __init__(self, resolver_context, path_spec)" }, { "docstring": "Closes the file-like object.", ...
5
null
Implement the Python class `QCOWFile` described below. Class description: File input/output (IO) object using pyqcow. Method signatures and docstrings: - def __init__(self, resolver_context, path_spec): Initializes a file input/output (IO) object. Args: resolver_context (Context): resolver context. path_spec (PathSpe...
Implement the Python class `QCOWFile` described below. Class description: File input/output (IO) object using pyqcow. Method signatures and docstrings: - def __init__(self, resolver_context, path_spec): Initializes a file input/output (IO) object. Args: resolver_context (Context): resolver context. path_spec (PathSpe...
28756d910e951a22c5f0b2bcf5184f055a19d544
<|skeleton|> class QCOWFile: """File input/output (IO) object using pyqcow.""" def __init__(self, resolver_context, path_spec): """Initializes a file input/output (IO) object. Args: resolver_context (Context): resolver context. path_spec (PathSpec): a path specification.""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QCOWFile: """File input/output (IO) object using pyqcow.""" def __init__(self, resolver_context, path_spec): """Initializes a file input/output (IO) object. Args: resolver_context (Context): resolver context. path_spec (PathSpec): a path specification.""" super(QCOWFile, self).__init__(re...
the_stack_v2_python_sparse
dfvfs/file_io/qcow_file_io.py
log2timeline/dfvfs
train
197
d33dacbaccd9541df099a93fba4afe1967e55b9d
[ "clientObject = clientModel.factory.create('ns0:load_case')\nclearAtributes(clientObject)\nclientObject.no = no\nclientObject.name = name\nclientObject.to_solve = True\nclientObject.analysis_type = AnalysisType.ANALYSIS_TYPE_STATIC.name\nclientObject.static_analysis_settings = 1\nclientObject.action_category = 'Per...
<|body_start_0|> clientObject = clientModel.factory.create('ns0:load_case') clearAtributes(clientObject) clientObject.no = no clientObject.name = name clientObject.to_solve = True clientObject.analysis_type = AnalysisType.ANALYSIS_TYPE_STATIC.name clientObject.sta...
LoadCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadCase: def __init__(self, no: int=1, name: str='Self-weight', self_weight=[True, 0.0, 0.0, 10.0], comment: str='Comment', params: dict={}): """Creates a default load case with no further options. Analysis type is static by default. Static analysis settings defaults to 1. Action catego...
stack_v2_sparse_classes_36k_train_010334
7,905
permissive
[ { "docstring": "Creates a default load case with no further options. Analysis type is static by default. Static analysis settings defaults to 1. Action category is Permanent | G by default.", "name": "__init__", "signature": "def __init__(self, no: int=1, name: str='Self-weight', self_weight=[True, 0.0,...
2
stack_v2_sparse_classes_30k_train_011521
Implement the Python class `LoadCase` described below. Class description: Implement the LoadCase class. Method signatures and docstrings: - def __init__(self, no: int=1, name: str='Self-weight', self_weight=[True, 0.0, 0.0, 10.0], comment: str='Comment', params: dict={}): Creates a default load case with no further o...
Implement the Python class `LoadCase` described below. Class description: Implement the LoadCase class. Method signatures and docstrings: - def __init__(self, no: int=1, name: str='Self-weight', self_weight=[True, 0.0, 0.0, 10.0], comment: str='Comment', params: dict={}): Creates a default load case with no further o...
4bd0d744007bdc27d86d6ce535a507cdc81552ca
<|skeleton|> class LoadCase: def __init__(self, no: int=1, name: str='Self-weight', self_weight=[True, 0.0, 0.0, 10.0], comment: str='Comment', params: dict={}): """Creates a default load case with no further options. Analysis type is static by default. Static analysis settings defaults to 1. Action catego...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoadCase: def __init__(self, no: int=1, name: str='Self-weight', self_weight=[True, 0.0, 0.0, 10.0], comment: str='Comment', params: dict={}): """Creates a default load case with no further options. Analysis type is static by default. Static analysis settings defaults to 1. Action category is Permanen...
the_stack_v2_python_sparse
RFEM/LoadCasesAndCombinations/loadCase.py
r0m30d4c/DlubalRFEM6
train
1
532a27a4eaf4b99ff116957218a6905674767f5d
[ "self.net = net\nself.img_size = img_size\nself.isCuda = isCuda\nself.opt = torch.optim.Adam(self.net.parameters(), lr=lr)\nif self.isCuda:\n self.net.cuda()", "self.data = data_torch.FaceDataset('D:/celeba/train_data/{}/'.format(self.img_size))\nself.loader = data.DataLoader(dataset=self.data, batch_size=batc...
<|body_start_0|> self.net = net self.img_size = img_size self.isCuda = isCuda self.opt = torch.optim.Adam(self.net.parameters(), lr=lr) if self.isCuda: self.net.cuda() <|end_body_0|> <|body_start_1|> self.data = data_torch.FaceDataset('D:/celeba/train_data/{}...
Trainer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trainer: def __init__(self, net, img_size, lr=0.001, isCuda=False): """:param net: 传入网络 :param size: 传入网络训练的图大小,相当于选择训练集 :param batch: 传入训练的批次大小""" <|body_0|> def train(self, batch, isLoad=False, isSave=False): """:param batch: 训练的批次 :return: 训练网络""" <|body_1...
stack_v2_sparse_classes_36k_train_010335
5,050
no_license
[ { "docstring": ":param net: 传入网络 :param size: 传入网络训练的图大小,相当于选择训练集 :param batch: 传入训练的批次大小", "name": "__init__", "signature": "def __init__(self, net, img_size, lr=0.001, isCuda=False)" }, { "docstring": ":param batch: 训练的批次 :return: 训练网络", "name": "train", "signature": "def train(self, b...
3
stack_v2_sparse_classes_30k_train_007319
Implement the Python class `Trainer` described below. Class description: Implement the Trainer class. Method signatures and docstrings: - def __init__(self, net, img_size, lr=0.001, isCuda=False): :param net: 传入网络 :param size: 传入网络训练的图大小,相当于选择训练集 :param batch: 传入训练的批次大小 - def train(self, batch, isLoad=False, isSave=F...
Implement the Python class `Trainer` described below. Class description: Implement the Trainer class. Method signatures and docstrings: - def __init__(self, net, img_size, lr=0.001, isCuda=False): :param net: 传入网络 :param size: 传入网络训练的图大小,相当于选择训练集 :param batch: 传入训练的批次大小 - def train(self, batch, isLoad=False, isSave=F...
1e33b81003e23f5c2e69293edee1f01fca5b7263
<|skeleton|> class Trainer: def __init__(self, net, img_size, lr=0.001, isCuda=False): """:param net: 传入网络 :param size: 传入网络训练的图大小,相当于选择训练集 :param batch: 传入训练的批次大小""" <|body_0|> def train(self, batch, isLoad=False, isSave=False): """:param batch: 训练的批次 :return: 训练网络""" <|body_1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trainer: def __init__(self, net, img_size, lr=0.001, isCuda=False): """:param net: 传入网络 :param size: 传入网络训练的图大小,相当于选择训练集 :param batch: 传入训练的批次大小""" self.net = net self.img_size = img_size self.isCuda = isCuda self.opt = torch.optim.Adam(self.net.parameters(), lr=lr) ...
the_stack_v2_python_sparse
Mtcnn_Step/Step/step3_Net_and_train/trainer2.py
zh3389/MTCNN
train
5
fb41e4efa4c4fcc14d26743bdc0ca7ca7df7f855
[ "self.debug = debug\nself.message = message\nself.errors = validation_errors\nif self.debug:\n print('ParserError - init' + lineno())", "if self.debug:\n print('to_hash ' + lineno())\nhash = {}\nhash[self.message] = self.errors\nreturn hash", "if self.debug:\n print('to_string' + lineno())\nprint()\nre...
<|body_start_0|> self.debug = debug self.message = message self.errors = validation_errors if self.debug: print('ParserError - init' + lineno()) <|end_body_0|> <|body_start_1|> if self.debug: print('to_hash ' + lineno()) hash = {} hash[sel...
Parser error
ParserError
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParserError: """Parser error""" def __init__(self, message, validation_errors='None', debug=False): """Initialize :param message: :param validation_errors: :param debug:""" <|body_0|> def to_hash(self): """Convert to hash :return:""" <|body_1|> def t...
stack_v2_sparse_classes_36k_train_010336
1,208
permissive
[ { "docstring": "Initialize :param message: :param validation_errors: :param debug:", "name": "__init__", "signature": "def __init__(self, message, validation_errors='None', debug=False)" }, { "docstring": "Convert to hash :return:", "name": "to_hash", "signature": "def to_hash(self)" }...
3
null
Implement the Python class `ParserError` described below. Class description: Parser error Method signatures and docstrings: - def __init__(self, message, validation_errors='None', debug=False): Initialize :param message: :param validation_errors: :param debug: - def to_hash(self): Convert to hash :return: - def to_st...
Implement the Python class `ParserError` described below. Class description: Parser error Method signatures and docstrings: - def __init__(self, message, validation_errors='None', debug=False): Initialize :param message: :param validation_errors: :param debug: - def to_hash(self): Convert to hash :return: - def to_st...
a9d0335a532acdb4070e5537155b03b34915b73e
<|skeleton|> class ParserError: """Parser error""" def __init__(self, message, validation_errors='None', debug=False): """Initialize :param message: :param validation_errors: :param debug:""" <|body_0|> def to_hash(self): """Convert to hash :return:""" <|body_1|> def t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParserError: """Parser error""" def __init__(self, message, validation_errors='None', debug=False): """Initialize :param message: :param validation_errors: :param debug:""" self.debug = debug self.message = message self.errors = validation_errors if self.debug: ...
the_stack_v2_python_sparse
terraform_model/parser/ParserError.py
rubelw/terraform-validator
train
7
7e3c1e4b6f542e219c60bd052f7d288bc9794a6c
[ "client = MongoClient()\ndb = client['database']\nself.assertEqual(((4, 4, 4), (0, 0, 0)), import_data(db, '', 'products.csv', 'customers.csv', 'rentals.csv'))\ndrop_all(db)", "client = MongoClient()\ndb = client['database']\nproduct = db['product']\ncustomer = db['customer']\nrentals = db['rentals']\nself.assert...
<|body_start_0|> client = MongoClient() db = client['database'] self.assertEqual(((4, 4, 4), (0, 0, 0)), import_data(db, '', 'products.csv', 'customers.csv', 'rentals.csv')) drop_all(db) <|end_body_0|> <|body_start_1|> client = MongoClient() db = client['database'] ...
Unittest functions for testing database.py
TestDatabase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDatabase: """Unittest functions for testing database.py""" def test_import_data(self): """Test for import_data function from database.py""" <|body_0|> def test_add_data(self): """Test for add_data function from database.py""" <|body_1|> def test_...
stack_v2_sparse_classes_36k_train_010337
3,507
no_license
[ { "docstring": "Test for import_data function from database.py", "name": "test_import_data", "signature": "def test_import_data(self)" }, { "docstring": "Test for add_data function from database.py", "name": "test_add_data", "signature": "def test_add_data(self)" }, { "docstring"...
6
null
Implement the Python class `TestDatabase` described below. Class description: Unittest functions for testing database.py Method signatures and docstrings: - def test_import_data(self): Test for import_data function from database.py - def test_add_data(self): Test for add_data function from database.py - def test_csv_...
Implement the Python class `TestDatabase` described below. Class description: Unittest functions for testing database.py Method signatures and docstrings: - def test_import_data(self): Test for import_data function from database.py - def test_add_data(self): Test for add_data function from database.py - def test_csv_...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class TestDatabase: """Unittest functions for testing database.py""" def test_import_data(self): """Test for import_data function from database.py""" <|body_0|> def test_add_data(self): """Test for add_data function from database.py""" <|body_1|> def test_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestDatabase: """Unittest functions for testing database.py""" def test_import_data(self): """Test for import_data function from database.py""" client = MongoClient() db = client['database'] self.assertEqual(((4, 4, 4), (0, 0, 0)), import_data(db, '', 'products.csv', 'cust...
the_stack_v2_python_sparse
students/njschafi/Lesson05/assignment/test_database.py
JavaRod/SP_Python220B_2019
train
1
a71e730a60260c3af1028e7376343b29e1c17e46
[ "if not email:\n raise ValueError('Email is needed')\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "extra_fields.setdefault('is_staff', False)\nextra_fields.setdefault('is_superuser', False)\nextra_fie...
<|body_start_0|> if not email: raise ValueError('Email is needed') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> ext...
overrides BaseUserManager class for default django random password and normalize_email functionality
ScfUserManager
[ "Apache-2.0", "GPL-3.0-only", "BSD-3-Clause", "AGPL-3.0-only", "GPL-1.0-or-later", "Python-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScfUserManager: """overrides BaseUserManager class for default django random password and normalize_email functionality""" def _create_user(self, email, password, **extra_fields): """Creates and saves a User with the given email and password.""" <|body_0|> def create_use...
stack_v2_sparse_classes_36k_train_010338
2,740
permissive
[ { "docstring": "Creates and saves a User with the given email and password.", "name": "_create_user", "signature": "def _create_user(self, email, password, **extra_fields)" }, { "docstring": "create normal user", "name": "create_user", "signature": "def create_user(self, email, password,...
4
null
Implement the Python class `ScfUserManager` described below. Class description: overrides BaseUserManager class for default django random password and normalize_email functionality Method signatures and docstrings: - def _create_user(self, email, password, **extra_fields): Creates and saves a User with the given emai...
Implement the Python class `ScfUserManager` described below. Class description: overrides BaseUserManager class for default django random password and normalize_email functionality Method signatures and docstrings: - def _create_user(self, email, password, **extra_fields): Creates and saves a User with the given emai...
4df3f46e35eb8fcab796be27fc1cc7fa7ed561f3
<|skeleton|> class ScfUserManager: """overrides BaseUserManager class for default django random password and normalize_email functionality""" def _create_user(self, email, password, **extra_fields): """Creates and saves a User with the given email and password.""" <|body_0|> def create_use...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScfUserManager: """overrides BaseUserManager class for default django random password and normalize_email functionality""" def _create_user(self, email, password, **extra_fields): """Creates and saves a User with the given email and password.""" if not email: raise ValueError(...
the_stack_v2_python_sparse
SCRM/ums/managers.py
aricent/secure-cloud-native-fabric
train
2
69af30d67b25d4adfa14de6e4d932ab1bae5b846
[ "counts = collections.defaultdict(int)\nfor v in nums:\n counts[v] += 1\n if len(counts.keys()) == 3:\n rmks = []\n for k in counts.keys():\n counts[k] -= 1\n if counts[k] == 0:\n rmks.append(k)\n for k in rmks:\n counts.pop(k)\nreturn list(...
<|body_start_0|> counts = collections.defaultdict(int) for v in nums: counts[v] += 1 if len(counts.keys()) == 3: rmks = [] for k in counts.keys(): counts[k] -= 1 if counts[k] == 0: rmk...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def majorityElement(self, nums): """每次去除3个不一样的数字,最后剩下的数字中一定包含出现次数超过1/3的数字。 1. 假设出现次数超过1/3的数字是X,假设最后剩下的数字中不包含它,那么即使前面 每次去掉的三个数字中都包含一个X,它出现的次数也只有N//3,与题意矛盾。 2. 最后最多剩下2个数字, 再分别遍历一次 :param nums: :return:""" <|body_0|> def majorityElement2(self, nums): """Very f...
stack_v2_sparse_classes_36k_train_010339
2,062
permissive
[ { "docstring": "每次去除3个不一样的数字,最后剩下的数字中一定包含出现次数超过1/3的数字。 1. 假设出现次数超过1/3的数字是X,假设最后剩下的数字中不包含它,那么即使前面 每次去掉的三个数字中都包含一个X,它出现的次数也只有N//3,与题意矛盾。 2. 最后最多剩下2个数字, 再分别遍历一次 :param nums: :return:", "name": "majorityElement", "signature": "def majorityElement(self, nums)" }, { "docstring": "Very fast, but not O(...
2
stack_v2_sparse_classes_30k_train_018048
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def majorityElement(self, nums): 每次去除3个不一样的数字,最后剩下的数字中一定包含出现次数超过1/3的数字。 1. 假设出现次数超过1/3的数字是X,假设最后剩下的数字中不包含它,那么即使前面 每次去掉的三个数字中都包含一个X,它出现的次数也只有N//3,与题意矛盾。 2. 最后最多剩下2个数字, 再分别遍历一次 :pa...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def majorityElement(self, nums): 每次去除3个不一样的数字,最后剩下的数字中一定包含出现次数超过1/3的数字。 1. 假设出现次数超过1/3的数字是X,假设最后剩下的数字中不包含它,那么即使前面 每次去掉的三个数字中都包含一个X,它出现的次数也只有N//3,与题意矛盾。 2. 最后最多剩下2个数字, 再分别遍历一次 :pa...
2830c7e2ada8dfd3dcdda7c06846116d4f944a27
<|skeleton|> class Solution: def majorityElement(self, nums): """每次去除3个不一样的数字,最后剩下的数字中一定包含出现次数超过1/3的数字。 1. 假设出现次数超过1/3的数字是X,假设最后剩下的数字中不包含它,那么即使前面 每次去掉的三个数字中都包含一个X,它出现的次数也只有N//3,与题意矛盾。 2. 最后最多剩下2个数字, 再分别遍历一次 :param nums: :return:""" <|body_0|> def majorityElement2(self, nums): """Very f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def majorityElement(self, nums): """每次去除3个不一样的数字,最后剩下的数字中一定包含出现次数超过1/3的数字。 1. 假设出现次数超过1/3的数字是X,假设最后剩下的数字中不包含它,那么即使前面 每次去掉的三个数字中都包含一个X,它出现的次数也只有N//3,与题意矛盾。 2. 最后最多剩下2个数字, 再分别遍历一次 :param nums: :return:""" counts = collections.defaultdict(int) for v in nums: counts[v...
the_stack_v2_python_sparse
leetcode/medium/Major_Element_II.py
shhuan/algorithms
train
0
f1326a96f183025268d5f01182b82121f8126419
[ "from pywallet.controller import Controller\nsuper(AliasForm, self).__init__(**kwargs)\nself.address = '0x' + account.address.hex()\ntry:\n self.alias = Controller.get_address_alias(self.address)\nexcept KeyError:\n self.alias = ''", "title = 'Update your alias'\ncontent = cls(account)\ndialog = MDDialog(ti...
<|body_start_0|> from pywallet.controller import Controller super(AliasForm, self).__init__(**kwargs) self.address = '0x' + account.address.hex() try: self.alias = Controller.get_address_alias(self.address) except KeyError: self.alias = '' <|end_body_0|> ...
AliasForm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AliasForm: def __init__(self, account, **kwargs): """Setups the current alias for the given account.""" <|body_0|> def create_alias_dialog(cls, account): """Creates the update alias dialog.""" <|body_1|> <|end_skeleton|> <|body_start_0|> from pywall...
stack_v2_sparse_classes_36k_train_010340
1,310
permissive
[ { "docstring": "Setups the current alias for the given account.", "name": "__init__", "signature": "def __init__(self, account, **kwargs)" }, { "docstring": "Creates the update alias dialog.", "name": "create_alias_dialog", "signature": "def create_alias_dialog(cls, account)" } ]
2
stack_v2_sparse_classes_30k_train_008306
Implement the Python class `AliasForm` described below. Class description: Implement the AliasForm class. Method signatures and docstrings: - def __init__(self, account, **kwargs): Setups the current alias for the given account. - def create_alias_dialog(cls, account): Creates the update alias dialog.
Implement the Python class `AliasForm` described below. Class description: Implement the AliasForm class. Method signatures and docstrings: - def __init__(self, account, **kwargs): Setups the current alias for the given account. - def create_alias_dialog(cls, account): Creates the update alias dialog. <|skeleton|> c...
97c665a63d0dbab181657100bb42c4b5cc8270b1
<|skeleton|> class AliasForm: def __init__(self, account, **kwargs): """Setups the current alias for the given account.""" <|body_0|> def create_alias_dialog(cls, account): """Creates the update alias dialog.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AliasForm: def __init__(self, account, **kwargs): """Setups the current alias for the given account.""" from pywallet.controller import Controller super(AliasForm, self).__init__(**kwargs) self.address = '0x' + account.address.hex() try: self.alias = Control...
the_stack_v2_python_sparse
src/pywallet/aliasform.py
AndreMiras/PyWallet
train
71
27e2db0f96453751978fe2b1455273cfe2e8b1f6
[ "add_input_output_information(self, input_names, output_name, output_shape)\nself.window_size = np.ascontiguousarray(window_size, dtype=np.uintp)\nself.input_shape = np.ascontiguousarray(image_shape, dtype=np.uintp)\nself.stride = np.ascontiguousarray(strides, dtype=np.uintp)\nself.pad_top = pad_top\nself.pad_left ...
<|body_start_0|> add_input_output_information(self, input_names, output_name, output_shape) self.window_size = np.ascontiguousarray(window_size, dtype=np.uintp) self.input_shape = np.ascontiguousarray(image_shape, dtype=np.uintp) self.stride = np.ascontiguousarray(strides, dtype=np.uintp...
DeepzonoPool
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeepzonoPool: def __init__(self, image_shape, window_size, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape, is_maxpool): """Arguments --------- image_shape : numpy.ndarray 1D array of shape [height, width, channels] window_size : numpy.ndarray 1D...
stack_v2_sparse_classes_36k_train_010341
34,420
permissive
[ { "docstring": "Arguments --------- image_shape : numpy.ndarray 1D array of shape [height, width, channels] window_size : numpy.ndarray 1D array of shape [height, width] representing the window's size in these directions strides : numpy.ndarray 1D array of shape [height, width] representing the stride in these ...
2
stack_v2_sparse_classes_30k_train_021160
Implement the Python class `DeepzonoPool` described below. Class description: Implement the DeepzonoPool class. Method signatures and docstrings: - def __init__(self, image_shape, window_size, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape, is_maxpool): Arguments --------- i...
Implement the Python class `DeepzonoPool` described below. Class description: Implement the DeepzonoPool class. Method signatures and docstrings: - def __init__(self, image_shape, window_size, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape, is_maxpool): Arguments --------- i...
8771d3158b2c64a360d5bdfd4433490863257dd6
<|skeleton|> class DeepzonoPool: def __init__(self, image_shape, window_size, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape, is_maxpool): """Arguments --------- image_shape : numpy.ndarray 1D array of shape [height, width, channels] window_size : numpy.ndarray 1D...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeepzonoPool: def __init__(self, image_shape, window_size, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape, is_maxpool): """Arguments --------- image_shape : numpy.ndarray 1D array of shape [height, width, channels] window_size : numpy.ndarray 1D array of shap...
the_stack_v2_python_sparse
tf_verify/deepzono_nodes.py
eth-sri/eran
train
306
9cfb684630fd561a1d06f476701dba6620760258
[ "if self._locked:\n raise AlreadyLockedException('File %s is already locked' % self._filename)\nstart_time = time.time()\nvalidate_file(self._filename)\ntry:\n self._fh = open(self._filename, self._mode)\nexcept IOError as e:\n if e.errno in (errno.EPERM, errno.EACCES):\n self._fh = open(self._filen...
<|body_start_0|> if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) start_time = time.time() validate_file(self._filename) try: self._fh = open(self._filename, self._mode) except IOError as e: if e.errno...
Open, lock, and unlock a file using fcntl.lockf.
_FcntlOpener
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _FcntlOpener: """Open, lock, and unlock a file using fcntl.lockf.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is...
stack_v2_sparse_classes_36k_train_010342
11,504
permissive
[ { "docstring": "Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. CredentialsFileSymbolicLinkError if the file is a symbolic link.", "name":...
2
null
Implement the Python class `_FcntlOpener` described below. Class description: Open, lock, and unlock a file using fcntl.lockf. Method signatures and docstrings: - def open_and_lock(self, timeout, delay): Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait betwe...
Implement the Python class `_FcntlOpener` described below. Class description: Open, lock, and unlock a file using fcntl.lockf. Method signatures and docstrings: - def open_and_lock(self, timeout, delay): Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait betwe...
53102de187a48ac2cfc241fef54dcbc29c453a8e
<|skeleton|> class _FcntlOpener: """Open, lock, and unlock a file using fcntl.lockf.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _FcntlOpener: """Open, lock, and unlock a file using fcntl.lockf.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acqu...
the_stack_v2_python_sparse
third_party/gae_ts_mon/gae_ts_mon/third_party/oauth2client/locked_file.py
catapult-project/catapult
train
2,032
70ff8e149ff472e3cf813a317403512e988eac57
[ "try:\n subject = Subject.objects.get(pk=pk)\n serializer = SubjectSerializer(subject, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)", "subjects = Subject.objects.all().order_by('label')\nserializer = SubjectSerializer(su...
<|body_start_0|> try: subject = Subject.objects.get(pk=pk) serializer = SubjectSerializer(subject, context={'request': request}) return Response(serializer.data) except Exception as ex: return HttpResponseServerError(ex) <|end_body_0|> <|body_start_1|> ...
Journey Subjects
SubjectViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubjectViewSet: """Journey Subjects""" def retrieve(self, request, pk=None): """Handle GET requests for single subject returns: Response -- JSON serialized subject""" <|body_0|> def list(self, request): """Handle GET requests to get all subjects Returns: Response...
stack_v2_sparse_classes_36k_train_010343
1,370
no_license
[ { "docstring": "Handle GET requests for single subject returns: Response -- JSON serialized subject", "name": "retrieve", "signature": "def retrieve(self, request, pk=None)" }, { "docstring": "Handle GET requests to get all subjects Returns: Response -- JSON serialized list of subjects", "na...
2
stack_v2_sparse_classes_30k_train_002281
Implement the Python class `SubjectViewSet` described below. Class description: Journey Subjects Method signatures and docstrings: - def retrieve(self, request, pk=None): Handle GET requests for single subject returns: Response -- JSON serialized subject - def list(self, request): Handle GET requests to get all subje...
Implement the Python class `SubjectViewSet` described below. Class description: Journey Subjects Method signatures and docstrings: - def retrieve(self, request, pk=None): Handle GET requests for single subject returns: Response -- JSON serialized subject - def list(self, request): Handle GET requests to get all subje...
bd996853f6bd9a95d15115248300e6d801c0dc47
<|skeleton|> class SubjectViewSet: """Journey Subjects""" def retrieve(self, request, pk=None): """Handle GET requests for single subject returns: Response -- JSON serialized subject""" <|body_0|> def list(self, request): """Handle GET requests to get all subjects Returns: Response...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubjectViewSet: """Journey Subjects""" def retrieve(self, request, pk=None): """Handle GET requests for single subject returns: Response -- JSON serialized subject""" try: subject = Subject.objects.get(pk=pk) serializer = SubjectSerializer(subject, context={'reques...
the_stack_v2_python_sparse
capstoneapi/views/subject.py
jeaninebeckle/backend-capstone-api
train
0
2cf2edd25c0f87c671c3af1bca5be7385563ec60
[ "super().__init__()\nself.vocab_size = vocab_size\nself.embed_size = embed_size\nself.lstm_size = lstm_size\nself.output_size = output_size\nself.lstm_layers = lstm_layers\nself.dropout = dropout\nself.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embed_size)\nself.lstm = nn.LSTM(embed_size, lst...
<|body_start_0|> super().__init__() self.vocab_size = vocab_size self.embed_size = embed_size self.lstm_size = lstm_size self.output_size = output_size self.lstm_layers = lstm_layers self.dropout = dropout self.embedding = nn.Embedding(num_embeddings=vocab...
TextClassifier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextClassifier: def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): """Initialize the model by setting up the layers. Parameters ---------- vocab_size : The vocabulary size. embed_size : The embedding layer size. embedding_dim lstm_size : The L...
stack_v2_sparse_classes_36k_train_010344
11,718
no_license
[ { "docstring": "Initialize the model by setting up the layers. Parameters ---------- vocab_size : The vocabulary size. embed_size : The embedding layer size. embedding_dim lstm_size : The LSTM layer size. hidden_dim output_size : The output size. lstm_layers : The number of LSTM layers. n_layers dropout : The d...
3
stack_v2_sparse_classes_30k_train_000262
Implement the Python class `TextClassifier` described below. Class description: Implement the TextClassifier class. Method signatures and docstrings: - def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): Initialize the model by setting up the layers. Parameters ---------- v...
Implement the Python class `TextClassifier` described below. Class description: Implement the TextClassifier class. Method signatures and docstrings: - def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): Initialize the model by setting up the layers. Parameters ---------- v...
0cdabea4afb58af71b909fbde7a9260eaa2b7849
<|skeleton|> class TextClassifier: def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): """Initialize the model by setting up the layers. Parameters ---------- vocab_size : The vocabulary size. embed_size : The embedding layer size. embedding_dim lstm_size : The L...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextClassifier: def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): """Initialize the model by setting up the layers. Parameters ---------- vocab_size : The vocabulary size. embed_size : The embedding layer size. embedding_dim lstm_size : The LSTM layer size...
the_stack_v2_python_sparse
trial_calculations_2/LSTMs.py
ThesisNegatif/Thesis
train
2
a25fdc277578b2111e1eb7828565387d18c757b4
[ "expr = expr.replace(' ', '').replace(',', '.')\nself.app = app\nif expr.count('=') > 1:\n raise InvalidEquacaoException(\"Há mais que um '=' na equação\")\nelif expr.count('=') == 0:\n expr += '=0'\nterm, term2 = expr.split('=')\nself.first = Expressao(term)\nself.last = Expressao(term2)", "if self.first !...
<|body_start_0|> expr = expr.replace(' ', '').replace(',', '.') self.app = app if expr.count('=') > 1: raise InvalidEquacaoException("Há mais que um '=' na equação") elif expr.count('=') == 0: expr += '=0' term, term2 = expr.split('=') self.first =...
Classe que representa a equação do segundo grau.
Equacao
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Equacao: """Classe que representa a equação do segundo grau.""" def __init__(self, app, expr): """Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas uma, inicializa a outra com o valor 0.""" <|body_0|...
stack_v2_sparse_classes_36k_train_010345
2,803
no_license
[ { "docstring": "Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas uma, inicializa a outra com o valor 0.", "name": "__init__", "signature": "def __init__(self, app, expr)" }, { "docstring": "Faz a segunda verificação, c...
5
stack_v2_sparse_classes_30k_train_019114
Implement the Python class `Equacao` described below. Class description: Classe que representa a equação do segundo grau. Method signatures and docstrings: - def __init__(self, app, expr): Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas um...
Implement the Python class `Equacao` described below. Class description: Classe que representa a equação do segundo grau. Method signatures and docstrings: - def __init__(self, app, expr): Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas um...
f17de5dcfe057df28e956213737a95321693e848
<|skeleton|> class Equacao: """Classe que representa a equação do segundo grau.""" def __init__(self, app, expr): """Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas uma, inicializa a outra com o valor 0.""" <|body_0|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Equacao: """Classe que representa a equação do segundo grau.""" def __init__(self, app, expr): """Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas uma, inicializa a outra com o valor 0.""" expr = expr.replace(' ...
the_stack_v2_python_sparse
equacao_resolver/equacao.py
rafael146/workufal
train
0
01b1959a87e5d0745caeceb32d6188b53395ae79
[ "print('Enter the values for filters you want to apply (Press enter to skip)')\nfor key in self.FILTERS:\n while True:\n value = SelectFiles.validate(input(self.FILTERS[key]['description']), key)\n if value == '':\n break\n elif not isinstance(value, bool):\n self.FILTE...
<|body_start_0|> print('Enter the values for filters you want to apply (Press enter to skip)') for key in self.FILTERS: while True: value = SelectFiles.validate(input(self.FILTERS[key]['description']), key) if value == '': break ...
Class containing method to select and filter files at a path. It contains different filters based on which, the files can be filtered
SelectFiles
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SelectFiles: """Class containing method to select and filter files at a path. It contains different filters based on which, the files can be filtered""" def __init__(self): """Takes in arguments from the user for filtering files""" <|body_0|> def list_all_files(path): ...
stack_v2_sparse_classes_36k_train_010346
8,019
permissive
[ { "docstring": "Takes in arguments from the user for filtering files", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Returns a Dict object of all the files present at the path argument.", "name": "list_all_files", "signature": "def list_all_files(path)" }, ...
5
stack_v2_sparse_classes_30k_test_000014
Implement the Python class `SelectFiles` described below. Class description: Class containing method to select and filter files at a path. It contains different filters based on which, the files can be filtered Method signatures and docstrings: - def __init__(self): Takes in arguments from the user for filtering file...
Implement the Python class `SelectFiles` described below. Class description: Class containing method to select and filter files at a path. It contains different filters based on which, the files can be filtered Method signatures and docstrings: - def __init__(self): Takes in arguments from the user for filtering file...
31fd3fb1233f39ea2252a7a44160ff8a2140f7bd
<|skeleton|> class SelectFiles: """Class containing method to select and filter files at a path. It contains different filters based on which, the files can be filtered""" def __init__(self): """Takes in arguments from the user for filtering files""" <|body_0|> def list_all_files(path): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SelectFiles: """Class containing method to select and filter files at a path. It contains different filters based on which, the files can be filtered""" def __init__(self): """Takes in arguments from the user for filtering files""" print('Enter the values for filters you want to apply (Pr...
the_stack_v2_python_sparse
Python/Bulk_File_Renamer/utils.py
HarshCasper/Rotten-Scripts
train
1,474
c1fb96d281ff340126642b38e421cb45381803dd
[ "config = current_app.cea_config\ndashboards = cea.plots.read_dashboards(config, current_app.plot_cache)\nout = []\nfor d in dashboards:\n out.append(dashboard_to_dict(d))\nreturn out", "form = api.payload\nconfig = current_app.cea_config\nif 'grid' in form['layout']:\n types = [[2] + [1] * 4, [1] * 6, [1] ...
<|body_start_0|> config = current_app.cea_config dashboards = cea.plots.read_dashboards(config, current_app.plot_cache) out = [] for d in dashboards: out.append(dashboard_to_dict(d)) return out <|end_body_0|> <|body_start_1|> form = api.payload config...
Dashboards
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dashboards: def get(self): """Get list of Dashboards""" <|body_0|> def post(self): """Create Dashboard""" <|body_1|> <|end_skeleton|> <|body_start_0|> config = current_app.cea_config dashboards = cea.plots.read_dashboards(config, current_app...
stack_v2_sparse_classes_36k_train_010347
9,106
permissive
[ { "docstring": "Get list of Dashboards", "name": "get", "signature": "def get(self)" }, { "docstring": "Create Dashboard", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_017597
Implement the Python class `Dashboards` described below. Class description: Implement the Dashboards class. Method signatures and docstrings: - def get(self): Get list of Dashboards - def post(self): Create Dashboard
Implement the Python class `Dashboards` described below. Class description: Implement the Dashboards class. Method signatures and docstrings: - def get(self): Get list of Dashboards - def post(self): Create Dashboard <|skeleton|> class Dashboards: def get(self): """Get list of Dashboards""" <|bo...
b84bcefdfdfc2bc0e009b5284b74391a957995ac
<|skeleton|> class Dashboards: def get(self): """Get list of Dashboards""" <|body_0|> def post(self): """Create Dashboard""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dashboards: def get(self): """Get list of Dashboards""" config = current_app.cea_config dashboards = cea.plots.read_dashboards(config, current_app.plot_cache) out = [] for d in dashboards: out.append(dashboard_to_dict(d)) return out def post(sel...
the_stack_v2_python_sparse
cea/interfaces/dashboard/api/dashboard.py
architecture-building-systems/CityEnergyAnalyst
train
166
949909c103bfbcd9b9b0f1250e66cc2695491108
[ "if RedisPool.__pool == None:\n RedisPool()\nreturn RedisPool.__pool", "if RedisPool.__pool != None:\n logger.info('Using redis pool singleton')\nelse:\n try:\n RedisPool.__pool = redis.ConnectionPool(host=REDIS_HOST, port=int(REDIS_PORT), db=0, decode_responses=True)\n except Exception as e:\n...
<|body_start_0|> if RedisPool.__pool == None: RedisPool() return RedisPool.__pool <|end_body_0|> <|body_start_1|> if RedisPool.__pool != None: logger.info('Using redis pool singleton') else: try: RedisPool.__pool = redis.ConnectionPool...
RedisPool
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedisPool: def getPool(): """Static access method.""" <|body_0|> def __init__(self): """Virtually private constructor.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if RedisPool.__pool == None: RedisPool() return RedisPool.__po...
stack_v2_sparse_classes_36k_train_010348
2,420
permissive
[ { "docstring": "Static access method.", "name": "getPool", "signature": "def getPool()" }, { "docstring": "Virtually private constructor.", "name": "__init__", "signature": "def __init__(self)" } ]
2
stack_v2_sparse_classes_30k_train_015223
Implement the Python class `RedisPool` described below. Class description: Implement the RedisPool class. Method signatures and docstrings: - def getPool(): Static access method. - def __init__(self): Virtually private constructor.
Implement the Python class `RedisPool` described below. Class description: Implement the RedisPool class. Method signatures and docstrings: - def getPool(): Static access method. - def __init__(self): Virtually private constructor. <|skeleton|> class RedisPool: def getPool(): """Static access method."""...
7da0de453163130e116611f0ed750414d6d5c107
<|skeleton|> class RedisPool: def getPool(): """Static access method.""" <|body_0|> def __init__(self): """Virtually private constructor.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RedisPool: def getPool(): """Static access method.""" if RedisPool.__pool == None: RedisPool() return RedisPool.__pool def __init__(self): """Virtually private constructor.""" if RedisPool.__pool != None: logger.info('Using redis pool single...
the_stack_v2_python_sparse
gamechangerml/api/utils/redisdriver.py
iamjoshbinder/gamechanger-ml
train
0
952285a1e4b540700db6b28055fcb686b15938a5
[ "output_schema = CMOutput()\njson_testdata = get_json_testdata('marshmallow.json')\nout = output_schema.load(data=json_testdata)\nself.assertGreater(len(out), 0)", "output_schema = CMOutput()\njson_testdata = get_json_testdata('test.json')\nout = output_schema.load(data=json_testdata)\nself.assertGreater(len(out)...
<|body_start_0|> output_schema = CMOutput() json_testdata = get_json_testdata('marshmallow.json') out = output_schema.load(data=json_testdata) self.assertGreater(len(out), 0) <|end_body_0|> <|body_start_1|> output_schema = CMOutput() json_testdata = get_json_testdata('te...
TestSchema
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSchema: def testLoad(self): """Test the load and the validation of json""" <|body_0|> def testLongLoad(self): """Test the load and the validation of long json""" <|body_1|> def testEmptyLoad(self): """Test the load and the validation of empty...
stack_v2_sparse_classes_36k_train_010349
3,351
permissive
[ { "docstring": "Test the load and the validation of json", "name": "testLoad", "signature": "def testLoad(self)" }, { "docstring": "Test the load and the validation of long json", "name": "testLongLoad", "signature": "def testLongLoad(self)" }, { "docstring": "Test the load and t...
3
null
Implement the Python class `TestSchema` described below. Class description: Implement the TestSchema class. Method signatures and docstrings: - def testLoad(self): Test the load and the validation of json - def testLongLoad(self): Test the load and the validation of long json - def testEmptyLoad(self): Test the load ...
Implement the Python class `TestSchema` described below. Class description: Implement the TestSchema class. Method signatures and docstrings: - def testLoad(self): Test the load and the validation of json - def testLongLoad(self): Test the load and the validation of long json - def testEmptyLoad(self): Test the load ...
bb336e434afcc11463b53880558d9c314f309c0e
<|skeleton|> class TestSchema: def testLoad(self): """Test the load and the validation of json""" <|body_0|> def testLongLoad(self): """Test the load and the validation of long json""" <|body_1|> def testEmptyLoad(self): """Test the load and the validation of empty...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestSchema: def testLoad(self): """Test the load and the validation of json""" output_schema = CMOutput() json_testdata = get_json_testdata('marshmallow.json') out = output_schema.load(data=json_testdata) self.assertGreater(len(out), 0) def testLongLoad(self): ...
the_stack_v2_python_sparse
cm/base/BaseCM/test.py
sfrias/enermaps
train
0
ecabc9886fa79310e177369c541ac253b6e8315e
[ "quick = head\nslow = head\nwhile quick.next:\n quick = quick.next.next\n slow = slow.next\n if quick == slow:\n return True\n if not quick:\n return False\nreturn False", "if not head:\n print('null')\n return\nif not self.checkLoop(head):\n print('null')\n return\nelse:\n ...
<|body_start_0|> quick = head slow = head while quick.next: quick = quick.next.next slow = slow.next if quick == slow: return True if not quick: return False return False <|end_body_0|> <|body_start_1|> ...
判断链表中环的入口节点解决方案
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """判断链表中环的入口节点解决方案""" def checkLoop(self, head): """检查是否存在环""" <|body_0|> def EntryNodeOfLoop(self, head): """获取链表环的入口节点""" <|body_1|> def EntryNodeOfLoop2(self, head): """获取链表环的入口节点——减少了计算环长度步骤和控制双指针间隔的步骤(2x-x=n)""" <|body_...
stack_v2_sparse_classes_36k_train_010350
5,548
no_license
[ { "docstring": "检查是否存在环", "name": "checkLoop", "signature": "def checkLoop(self, head)" }, { "docstring": "获取链表环的入口节点", "name": "EntryNodeOfLoop", "signature": "def EntryNodeOfLoop(self, head)" }, { "docstring": "获取链表环的入口节点——减少了计算环长度步骤和控制双指针间隔的步骤(2x-x=n)", "name": "EntryNodeO...
3
null
Implement the Python class `Solution` described below. Class description: 判断链表中环的入口节点解决方案 Method signatures and docstrings: - def checkLoop(self, head): 检查是否存在环 - def EntryNodeOfLoop(self, head): 获取链表环的入口节点 - def EntryNodeOfLoop2(self, head): 获取链表环的入口节点——减少了计算环长度步骤和控制双指针间隔的步骤(2x-x=n)
Implement the Python class `Solution` described below. Class description: 判断链表中环的入口节点解决方案 Method signatures and docstrings: - def checkLoop(self, head): 检查是否存在环 - def EntryNodeOfLoop(self, head): 获取链表环的入口节点 - def EntryNodeOfLoop2(self, head): 获取链表环的入口节点——减少了计算环长度步骤和控制双指针间隔的步骤(2x-x=n) <|skeleton|> class Solution: ...
4e4f739402b95691f6c91411da26d7d3bfe042b6
<|skeleton|> class Solution: """判断链表中环的入口节点解决方案""" def checkLoop(self, head): """检查是否存在环""" <|body_0|> def EntryNodeOfLoop(self, head): """获取链表环的入口节点""" <|body_1|> def EntryNodeOfLoop2(self, head): """获取链表环的入口节点——减少了计算环长度步骤和控制双指针间隔的步骤(2x-x=n)""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """判断链表中环的入口节点解决方案""" def checkLoop(self, head): """检查是否存在环""" quick = head slow = head while quick.next: quick = quick.next.next slow = slow.next if quick == slow: return True if not quick: ...
the_stack_v2_python_sparse
剑指offer/55、链表中环的入口节点.py
hugechuanqi/Algorithms-and-Data-Structures
train
3
eff6e0b49dee7e51b28edb61300870e80bc9f8e1
[ "filename = TRUKeywords.download_tru()\nself.assertTrue(path.exists(filename))\nremove(filename)\nfilename = TRUKeywords.download_tru(file_name='tru.zip')\nself.assertTrue(path.exists('tru.zip'))\nremove(filename)\nret_file_path = TRUKeywords.download_tru(file_type='tarball')\nself.assertTrue(path.exists(ret_file_p...
<|body_start_0|> filename = TRUKeywords.download_tru() self.assertTrue(path.exists(filename)) remove(filename) filename = TRUKeywords.download_tru(file_name='tru.zip') self.assertTrue(path.exists('tru.zip')) remove(filename) ret_file_path = TRUKeywords.download_tr...
Unit tests for TRUKeywords
TruTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TruTests: """Unit tests for TRUKeywords""" def test_download_latest(self): """Test latest versions""" <|body_0|> def test_download_specific(self): """Test specific versions""" <|body_1|> def test_run_tru(self): """Test full run and retrieval"...
stack_v2_sparse_classes_36k_train_010351
10,750
no_license
[ { "docstring": "Test latest versions", "name": "test_download_latest", "signature": "def test_download_latest(self)" }, { "docstring": "Test specific versions", "name": "test_download_specific", "signature": "def test_download_specific(self)" }, { "docstring": "Test full run and ...
3
stack_v2_sparse_classes_30k_train_002429
Implement the Python class `TruTests` described below. Class description: Unit tests for TRUKeywords Method signatures and docstrings: - def test_download_latest(self): Test latest versions - def test_download_specific(self): Test specific versions - def test_run_tru(self): Test full run and retrieval
Implement the Python class `TruTests` described below. Class description: Unit tests for TRUKeywords Method signatures and docstrings: - def test_download_latest(self): Test latest versions - def test_download_specific(self): Test specific versions - def test_run_tru(self): Test full run and retrieval <|skeleton|> c...
24a74926170cbdfafa47e972644e2fe5b627d8ff
<|skeleton|> class TruTests: """Unit tests for TRUKeywords""" def test_download_latest(self): """Test latest versions""" <|body_0|> def test_download_specific(self): """Test specific versions""" <|body_1|> def test_run_tru(self): """Test full run and retrieval"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TruTests: """Unit tests for TRUKeywords""" def test_download_latest(self): """Test latest versions""" filename = TRUKeywords.download_tru() self.assertTrue(path.exists(filename)) remove(filename) filename = TRUKeywords.download_tru(file_name='tru.zip') self...
the_stack_v2_python_sparse
robo4.2/fusion/FusionLibrary/keywords/tru.py
richa92/Jenkin_Regression_Testing
train
0
2e7f37a250c9756984f1672ea51b26f386c7e40d
[ "super(Assert, self).__init__(*args, **kw)\nself.func = func\nself.err_msg = err_msg", "result = self.func(value, *args, **kw)\nmessage = self._build_message(value, result) + (self.err_msg if not result else '')\nreturn ValidationResult(value, result, message)" ]
<|body_start_0|> super(Assert, self).__init__(*args, **kw) self.func = func self.err_msg = err_msg <|end_body_0|> <|body_start_1|> result = self.func(value, *args, **kw) message = self._build_message(value, result) + (self.err_msg if not result else '') return Validation...
Generic validator which is using function to validate value. .. code-block:: python validation_expression = Assert(lambda x: isString(x), 'Value is not correct') validation_expression.validate('test_string') # returns ValidationResult object
Assert
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Assert: """Generic validator which is using function to validate value. .. code-block:: python validation_expression = Assert(lambda x: isString(x), 'Value is not correct') validation_expression.validate('test_string') # returns ValidationResult object""" def __init__(self, func, err_msg, *a...
stack_v2_sparse_classes_36k_train_010352
16,665
no_license
[ { "docstring": ":param func: Validation function. :param string err_msg: Message which will be add when validation fail.", "name": "__init__", "signature": "def __init__(self, func, err_msg, *args, **kw)" }, { "docstring": "Method checks if specified value meet requirements.", "name": "valid...
2
null
Implement the Python class `Assert` described below. Class description: Generic validator which is using function to validate value. .. code-block:: python validation_expression = Assert(lambda x: isString(x), 'Value is not correct') validation_expression.validate('test_string') # returns ValidationResult object Meth...
Implement the Python class `Assert` described below. Class description: Generic validator which is using function to validate value. .. code-block:: python validation_expression = Assert(lambda x: isString(x), 'Value is not correct') validation_expression.validate('test_string') # returns ValidationResult object Meth...
75487a40ac2cc5f24f70d011ad6cd3924908f783
<|skeleton|> class Assert: """Generic validator which is using function to validate value. .. code-block:: python validation_expression = Assert(lambda x: isString(x), 'Value is not correct') validation_expression.validate('test_string') # returns ValidationResult object""" def __init__(self, func, err_msg, *a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Assert: """Generic validator which is using function to validate value. .. code-block:: python validation_expression = Assert(lambda x: isString(x), 'Value is not correct') validation_expression.validate('test_string') # returns ValidationResult object""" def __init__(self, func, err_msg, *args, **kw): ...
the_stack_v2_python_sparse
bts_infomodel/ute_common_validator/validator.py
jufei/BtsShell
train
0
f9170b9912c228cfa84c28c689686b5386e0da78
[ "self.old_username = self.instance.username\nself.old_file_root = self.instance.file_root()\nif User.objects.filter(username__iexact=self.cleaned_data['username']):\n raise forms.ValidationError('A user with that username already exists.')\nreturn self.cleaned_data['username'].lower()", "new_username = self.cl...
<|body_start_0|> self.old_username = self.instance.username self.old_file_root = self.instance.file_root() if User.objects.filter(username__iexact=self.cleaned_data['username']): raise forms.ValidationError('A user with that username already exists.') return self.cleaned_data...
Updating the username filed
UsernameChangeForm
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UsernameChangeForm: """Updating the username filed""" def clean_username(self): """Record the original username in case it is needed""" <|body_0|> def save(self): """Change the media file directory name and photo name if any, to match the new username""" ...
stack_v2_sparse_classes_36k_train_010353
26,163
permissive
[ { "docstring": "Record the original username in case it is needed", "name": "clean_username", "signature": "def clean_username(self)" }, { "docstring": "Change the media file directory name and photo name if any, to match the new username", "name": "save", "signature": "def save(self)" ...
2
stack_v2_sparse_classes_30k_train_020364
Implement the Python class `UsernameChangeForm` described below. Class description: Updating the username filed Method signatures and docstrings: - def clean_username(self): Record the original username in case it is needed - def save(self): Change the media file directory name and photo name if any, to match the new...
Implement the Python class `UsernameChangeForm` described below. Class description: Updating the username filed Method signatures and docstrings: - def clean_username(self): Record the original username in case it is needed - def save(self): Change the media file directory name and photo name if any, to match the new...
e7c8ed0b07a4c9a1b4007f6089f59aafa6a3ac57
<|skeleton|> class UsernameChangeForm: """Updating the username filed""" def clean_username(self): """Record the original username in case it is needed""" <|body_0|> def save(self): """Change the media file directory name and photo name if any, to match the new username""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UsernameChangeForm: """Updating the username filed""" def clean_username(self): """Record the original username in case it is needed""" self.old_username = self.instance.username self.old_file_root = self.instance.file_root() if User.objects.filter(username__iexact=self.cl...
the_stack_v2_python_sparse
physionet-django/user/forms.py
tompollard/physionet-build
train
0
fbe855af2c1ba4df177f09df1d7de8e93c5376b8
[ "if hasattr(self, '_x'):\n return\nself._x = Int(0)", "from apysc.type import value_util\nself._initialize_x_if_not_initialized()\nreturn value_util.get_copy(value=self._x)", "from apysc.type.number_value_interface import NumberValueInterface\nfrom apysc.validation import number_validation\nif not isinstance...
<|body_start_0|> if hasattr(self, '_x'): return self._x = Int(0) <|end_body_0|> <|body_start_1|> from apysc.type import value_util self._initialize_x_if_not_initialized() return value_util.get_copy(value=self._x) <|end_body_1|> <|body_start_2|> from apysc.ty...
XInterface
[ "MIT", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XInterface: def _initialize_x_if_not_initialized(self) -> None: """Initialize _x attribute if it is not initialized yet.""" <|body_0|> def x(self) -> Int: """Get a x-coordinate. Returns ------- x : Int X-coordinate.""" <|body_1|> def x(self, value: Int) ...
stack_v2_sparse_classes_36k_train_010354
2,964
permissive
[ { "docstring": "Initialize _x attribute if it is not initialized yet.", "name": "_initialize_x_if_not_initialized", "signature": "def _initialize_x_if_not_initialized(self) -> None" }, { "docstring": "Get a x-coordinate. Returns ------- x : Int X-coordinate.", "name": "x", "signature": "...
6
null
Implement the Python class `XInterface` described below. Class description: Implement the XInterface class. Method signatures and docstrings: - def _initialize_x_if_not_initialized(self) -> None: Initialize _x attribute if it is not initialized yet. - def x(self) -> Int: Get a x-coordinate. Returns ------- x : Int X-...
Implement the Python class `XInterface` described below. Class description: Implement the XInterface class. Method signatures and docstrings: - def _initialize_x_if_not_initialized(self) -> None: Initialize _x attribute if it is not initialized yet. - def x(self) -> Int: Get a x-coordinate. Returns ------- x : Int X-...
5c6a4674e2e9684cb2cb1325dc9b070879d4d355
<|skeleton|> class XInterface: def _initialize_x_if_not_initialized(self) -> None: """Initialize _x attribute if it is not initialized yet.""" <|body_0|> def x(self) -> Int: """Get a x-coordinate. Returns ------- x : Int X-coordinate.""" <|body_1|> def x(self, value: Int) ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XInterface: def _initialize_x_if_not_initialized(self) -> None: """Initialize _x attribute if it is not initialized yet.""" if hasattr(self, '_x'): return self._x = Int(0) def x(self) -> Int: """Get a x-coordinate. Returns ------- x : Int X-coordinate.""" ...
the_stack_v2_python_sparse
apysc/display/x_interface.py
TrendingTechnology/apysc
train
0
dee29fa7db02c6dce5694df7a2e2ae9ea9e8f6dd
[ "self.mod_type = mod_type\nself.mval = mval\nself.num_bits = 0\nself.num_preamble_bits = 0\nself.num_pilot_bits = 0\nself.tr_extend_on = tr_extend\nself.fs_base = fs_base\nself.barker_type = barker_type\nself.pilot_sym = pilot_sym\nself._create_pilot_tone()\nself._create_preamble()\nif plot:\n self._plot()", "...
<|body_start_0|> self.mod_type = mod_type self.mval = mval self.num_bits = 0 self.num_preamble_bits = 0 self.num_pilot_bits = 0 self.tr_extend_on = tr_extend self.fs_base = fs_base self.barker_type = barker_type self.pilot_sym = pilot_sym s...
PreambleClass
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreambleClass: def __init__(self, mod_type='fm0', mval=1, tr_extend=None, fs_base=1, barker_type='barker11', pilot_sym=12, plot=False): """Generate a Gen2 reverse link preamble including (optional) pilot tone Args: mod_type : One of ['fm0', 'miller', 'square'] mval : One of [1, 2, 4, 8] ...
stack_v2_sparse_classes_36k_train_010355
36,290
no_license
[ { "docstring": "Generate a Gen2 reverse link preamble including (optional) pilot tone Args: mod_type : One of ['fm0', 'miller', 'square'] mval : One of [1, 2, 4, 8] tr_extend: True/False = pilot tone enabled/disabled fs_base: samples per BLF plot: True=create plot, False=do not create plot", "name": "__init...
5
stack_v2_sparse_classes_30k_train_004478
Implement the Python class `PreambleClass` described below. Class description: Implement the PreambleClass class. Method signatures and docstrings: - def __init__(self, mod_type='fm0', mval=1, tr_extend=None, fs_base=1, barker_type='barker11', pilot_sym=12, plot=False): Generate a Gen2 reverse link preamble including...
Implement the Python class `PreambleClass` described below. Class description: Implement the PreambleClass class. Method signatures and docstrings: - def __init__(self, mod_type='fm0', mval=1, tr_extend=None, fs_base=1, barker_type='barker11', pilot_sym=12, plot=False): Generate a Gen2 reverse link preamble including...
cc7ea7eae78bcc3709117ede81f89ed23d756e26
<|skeleton|> class PreambleClass: def __init__(self, mod_type='fm0', mval=1, tr_extend=None, fs_base=1, barker_type='barker11', pilot_sym=12, plot=False): """Generate a Gen2 reverse link preamble including (optional) pilot tone Args: mod_type : One of ['fm0', 'miller', 'square'] mval : One of [1, 2, 4, 8] ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PreambleClass: def __init__(self, mod_type='fm0', mval=1, tr_extend=None, fs_base=1, barker_type='barker11', pilot_sym=12, plot=False): """Generate a Gen2 reverse link preamble including (optional) pilot tone Args: mod_type : One of ['fm0', 'miller', 'square'] mval : One of [1, 2, 4, 8] tr_extend: Tru...
the_stack_v2_python_sparse
systems_r700/model/src/tag/tag_waveforms.py
NopMicrowave/Impinj_R700_Indy_Reader_Chip_and_Speedway_Reader_Simulation
train
0
29f3acec0536d9e868f177e29704862b3f6ee06d
[ "super().__init__(verbose=verbose)\nif isinstance(fbp_filter, str):\n fbp_filter = fbp_filter.lower()\nself.fbp_filter = fbp_filter\nself.pad_mode = pad_mode", "if isinstance(self.fbp_filter, str):\n return super().info() + '(F:' + self.fbp_filter.upper() + ')'\nelif isinstance(self.fbp_filter, np.ndarray):...
<|body_start_0|> super().__init__(verbose=verbose) if isinstance(fbp_filter, str): fbp_filter = fbp_filter.lower() self.fbp_filter = fbp_filter self.pad_mode = pad_mode <|end_body_0|> <|body_start_1|> if isinstance(self.fbp_filter, str): return super().in...
Implementation of the Filtered Back-Projection (FBP) algorithm.
FBP
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FBP: """Implementation of the Filtered Back-Projection (FBP) algorithm.""" def __init__(self, verbose: bool=False, regularizer: Union[Sequence[BaseRegularizer], BaseRegularizer, None]=None, data_term: Union[str, DataFidelityBase]='l2', fbp_filter: Union[str, NDArrayFloat, filters.Filter]='ra...
stack_v2_sparse_classes_36k_train_010356
35,110
permissive
[ { "docstring": "Initialize the Filtered Back-Projection (FBP) algorithm. Parameters ---------- verbose : bool, optional Turn on verbose output. The default is False. regularizer : Sequence[BaseRegularizer] | BaseRegularizer | None, optional NOT USED, only exposed for compatibility reasons. data_term : Union[str...
3
stack_v2_sparse_classes_30k_train_010426
Implement the Python class `FBP` described below. Class description: Implementation of the Filtered Back-Projection (FBP) algorithm. Method signatures and docstrings: - def __init__(self, verbose: bool=False, regularizer: Union[Sequence[BaseRegularizer], BaseRegularizer, None]=None, data_term: Union[str, DataFidelity...
Implement the Python class `FBP` described below. Class description: Implementation of the Filtered Back-Projection (FBP) algorithm. Method signatures and docstrings: - def __init__(self, verbose: bool=False, regularizer: Union[Sequence[BaseRegularizer], BaseRegularizer, None]=None, data_term: Union[str, DataFidelity...
66ea08345fe7f7e15f561e66cba5d5b7d02169dd
<|skeleton|> class FBP: """Implementation of the Filtered Back-Projection (FBP) algorithm.""" def __init__(self, verbose: bool=False, regularizer: Union[Sequence[BaseRegularizer], BaseRegularizer, None]=None, data_term: Union[str, DataFidelityBase]='l2', fbp_filter: Union[str, NDArrayFloat, filters.Filter]='ra...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FBP: """Implementation of the Filtered Back-Projection (FBP) algorithm.""" def __init__(self, verbose: bool=False, regularizer: Union[Sequence[BaseRegularizer], BaseRegularizer, None]=None, data_term: Union[str, DataFidelityBase]='l2', fbp_filter: Union[str, NDArrayFloat, filters.Filter]='ramp', pad_mode...
the_stack_v2_python_sparse
corrct/solvers.py
cicwi/PyCorrectedEmissionCT
train
5
5b4aec72b768dc96f5310aea98c1d8e0897e3970
[ "super().__init__()\nself.postnet = nn.LayerList()\nfor layer in six.moves.range(n_layers - 1):\n ichans = odim if layer == 0 else n_chans\n ochans = odim if layer == n_layers - 1 else n_chans\n if use_batch_norm:\n self.postnet.append(nn.Sequential(nn.Conv1D(ichans, ochans, n_filts, stride=1, paddi...
<|body_start_0|> super().__init__() self.postnet = nn.LayerList() for layer in six.moves.range(n_layers - 1): ichans = odim if layer == 0 else n_chans ochans = odim if layer == n_layers - 1 else n_chans if use_batch_norm: self.postnet.append(nn...
Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decoder, which helps to compensate the de...
Postnet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Postnet: """Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decode...
stack_v2_sparse_classes_36k_train_010357
6,559
permissive
[ { "docstring": "Initialize postnet module. Parameters ---------- idim : int Dimension of the inputs. odim : int Dimension of the outputs. n_layers : int, optional The number of layers. n_filts : int, optional The number of filter size. n_units : int, optional The number of filter channels. use_batch_norm : bool...
2
null
Implement the Python class `Postnet` described below. Class description: Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the...
Implement the Python class `Postnet` described below. Class description: Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the...
8705a2a8405e3c63f2174d69880d2b5525a6c9fd
<|skeleton|> class Postnet: """Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decode...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Postnet: """Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decoder, which help...
the_stack_v2_python_sparse
parakeet/modules/tacotron2/decoder.py
PaddlePaddle/Parakeet
train
609
8f42eb8d9d3d6c628d52930e874ac5f67242d578
[ "db = DatabaseConnection()\nconn = db.getconnection()\ntry:\n with conn.cursor() as cursor:\n sql = \"SELECT A.user_pref, AST.assertion_type, A.parameters FROM assertions A LEFT JOIN assertions_types AST ON A.assertion_type = AST.id WHERE A.user_pref = '\" + user_pref + \"' ORDER BY A.assertion_type\"\n ...
<|body_start_0|> db = DatabaseConnection() conn = db.getconnection() try: with conn.cursor() as cursor: sql = "SELECT A.user_pref, AST.assertion_type, A.parameters FROM assertions A LEFT JOIN assertions_types AST ON A.assertion_type = AST.id WHERE A.user_pref = '" + u...
AssertionModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssertionModel: def getAssertionByUserPreference(self, user_pref): """:param user_pref: :returns the assertions by user preference:""" <|body_0|> def getLikedPagesAndEvents(self): """:returns list of LikedPagesAndEvents object:""" <|body_1|> def getAsser...
stack_v2_sparse_classes_36k_train_010358
4,087
no_license
[ { "docstring": ":param user_pref: :returns the assertions by user preference:", "name": "getAssertionByUserPreference", "signature": "def getAssertionByUserPreference(self, user_pref)" }, { "docstring": ":returns list of LikedPagesAndEvents object:", "name": "getLikedPagesAndEvents", "si...
4
stack_v2_sparse_classes_30k_train_004102
Implement the Python class `AssertionModel` described below. Class description: Implement the AssertionModel class. Method signatures and docstrings: - def getAssertionByUserPreference(self, user_pref): :param user_pref: :returns the assertions by user preference: - def getLikedPagesAndEvents(self): :returns list of ...
Implement the Python class `AssertionModel` described below. Class description: Implement the AssertionModel class. Method signatures and docstrings: - def getAssertionByUserPreference(self, user_pref): :param user_pref: :returns the assertions by user preference: - def getLikedPagesAndEvents(self): :returns list of ...
44a7dc53f33cb342b087d3c62149437eb655a3c7
<|skeleton|> class AssertionModel: def getAssertionByUserPreference(self, user_pref): """:param user_pref: :returns the assertions by user preference:""" <|body_0|> def getLikedPagesAndEvents(self): """:returns list of LikedPagesAndEvents object:""" <|body_1|> def getAsser...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AssertionModel: def getAssertionByUserPreference(self, user_pref): """:param user_pref: :returns the assertions by user preference:""" db = DatabaseConnection() conn = db.getconnection() try: with conn.cursor() as cursor: sql = "SELECT A.user_pref, A...
the_stack_v2_python_sparse
StoryGenerator/storygenappv2/storygen/models/AssertionModel.py
hbrosas/Persona-Based-Life-Story-Generation
train
0
692132eba1fbb4d74c05d078887d8a3901db52d4
[ "c = Client()\nresp = c.get('/react-example/')\nself.assertIn(b'<div id=\"react_container\"></div>', resp.content)\nself.assertIn(b'<script crossorigin src=\"https://unpkg.com/react@16/umd/react.development.js\"></script>', resp.content)\nself.assertIn(b'<script crossorigin src=\"https://unpkg.com/react-dom@16/umd/...
<|body_start_0|> c = Client() resp = c.get('/react-example/') self.assertIn(b'<div id="react_container"></div>', resp.content) self.assertIn(b'<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>', resp.content) self.assertIn(b'<script crossorig...
Exercise4Test
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exercise4Test: def test_view_and_template(self): """Test that the view, URLs and template are set up properly by checking the contents of the response.""" <|body_0|> def test_js_content(self): """Test that some expected things are in the JS file.""" <|body_1|...
stack_v2_sparse_classes_36k_train_010359
2,702
permissive
[ { "docstring": "Test that the view, URLs and template are set up properly by checking the contents of the response.", "name": "test_view_and_template", "signature": "def test_view_and_template(self)" }, { "docstring": "Test that some expected things are in the JS file.", "name": "test_js_con...
2
null
Implement the Python class `Exercise4Test` described below. Class description: Implement the Exercise4Test class. Method signatures and docstrings: - def test_view_and_template(self): Test that the view, URLs and template are set up properly by checking the contents of the response. - def test_js_content(self): Test ...
Implement the Python class `Exercise4Test` described below. Class description: Implement the Exercise4Test class. Method signatures and docstrings: - def test_view_and_template(self): Test that the view, URLs and template are set up properly by checking the contents of the response. - def test_js_content(self): Test ...
52e86a8f93cb38bf70d50e9b8d2c6d7dac416f62
<|skeleton|> class Exercise4Test: def test_view_and_template(self): """Test that the view, URLs and template are set up properly by checking the contents of the response.""" <|body_0|> def test_js_content(self): """Test that some expected things are in the JS file.""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Exercise4Test: def test_view_and_template(self): """Test that the view, URLs and template are set up properly by checking the contents of the response.""" c = Client() resp = c.get('/react-example/') self.assertIn(b'<div id="react_container"></div>', resp.content) self....
the_stack_v2_python_sparse
Chapter16/Exercise16.04/bookr/reviews/tests.py
lmoshood/The-Django-Workshop
train
0
89e34bdb92d7bf94d16257a84928320dde6832a3
[ "import numpy as np\nimport healpy as hp\nsuper(GSMObserver2016, self).__init__()\nself.gsm = GlobalSkyModel2016(freq_unit='MHz')\nself.observed_sky = None\nself.gsm.generate(1000)\nself._n_pix = hp.get_map_size(self.gsm.generated_map_data)\nself._n_side = hp.npix2nside(self._n_pix)\nself._theta, self._phi = hp.pix...
<|body_start_0|> import numpy as np import healpy as hp super(GSMObserver2016, self).__init__() self.gsm = GlobalSkyModel2016(freq_unit='MHz') self.observed_sky = None self.gsm.generate(1000) self._n_pix = hp.get_map_size(self.gsm.generated_map_data) self....
Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. This class is based on pyephem's Observer(). The GSM bit can be thought of as an '...
pyGSM2016Obs
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class pyGSM2016Obs: """Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. This class is based on pyephem's Observer(...
stack_v2_sparse_classes_36k_train_010360
21,210
no_license
[ { "docstring": "Initialize the Observer object. Calls ephem.Observer.__init__ function and adds on gsm", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Generate the observed sky for the observer, based on the GSM. Parameters ---------- freq: float Frequency of map to ge...
4
null
Implement the Python class `pyGSM2016Obs` described below. Class description: Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. Thi...
Implement the Python class `pyGSM2016Obs` described below. Class description: Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. Thi...
b49777105a76b5ae03555a9f93f116454c8245a9
<|skeleton|> class pyGSM2016Obs: """Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. This class is based on pyephem's Observer(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class pyGSM2016Obs: """Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. This class is based on pyephem's Observer(). The GSM bi...
the_stack_v2_python_sparse
Astro/pyGSM.py
jizhi/jizhipy
train
1
64d94509752f81351b397f6d53dcdb863a2651b2
[ "super(MultiHeadAttention, self).__init__()\nself.h = h\nself.dm = dm\nself.depth = self.dm // self.h\nself.Wq = tf.keras.layers.Dense(self.dm)\nself.Wk = tf.keras.layers.Dense(self.dm)\nself.Wv = tf.keras.layers.Dense(self.dm)\nself.linear = tf.keras.layers.Dense(self.dm)", "batch_size = tf.shape(Q)[0]\nq = self...
<|body_start_0|> super(MultiHeadAttention, self).__init__() self.h = h self.dm = dm self.depth = self.dm // self.h self.Wq = tf.keras.layers.Dense(self.dm) self.Wk = tf.keras.layers.Dense(self.dm) self.Wv = tf.keras.layers.Dense(self.dm) self.linear = tf.k...
MultiHeadAttention class perform multi-head attention
MultiHeadAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiHeadAttention: """MultiHeadAttention class perform multi-head attention""" def __init__(self, dm, h) -> None: """Initializer Arguments: dm {int} -- Is representing the dimensionality of the model h {int} -- Is representing the number of heads""" <|body_0|> def call(...
stack_v2_sparse_classes_36k_train_010361
2,227
no_license
[ { "docstring": "Initializer Arguments: dm {int} -- Is representing the dimensionality of the model h {int} -- Is representing the number of heads", "name": "__init__", "signature": "def __init__(self, dm, h) -> None" }, { "docstring": "Instance call Arguments: Q {tf.Tensor} -- Is a tensor of sha...
2
null
Implement the Python class `MultiHeadAttention` described below. Class description: MultiHeadAttention class perform multi-head attention Method signatures and docstrings: - def __init__(self, dm, h) -> None: Initializer Arguments: dm {int} -- Is representing the dimensionality of the model h {int} -- Is representing...
Implement the Python class `MultiHeadAttention` described below. Class description: MultiHeadAttention class perform multi-head attention Method signatures and docstrings: - def __init__(self, dm, h) -> None: Initializer Arguments: dm {int} -- Is representing the dimensionality of the model h {int} -- Is representing...
2ddae38cc25d914488451b8c30e1234f1fa55ebe
<|skeleton|> class MultiHeadAttention: """MultiHeadAttention class perform multi-head attention""" def __init__(self, dm, h) -> None: """Initializer Arguments: dm {int} -- Is representing the dimensionality of the model h {int} -- Is representing the number of heads""" <|body_0|> def call(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiHeadAttention: """MultiHeadAttention class perform multi-head attention""" def __init__(self, dm, h) -> None: """Initializer Arguments: dm {int} -- Is representing the dimensionality of the model h {int} -- Is representing the number of heads""" super(MultiHeadAttention, self).__init...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/6-multihead_attention.py
KoeusIss/holbertonschool-machine_learning
train
0
7602f95cd08a30236f27ac25319a1eefeb5c0ec8
[ "msg = f'Model object must be of type flopy.mfusg.MfUsg\\nbut received type: {type(model)}.'\nassert isinstance(model, MfUsg), msg\nfilenames = self._prepare_filenames(filenames)\nsuper().__init__(model, ipakcb=ipakcb, stress_period_data=stress_period_data, dtype=dtype, extension=extension, options=options, binary=...
<|body_start_0|> msg = f'Model object must be of type flopy.mfusg.MfUsg\nbut received type: {type(model)}.' assert isinstance(model, MfUsg), msg filenames = self._prepare_filenames(filenames) super().__init__(model, ipakcb=ipakcb, stress_period_data=stress_period_data, dtype=dtype, exten...
MODFLOW-USG Well Package Class. Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. ipakcb : int A flag that is used to determine if cell-by-cell budget data should be saved. If ipakcb is non-zero cell-by-cell budget data will be s...
MfUsgWel
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MfUsgWel: """MODFLOW-USG Well Package Class. Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. ipakcb : int A flag that is used to determine if cell-by-cell budget data should be saved. If ipakcb is non-zer...
stack_v2_sparse_classes_36k_train_010362
10,176
permissive
[ { "docstring": "Package constructor.", "name": "__init__", "signature": "def __init__(self, model, ipakcb=None, stress_period_data=None, cln_stress_period_data=None, dtype=None, cln_dtype=None, extension='wel', options=None, binary=False, unitnumber=None, filenames=None, add_package=True)" }, { ...
3
null
Implement the Python class `MfUsgWel` described below. Class description: MODFLOW-USG Well Package Class. Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. ipakcb : int A flag that is used to determine if cell-by-cell budget dat...
Implement the Python class `MfUsgWel` described below. Class description: MODFLOW-USG Well Package Class. Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. ipakcb : int A flag that is used to determine if cell-by-cell budget dat...
22ef330bcfb9259fc23735d6b174d27804b624a0
<|skeleton|> class MfUsgWel: """MODFLOW-USG Well Package Class. Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. ipakcb : int A flag that is used to determine if cell-by-cell budget data should be saved. If ipakcb is non-zer...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MfUsgWel: """MODFLOW-USG Well Package Class. Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. ipakcb : int A flag that is used to determine if cell-by-cell budget data should be saved. If ipakcb is non-zero cell-by-cel...
the_stack_v2_python_sparse
flopy/mfusg/mfusgwel.py
robinthibaut/flopy
train
0
047db63311d0359ae9ba8de7b5900a2cc655848f
[ "source = yaml.get('source', None)\nself.source: Optional[SourceName] = None if source is None else SourceName(source)\nself.remote: Optional[str] = yaml.get('remote', None)\ngit = yaml.get('git', None)\nself.git_settings: Optional[GitSettings] = None if git is None else GitSettings(git)\nself.branch: Optional[str]...
<|body_start_0|> source = yaml.get('source', None) self.source: Optional[SourceName] = None if source is None else SourceName(source) self.remote: Optional[str] = yaml.get('remote', None) git = yaml.get('git', None) self.git_settings: Optional[GitSettings] = None if git is None e...
clowder yaml Defaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name :ivar Optional[GitSettings] git_settings: Custom git settings :ivar Optional[str] branch: Default git branch :ivar Optional[str] tag: Default git tag :ivar Optional[str] commit: Defau...
Defaults
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Defaults: """clowder yaml Defaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name :ivar Optional[GitSettings] git_settings: Custom git settings :ivar Optional[str] branch: Default git branch :ivar Optional[str] tag: Default git t...
stack_v2_sparse_classes_36k_train_010363
2,342
permissive
[ { "docstring": "Defaults __init__ :param dict yaml: Parsed YAML python object for defaults", "name": "__init__", "signature": "def __init__(self, yaml: dict)" }, { "docstring": "Return python object representation for saving yaml :return: YAML python object", "name": "get_yaml", "signatu...
2
stack_v2_sparse_classes_30k_train_005269
Implement the Python class `Defaults` described below. Class description: clowder yaml Defaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name :ivar Optional[GitSettings] git_settings: Custom git settings :ivar Optional[str] branch: Default git branch...
Implement the Python class `Defaults` described below. Class description: clowder yaml Defaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name :ivar Optional[GitSettings] git_settings: Custom git settings :ivar Optional[str] branch: Default git branch...
1438fc8b1bb7379de66142ffcb0e20b459b59159
<|skeleton|> class Defaults: """clowder yaml Defaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name :ivar Optional[GitSettings] git_settings: Custom git settings :ivar Optional[str] branch: Default git branch :ivar Optional[str] tag: Default git t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Defaults: """clowder yaml Defaults model class :ivar Optional[SourceName] source: Default source name :ivar Optional[str] remote: Default remote name :ivar Optional[GitSettings] git_settings: Custom git settings :ivar Optional[str] branch: Default git branch :ivar Optional[str] tag: Default git tag :ivar Opti...
the_stack_v2_python_sparse
clowder/model/defaults.py
JrGoodle/clowder
train
17
1bfe38249ba97406c12af39807b10ccb13ed1d8f
[ "if not pHead1 or not pHead2:\n return None\nids = []\np1 = pHead1\np2 = pHead2\nwhile p1:\n ids.append(id(p1))\n p1 = p1.next\nwhile p2:\n if id(p2) in ids:\n return p2\n p2 = p2.next\nreturn None", "if not pHead1 or not pHead2:\n return None\nstack1 = []\nstack2 = []\np1 = pHead1\np2 = ...
<|body_start_0|> if not pHead1 or not pHead2: return None ids = [] p1 = pHead1 p2 = pHead2 while p1: ids.append(id(p1)) p1 = p1.next while p2: if id(p2) in ids: return p2 p2 = p2.next retu...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def FindFirstCommonNode(self, pHead1, pHead2): """Python特色的解法""" <|body_0|> def FindFirstCommonNode2(self, pHead1, pHead2): """由于是单向链表,因此若存在公共节点,则两个链表的尾节点一定相同 可以从尾节点开始比较,第一个不相同的节点的next节点就是第一个公共节点""" <|body_1|> def FindFirstCommonNode3(self, pHe...
stack_v2_sparse_classes_36k_train_010364
3,088
no_license
[ { "docstring": "Python特色的解法", "name": "FindFirstCommonNode", "signature": "def FindFirstCommonNode(self, pHead1, pHead2)" }, { "docstring": "由于是单向链表,因此若存在公共节点,则两个链表的尾节点一定相同 可以从尾节点开始比较,第一个不相同的节点的next节点就是第一个公共节点", "name": "FindFirstCommonNode2", "signature": "def FindFirstCommonNode2(self,...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def FindFirstCommonNode(self, pHead1, pHead2): Python特色的解法 - def FindFirstCommonNode2(self, pHead1, pHead2): 由于是单向链表,因此若存在公共节点,则两个链表的尾节点一定相同 可以从尾节点开始比较,第一个不相同的节点的next节点就是第一个公共节点 ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def FindFirstCommonNode(self, pHead1, pHead2): Python特色的解法 - def FindFirstCommonNode2(self, pHead1, pHead2): 由于是单向链表,因此若存在公共节点,则两个链表的尾节点一定相同 可以从尾节点开始比较,第一个不相同的节点的next节点就是第一个公共节点 ...
24dd0fcf44a84126d7c88e3d4622c26262e72863
<|skeleton|> class Solution: def FindFirstCommonNode(self, pHead1, pHead2): """Python特色的解法""" <|body_0|> def FindFirstCommonNode2(self, pHead1, pHead2): """由于是单向链表,因此若存在公共节点,则两个链表的尾节点一定相同 可以从尾节点开始比较,第一个不相同的节点的next节点就是第一个公共节点""" <|body_1|> def FindFirstCommonNode3(self, pHe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def FindFirstCommonNode(self, pHead1, pHead2): """Python特色的解法""" if not pHead1 or not pHead2: return None ids = [] p1 = pHead1 p2 = pHead2 while p1: ids.append(id(p1)) p1 = p1.next while p2: if id...
the_stack_v2_python_sparse
54.两个链表的第一个公共节点.py
costume24/Sword-to-Offer
train
0
a010d69c47164225eb4103b9030e9501db02118e
[ "assert nums is not None\nnums.sort()\nn = len(nums)\nres = set()\nadict = {}\nfor i in xrange(n - 1):\n for j in xrange(i + 1, n):\n asum = nums[i] + nums[j]\n if asum not in adict:\n adict[asum] = [(i, j)]\n else:\n adict[asum].append((i, j))\nfor i in xrange(n - 4 + ...
<|body_start_0|> assert nums is not None nums.sort() n = len(nums) res = set() adict = {} for i in xrange(n - 1): for j in xrange(i + 1, n): asum = nums[i] + nums[j] if asum not in adict: adict[asum] = [(i, j...
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a+b+c+d) The solution set must not contain duplicate quadruplets...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a+b+c+d) The solution set mu...
stack_v2_sparse_classes_36k_train_010365
2,724
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]", "name": "fourSum_hash", "signature": "def fourSum_hash(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]", "name": "fourSum_Generic", "signature": "def ...
2
stack_v2_sparse_classes_30k_train_018960
Implement the Python class `Solution` described below. Class description: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending o...
Implement the Python class `Solution` described below. Class description: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending o...
cbe6a7e7f05eccb4f9c5fce8651c0d87e5168516
<|skeleton|> class Solution: """Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a+b+c+d) The solution set mu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a+b+c+d) The solution set must not contai...
the_stack_v2_python_sparse
src/array/leetcode18_4Sum.py
apepkuss/Cracking-Leetcode-in-Python
train
2
95b8145b69bb78f1bdb97ab2afbddb341dde14d1
[ "cls = kwargs.pop('cls', None)\nerror_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}\nerror_map.update(kwargs.pop('error_map', {}))\napi_version = kwargs.pop('api_version', '2021-05-01-preview')\nrequest = build_get_sip_configuration_request(api_version=api_version, tem...
<|body_start_0|> cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = kwargs.pop('api_version', '2021-05-01-preview') request = build_get_sip_co...
SIPRoutingServiceOperationsMixin
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SIPRoutingServiceOperationsMixin: def get_sip_configuration(self, **kwargs): """Gets SIP configuration for resource. Gets SIP configuration for resource. :keyword callable cls: A custom type or function that will be passed the direct response :return: SipConfiguration, or the result of c...
stack_v2_sparse_classes_36k_train_010366
8,134
permissive
[ { "docstring": "Gets SIP configuration for resource. Gets SIP configuration for resource. :keyword callable cls: A custom type or function that will be passed the direct response :return: SipConfiguration, or the result of cls(response) :rtype: ~azure.communication.phonenumbers.siprouting.models.SipConfiguratio...
2
stack_v2_sparse_classes_30k_train_006735
Implement the Python class `SIPRoutingServiceOperationsMixin` described below. Class description: Implement the SIPRoutingServiceOperationsMixin class. Method signatures and docstrings: - def get_sip_configuration(self, **kwargs): Gets SIP configuration for resource. Gets SIP configuration for resource. :keyword call...
Implement the Python class `SIPRoutingServiceOperationsMixin` described below. Class description: Implement the SIPRoutingServiceOperationsMixin class. Method signatures and docstrings: - def get_sip_configuration(self, **kwargs): Gets SIP configuration for resource. Gets SIP configuration for resource. :keyword call...
b23e71b289c71f179b9cf9b8c75b1922833a542a
<|skeleton|> class SIPRoutingServiceOperationsMixin: def get_sip_configuration(self, **kwargs): """Gets SIP configuration for resource. Gets SIP configuration for resource. :keyword callable cls: A custom type or function that will be passed the direct response :return: SipConfiguration, or the result of c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SIPRoutingServiceOperationsMixin: def get_sip_configuration(self, **kwargs): """Gets SIP configuration for resource. Gets SIP configuration for resource. :keyword callable cls: A custom type or function that will be passed the direct response :return: SipConfiguration, or the result of cls(response) :...
the_stack_v2_python_sparse
sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/operations/_sip_routing_service_operations.py
kurtzeborn/azure-sdk-for-python
train
0
8e13433aa32802d85924f63b27a40189790fd67c
[ "self.api = board.apis.uart\nself.initialized = False\nself.baud = baud\nself.data_bits = data_bits\nself.stop_bits = stop_bits\nself.parity = parity or self.PARITY_NONE\nself.uart_number = 0\nself.actual_baud = 0", "self.baud = baud if baud is not None else self.baud\nself.data_bits = data_bits if data_bits is n...
<|body_start_0|> self.api = board.apis.uart self.initialized = False self.baud = baud self.data_bits = data_bits self.stop_bits = stop_bits self.parity = parity or self.PARITY_NONE self.uart_number = 0 self.actual_baud = 0 <|end_body_0|> <|body_start_1|> ...
TODO: description
UART
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UART: """TODO: description""" def __init__(self, board, baud=115200, data_bits=8, stop_bits=1, parity=None, uart_number=0): """Args: board -- GreatFET board whose UART lines are to be controlled""" <|body_0|> def update_parameters(self, baud=None, data_bits=None, stop_bi...
stack_v2_sparse_classes_36k_train_010367
2,821
permissive
[ { "docstring": "Args: board -- GreatFET board whose UART lines are to be controlled", "name": "__init__", "signature": "def __init__(self, board, baud=115200, data_bits=8, stop_bits=1, parity=None, uart_number=0)" }, { "docstring": "Updates the UART parameters for the provided board. This is int...
4
null
Implement the Python class `UART` described below. Class description: TODO: description Method signatures and docstrings: - def __init__(self, board, baud=115200, data_bits=8, stop_bits=1, parity=None, uart_number=0): Args: board -- GreatFET board whose UART lines are to be controlled - def update_parameters(self, ba...
Implement the Python class `UART` described below. Class description: TODO: description Method signatures and docstrings: - def __init__(self, board, baud=115200, data_bits=8, stop_bits=1, parity=None, uart_number=0): Args: board -- GreatFET board whose UART lines are to be controlled - def update_parameters(self, ba...
2409575d28fc7c9cae44c9085c7457ddfb54f893
<|skeleton|> class UART: """TODO: description""" def __init__(self, board, baud=115200, data_bits=8, stop_bits=1, parity=None, uart_number=0): """Args: board -- GreatFET board whose UART lines are to be controlled""" <|body_0|> def update_parameters(self, baud=None, data_bits=None, stop_bi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UART: """TODO: description""" def __init__(self, board, baud=115200, data_bits=8, stop_bits=1, parity=None, uart_number=0): """Args: board -- GreatFET board whose UART lines are to be controlled""" self.api = board.apis.uart self.initialized = False self.baud = baud ...
the_stack_v2_python_sparse
host/greatfet/interfaces/uart.py
greatscottgadgets/greatfet
train
273
58c0cb36d14e9b9f12af452961dd3e0dbf540586
[ "allowed_fields = {'process_id', 'output', 'input', 'tags', 'entity', 'entity_id', 'collection', 'collection_id', 'name'}\nnot_allowed_keys = set(model_data.keys()) - allowed_fields\nif not_allowed_keys:\n raise RuntimeError(f\"Not allowed to set {','.join(not_allowed_keys)}.\")\nself._has_permission(user, Proce...
<|body_start_0|> allowed_fields = {'process_id', 'output', 'input', 'tags', 'entity', 'entity_id', 'collection', 'collection_id', 'name'} not_allowed_keys = set(model_data.keys()) - allowed_fields if not_allowed_keys: raise RuntimeError(f"Not allowed to set {','.join(not_allowed_keys...
Expose the Data model.
ExposeData
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExposeData: """Expose the Data model.""" def can_create(self, user: 'UserType', model_data: dict, data_id: int): """Can user update the given model instance. :raises RuntimeError: if user does not have permissions to create the given model.""" <|body_0|> def can_update(s...
stack_v2_sparse_classes_36k_train_010368
13,286
permissive
[ { "docstring": "Can user update the given model instance. :raises RuntimeError: if user does not have permissions to create the given model.", "name": "can_create", "signature": "def can_create(self, user: 'UserType', model_data: dict, data_id: int)" }, { "docstring": "Can user update the given ...
3
null
Implement the Python class `ExposeData` described below. Class description: Expose the Data model. Method signatures and docstrings: - def can_create(self, user: 'UserType', model_data: dict, data_id: int): Can user update the given model instance. :raises RuntimeError: if user does not have permissions to create the...
Implement the Python class `ExposeData` described below. Class description: Expose the Data model. Method signatures and docstrings: - def can_create(self, user: 'UserType', model_data: dict, data_id: int): Can user update the given model instance. :raises RuntimeError: if user does not have permissions to create the...
25c0c45235ef37beb45c1af4c917fbbae6282016
<|skeleton|> class ExposeData: """Expose the Data model.""" def can_create(self, user: 'UserType', model_data: dict, data_id: int): """Can user update the given model instance. :raises RuntimeError: if user does not have permissions to create the given model.""" <|body_0|> def can_update(s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExposeData: """Expose the Data model.""" def can_create(self, user: 'UserType', model_data: dict, data_id: int): """Can user update the given model instance. :raises RuntimeError: if user does not have permissions to create the given model.""" allowed_fields = {'process_id', 'output', 'in...
the_stack_v2_python_sparse
resolwe/flow/managers/listener/permission_plugin.py
genialis/resolwe
train
35
e8645b24f89a25162c401501d9a79fc8da214a54
[ "self._cache = cache\nself._package = package\nself._service_manager = service_manager", "self._service_manager.RecordServices()\ntry:\n self._package.mark_install(True, True, False)\n logging.info('Installing...')\n self._cache.commit()\nexcept (apt.cache.FetchFailedException, SystemError) as e:\n lo...
<|body_start_0|> self._cache = cache self._package = package self._service_manager = service_manager <|end_body_0|> <|body_start_1|> self._service_manager.RecordServices() try: self._package.mark_install(True, True, False) logging.info('Installing...') ...
A Debian "install" trigger.
DebInstall
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DebInstall: """A Debian "install" trigger.""" def __init__(self, cache, package, service_manager): """Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the application.""" <|body_0|> def RunTrigger(self): ...
stack_v2_sparse_classes_36k_train_010369
10,965
no_license
[ { "docstring": "Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the application.", "name": "__init__", "signature": "def __init__(self, cache, package, service_manager)" }, { "docstring": "Run a Debian \"install\" trigger. This t...
2
stack_v2_sparse_classes_30k_train_021256
Implement the Python class `DebInstall` described below. Class description: A Debian "install" trigger. Method signatures and docstrings: - def __init__(self, cache, package, service_manager): Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the applic...
Implement the Python class `DebInstall` described below. Class description: A Debian "install" trigger. Method signatures and docstrings: - def __init__(self, cache, package, service_manager): Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the applic...
3fa5a9d67eb4eea87d3a54b1af5946cec8b67cca
<|skeleton|> class DebInstall: """A Debian "install" trigger.""" def __init__(self, cache, package, service_manager): """Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the application.""" <|body_0|> def RunTrigger(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DebInstall: """A Debian "install" trigger.""" def __init__(self, cache, package, service_manager): """Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the application.""" self._cache = cache self._package = package ...
the_stack_v2_python_sparse
guest/deb_triggers.py
tojo2000/wheelbarrow
train
0
dea5b347ac137197c39d64d7f2b5ed5fd6881a45
[ "self.token = random_number_token(length)\nself.valid_until = timezone.now() + timedelta(seconds=valid_secs)\nif commit:\n self.save()", "_now = timezone.now()\nif self.token is not None and token == self.token and (_now < self.valid_until):\n self.token = None\n self.valid_until = _now\n self.save()\...
<|body_start_0|> self.token = random_number_token(length) self.valid_until = timezone.now() + timedelta(seconds=valid_secs) if commit: self.save() <|end_body_0|> <|body_start_1|> _now = timezone.now() if self.token is not None and token == self.token and (_now < self...
Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery.
SideChannelDevice
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SideChannelDevice: """Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery.""" def generate_token(self, length=6, valid_secs=300, commit=True): ...
stack_v2_sparse_classes_36k_train_010370
13,172
permissive
[ { "docstring": "Generates a token of the specified length, then sets it on the model and sets the expiration of the token on the model. Pass 'commit=False' to avoid calling self.save(). :param int length: Number of decimal digits in the generated token. :param int valid_secs: Amount of seconds the token should ...
2
stack_v2_sparse_classes_30k_train_012892
Implement the Python class `SideChannelDevice` described below. Class description: Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery. Method signatures and docstrings: -...
Implement the Python class `SideChannelDevice` described below. Class description: Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery. Method signatures and docstrings: -...
d65a039582509a08c56c35f905380fe3ff8507cb
<|skeleton|> class SideChannelDevice: """Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery.""" def generate_token(self, length=6, valid_secs=300, commit=True): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SideChannelDevice: """Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery.""" def generate_token(self, length=6, valid_secs=300, commit=True): """Gene...
the_stack_v2_python_sparse
src/django_otp/models.py
django-otp/django-otp
train
460
9a41b66cb097b527e50226d6af9fb3571758f1e9
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WorkforceIntegration()", "from .change_tracked_entity import ChangeTrackedEntity\nfrom .workforce_integration_encryption import WorkforceIntegrationEncryption\nfrom .workforce_integration_supported_entities import WorkforceIntegrationS...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return WorkforceIntegration() <|end_body_0|> <|body_start_1|> from .change_tracked_entity import ChangeTrackedEntity from .workforce_integration_encryption import WorkforceIntegrationEncryption...
WorkforceIntegration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkforceIntegration: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkforceIntegration: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ...
stack_v2_sparse_classes_36k_train_010371
4,400
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: WorkforceIntegration", "name": "create_from_discriminator_value", "signature": "def create_from_discriminato...
3
null
Implement the Python class `WorkforceIntegration` described below. Class description: Implement the WorkforceIntegration class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkforceIntegration: Creates a new instance of the appropriate class based o...
Implement the Python class `WorkforceIntegration` described below. Class description: Implement the WorkforceIntegration class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkforceIntegration: Creates a new instance of the appropriate class based o...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class WorkforceIntegration: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkforceIntegration: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WorkforceIntegration: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkforceIntegration: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns...
the_stack_v2_python_sparse
msgraph/generated/models/workforce_integration.py
microsoftgraph/msgraph-sdk-python
train
135
74e1a8d745d8263614e8b7e080fedc65d9709b81
[ "self.years = [year for year in range(year_i, year_f + 1)]\nself.type_AOD = type_AOD\nself.year_i = year_i\nself.year_f = year_f\nself.file = file", "self.data = pd.read_csv(path + self.file + '.csv')\nself.clean_data()\nself.data = self.data.fillna(-1)\nself.len_data = len(self.data[self.type_AOD])", "for key ...
<|body_start_0|> self.years = [year for year in range(year_i, year_f + 1)] self.type_AOD = type_AOD self.year_i = year_i self.year_f = year_f self.file = file <|end_body_0|> <|body_start_1|> self.data = pd.read_csv(path + self.file + '.csv') self.clean_data() ...
Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS
MODIS_data
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MODIS_data: """Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS""" def __init__(self, file, year_i, year_f, type_AOD): """Describcion de variables: type_AOD---> columna de AOD que leer file ---> archivo que contiene la informacion del AOD year_i ---> ...
stack_v2_sparse_classes_36k_train_010372
2,794
no_license
[ { "docstring": "Describcion de variables: type_AOD---> columna de AOD que leer file ---> archivo que contiene la informacion del AOD year_i ---> año en el que inicia el analisis year_f ---> año en el que finaliza el analisis", "name": "__init__", "signature": "def __init__(self, file, year_i, year_f, ty...
5
stack_v2_sparse_classes_30k_train_014470
Implement the Python class `MODIS_data` described below. Class description: Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS Method signatures and docstrings: - def __init__(self, file, year_i, year_f, type_AOD): Describcion de variables: type_AOD---> columna de AOD que leer file --->...
Implement the Python class `MODIS_data` described below. Class description: Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS Method signatures and docstrings: - def __init__(self, file, year_i, year_f, type_AOD): Describcion de variables: type_AOD---> columna de AOD que leer file --->...
43c7c6e6c57e76a0f80a3052a9060161d9b9dd41
<|skeleton|> class MODIS_data: """Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS""" def __init__(self, file, year_i, year_f, type_AOD): """Describcion de variables: type_AOD---> columna de AOD que leer file ---> archivo que contiene la informacion del AOD year_i ---> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MODIS_data: """Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS""" def __init__(self, file, year_i, year_f, type_AOD): """Describcion de variables: type_AOD---> columna de AOD que leer file ---> archivo que contiene la informacion del AOD year_i ---> año en el que...
the_stack_v2_python_sparse
Scripts/functions_MODIS.py
iphadra/SIMA
train
0
e0416be9a7b208860b912f07d9a5a0e52a8a25b6
[ "if not password_file:\n raise RuntimeError('No password file specified')\nif not os.path.exists(password_file):\n raise RuntimeError(f\"password file '{password_file}' does not exist\")\nself.password_file = password_file\nself.newt_base_url = newt_base_url if newt_base_url else _NEWT_BASE_URL\nif not self.n...
<|body_start_0|> if not password_file: raise RuntimeError('No password file specified') if not os.path.exists(password_file): raise RuntimeError(f"password file '{password_file}' does not exist") self.password_file = password_file self.newt_base_url = newt_base_ur...
Newt
[ "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Newt: def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0): """Constructor that takes path to password file and optional Newt base URL :param password_file: path to password file :param newt_base_url: Newt base URL (default will be _NEWT_BASE_URL)"...
stack_v2_sparse_classes_36k_train_010373
5,141
permissive
[ { "docstring": "Constructor that takes path to password file and optional Newt base URL :param password_file: path to password file :param newt_base_url: Newt base URL (default will be _NEWT_BASE_URL)", "name": "__init__", "signature": "def __init__(self, password_file, newt_base_url=None, max_retries=0...
6
stack_v2_sparse_classes_30k_train_010630
Implement the Python class `Newt` described below. Class description: Implement the Newt class. Method signatures and docstrings: - def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0): Constructor that takes path to password file and optional Newt base URL :param password_file...
Implement the Python class `Newt` described below. Class description: Implement the Newt class. Method signatures and docstrings: - def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0): Constructor that takes path to password file and optional Newt base URL :param password_file...
842fdc91a31879084906d71a7d0c317e5035a925
<|skeleton|> class Newt: def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0): """Constructor that takes path to password file and optional Newt base URL :param password_file: path to password file :param newt_base_url: Newt base URL (default will be _NEWT_BASE_URL)"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Newt: def __init__(self, password_file, newt_base_url=None, max_retries=0, retry_backoff_factor=0): """Constructor that takes path to password file and optional Newt base URL :param password_file: path to password file :param newt_base_url: Newt base URL (default will be _NEWT_BASE_URL)""" if ...
the_stack_v2_python_sparse
src/decisionengine_modules/NERSC/util/newt.py
HEPCloud/decisionengine_modules
train
2
bed83aa1055c3d8905a3a360f4de307ca0c0587d
[ "self.sc_middleware = SharedContextMiddleware()\nself.request = MagicMock()\nself.request.GET = {'q': 'a_deal_search_key'}\nself.response = MagicMock()\nself.response.context_data = {'context_var_from_view': 'blah blah blah'}", "response = self.sc_middleware.process_template_response(self.request, self.response)\...
<|body_start_0|> self.sc_middleware = SharedContextMiddleware() self.request = MagicMock() self.request.GET = {'q': 'a_deal_search_key'} self.response = MagicMock() self.response.context_data = {'context_var_from_view': 'blah blah blah'} <|end_body_0|> <|body_start_1|> r...
Testcase for the SharedContextMiddleware class
SharedContextMiddlewareTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SharedContextMiddlewareTestCase: """Testcase for the SharedContextMiddleware class""" def setUp(self): """operations to run before every test""" <|body_0|> def test_that_middleware_updates_context_with_categories(self): """tests that the response context_data was...
stack_v2_sparse_classes_36k_train_010374
2,698
permissive
[ { "docstring": "operations to run before every test", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "tests that the response context_data was updated with correct data for categories, cities, advertisers and search.", "name": "test_that_middleware_updates_context_with_cat...
3
null
Implement the Python class `SharedContextMiddlewareTestCase` described below. Class description: Testcase for the SharedContextMiddleware class Method signatures and docstrings: - def setUp(self): operations to run before every test - def test_that_middleware_updates_context_with_categories(self): tests that the resp...
Implement the Python class `SharedContextMiddlewareTestCase` described below. Class description: Testcase for the SharedContextMiddleware class Method signatures and docstrings: - def setUp(self): operations to run before every test - def test_that_middleware_updates_context_with_categories(self): tests that the resp...
3704cbe6e69ba3e4c53401d3bbc339208e9ebccd
<|skeleton|> class SharedContextMiddlewareTestCase: """Testcase for the SharedContextMiddleware class""" def setUp(self): """operations to run before every test""" <|body_0|> def test_that_middleware_updates_context_with_categories(self): """tests that the response context_data was...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SharedContextMiddlewareTestCase: """Testcase for the SharedContextMiddleware class""" def setUp(self): """operations to run before every test""" self.sc_middleware = SharedContextMiddleware() self.request = MagicMock() self.request.GET = {'q': 'a_deal_search_key'} ...
the_stack_v2_python_sparse
troupon/middleware/test_middleware.py
morristech/troupon
train
0
4e0006352d5b8dc5f80ebb467d94a86b12073fff
[ "credential, unused_project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/gerritcodereview'])\ncredential.refresh(google.auth.transport.requests.Request())\nreturn 'o=git-{service_account_name}={token}'.format(service_account_name=credential.service_account_email, token=credential.token)", "tr...
<|body_start_0|> credential, unused_project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/gerritcodereview']) credential.refresh(google.auth.transport.requests.Request()) return 'o=git-{service_account_name}={token}'.format(service_account_name=credential.service_account_emai...
A helper class for the gerrit connector.
GerritConnectorHelper
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GerritConnectorHelper: """A helper class for the gerrit connector.""" def GetGerritAuthCookie(self) -> str: """Get the OAuth cookie of gerrit code review. Returns: An string of the cookie.""" <|body_0|> def ConvertDataToJson(self, data) -> dict: """Convert the da...
stack_v2_sparse_classes_36k_train_010375
5,382
permissive
[ { "docstring": "Get the OAuth cookie of gerrit code review. Returns: An string of the cookie.", "name": "GetGerritAuthCookie", "signature": "def GetGerritAuthCookie(self) -> str" }, { "docstring": "Convert the data responded from the Gerrit Rest API to the json type. Args: data: The string from ...
3
null
Implement the Python class `GerritConnectorHelper` described below. Class description: A helper class for the gerrit connector. Method signatures and docstrings: - def GetGerritAuthCookie(self) -> str: Get the OAuth cookie of gerrit code review. Returns: An string of the cookie. - def ConvertDataToJson(self, data) ->...
Implement the Python class `GerritConnectorHelper` described below. Class description: A helper class for the gerrit connector. Method signatures and docstrings: - def GetGerritAuthCookie(self) -> str: Get the OAuth cookie of gerrit code review. Returns: An string of the cookie. - def ConvertDataToJson(self, data) ->...
a1b0fccd68987d8cd9c89710adc3c04b868347ec
<|skeleton|> class GerritConnectorHelper: """A helper class for the gerrit connector.""" def GetGerritAuthCookie(self) -> str: """Get the OAuth cookie of gerrit code review. Returns: An string of the cookie.""" <|body_0|> def ConvertDataToJson(self, data) -> dict: """Convert the da...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GerritConnectorHelper: """A helper class for the gerrit connector.""" def GetGerritAuthCookie(self) -> str: """Get the OAuth cookie of gerrit code review. Returns: An string of the cookie.""" credential, unused_project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/gerr...
the_stack_v2_python_sparse
py/probe_info_service/app_engine/gerrit_connector.py
bridder/factory
train
0
62ead22077b5657537030bbdd1c9a176ae2bf000
[ "super(BilinearNetworkLayer, self).__init__()\nself.inputs_size = inputs_size\nself.model = nn.ModuleList()\nfor _ in range(num_layers):\n self.model.append(nn.Bilinear(inputs_size, inputs_size, inputs_size))", "outputs = emb_inputs.detach().requires_grad_()\nfor layer in self.model:\n outputs = layer(emb_i...
<|body_start_0|> super(BilinearNetworkLayer, self).__init__() self.inputs_size = inputs_size self.model = nn.ModuleList() for _ in range(num_layers): self.model.append(nn.Bilinear(inputs_size, inputs_size, inputs_size)) <|end_body_0|> <|body_start_1|> outputs = emb_i...
Layer class of Bilinear. Bilinear is to calculate interaction in element-wise by nn.Bilinear, which the calculation is: for i-th layer, :math:`x_{i} = (x_{0} * A_{i} * x_{i - 1}) + b_{i} + x_{0}`, where :math:`A_{i}` is the weight of module of shape :math:`(O_{i}, I_{i1}, I_{i2})`.
BilinearNetworkLayer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BilinearNetworkLayer: """Layer class of Bilinear. Bilinear is to calculate interaction in element-wise by nn.Bilinear, which the calculation is: for i-th layer, :math:`x_{i} = (x_{0} * A_{i} * x_{i - 1}) + b_{i} + x_{0}`, where :math:`A_{i}` is the weight of module of shape :math:`(O_{i}, I_{i1},...
stack_v2_sparse_classes_36k_train_010376
2,600
permissive
[ { "docstring": "Initialize BilinearNetworkLayer Args: inputs_size (int): Input size of Bilinear, i.e. size of embedding tensor. num_layers (int): Number of layers of Bilinear Network Attributes: inputs_size (int): Size of inputs, or Product of embed_size and num_fields. model (torch.nn.ModuleList): Module List ...
2
stack_v2_sparse_classes_30k_train_021131
Implement the Python class `BilinearNetworkLayer` described below. Class description: Layer class of Bilinear. Bilinear is to calculate interaction in element-wise by nn.Bilinear, which the calculation is: for i-th layer, :math:`x_{i} = (x_{0} * A_{i} * x_{i - 1}) + b_{i} + x_{0}`, where :math:`A_{i}` is the weight of...
Implement the Python class `BilinearNetworkLayer` described below. Class description: Layer class of Bilinear. Bilinear is to calculate interaction in element-wise by nn.Bilinear, which the calculation is: for i-th layer, :math:`x_{i} = (x_{0} * A_{i} * x_{i - 1}) + b_{i} + x_{0}`, where :math:`A_{i}` is the weight of...
07a6a38c7eb44225f2b22f332081f697c3b92894
<|skeleton|> class BilinearNetworkLayer: """Layer class of Bilinear. Bilinear is to calculate interaction in element-wise by nn.Bilinear, which the calculation is: for i-th layer, :math:`x_{i} = (x_{0} * A_{i} * x_{i - 1}) + b_{i} + x_{0}`, where :math:`A_{i}` is the weight of module of shape :math:`(O_{i}, I_{i1},...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BilinearNetworkLayer: """Layer class of Bilinear. Bilinear is to calculate interaction in element-wise by nn.Bilinear, which the calculation is: for i-th layer, :math:`x_{i} = (x_{0} * A_{i} * x_{i - 1}) + b_{i} + x_{0}`, where :math:`A_{i}` is the weight of module of shape :math:`(O_{i}, I_{i1}, I_{i2})`."""...
the_stack_v2_python_sparse
torecsys/layers/ctr/bilinear.py
zwcdp/torecsys
train
0
e79d104ebc2456ebc8816db0762f2e2dc74a2df8
[ "super().__init__()\nself.mlp = mlp\nself.use_softmax = use_softmax", "B, C, N = feature.size()\nfeature = feature.view(B, C, N, 1).repeat(1, 1, 1, N)\nif feature.device.type == 'cpu':\n feature = feature - feature.transpose(2, 3).contiguous() + torch.mul(feature, torch.eye(N).view(1, 1, N, N))\nelse:\n fea...
<|body_start_0|> super().__init__() self.mlp = mlp self.use_softmax = use_softmax <|end_body_0|> <|body_start_1|> B, C, N = feature.size() feature = feature.view(B, C, N, 1).repeat(1, 1, 1, N) if feature.device.type == 'cpu': feature = feature - feature.trans...
AFAModule
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AFAModule: def __init__(self, mlp, use_softmax=False): """:param mlp: mlp for learning weight mode: transformation or aggregation""" <|body_0|> def forward(self, feature: torch.Tensor) -> torch.Tensor: """Parameters ---------- features : torch.Tensor (B, C, N, M) or ...
stack_v2_sparse_classes_36k_train_010377
12,242
permissive
[ { "docstring": ":param mlp: mlp for learning weight mode: transformation or aggregation", "name": "__init__", "signature": "def __init__(self, mlp, use_softmax=False)" }, { "docstring": "Parameters ---------- features : torch.Tensor (B, C, N, M) or (B, C, N) Returns ------- new_features : torch....
2
stack_v2_sparse_classes_30k_train_014991
Implement the Python class `AFAModule` described below. Class description: Implement the AFAModule class. Method signatures and docstrings: - def __init__(self, mlp, use_softmax=False): :param mlp: mlp for learning weight mode: transformation or aggregation - def forward(self, feature: torch.Tensor) -> torch.Tensor: ...
Implement the Python class `AFAModule` described below. Class description: Implement the AFAModule class. Method signatures and docstrings: - def __init__(self, mlp, use_softmax=False): :param mlp: mlp for learning weight mode: transformation or aggregation - def forward(self, feature: torch.Tensor) -> torch.Tensor: ...
241b3c94112efb2944a27e4cc3eb1d65775edc10
<|skeleton|> class AFAModule: def __init__(self, mlp, use_softmax=False): """:param mlp: mlp for learning weight mode: transformation or aggregation""" <|body_0|> def forward(self, feature: torch.Tensor) -> torch.Tensor: """Parameters ---------- features : torch.Tensor (B, C, N, M) or ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AFAModule: def __init__(self, mlp, use_softmax=False): """:param mlp: mlp for learning weight mode: transformation or aggregation""" super().__init__() self.mlp = mlp self.use_softmax = use_softmax def forward(self, feature: torch.Tensor) -> torch.Tensor: """Parame...
the_stack_v2_python_sparse
crowd_nav/policy/gipcarl.py
sustech-isus/AEMCARL
train
0
0bcdf7b7d27e6f6462f5a35ea2ff631bbf095ebe
[ "memo = {}\nfor num in nums1:\n memo[num] = memo.get(num, 0) + 1\nresult = []\nfor num in nums2:\n if num in memo and memo[num] > 0:\n result.append(num)\n memo[num] -= 1\nreturn result", "nums1.sort()\nnums2.sort()\nresult = []\ni1 = i2 = 0\nwhile i1 < len(nums1) and i2 < len(nums2):\n if ...
<|body_start_0|> memo = {} for num in nums1: memo[num] = memo.get(num, 0) + 1 result = [] for num in nums2: if num in memo and memo[num] > 0: result.append(num) memo[num] -= 1 return result <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def intersect_0(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" <|body_0|> def intersect_1(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k_train_010378
2,179
no_license
[ { "docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]", "name": "intersect_0", "signature": "def intersect_0(self, nums1, nums2)" }, { "docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]", "name": "intersect_1", "signature": "def inters...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def intersect_0(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int] - def intersect_1(self, nums1, nums2): :type nums1: List[int] :type nums2: Li...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def intersect_0(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int] - def intersect_1(self, nums1, nums2): :type nums1: List[int] :type nums2: Li...
9ac54720f571a4bea09d0cceb0039381a78df9e8
<|skeleton|> class Solution: def intersect_0(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" <|body_0|> def intersect_1(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def intersect_0(self, nums1, nums2): """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]""" memo = {} for num in nums1: memo[num] = memo.get(num, 0) + 1 result = [] for num in nums2: if num in memo and memo[num] > 0: ...
the_stack_v2_python_sparse
code/350_intersection-of-two-arrays-ii.py
linhdvu14/leetcode-solutions
train
2
e8aefc791b1d2b255a182bd702708bfe12feb5d8
[ "parser.add_argument('job_name', metavar='JOB_NAME', help='The unique name to assign to the job.')\nparser.add_argument('--gcs-location', help='The location of the job template to run.', required=True)\nparser.add_argument('--zone', type=arg_parsers.RegexpValidator('\\\\w+-\\\\w+\\\\d-\\\\w', 'must provide a valid ...
<|body_start_0|> parser.add_argument('job_name', metavar='JOB_NAME', help='The unique name to assign to the job.') parser.add_argument('--gcs-location', help='The location of the job template to run.', required=True) parser.add_argument('--zone', type=arg_parsers.RegexpValidator('\\w+-\\w+\\d-\\...
Runs a job from the specified path.
Run
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Run: """Runs a job from the specified path.""" def Args(parser): """Register flags for this command. Args: parser: argparse.ArgumentParser to register arguments with.""" <|body_0|> def Run(self, args): """Runs the command. Args: args: The arguments that were prov...
stack_v2_sparse_classes_36k_train_010379
2,918
permissive
[ { "docstring": "Register flags for this command. Args: parser: argparse.ArgumentParser to register arguments with.", "name": "Args", "signature": "def Args(parser)" }, { "docstring": "Runs the command. Args: args: The arguments that were provided to this command invocation. Returns: A Job messag...
2
null
Implement the Python class `Run` described below. Class description: Runs a job from the specified path. Method signatures and docstrings: - def Args(parser): Register flags for this command. Args: parser: argparse.ArgumentParser to register arguments with. - def Run(self, args): Runs the command. Args: args: The arg...
Implement the Python class `Run` described below. Class description: Runs a job from the specified path. Method signatures and docstrings: - def Args(parser): Register flags for this command. Args: parser: argparse.ArgumentParser to register arguments with. - def Run(self, args): Runs the command. Args: args: The arg...
c98b58aeb0994e011df960163541e9379ae7ea06
<|skeleton|> class Run: """Runs a job from the specified path.""" def Args(parser): """Register flags for this command. Args: parser: argparse.ArgumentParser to register arguments with.""" <|body_0|> def Run(self, args): """Runs the command. Args: args: The arguments that were prov...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Run: """Runs a job from the specified path.""" def Args(parser): """Register flags for this command. Args: parser: argparse.ArgumentParser to register arguments with.""" parser.add_argument('job_name', metavar='JOB_NAME', help='The unique name to assign to the job.') parser.add_ar...
the_stack_v2_python_sparse
google-cloud-sdk/.install/.backup/lib/surface/dataflow/jobs/run.py
KaranToor/MA450
train
1
6c0fa090a6cfb14576aa2adc98c69dd5075836d5
[ "res = deque()\nfor i in range(len(nums)):\n if nums[i] % 2 == 0:\n res.append(nums[i])\n else:\n res.appendleft(nums[i])\nreturn list(res)", "i, j = (0, len(nums) - 1)\nwhile i < j:\n while i < j and nums[i] & 1 == 1:\n i += 1\n while i < j and nums[j] & 1 == 0:\n j -= 1\n...
<|body_start_0|> res = deque() for i in range(len(nums)): if nums[i] % 2 == 0: res.append(nums[i]) else: res.appendleft(nums[i]) return list(res) <|end_body_0|> <|body_start_1|> i, j = (0, len(nums) - 1) while i < j: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def exchange_1(self, nums: List[int]) -> List[int]: """双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:""" <|body_0|> def exchange_2(self, nums: List[int]) -> List[int]: """双指针 时间复杂度 O(N) 空间复杂度 O(1) :param nums: :return:""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_010380
1,516
no_license
[ { "docstring": "双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:", "name": "exchange_1", "signature": "def exchange_1(self, nums: List[int]) -> List[int]" }, { "docstring": "双指针 时间复杂度 O(N) 空间复杂度 O(1) :param nums: :return:", "name": "exchange_2", "signature": "def exchange_2(self, nums: L...
2
stack_v2_sparse_classes_30k_train_009393
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def exchange_1(self, nums: List[int]) -> List[int]: 双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return: - def exchange_2(self, nums: List[int]) -> List[int]: 双指针 时间复杂度 O(N) 空间复杂度 O(...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def exchange_1(self, nums: List[int]) -> List[int]: 双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return: - def exchange_2(self, nums: List[int]) -> List[int]: 双指针 时间复杂度 O(N) 空间复杂度 O(...
62419b49000e79962bcdc99cd98afd2fb82ea345
<|skeleton|> class Solution: def exchange_1(self, nums: List[int]) -> List[int]: """双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:""" <|body_0|> def exchange_2(self, nums: List[int]) -> List[int]: """双指针 时间复杂度 O(N) 空间复杂度 O(1) :param nums: :return:""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def exchange_1(self, nums: List[int]) -> List[int]: """双端队列 时间复杂度 O(N) 空间复杂度 O(N) :param nums: :return:""" res = deque() for i in range(len(nums)): if nums[i] % 2 == 0: res.append(nums[i]) else: res.appendleft(nums[i]) ...
the_stack_v2_python_sparse
剑指 Offer(第 2 版)/exchange.py
MaoningGuan/LeetCode
train
3
70ca41daa6d3c92741d6a2fe027d4c8f34b167f8
[ "if not isinstance(document, Mapping):\n raise ValueError('Document is not a Mapping')\nif isinstance(document, Document):\n doc_id = document.doc_id\n self._next_id = None\nelse:\n doc_id = self._get_next_id()\n\ndef updater(table: dict):\n assert doc_id not in table, 'doc_id ' + str(doc_id) + ' alr...
<|body_start_0|> if not isinstance(document, Mapping): raise ValueError('Document is not a Mapping') if isinstance(document, Document): doc_id = document.doc_id self._next_id = None else: doc_id = self._get_next_id() def updater(table: dic...
MyDb
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyDb: def insert(self, document): """Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID""" <|body_0|> def insert_multiple(self, documents: Iterable[Mapping]) -> List[int]: """Insert multiple documents in...
stack_v2_sparse_classes_36k_train_010381
3,238
no_license
[ { "docstring": "Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID", "name": "insert", "signature": "def insert(self, document)" }, { "docstring": "Insert multiple documents into the table. :param documents: a Iterable of documents ...
2
null
Implement the Python class `MyDb` described below. Class description: Implement the MyDb class. Method signatures and docstrings: - def insert(self, document): Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID - def insert_multiple(self, documents: Iter...
Implement the Python class `MyDb` described below. Class description: Implement the MyDb class. Method signatures and docstrings: - def insert(self, document): Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID - def insert_multiple(self, documents: Iter...
095d6587d6620469e0f1803d59a506682714da17
<|skeleton|> class MyDb: def insert(self, document): """Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID""" <|body_0|> def insert_multiple(self, documents: Iterable[Mapping]) -> List[int]: """Insert multiple documents in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyDb: def insert(self, document): """Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID""" if not isinstance(document, Mapping): raise ValueError('Document is not a Mapping') if isinstance(document, Document): ...
the_stack_v2_python_sparse
_msic/py/tinydb/test_use.py
FXTD-ODYSSEY/MayaScript
train
45
979e39a1c51c0a72875cfa6144beaa7ea504af40
[ "if isinstance(value, (ipaddress.IPv4Address, ipaddress.IPv6Address)):\n ip = value\nelse:\n ip = ipaddress.ip_address(value)\nif ip.version != self.version:\n raise FieldValueError(f'IP version mismatch: {ip.version} != {self.version}')\nreturn ip.packed", "val = ipaddress.ip_address(value)\nif val.vers...
<|body_start_0|> if isinstance(value, (ipaddress.IPv4Address, ipaddress.IPv6Address)): ip = value else: ip = ipaddress.ip_address(value) if ip.version != self.version: raise FieldValueError(f'IP version mismatch: {ip.version} != {self.version}') return...
Internal IP address value for protocol fields. Args: length: Field size (in bytes). callback: Callback function to be called upon :meth:`self.__call__ <pcapkit.corekit.fields.field._Field.__call__>`.
_IPAddressField
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _IPAddressField: """Internal IP address value for protocol fields. Args: length: Field size (in bytes). callback: Callback function to be called upon :meth:`self.__call__ <pcapkit.corekit.fields.field._Field.__call__>`.""" def pre_process(self, value: '_AT | bytes | int | str', packet: 'dict...
stack_v2_sparse_classes_36k_train_010382
8,370
permissive
[ { "docstring": "Process field value before packing. Args: value: Field value. packet: Packet data. Returns: Processed field value.", "name": "pre_process", "signature": "def pre_process(self, value: '_AT | bytes | int | str', packet: 'dict[str, Any]') -> 'bytes'" }, { "docstring": "Process field...
2
stack_v2_sparse_classes_30k_train_008212
Implement the Python class `_IPAddressField` described below. Class description: Internal IP address value for protocol fields. Args: length: Field size (in bytes). callback: Callback function to be called upon :meth:`self.__call__ <pcapkit.corekit.fields.field._Field.__call__>`. Method signatures and docstrings: - d...
Implement the Python class `_IPAddressField` described below. Class description: Internal IP address value for protocol fields. Args: length: Field size (in bytes). callback: Callback function to be called upon :meth:`self.__call__ <pcapkit.corekit.fields.field._Field.__call__>`. Method signatures and docstrings: - d...
a6fe49ec58f09e105bec5a00fb66d9b3f22730d9
<|skeleton|> class _IPAddressField: """Internal IP address value for protocol fields. Args: length: Field size (in bytes). callback: Callback function to be called upon :meth:`self.__call__ <pcapkit.corekit.fields.field._Field.__call__>`.""" def pre_process(self, value: '_AT | bytes | int | str', packet: 'dict...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _IPAddressField: """Internal IP address value for protocol fields. Args: length: Field size (in bytes). callback: Callback function to be called upon :meth:`self.__call__ <pcapkit.corekit.fields.field._Field.__call__>`.""" def pre_process(self, value: '_AT | bytes | int | str', packet: 'dict[str, Any]') ...
the_stack_v2_python_sparse
pcapkit/corekit/fields/ipaddress.py
JarryShaw/PyPCAPKit
train
204
a4a18c37df588cc7d4965486140b62e9b15bba47
[ "dp = [0] * (n + 1)\nif n <= 2:\n return n\ndp[1] = 1\ndp[2] = 2\nfor i in range(3, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\nprint(dp[n])\nreturn dp[n]", "def rec(n, memo):\n if n in memo:\n return memo[n]\n memo[n] = rec(n - 1, memo) + rec(n - 2, memo)\n return memo[n]\nmemo = {}\nmemo[1] =...
<|body_start_0|> dp = [0] * (n + 1) if n <= 2: return n dp[1] = 1 dp[2] = 2 for i in range(3, n + 1): dp[i] = dp[i - 1] + dp[i - 2] print(dp[n]) return dp[n] <|end_body_0|> <|body_start_1|> def rec(n, memo): if n in mem...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def climbStairs(self, n): """:type n: int :rtype: int""" <|body_0|> def climbStairs_rec(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> dp = [0] * (n + 1) if n <= 2: return n ...
stack_v2_sparse_classes_36k_train_010383
1,740
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "climbStairs", "signature": "def climbStairs(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "climbStairs_rec", "signature": "def climbStairs_rec(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_005402
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def climbStairs(self, n): :type n: int :rtype: int - def climbStairs_rec(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def climbStairs(self, n): :type n: int :rtype: int - def climbStairs_rec(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def climbStairs(self, n): "...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def climbStairs(self, n): """:type n: int :rtype: int""" <|body_0|> def climbStairs_rec(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def climbStairs(self, n): """:type n: int :rtype: int""" dp = [0] * (n + 1) if n <= 2: return n dp[1] = 1 dp[2] = 2 for i in range(3, n + 1): dp[i] = dp[i - 1] + dp[i - 2] print(dp[n]) return dp[n] def climb...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00070.Climbing Stairs.py
roger6blog/LeetCode
train
0
dce82b60dd0ac35efad9427b0f7fb5878127c0ed
[ "cmd = 'nova'\nif api_version:\n cmd += ' --os-compute-api-version {0}'.format(api_version)\ncmd += ' list'\nexit_code, stdout, stderr = self.execute_command(cmd, timeout=config.SERVER_LIST_TIMEOUT, check=check)\nif check:\n list_result = output_parser.listing(stdout)\n assert_that(list_result, is_not(empt...
<|body_start_0|> cmd = 'nova' if api_version: cmd += ' --os-compute-api-version {0}'.format(api_version) cmd += ' list' exit_code, stdout, stderr = self.execute_command(cmd, timeout=config.SERVER_LIST_TIMEOUT, check=check) if check: list_result = output_pa...
CLI nova client steps.
CliNovaSteps
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CliNovaSteps: """CLI nova client steps.""" def nova_list(self, api_version=None, check=True): """Step to get nova list. Args: api_version (str|None): micro version for nova list command check (bool): flag whether to check result or not Raises: TimeoutExpired|AssertionError: if check ...
stack_v2_sparse_classes_36k_train_010384
2,899
no_license
[ { "docstring": "Step to get nova list. Args: api_version (str|None): micro version for nova list command check (bool): flag whether to check result or not Raises: TimeoutExpired|AssertionError: if check failed after timeout", "name": "nova_list", "signature": "def nova_list(self, api_version=None, check...
2
stack_v2_sparse_classes_30k_train_004245
Implement the Python class `CliNovaSteps` described below. Class description: CLI nova client steps. Method signatures and docstrings: - def nova_list(self, api_version=None, check=True): Step to get nova list. Args: api_version (str|None): micro version for nova list command check (bool): flag whether to check resul...
Implement the Python class `CliNovaSteps` described below. Class description: CLI nova client steps. Method signatures and docstrings: - def nova_list(self, api_version=None, check=True): Step to get nova list. Args: api_version (str|None): micro version for nova list command check (bool): flag whether to check resul...
e7583444cd24893ec6ae237b47db7c605b99b0c5
<|skeleton|> class CliNovaSteps: """CLI nova client steps.""" def nova_list(self, api_version=None, check=True): """Step to get nova list. Args: api_version (str|None): micro version for nova list command check (bool): flag whether to check result or not Raises: TimeoutExpired|AssertionError: if check ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CliNovaSteps: """CLI nova client steps.""" def nova_list(self, api_version=None, check=True): """Step to get nova list. Args: api_version (str|None): micro version for nova list command check (bool): flag whether to check result or not Raises: TimeoutExpired|AssertionError: if check failed after ...
the_stack_v2_python_sparse
stepler/cli_clients/steps/nova.py
Mirantis/stepler
train
16
7cebaa98aa274383b70615d2869af2d0889a37c6
[ "super(AfterSaleServiceConditionImpliedWarranties, self).__init__(*args, **kwargs)\nself.endpoint = '/after-sales-service-conditions/implied-warranties'\nself.seller_id = None\nself._headers = {'Accept': 'application/vnd.allegro.public.v1+json', 'Content-type': 'application/vnd.allegro.public.v1+json'}", "self.se...
<|body_start_0|> super(AfterSaleServiceConditionImpliedWarranties, self).__init__(*args, **kwargs) self.endpoint = '/after-sales-service-conditions/implied-warranties' self.seller_id = None self._headers = {'Accept': 'application/vnd.allegro.public.v1+json', 'Content-type': 'application/...
Manage category tree
AfterSaleServiceConditionImpliedWarranties
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AfterSaleServiceConditionImpliedWarranties: """Manage category tree""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" <|body_0|> def all(self, seller_id=None): """Get a list of categories :param seller_id: The seller's unique id. :type seller_...
stack_v2_sparse_classes_36k_train_010385
1,357
permissive
[ { "docstring": "Initialize the endpoint", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Get a list of categories :param seller_id: The seller's unique id. :type seller_id: :py:class:`str` :return: The JSON response from API or error or None (if 204) :r...
2
stack_v2_sparse_classes_30k_test_000220
Implement the Python class `AfterSaleServiceConditionImpliedWarranties` described below. Class description: Manage category tree Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the endpoint - def all(self, seller_id=None): Get a list of categories :param seller_id: The seller's uni...
Implement the Python class `AfterSaleServiceConditionImpliedWarranties` described below. Class description: Manage category tree Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the endpoint - def all(self, seller_id=None): Get a list of categories :param seller_id: The seller's uni...
112b0f2570fcf3840645dd62f6f7150956e56f9c
<|skeleton|> class AfterSaleServiceConditionImpliedWarranties: """Manage category tree""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" <|body_0|> def all(self, seller_id=None): """Get a list of categories :param seller_id: The seller's unique id. :type seller_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AfterSaleServiceConditionImpliedWarranties: """Manage category tree""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" super(AfterSaleServiceConditionImpliedWarranties, self).__init__(*args, **kwargs) self.endpoint = '/after-sales-service-conditions/implied-warr...
the_stack_v2_python_sparse
allegroapi/entities/aftersalesserviceconditionsimpliedwarranties.py
krystianmagdziarz/python-allegro
train
0
e44ca393f1970a08b88b045422a099b883e84ae4
[ "if not root:\n return ''\narr = []\nqueue = [root]\nwhile queue:\n node = queue.pop(0)\n arr.append(str(node.val) if node else 'null')\n if node:\n queue.append(node.left)\n queue.append(node.right)\nwhile arr[-1] == 'null':\n arr.pop()\nreturn ','.join(arr)", "if not data:\n retu...
<|body_start_0|> if not root: return '' arr = [] queue = [root] while queue: node = queue.pop(0) arr.append(str(node.val) if node else 'null') if node: queue.append(node.left) queue.append(node.right) ...
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_36k_train_010386
2,195
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
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
26fddfdbd09c30376cb0720e13baf0402c3a1e90
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '' arr = [] queue = [root] while queue: node = queue.pop(0) arr.append(str(node.val) if node else 'null') ...
the_stack_v2_python_sparse
2022.2.8start/297.二叉树的序列化与反序列化.py
cosJin/LeetCode
train
0
587fcc5493081aa26787413f58e6f8e5d8782256
[ "adm = ProjektAdministration()\nsemester = adm.get_alle_semester()\nreturn semester", "id = request.args.get('id')\nadm = ProjektAdministration()\nadm.delete_semester(id)", "adm = ProjektAdministration()\nsemester = Semester.from_dict(api.payload)\nif semester is not None:\n ' Wir verwenden semester des Prop...
<|body_start_0|> adm = ProjektAdministration() semester = adm.get_alle_semester() return semester <|end_body_0|> <|body_start_1|> id = request.args.get('id') adm = ProjektAdministration() adm.delete_semester(id) <|end_body_1|> <|body_start_2|> adm = ProjektAdmin...
SemesterOperationen
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SemesterOperationen: def get(self): """Auslesen aller Semester-Objekten. Sollten keine User-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben.""" <|body_0|> def delete(self): """Löschen eines bestimmten Semester-Objekts nach id.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_010387
29,521
no_license
[ { "docstring": "Auslesen aller Semester-Objekten. Sollten keine User-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben.", "name": "get", "signature": "def get(self)" }, { "docstring": "Löschen eines bestimmten Semester-Objekts nach id.", "name": "delete", "signature": "def...
4
stack_v2_sparse_classes_30k_train_009898
Implement the Python class `SemesterOperationen` described below. Class description: Implement the SemesterOperationen class. Method signatures and docstrings: - def get(self): Auslesen aller Semester-Objekten. Sollten keine User-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben. - def delete(self): Lö...
Implement the Python class `SemesterOperationen` described below. Class description: Implement the SemesterOperationen class. Method signatures and docstrings: - def get(self): Auslesen aller Semester-Objekten. Sollten keine User-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben. - def delete(self): Lö...
9014f16fed08956bd28216e1373b60139e5caea1
<|skeleton|> class SemesterOperationen: def get(self): """Auslesen aller Semester-Objekten. Sollten keine User-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben.""" <|body_0|> def delete(self): """Löschen eines bestimmten Semester-Objekts nach id.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SemesterOperationen: def get(self): """Auslesen aller Semester-Objekten. Sollten keine User-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben.""" adm = ProjektAdministration() semester = adm.get_alle_semester() return semester def delete(self): """Lö...
the_stack_v2_python_sparse
src/main.py
leanderpeter/university_project_selector
train
3
e1693b454a5a36cbb1ef53743dbad728954c1078
[ "team.trusted = trusted\nteam.save(update_fields=['trusted'])\nreturn Response({'detail': 'Mapping Team set as {}.'.format('trusted' if trusted else 'untrusted')}, status=status.HTTP_200_OK)", "team = self.get_object()\nif team.trusted:\n return Response({'detail': 'Mapping team is already trusted.'}, status=s...
<|body_start_0|> team.trusted = trusted team.save(update_fields=['trusted']) return Response({'detail': 'Mapping Team set as {}.'.format('trusted' if trusted else 'untrusted')}, status=status.HTTP_200_OK) <|end_body_0|> <|body_start_1|> team = self.get_object() if team.trusted: ...
MappingTeamTrustingAPIView
[ "BSD-3-Clause", "BSD-2-Clause", "ISC", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MappingTeamTrustingAPIView: def update_team(self, team, request, trusted): """Update 'checked', 'harmful', 'check_user', 'check_date' fields of the changeset and return a 200 response""" <|body_0|> def set_trusted(self, request, pk): """Set a Mapping Team as trusted....
stack_v2_sparse_classes_36k_train_010388
9,317
permissive
[ { "docstring": "Update 'checked', 'harmful', 'check_user', 'check_date' fields of the changeset and return a 200 response", "name": "update_team", "signature": "def update_team(self, team, request, trusted)" }, { "docstring": "Set a Mapping Team as trusted. You don't need to send data, just make...
3
stack_v2_sparse_classes_30k_train_001514
Implement the Python class `MappingTeamTrustingAPIView` described below. Class description: Implement the MappingTeamTrustingAPIView class. Method signatures and docstrings: - def update_team(self, team, request, trusted): Update 'checked', 'harmful', 'check_user', 'check_date' fields of the changeset and return a 20...
Implement the Python class `MappingTeamTrustingAPIView` described below. Class description: Implement the MappingTeamTrustingAPIView class. Method signatures and docstrings: - def update_team(self, team, request, trusted): Update 'checked', 'harmful', 'check_user', 'check_date' fields of the changeset and return a 20...
603496dce834bf3ecf28cc949da619b837e2873c
<|skeleton|> class MappingTeamTrustingAPIView: def update_team(self, team, request, trusted): """Update 'checked', 'harmful', 'check_user', 'check_date' fields of the changeset and return a 200 response""" <|body_0|> def set_trusted(self, request, pk): """Set a Mapping Team as trusted....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MappingTeamTrustingAPIView: def update_team(self, team, request, trusted): """Update 'checked', 'harmful', 'check_user', 'check_date' fields of the changeset and return a 200 response""" team.trusted = trusted team.save(update_fields=['trusted']) return Response({'detail': 'Map...
the_stack_v2_python_sparse
Backend/osmchadjango/users/views.py
habi/srz-edi
train
1
4109b0a3748f7d5d98c91fd5f9cadfed173c5270
[ "self.BATT_SIZE = 50\nself.FULL_CHAR = '+'\nself.EMPTY_CHAR = '.'\nself.empty = empty\nself.full = full\nself.charge = None", "if self.charge is None:\n return None\nreturn saturate(self.charge, self.empty, self.full, 0, 100)", "level = self.get_level()\nif level is None:\n return 'Awaiting data...'\nasse...
<|body_start_0|> self.BATT_SIZE = 50 self.FULL_CHAR = '+' self.EMPTY_CHAR = '.' self.empty = empty self.full = full self.charge = None <|end_body_0|> <|body_start_1|> if self.charge is None: return None return saturate(self.charge, self.empty,...
Represents a battery and defines its analog port and charge limits (eg, full, empty).
Battery
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Battery: """Represents a battery and defines its analog port and charge limits (eg, full, empty).""" def __init__(self, empty=120, full=150): """Constructor. @param empty: the raw signal value that indicates empty battery @param full: the raw signal value that indicates full battery"...
stack_v2_sparse_classes_36k_train_010389
5,209
no_license
[ { "docstring": "Constructor. @param empty: the raw signal value that indicates empty battery @param full: the raw signal value that indicates full battery", "name": "__init__", "signature": "def __init__(self, empty=120, full=150)" }, { "docstring": "@return: the current charge of the battery as...
3
null
Implement the Python class `Battery` described below. Class description: Represents a battery and defines its analog port and charge limits (eg, full, empty). Method signatures and docstrings: - def __init__(self, empty=120, full=150): Constructor. @param empty: the raw signal value that indicates empty battery @para...
Implement the Python class `Battery` described below. Class description: Represents a battery and defines its analog port and charge limits (eg, full, empty). Method signatures and docstrings: - def __init__(self, empty=120, full=150): Constructor. @param empty: the raw signal value that indicates empty battery @para...
52bacd9f58524090e0ab421a47714629249ca273
<|skeleton|> class Battery: """Represents a battery and defines its analog port and charge limits (eg, full, empty).""" def __init__(self, empty=120, full=150): """Constructor. @param empty: the raw signal value that indicates empty battery @param full: the raw signal value that indicates full battery"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Battery: """Represents a battery and defines its analog port and charge limits (eg, full, empty).""" def __init__(self, empty=120, full=150): """Constructor. @param empty: the raw signal value that indicates empty battery @param full: the raw signal value that indicates full battery""" se...
the_stack_v2_python_sparse
src/09-10/ubc-tbird-ros-pkg/sb_util/scripts/battery_monitor.py
jpearkes/snowbots
train
0
3e9af28a4872dd2a0eb5fafb9a1795c385c75977
[ "if not matrix:\n self.dp = None\n return\nm = len(matrix)\nn = len(matrix[0])\ndp = self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\nfor x in range(1, m + 1):\n for y in range(1, n + 1):\n dp[x][y] = dp[x - 1][y] + dp[x][y - 1] - dp[x - 1][y - 1] + matrix[x - 1][y - 1]", "if not self....
<|body_start_0|> if not matrix: self.dp = None return m = len(matrix) n = len(matrix[0]) dp = self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for x in range(1, m + 1): for y in range(1, n + 1): dp[x][y] = dp[x - 1][y...
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_36k_train_010390
1,287
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
stack_v2_sparse_classes_30k_train_001395
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)...
a041962eeab9192799ad7f74b4bbd3e4f74933d0
<|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_36k
data/stack_v2_sparse_classes_30k
class NumMatrix: def __init__(self, matrix): """initialize your data structure here. :type matrix: List[List[int]]""" if not matrix: self.dp = None return m = len(matrix) n = len(matrix[0]) dp = self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1...
the_stack_v2_python_sparse
codes/304. Range Sum Query 2D - Immutable.py
zcgu/leetcode
train
1
daf7ce02d1a3d3a275d7e2a771f708388619e0df
[ "self.log.info('login from Weibo Sina')\ncode = context.get('code')\nredirect_uri = context.get('redirect_uri')\nif not code or not redirect_uri:\n return None\naccess_token = self.get_token(code, redirect_uri)\nuser_info = self.get_user_info(access_token['access_token'], access_token['uid'])\nemail_list = []\nn...
<|body_start_0|> self.log.info('login from Weibo Sina') code = context.get('code') redirect_uri = context.get('redirect_uri') if not code or not redirect_uri: return None access_token = self.get_token(code, redirect_uri) user_info = self.get_user_info(access_t...
Sign in with weibo :Example: from client.user.login import WeiboLogin WeiboLogin() .. notes::
WeiboLogin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeiboLogin: """Sign in with weibo :Example: from client.user.login import WeiboLogin WeiboLogin() .. notes::""" def login(self, context): """weibo Login :type context: Context :param context: :rtype: dict :return: token and instance of user""" <|body_0|> def get_token(se...
stack_v2_sparse_classes_36k_train_010391
17,886
permissive
[ { "docstring": "weibo Login :type context: Context :param context: :rtype: dict :return: token and instance of user", "name": "login", "signature": "def login(self, context)" }, { "docstring": "Get weibo access token :type code: str :param code: :type redirect_uri: str :param redirect_uri: :rtyp...
4
stack_v2_sparse_classes_30k_train_016664
Implement the Python class `WeiboLogin` described below. Class description: Sign in with weibo :Example: from client.user.login import WeiboLogin WeiboLogin() .. notes:: Method signatures and docstrings: - def login(self, context): weibo Login :type context: Context :param context: :rtype: dict :return: token and ins...
Implement the Python class `WeiboLogin` described below. Class description: Sign in with weibo :Example: from client.user.login import WeiboLogin WeiboLogin() .. notes:: Method signatures and docstrings: - def login(self, context): weibo Login :type context: Context :param context: :rtype: dict :return: token and ins...
945c4fd2755f5b0dea11e54eb649eeb37ec93d01
<|skeleton|> class WeiboLogin: """Sign in with weibo :Example: from client.user.login import WeiboLogin WeiboLogin() .. notes::""" def login(self, context): """weibo Login :type context: Context :param context: :rtype: dict :return: token and instance of user""" <|body_0|> def get_token(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WeiboLogin: """Sign in with weibo :Example: from client.user.login import WeiboLogin WeiboLogin() .. notes::""" def login(self, context): """weibo Login :type context: Context :param context: :rtype: dict :return: token and instance of user""" self.log.info('login from Weibo Sina') ...
the_stack_v2_python_sparse
open-hackathon-server/src/hackathon/user/oauth_login.py
kaiyuanshe/open-hackathon
train
46
4c8a321d05ea10be2837e0358786c29c5a538a36
[ "try:\n response, status = (DistributionCodeService.find_all(), HTTPStatus.OK)\nexcept BusinessException as exception:\n return exception.response()\nreturn (jsonify(response), status)", "request_json = request.get_json()\nvalid_format, errors = schema_utils.validate(request_json, 'distribution_code')\nif n...
<|body_start_0|> try: response, status = (DistributionCodeService.find_all(), HTTPStatus.OK) except BusinessException as exception: return exception.response() return (jsonify(response), status) <|end_body_0|> <|body_start_1|> request_json = request.get_json() ...
Endpoint resource to get and post distribution.
Distributions
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Distributions: """Endpoint resource to get and post distribution.""" def get(): """Return all distributions.""" <|body_0|> def post(): """Create a new distribution from the payload.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: ...
stack_v2_sparse_classes_36k_train_010392
5,455
permissive
[ { "docstring": "Return all distributions.", "name": "get", "signature": "def get()" }, { "docstring": "Create a new distribution from the payload.", "name": "post", "signature": "def post()" } ]
2
null
Implement the Python class `Distributions` described below. Class description: Endpoint resource to get and post distribution. Method signatures and docstrings: - def get(): Return all distributions. - def post(): Create a new distribution from the payload.
Implement the Python class `Distributions` described below. Class description: Endpoint resource to get and post distribution. Method signatures and docstrings: - def get(): Return all distributions. - def post(): Create a new distribution from the payload. <|skeleton|> class Distributions: """Endpoint resource ...
0d71d37b0e08d11f6b6d9f59a4b202dfabc98fc1
<|skeleton|> class Distributions: """Endpoint resource to get and post distribution.""" def get(): """Return all distributions.""" <|body_0|> def post(): """Create a new distribution from the payload.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Distributions: """Endpoint resource to get and post distribution.""" def get(): """Return all distributions.""" try: response, status = (DistributionCodeService.find_all(), HTTPStatus.OK) except BusinessException as exception: return exception.response() ...
the_stack_v2_python_sparse
pay-api/src/pay_api/resources/distributions.py
bcgov/sbc-pay
train
6
c7dcb9f944b98b04eb1d0c37294b000a1c32da57
[ "for order in self:\n unit = ['', 'Satu', 'Dua', 'Tiga', 'Empat', 'Lima', 'Enam', 'Tujuh', 'Delapan', 'Sembilan', 'Sepuluh', 'Sebelas']\n result = ' '\n total_terbilang = self.total_terbilang\n n = int(amount_total)\n if n >= 0 and n <= 11:\n result = result + unit[n]\n elif n < 20:\n ...
<|body_start_0|> for order in self: unit = ['', 'Satu', 'Dua', 'Tiga', 'Empat', 'Lima', 'Enam', 'Tujuh', 'Delapan', 'Sembilan', 'Sepuluh', 'Sebelas'] result = ' ' total_terbilang = self.total_terbilang n = int(amount_total) if n >= 0 and n <= 11: ...
inherit sale.order
SaleOrder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SaleOrder: """inherit sale.order""" def total_terbilang(self, amount_total): """function total terbilang""" <|body_0|> def write(self, vals): """extend function write to add warning if payment term customer is different with sale order""" <|body_1|> <|en...
stack_v2_sparse_classes_36k_train_010393
5,118
no_license
[ { "docstring": "function total terbilang", "name": "total_terbilang", "signature": "def total_terbilang(self, amount_total)" }, { "docstring": "extend function write to add warning if payment term customer is different with sale order", "name": "write", "signature": "def write(self, vals...
2
stack_v2_sparse_classes_30k_train_001351
Implement the Python class `SaleOrder` described below. Class description: inherit sale.order Method signatures and docstrings: - def total_terbilang(self, amount_total): function total terbilang - def write(self, vals): extend function write to add warning if payment term customer is different with sale order
Implement the Python class `SaleOrder` described below. Class description: inherit sale.order Method signatures and docstrings: - def total_terbilang(self, amount_total): function total terbilang - def write(self, vals): extend function write to add warning if payment term customer is different with sale order <|ske...
976928395f3b600275f6ab53445605fe1167c6ba
<|skeleton|> class SaleOrder: """inherit sale.order""" def total_terbilang(self, amount_total): """function total terbilang""" <|body_0|> def write(self, vals): """extend function write to add warning if payment term customer is different with sale order""" <|body_1|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SaleOrder: """inherit sale.order""" def total_terbilang(self, amount_total): """function total terbilang""" for order in self: unit = ['', 'Satu', 'Dua', 'Tiga', 'Empat', 'Lima', 'Enam', 'Tujuh', 'Delapan', 'Sembilan', 'Sepuluh', 'Sebelas'] result = ' ' ...
the_stack_v2_python_sparse
pn_sale/models/sale.py
detian08/pennyu
train
0
eee63d2f4aba5b57e557cab0ffb52af98669bc6a
[ "if len(s) != len(t):\n return False\ncache = {}\nresult = [0] * len(s)\ncounter = 0\nfor i in range(len(s)):\n if s[i] not in cache:\n cache[s[i]] = counter\n counter += 1\n result[i] = cache[s[i]]\ncache = {}\ncounter = 0\nfor j in range(len(t)):\n if t[j] not in cache:\n cache[t[...
<|body_start_0|> if len(s) != len(t): return False cache = {} result = [0] * len(s) counter = 0 for i in range(len(s)): if s[i] not in cache: cache[s[i]] = counter counter += 1 result[i] = cache[s[i]] cac...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_0|> def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(s) != len(t): ...
stack_v2_sparse_classes_36k_train_010394
1,393
no_license
[ { "docstring": ":type s: str :type t: str :rtype: bool", "name": "isIsomorphic", "signature": "def isIsomorphic(self, s, t)" }, { "docstring": ":type s: str :type t: str :rtype: bool", "name": "isIsomorphic", "signature": "def isIsomorphic(self, s, t)" } ]
2
stack_v2_sparse_classes_30k_train_007301
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool - def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool - def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool <|skeleton|> class Solution: def...
d75876ae96bcd85c67bbfbf91bbc0f0bc773e97c
<|skeleton|> class Solution: def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_0|> def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" if len(s) != len(t): return False cache = {} result = [0] * len(s) counter = 0 for i in range(len(s)): if s[i] not in cache: cache[s[i]] ...
the_stack_v2_python_sparse
205. Isomorphic Strings.py
samir-0711/Leetcode-Python
train
0
e43b33087eb346d2f5693e879f6276d4787e9565
[ "N = len(nums)\nA = nums\nleft = [0] * (N + 1)\nfor i in range(1, N + 1):\n left[i] = left[i - 1] + A[i - 1]\n\ndef check(val, numsplit):\n i, v, c = (0, 0, 0)\n while i < N + 1:\n c += 1\n j = bisect.bisect_right(left, v + val, i)\n if i == j:\n return False\n i = j\...
<|body_start_0|> N = len(nums) A = nums left = [0] * (N + 1) for i in range(1, N + 1): left[i] = left[i - 1] + A[i - 1] def check(val, numsplit): i, v, c = (0, 0, 0) while i < N + 1: c += 1 j = bisect.bisect_rig...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def splitArray(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" <|body_0|> def splitArray2(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> N = len(nums) ...
stack_v2_sparse_classes_36k_train_010395
6,363
permissive
[ { "docstring": ":type nums: List[int] :type m: int :rtype: int", "name": "splitArray", "signature": "def splitArray(self, nums, m)" }, { "docstring": ":type nums: List[int] :type m: int :rtype: int", "name": "splitArray2", "signature": "def splitArray2(self, nums, m)" } ]
2
stack_v2_sparse_classes_30k_train_012918
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int - def splitArray2(self, nums, m): :type nums: List[int] :type m: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int - def splitArray2(self, nums, m): :type nums: List[int] :type m: int :rtype: int <|skeleton|> class...
2830c7e2ada8dfd3dcdda7c06846116d4f944a27
<|skeleton|> class Solution: def splitArray(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" <|body_0|> def splitArray2(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def splitArray(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" N = len(nums) A = nums left = [0] * (N + 1) for i in range(1, N + 1): left[i] = left[i - 1] + A[i - 1] def check(val, numsplit): i, v, c = (0, ...
the_stack_v2_python_sparse
leetcode/hard/Split_Array_Largest_Sum.py
shhuan/algorithms
train
0
9b4d7eefb4fa087cea6fd65d4e67d15cc1000620
[ "super().__init__(problem, name=name, **kwargs)\nif distance_weight_type not in ['squared', 'uniform']:\n raise ValueError(\"Parameter distance_weight_type must be either 'squared' or 'uniform'.\")\nself._distance_weight_mode = distance_weight_type\nif max_distance < 0.0:\n raise ValueError(\"Parameter max_di...
<|body_start_0|> super().__init__(problem, name=name, **kwargs) if distance_weight_type not in ['squared', 'uniform']: raise ValueError("Parameter distance_weight_type must be either 'squared' or 'uniform'.") self._distance_weight_mode = distance_weight_type if max_distance <...
Implementation of the KNN-Averaging algorithm[^quatic21]. [^quatic21]: Klikovits, S., Arcaini, P. (2021). KNN-Averaging for Noisy Multi-objective Optimisation. In: Paiva, A.C.R., Cavalli, A.R., Ventura Martins, P., Pérez-Castillo, R. (eds) Quality of Information and Communications Technology. QUATIC 2021. Communication...
KNNAvg
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KNNAvg: """Implementation of the KNN-Averaging algorithm[^quatic21]. [^quatic21]: Klikovits, S., Arcaini, P. (2021). KNN-Averaging for Noisy Multi-objective Optimisation. In: Paiva, A.C.R., Cavalli, A.R., Ventura Martins, P., Pérez-Castillo, R. (eds) Quality of Information and Communications Tech...
stack_v2_sparse_classes_36k_train_010396
4,578
permissive
[ { "docstring": "Constructor. Args: problem (`nmoo.wrapped_problem.WrappedProblem`): Noisy problem. For memory optimization reasons, this should be a `nmoo.wrapped_problem.WrappedProblem` as opposed to a pymoo `Problem`. distance_weight_type (str): Either `squared` or `uniform` (the default). max_distance (float...
2
stack_v2_sparse_classes_30k_train_001585
Implement the Python class `KNNAvg` described below. Class description: Implementation of the KNN-Averaging algorithm[^quatic21]. [^quatic21]: Klikovits, S., Arcaini, P. (2021). KNN-Averaging for Noisy Multi-objective Optimisation. In: Paiva, A.C.R., Cavalli, A.R., Ventura Martins, P., Pérez-Castillo, R. (eds) Quality...
Implement the Python class `KNNAvg` described below. Class description: Implementation of the KNN-Averaging algorithm[^quatic21]. [^quatic21]: Klikovits, S., Arcaini, P. (2021). KNN-Averaging for Noisy Multi-objective Optimisation. In: Paiva, A.C.R., Cavalli, A.R., Ventura Martins, P., Pérez-Castillo, R. (eds) Quality...
bba29af38230040272a90e08571623a3a3a8e96f
<|skeleton|> class KNNAvg: """Implementation of the KNN-Averaging algorithm[^quatic21]. [^quatic21]: Klikovits, S., Arcaini, P. (2021). KNN-Averaging for Noisy Multi-objective Optimisation. In: Paiva, A.C.R., Cavalli, A.R., Ventura Martins, P., Pérez-Castillo, R. (eds) Quality of Information and Communications Tech...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KNNAvg: """Implementation of the KNN-Averaging algorithm[^quatic21]. [^quatic21]: Klikovits, S., Arcaini, P. (2021). KNN-Averaging for Noisy Multi-objective Optimisation. In: Paiva, A.C.R., Cavalli, A.R., Ventura Martins, P., Pérez-Castillo, R. (eds) Quality of Information and Communications Technology. QUATI...
the_stack_v2_python_sparse
nmoo/denoisers/knnavg.py
altaris/noisy-moo
train
3
ad62afe12fac08f8f15d5e451be6d1e5124370b7
[ "Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')\nself.lexicon = Lexicon()", "if tnode.gram_verbmod != 'cdn' or re.search('(aby|kdyby)', tnode.formeme):\n return\naconj = tnode.get_deref_attr('wild/conjugated')\nif aconj.afun == 'AuxV':\n...
<|body_start_0|> Block.__init__(self, scenario, args) if self.language is None: raise LoadingException('Language must be defined!') self.lexicon = Lexicon() <|end_body_0|> <|body_start_1|> if tnode.gram_verbmod != 'cdn' or re.search('(aby|kdyby)', tnode.formeme): ...
Add conditional auxiliary 'by'/'bych'. Arguments: language: the language of the target tree selector: the selector of the target tree
AddAuxVerbConditional
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddAuxVerbConditional: """Add conditional auxiliary 'by'/'bych'. Arguments: language: the language of the target tree selector: the selector of the target tree""" def __init__(self, scenario, args): """Constructor, just checking the argument values""" <|body_0|> def proc...
stack_v2_sparse_classes_36k_train_010397
1,984
permissive
[ { "docstring": "Constructor, just checking the argument values", "name": "__init__", "signature": "def __init__(self, scenario, args)" }, { "docstring": "Add conditional auxiliary to a node, where appropriate.", "name": "process_tnode", "signature": "def process_tnode(self, tnode)" } ]
2
null
Implement the Python class `AddAuxVerbConditional` described below. Class description: Add conditional auxiliary 'by'/'bych'. Arguments: language: the language of the target tree selector: the selector of the target tree Method signatures and docstrings: - def __init__(self, scenario, args): Constructor, just checkin...
Implement the Python class `AddAuxVerbConditional` described below. Class description: Add conditional auxiliary 'by'/'bych'. Arguments: language: the language of the target tree selector: the selector of the target tree Method signatures and docstrings: - def __init__(self, scenario, args): Constructor, just checkin...
73af644ec35c8a1cd0c37cd478c2afc1db717e0b
<|skeleton|> class AddAuxVerbConditional: """Add conditional auxiliary 'by'/'bych'. Arguments: language: the language of the target tree selector: the selector of the target tree""" def __init__(self, scenario, args): """Constructor, just checking the argument values""" <|body_0|> def proc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddAuxVerbConditional: """Add conditional auxiliary 'by'/'bych'. Arguments: language: the language of the target tree selector: the selector of the target tree""" def __init__(self, scenario, args): """Constructor, just checking the argument values""" Block.__init__(self, scenario, args) ...
the_stack_v2_python_sparse
alex/components/nlg/tectotpl/block/t2a/cs/addauxverbconditional.py
oplatek/alex
train
0
766e00129a6f048fc25fecdfc367691636b504dd
[ "n = len(nums)\nif n < 3:\n return []\nnums = sorted(nums)\nres = []\nfor i in range(n):\n l = i + 1\n h = n - 1\n if i - 1 >= 0 and nums[i] == nums[i - 1]:\n continue\n while l < h:\n cur = nums[l] + nums[h]\n if cur > -nums[i]:\n while h - 1 > l and nums[h] == nums[h...
<|body_start_0|> n = len(nums) if n < 3: return [] nums = sorted(nums) res = [] for i in range(n): l = i + 1 h = n - 1 if i - 1 >= 0 and nums[i] == nums[i - 1]: continue while l < h: cur =...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def threeSum(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = le...
stack_v2_sparse_classes_36k_train_010398
1,862
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "threeSum", "signature": "def threeSum(self, nums)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "threeSumClosest", "signature": "def threeSumClosest(self, nums, target)" } ]
2
stack_v2_sparse_classes_30k_train_016454
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]] - def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]] - def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int <|skeleton...
176cc1db3291843fb068f06d0180766dd8c3122c
<|skeleton|> class Solution: def threeSum(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def threeSum(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" n = len(nums) if n < 3: return [] nums = sorted(nums) res = [] for i in range(n): l = i + 1 h = n - 1 if i - 1 >= 0 and nums[i...
the_stack_v2_python_sparse
2019/array/three_sum_15.py
yehongyu/acode
train
0
a682f11cdbc20570ac456c882a4631f6fb46f7c3
[ "from collections import Counter\ncount = Counter(nums)\nfor key, val in count.items():\n if val == 1:\n return key", "s = set()\nfor num in nums:\n if num in s:\n s.discard(num)\n else:\n s.add(num)\nreturn s.pop()", "x = nums[0]\nfor num in nums[1:]:\n x ^= num\nreturn x" ]
<|body_start_0|> from collections import Counter count = Counter(nums) for key, val in count.items(): if val == 1: return key <|end_body_0|> <|body_start_1|> s = set() for num in nums: if num in s: s.discard(num) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" ...
stack_v2_sparse_classes_36k_train_010399
1,161
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "singleNumber", "signature": "def singleNumber(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "singleNumber", "signature": "def singleNumber(self, nums)" }, { "docstring": ":type nums: List[i...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber(self, nums): :type nums: List[int] :rtype: int - def singleNumber(self, nums): :type nums: List[int] :rtype: int - def singleNumber(self, nums): :type nums: List...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber(self, nums): :type nums: List[int] :rtype: int - def singleNumber(self, nums): :type nums: List[int] :rtype: int - def singleNumber(self, nums): :type nums: List...
b18786c06417a2781662805a7e0e984ee7fa5240
<|skeleton|> class Solution: def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" from collections import Counter count = Counter(nums) for key, val in count.items(): if val == 1: return key def singleNumber(self, nums): """:type nums: Lis...
the_stack_v2_python_sparse
data_structures/136. Single Number.py
YuriiPaziuk/leetcode
train
0