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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8ab60cab5996438781164dd5f8f4a1203bca3811 | [
"base_dir = os.path.dirname(os.path.abspath(__file__))\nbase_app.__init__(self, base_dir)\napp_expose(base_app.index)\napp_expose(base_app.input_select)\napp_expose(base_app.input_upload)\napp_expose(base_app.params)",
"tgz_file = self.dl_dir + 'two-photos-psf-estim.tar.gz'\nprog_file = self.bin_dir + 'two_photos... | <|body_start_0|>
base_dir = os.path.dirname(os.path.abspath(__file__))
base_app.__init__(self, base_dir)
app_expose(base_app.index)
app_expose(base_app.input_select)
app_expose(base_app.input_upload)
app_expose(base_app.params)
<|end_body_0|>
<|body_start_1|>
tgz... | demo app | app | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class app:
"""demo app"""
def __init__(self):
"""app setup"""
<|body_0|>
def build(self):
"""program build/update"""
<|body_1|>
def wait(self, s='3', k='13', t='0'):
"""params handling and run redirection"""
<|body_2|>
def run(self):
... | stack_v2_sparse_classes_36k_train_018600 | 7,483 | no_license | [
{
"docstring": "app setup",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "program build/update",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "params handling and run redirection",
"name": "wait",
"signature": "def wait(self... | 6 | null | Implement the Python class `app` described below.
Class description:
demo app
Method signatures and docstrings:
- def __init__(self): app setup
- def build(self): program build/update
- def wait(self, s='3', k='13', t='0'): params handling and run redirection
- def run(self): algo execution
- def run_algo(self, s, k,... | Implement the Python class `app` described below.
Class description:
demo app
Method signatures and docstrings:
- def __init__(self): app setup
- def build(self): program build/update
- def wait(self, s='3', k='13', t='0'): params handling and run redirection
- def run(self): algo execution
- def run_algo(self, s, k,... | 1ee176ad8578be2f0d48d2ffcacf7a0073e1b630 | <|skeleton|>
class app:
"""demo app"""
def __init__(self):
"""app setup"""
<|body_0|>
def build(self):
"""program build/update"""
<|body_1|>
def wait(self, s='3', k='13', t='0'):
"""params handling and run redirection"""
<|body_2|>
def run(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class app:
"""demo app"""
def __init__(self):
"""app setup"""
base_dir = os.path.dirname(os.path.abspath(__file__))
base_app.__init__(self, base_dir)
app_expose(base_app.index)
app_expose(base_app.input_select)
app_expose(base_app.input_upload)
app_expose... | the_stack_v2_python_sparse | app/77/app.py | nilx/ipol_demo | train | 1 |
5aa5225f0d68724246493fa5f05651c8a3e5581f | [
"while True:\n print({'message': 'Querying SIS Course API', 'page_number': page_number, 'page_size': page_size})\n try:\n yield from self._request(page_number, page_size)\n page_number += 1\n except:\n break",
"url = self.url % (page_number, page_size)\ntry:\n response = requests.... | <|body_start_0|>
while True:
print({'message': 'Querying SIS Course API', 'page_number': page_number, 'page_size': page_size})
try:
yield from self._request(page_number, page_size)
page_number += 1
except:
break
<|end_body_0|>
... | Resource for SIS Course API. | SISCourseResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SISCourseResource:
"""Resource for SIS Course API."""
def get(self, page_number=0, page_size=100):
"""Return a generator of response chunks starting at start_index."""
<|body_0|>
def _request(self, page_number, page_size):
"""Fetch SIS Course API response. (SIS k... | stack_v2_sparse_classes_36k_train_018601 | 1,964 | permissive | [
{
"docstring": "Return a generator of response chunks starting at start_index.",
"name": "get",
"signature": "def get(self, page_number=0, page_size=100)"
},
{
"docstring": "Fetch SIS Course API response. (SIS killed the v2 API 46) Old Docs: https://api-central.berkeley.edu/api/46/interactive-do... | 2 | stack_v2_sparse_classes_30k_train_006732 | Implement the Python class `SISCourseResource` described below.
Class description:
Resource for SIS Course API.
Method signatures and docstrings:
- def get(self, page_number=0, page_size=100): Return a generator of response chunks starting at start_index.
- def _request(self, page_number, page_size): Fetch SIS Course... | Implement the Python class `SISCourseResource` described below.
Class description:
Resource for SIS Course API.
Method signatures and docstrings:
- def get(self, page_number=0, page_size=100): Return a generator of response chunks starting at start_index.
- def _request(self, page_number, page_size): Fetch SIS Course... | 34578dc14c8e5c2cfb28f8d6710e791cdd773d59 | <|skeleton|>
class SISCourseResource:
"""Resource for SIS Course API."""
def get(self, page_number=0, page_size=100):
"""Return a generator of response chunks starting at start_index."""
<|body_0|>
def _request(self, page_number, page_size):
"""Fetch SIS Course API response. (SIS k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SISCourseResource:
"""Resource for SIS Course API."""
def get(self, page_number=0, page_size=100):
"""Return a generator of response chunks starting at start_index."""
while True:
print({'message': 'Querying SIS Course API', 'page_number': page_number, 'page_size': page_size})... | the_stack_v2_python_sparse | backend/catalog/resource/sis_course.py | AviFS/berkeleytime | train | 0 |
959e8db9f9e18ed7ea1a8b6c823cce644608fd77 | [
"if probability_fn is None:\n probability_fn = tf.nn.softmax\nif dtype is None:\n dtype = tf.float32\nwrapped_probability_fn = lambda score, _: probability_fn(score)\nsuper(MyAttention, self).__init__(query_layer=None, memory_layer=None, memory=memory, probability_fn=wrapped_probability_fn, memory_sequence_le... | <|body_start_0|>
if probability_fn is None:
probability_fn = tf.nn.softmax
if dtype is None:
dtype = tf.float32
wrapped_probability_fn = lambda score, _: probability_fn(score)
super(MyAttention, self).__init__(query_layer=None, memory_layer=None, memory=memory, pr... | Based on wrapper of tf.contrib.seq2seq.LuongAttention. Allows to use a customized mask. | MyAttention | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyAttention:
"""Based on wrapper of tf.contrib.seq2seq.LuongAttention. Allows to use a customized mask."""
def __init__(self, num_units, memory, memory_sequence_length=None, mask=None, scale=False, probability_fn=None, score_mask_value=None, dtype=None, name='MyAttention'):
"""Constr... | stack_v2_sparse_classes_36k_train_018602 | 20,121 | permissive | [
{
"docstring": "Construct the AttentionMechanism mechanism. Args: num_units: The depth of the attention mechanism. memory: The memory to query; usually the output of an RNN encoder. This tensor should be shaped `[batch_size, max_time, ...]`. memory_sequence_length: (optional) Sequence lengths for the batch entr... | 2 | null | Implement the Python class `MyAttention` described below.
Class description:
Based on wrapper of tf.contrib.seq2seq.LuongAttention. Allows to use a customized mask.
Method signatures and docstrings:
- def __init__(self, num_units, memory, memory_sequence_length=None, mask=None, scale=False, probability_fn=None, score... | Implement the Python class `MyAttention` described below.
Class description:
Based on wrapper of tf.contrib.seq2seq.LuongAttention. Allows to use a customized mask.
Method signatures and docstrings:
- def __init__(self, num_units, memory, memory_sequence_length=None, mask=None, scale=False, probability_fn=None, score... | ac9447064195e06de48cc91ff642f7fffa28ffe8 | <|skeleton|>
class MyAttention:
"""Based on wrapper of tf.contrib.seq2seq.LuongAttention. Allows to use a customized mask."""
def __init__(self, num_units, memory, memory_sequence_length=None, mask=None, scale=False, probability_fn=None, score_mask_value=None, dtype=None, name='MyAttention'):
"""Constr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyAttention:
"""Based on wrapper of tf.contrib.seq2seq.LuongAttention. Allows to use a customized mask."""
def __init__(self, num_units, memory, memory_sequence_length=None, mask=None, scale=False, probability_fn=None, score_mask_value=None, dtype=None, name='MyAttention'):
"""Construct the Atten... | the_stack_v2_python_sparse | language/labs/exemplar_decoding/models/attention.py | google-research/language | train | 1,567 |
3d8964c3943257226a2f79a7f9f5f536af386542 | [
"self.__zenhub = zenhub\nself.__client = client\nself.__log = getLogger(self)",
"self.__log.debug('Pinging zenhub')\ntry:\n response = (yield self.__zenhub.callRemote('ping'))\n self.__log.debug('Pinged zenhub: %s', response)\nexcept Exception as ex:\n self.__log.error('Ping failed: %s', ex)\n self._... | <|body_start_0|>
self.__zenhub = zenhub
self.__client = client
self.__log = getLogger(self)
<|end_body_0|>
<|body_start_1|>
self.__log.debug('Pinging zenhub')
try:
response = (yield self.__zenhub.callRemote('ping'))
self.__log.debug('Pinged zenhub: %s', ... | Simple task to ping ZenHub. PingZenHub's real purpose is to allow the ZenHubWorker to detect when ZenHub is no longer responsive (for whatever reason). | PingZenHub | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PingZenHub:
"""Simple task to ping ZenHub. PingZenHub's real purpose is to allow the ZenHubWorker to detect when ZenHub is no longer responsive (for whatever reason)."""
def __init__(self, zenhub, client):
"""Initialize a PingZenHub instance."""
<|body_0|>
def __call__(s... | stack_v2_sparse_classes_36k_train_018603 | 22,180 | no_license | [
{
"docstring": "Initialize a PingZenHub instance.",
"name": "__init__",
"signature": "def __init__(self, zenhub, client)"
},
{
"docstring": "Ping zenhub. If the ping fails, causes the connection to ZenHub to reset.",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012710 | Implement the Python class `PingZenHub` described below.
Class description:
Simple task to ping ZenHub. PingZenHub's real purpose is to allow the ZenHubWorker to detect when ZenHub is no longer responsive (for whatever reason).
Method signatures and docstrings:
- def __init__(self, zenhub, client): Initialize a PingZ... | Implement the Python class `PingZenHub` described below.
Class description:
Simple task to ping ZenHub. PingZenHub's real purpose is to allow the ZenHubWorker to detect when ZenHub is no longer responsive (for whatever reason).
Method signatures and docstrings:
- def __init__(self, zenhub, client): Initialize a PingZ... | 1ea508c3d2b51742bc3b448c445cd0a3dba9e798 | <|skeleton|>
class PingZenHub:
"""Simple task to ping ZenHub. PingZenHub's real purpose is to allow the ZenHubWorker to detect when ZenHub is no longer responsive (for whatever reason)."""
def __init__(self, zenhub, client):
"""Initialize a PingZenHub instance."""
<|body_0|>
def __call__(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PingZenHub:
"""Simple task to ping ZenHub. PingZenHub's real purpose is to allow the ZenHubWorker to detect when ZenHub is no longer responsive (for whatever reason)."""
def __init__(self, zenhub, client):
"""Initialize a PingZenHub instance."""
self.__zenhub = zenhub
self.__clien... | the_stack_v2_python_sparse | Products/ZenHub/zenhubworker.py | zenoss/zenoss-prodbin | train | 27 |
68bd69d310560ef1feedd7636012910247075cc1 | [
"self.sess = tf.Session(graph=tf.Graph(), target=session_target)\ngraph_def = tf.saved_model.load(self.sess, tags=[tf.saved_model.tag_constants.SERVING], export_dir=model_dir_path)\nsignature = graph_def.signature_def[tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\nself.input_tensor_name = si... | <|body_start_0|>
self.sess = tf.Session(graph=tf.Graph(), target=session_target)
graph_def = tf.saved_model.load(self.sess, tags=[tf.saved_model.tag_constants.SERVING], export_dir=model_dir_path)
signature = graph_def.signature_def[tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF... | WikiHop for inference / prediction using SavedModel. | WikiHopInference | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiHopInference:
"""WikiHop for inference / prediction using SavedModel."""
def __init__(self, model_dir_path: Text, session_target: Text):
"""Loads the WikiHop from an exported `tf.SavedModel`. Args: model_dir_path: Path to the exported directory of the model. session_target: The s... | stack_v2_sparse_classes_36k_train_018604 | 10,061 | permissive | [
{
"docstring": "Loads the WikiHop from an exported `tf.SavedModel`. Args: model_dir_path: Path to the exported directory of the model. session_target: The session target.",
"name": "__init__",
"signature": "def __init__(self, model_dir_path: Text, session_target: Text)"
},
{
"docstring": "Retrie... | 2 | null | Implement the Python class `WikiHopInference` described below.
Class description:
WikiHop for inference / prediction using SavedModel.
Method signatures and docstrings:
- def __init__(self, model_dir_path: Text, session_target: Text): Loads the WikiHop from an exported `tf.SavedModel`. Args: model_dir_path: Path to t... | Implement the Python class `WikiHopInference` described below.
Class description:
WikiHop for inference / prediction using SavedModel.
Method signatures and docstrings:
- def __init__(self, model_dir_path: Text, session_target: Text): Loads the WikiHop from an exported `tf.SavedModel`. Args: model_dir_path: Path to t... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class WikiHopInference:
"""WikiHop for inference / prediction using SavedModel."""
def __init__(self, model_dir_path: Text, session_target: Text):
"""Loads the WikiHop from an exported `tf.SavedModel`. Args: model_dir_path: Path to the exported directory of the model. session_target: The s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WikiHopInference:
"""WikiHop for inference / prediction using SavedModel."""
def __init__(self, model_dir_path: Text, session_target: Text):
"""Loads the WikiHop from an exported `tf.SavedModel`. Args: model_dir_path: Path to the exported directory of the model. session_target: The session target... | the_stack_v2_python_sparse | etcmodel/models/wikihop/wikihop_eval.py | Jimmy-INL/google-research | train | 1 |
e54d32824889b45846a506ca7cdecd0cffd5913e | [
"signature = 'hfppnetwork.partner.httpservices.PartnerHTTPServices.data_request'\nmethod_enter(signature, {'self': self})\nrequest_body = cherrypy.request.body.read().decode('utf-8')\nlogging.debug('%s:%s', 'request_body', request_body)\nif len(request_body) == 0:\n raise PartnerClientError('request body can not... | <|body_start_0|>
signature = 'hfppnetwork.partner.httpservices.PartnerHTTPServices.data_request'
method_enter(signature, {'self': self})
request_body = cherrypy.request.body.read().decode('utf-8')
logging.debug('%s:%s', 'request_body', request_body)
if len(request_body) == 0:
... | PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes use of thread local data for HTTP request/response data, hence the use of CherryPy modul... | PartnerHTTPServices | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartnerHTTPServices:
"""PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes use of thread local data for HTTP request... | stack_v2_sparse_classes_36k_train_018605 | 20,090 | permissive | [
{
"docstring": "This method is used to serve data request partner client http service. @param self the PartnerHTTPServices itself, it should be PartnerHTTPServices @throws PartnerClientError throws if request body is empty @throws Exception any error should be raised to caller. CherryPy will handle the error an... | 2 | stack_v2_sparse_classes_30k_train_016352 | Implement the Python class `PartnerHTTPServices` described below.
Class description:
PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes us... | Implement the Python class `PartnerHTTPServices` described below.
Class description:
PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes us... | 4facd935920e77239c25323ca7e233cb899ba9f5 | <|skeleton|>
class PartnerHTTPServices:
"""PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes use of thread local data for HTTP request... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartnerHTTPServices:
"""PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes use of thread local data for HTTP request/response dat... | the_stack_v2_python_sparse | partnerclient/hfppnetwork/partner/httpservices.py | joshuaeveleth/CoECI-CMS-Healthcare-Fraud-Prevention | train | 0 |
1f31566db5fe6c590859d9c67843667597c808cf | [
"request = pecan.request\ncontext = request.environ['context']\nreturn DesignateAdapter.render('API_v2', self.central_api.get_recordset(context, zone_id, recordset_id), request=request)",
"request = pecan.request\ncontext = request.environ['context']\nrecordsets = common.retrieve_matched_rrsets(context, self, zon... | <|body_start_0|>
request = pecan.request
context = request.environ['context']
return DesignateAdapter.render('API_v2', self.central_api.get_recordset(context, zone_id, recordset_id), request=request)
<|end_body_0|>
<|body_start_1|>
request = pecan.request
context = request.envir... | RecordSetsController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordSetsController:
def get_one(self, zone_id, recordset_id):
"""Get RecordSet"""
<|body_0|>
def get_all(self, zone_id, **params):
"""List RecordSets"""
<|body_1|>
def post_all(self, zone_id):
"""Create RecordSet"""
<|body_2|>
def ... | stack_v2_sparse_classes_36k_train_018606 | 5,877 | permissive | [
{
"docstring": "Get RecordSet",
"name": "get_one",
"signature": "def get_one(self, zone_id, recordset_id)"
},
{
"docstring": "List RecordSets",
"name": "get_all",
"signature": "def get_all(self, zone_id, **params)"
},
{
"docstring": "Create RecordSet",
"name": "post_all",
... | 5 | null | Implement the Python class `RecordSetsController` described below.
Class description:
Implement the RecordSetsController class.
Method signatures and docstrings:
- def get_one(self, zone_id, recordset_id): Get RecordSet
- def get_all(self, zone_id, **params): List RecordSets
- def post_all(self, zone_id): Create Reco... | Implement the Python class `RecordSetsController` described below.
Class description:
Implement the RecordSetsController class.
Method signatures and docstrings:
- def get_one(self, zone_id, recordset_id): Get RecordSet
- def get_all(self, zone_id, **params): List RecordSets
- def post_all(self, zone_id): Create Reco... | 360433b38b449d1c53ab1357fdb0c4608c09efa5 | <|skeleton|>
class RecordSetsController:
def get_one(self, zone_id, recordset_id):
"""Get RecordSet"""
<|body_0|>
def get_all(self, zone_id, **params):
"""List RecordSets"""
<|body_1|>
def post_all(self, zone_id):
"""Create RecordSet"""
<|body_2|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecordSetsController:
def get_one(self, zone_id, recordset_id):
"""Get RecordSet"""
request = pecan.request
context = request.environ['context']
return DesignateAdapter.render('API_v2', self.central_api.get_recordset(context, zone_id, recordset_id), request=request)
def ge... | the_stack_v2_python_sparse | designate/api/v2/controllers/zones/recordsets.py | openstack/designate | train | 156 | |
d37a3b546b684a37a6d66cae793aac786b13a612 | [
"super(NeuralFingerprint, self).__init__()\nself.num_layers = len(conv_layer_sizes)\nself.output_size = output_size\nself.batch_type = type_map['batch']\nself.ntype = type_map['node']\nself.etype = type_map['edge']\nself.degree_list = degree_list\nself.conv_layers = nn.ModuleList()\nself.out_layers = nn.ModuleList(... | <|body_start_0|>
super(NeuralFingerprint, self).__init__()
self.num_layers = len(conv_layer_sizes)
self.output_size = output_size
self.batch_type = type_map['batch']
self.ntype = type_map['node']
self.etype = type_map['edge']
self.degree_list = degree_list
... | NeuralFingerprint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralFingerprint:
def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True):
"""Args: node_size (int): dimension of node representations edge_size (int): dimension of edge representations conv_layer_sizes (list of int): the leng... | stack_v2_sparse_classes_36k_train_018607 | 6,911 | no_license | [
{
"docstring": "Args: node_size (int): dimension of node representations edge_size (int): dimension of edge representations conv_layer_sizes (list of int): the lengths of the output vectors of convolutional layers output_size (int): length of the finger print vector type_map (dict string:string): type of the ba... | 2 | stack_v2_sparse_classes_30k_train_010553 | Implement the Python class `NeuralFingerprint` described below.
Class description:
Implement the NeuralFingerprint class.
Method signatures and docstrings:
- def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True): Args: node_size (int): dimension of node r... | Implement the Python class `NeuralFingerprint` described below.
Class description:
Implement the NeuralFingerprint class.
Method signatures and docstrings:
- def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True): Args: node_size (int): dimension of node r... | e034dc60d156a577c16fa4217c00202030f1b6dc | <|skeleton|>
class NeuralFingerprint:
def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True):
"""Args: node_size (int): dimension of node representations edge_size (int): dimension of edge representations conv_layer_sizes (list of int): the leng... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeuralFingerprint:
def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True):
"""Args: node_size (int): dimension of node representations edge_size (int): dimension of edge representations conv_layer_sizes (list of int): the lengths of the out... | the_stack_v2_python_sparse | DrugTargetInteraction/methods/protein_ensemble/fingerprint/models.py | hansaimlim/thesis-works | train | 1 | |
576b110a7c0a6749527dedaa4d248256eaadffe2 | [
"res = []\nfor one in lists:\n while one:\n res.append(one.val)\n one = one.next\nres.sort()\nreturn res",
"if not lists:\n return None\nres = lists[0]\nfor one in lists[1:]:\n res = self.mergeTwoLists(res, one)\nreturn res",
"node = ListNode(0)\nres = node\nwhile l1 and l2:\n if l1.va... | <|body_start_0|>
res = []
for one in lists:
while one:
res.append(one.val)
one = one.next
res.sort()
return res
<|end_body_0|>
<|body_start_1|>
if not lists:
return None
res = lists[0]
for one in lists[1:]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists1(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListN... | stack_v2_sparse_classes_36k_train_018608 | 1,286 | no_license | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists1",
"signature": "def mergeKLists1(self, lists)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_011216 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists1(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists1(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self,... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists1(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListN... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
res = []
for one in lists:
while one:
res.append(one.val)
one = one.next
res.sort()
return res
def mergeKLists1(self, lists):
... | the_stack_v2_python_sparse | leetcode/023合并K个排序链表.py | ShawDa/Coding | train | 0 | |
3687c175c5dbc53b54e8ef982b25e27a4d52edfa | [
"self.log_type = log_type\nself.directory = directory\nself.extension = extension\nself.__check_exists()",
"self.__check_exists()\nfile_path = self.__get_path()\ntime_str = str(datetime.datetime.now()) + ' : ' if write_time else ''\nwith open(file_path, 'a') as log:\n log.write('%s%s\\n' % (time_str, text))",
... | <|body_start_0|>
self.log_type = log_type
self.directory = directory
self.extension = extension
self.__check_exists()
<|end_body_0|>
<|body_start_1|>
self.__check_exists()
file_path = self.__get_path()
time_str = str(datetime.datetime.now()) + ' : ' if write_time... | AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs | Logs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logs:
"""AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs"""
def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> None:
"""AUTHORS: -------- :author: Alix Leroy :author: Samu... | stack_v2_sparse_classes_36k_train_018609 | 4,235 | permissive | [
{
"docstring": "AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ Initialize a log object. PARAMETERS: ----------- :param log_type: str: The log type (notification, history :param directory: str :param extension: str: RETURN: ------- :return: None",
"name": "__init__",... | 6 | stack_v2_sparse_classes_30k_train_017168 | Implement the Python class `Logs` described below.
Class description:
AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs
Method signatures and docstrings:
- def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> ... | Implement the Python class `Logs` described below.
Class description:
AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs
Method signatures and docstrings:
- def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> ... | 3f9a1314ccfc1428d50de6a49a040aab4cb56dad | <|skeleton|>
class Logs:
"""AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs"""
def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> None:
"""AUTHORS: -------- :author: Alix Leroy :author: Samu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Logs:
"""AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs"""
def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> None:
"""AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake D... | the_stack_v2_python_sparse | deeplodocus/utils/logs.py | Deeplodocus/deeplodocus | train | 2 |
e96945fababa77d483574550ab01855da9d66d98 | [
"user = get_authenticated_user()\nif not user.stripe_id:\n raise NotFound()\nreturn {'fields': get_invoice_fields(user)[0]}",
"user = get_authenticated_user()\nif not user.stripe_id:\n raise NotFound()\ndata = request.get_json()\ncreated_field = create_billing_invoice_field(user, data['title'], data['value'... | <|body_start_0|>
user = get_authenticated_user()
if not user.stripe_id:
raise NotFound()
return {'fields': get_invoice_fields(user)[0]}
<|end_body_0|>
<|body_start_1|>
user = get_authenticated_user()
if not user.stripe_id:
raise NotFound()
data = ... | Resource for listing and creating a user's custom invoice fields. | UserInvoiceFieldList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserInvoiceFieldList:
"""Resource for listing and creating a user's custom invoice fields."""
def get(self):
"""List the invoice fields for the current user."""
<|body_0|>
def post(self):
"""Creates a new invoice field."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_018610 | 33,890 | permissive | [
{
"docstring": "List the invoice fields for the current user.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creates a new invoice field.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014308 | Implement the Python class `UserInvoiceFieldList` described below.
Class description:
Resource for listing and creating a user's custom invoice fields.
Method signatures and docstrings:
- def get(self): List the invoice fields for the current user.
- def post(self): Creates a new invoice field. | Implement the Python class `UserInvoiceFieldList` described below.
Class description:
Resource for listing and creating a user's custom invoice fields.
Method signatures and docstrings:
- def get(self): List the invoice fields for the current user.
- def post(self): Creates a new invoice field.
<|skeleton|>
class Us... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class UserInvoiceFieldList:
"""Resource for listing and creating a user's custom invoice fields."""
def get(self):
"""List the invoice fields for the current user."""
<|body_0|>
def post(self):
"""Creates a new invoice field."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserInvoiceFieldList:
"""Resource for listing and creating a user's custom invoice fields."""
def get(self):
"""List the invoice fields for the current user."""
user = get_authenticated_user()
if not user.stripe_id:
raise NotFound()
return {'fields': get_invoic... | the_stack_v2_python_sparse | endpoints/api/billing.py | quay/quay | train | 2,363 |
18f2b72990cd56490e71b21967ff35fbabf71892 | [
"LossyExchange.__init__(self, subswarm_keys, crashed_list, msg_publisher, lock, own_id)\nself._short_list_parser = bytes.UShortListParser()\nself._short_list_parser.source_id = self._own_id\nself._value_pair_parser = bytes.IdShortValuePairParser()\nself._value_pair_parser.source_id = self._own_id",
"if msg.id == ... | <|body_start_0|>
LossyExchange.__init__(self, subswarm_keys, crashed_list, msg_publisher, lock, own_id)
self._short_list_parser = bytes.UShortListParser()
self._short_list_parser.source_id = self._own_id
self._value_pair_parser = bytes.IdShortValuePairParser()
self._value_pair_pa... | Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort unsigned shorts to facilitate inter-UAV messaging. All values other than the one for th... | EagerConsensusSort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EagerConsensusSort:
"""Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort unsigned shorts to facilitate inter-UAV m... | stack_v2_sparse_classes_36k_train_018611 | 11,562 | no_license | [
{
"docstring": "Initializer for the class sets up class variables used for sorting @param subswarm_keys: Set object containing active subswarm IDs @param crashed_list: Set object containing IDs of possible crashed UAVs @param msg_publisher: ROS publisher to the swarm_data_msg topic @param lock: reentrant lock t... | 4 | stack_v2_sparse_classes_30k_train_016106 | Implement the Python class `EagerConsensusSort` described below.
Class description:
Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort un... | Implement the Python class `EagerConsensusSort` described below.
Class description:
Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort un... | ec2b5c43abed51a37c17bde0c000c2dfbfcbb9b1 | <|skeleton|>
class EagerConsensusSort:
"""Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort unsigned shorts to facilitate inter-UAV m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EagerConsensusSort:
"""Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort unsigned shorts to facilitate inter-UAV messaging. All... | the_stack_v2_python_sparse | ap_lib/src/ap_lib/distributed_algorithms.py | jaymonty/autonomy-payload | train | 0 |
5b3fd235aa5fee6d8d90209c226fdf6f45968453 | [
"super().__init__(db, version, uuid)\nself.columns = get_table_columns(self.conn, self.asset_table)\nself.table_name = self.asset_table",
"conn, cursor = self.db.get_db_connection()\ncursor.execute(f'SELECT * FROM {self.asset_table} WHERE ZUUID = ?', (self.uuid,))\nreturn result if (result := cursor.fetchall()) e... | <|body_start_0|>
super().__init__(db, version, uuid)
self.columns = get_table_columns(self.conn, self.asset_table)
self.table_name = self.asset_table
<|end_body_0|>
<|body_start_1|>
conn, cursor = self.db.get_db_connection()
cursor.execute(f'SELECT * FROM {self.asset_table} WHER... | ZASSET table. | AssetTable | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssetTable:
"""ZASSET table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
<|body_0|>
def rows(self) -> list[Any]:
"""Return row2 for this photo from the ZASSET table."""
<|body_1|>
def _get_colu... | stack_v2_sparse_classes_36k_train_018612 | 8,828 | permissive | [
{
"docstring": "Create a Table object.",
"name": "__init__",
"signature": "def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str)"
},
{
"docstring": "Return row2 for this photo from the ZASSET table.",
"name": "rows",
"signature": "def rows(self) -> list[Any]"
},
{
"... | 3 | null | Implement the Python class `AssetTable` described below.
Class description:
ZASSET table.
Method signatures and docstrings:
- def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str): Create a Table object.
- def rows(self) -> list[Any]: Return row2 for this photo from the ZASSET table.
- def _get_column(s... | Implement the Python class `AssetTable` described below.
Class description:
ZASSET table.
Method signatures and docstrings:
- def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str): Create a Table object.
- def rows(self) -> list[Any]: Return row2 for this photo from the ZASSET table.
- def _get_column(s... | 2cb5a4d18a27be6ccf68f5f35abd39418d238016 | <|skeleton|>
class AssetTable:
"""ZASSET table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
<|body_0|>
def rows(self) -> list[Any]:
"""Return row2 for this photo from the ZASSET table."""
<|body_1|>
def _get_colu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssetTable:
"""ZASSET table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
super().__init__(db, version, uuid)
self.columns = get_table_columns(self.conn, self.asset_table)
self.table_name = self.asset_table
def r... | the_stack_v2_python_sparse | osxphotos/phototables.py | RhetTbull/osxphotos | train | 1,287 |
7f54cd6f7b2da8328832b83200b7fedb1e3d9e51 | [
"if parameter_name == 'subkeys':\n if isinstance(parameter_value, dict):\n return parameter_value\nreturn super(VGUIMenu, self)._prepare_parameter(parameter_name, parameter_value)",
"if parameter_name == 'subkeys' and isinstance(field_value, dict):\n for key, value in field_value.items():\n su... | <|body_start_0|>
if parameter_name == 'subkeys':
if isinstance(parameter_value, dict):
return parameter_value
return super(VGUIMenu, self)._prepare_parameter(parameter_name, parameter_value)
<|end_body_0|>
<|body_start_1|>
if parameter_name == 'subkeys' and isinstanc... | Class used to send a VGUIMenu message. | VGUIMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGUIMenu:
"""Class used to send a VGUIMenu message."""
def _prepare_parameter(self, parameter_name, parameter_value):
"""Prepare the given parameter value."""
<|body_0|>
def _write_field_value(self, parameter_name, usermsg, field_type, field_name, field_value, field_inde... | stack_v2_sparse_classes_36k_train_018613 | 2,005 | no_license | [
{
"docstring": "Prepare the given parameter value.",
"name": "_prepare_parameter",
"signature": "def _prepare_parameter(self, parameter_name, parameter_value)"
},
{
"docstring": "Write the given field value to the given message.",
"name": "_write_field_value",
"signature": "def _write_fi... | 2 | stack_v2_sparse_classes_30k_train_008903 | Implement the Python class `VGUIMenu` described below.
Class description:
Class used to send a VGUIMenu message.
Method signatures and docstrings:
- def _prepare_parameter(self, parameter_name, parameter_value): Prepare the given parameter value.
- def _write_field_value(self, parameter_name, usermsg, field_type, fie... | Implement the Python class `VGUIMenu` described below.
Class description:
Class used to send a VGUIMenu message.
Method signatures and docstrings:
- def _prepare_parameter(self, parameter_name, parameter_value): Prepare the given parameter value.
- def _write_field_value(self, parameter_name, usermsg, field_type, fie... | 2d6fc3d0e0534e6eb2046fb11e40706ca42a2a59 | <|skeleton|>
class VGUIMenu:
"""Class used to send a VGUIMenu message."""
def _prepare_parameter(self, parameter_name, parameter_value):
"""Prepare the given parameter value."""
<|body_0|>
def _write_field_value(self, parameter_name, usermsg, field_type, field_name, field_value, field_inde... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGUIMenu:
"""Class used to send a VGUIMenu message."""
def _prepare_parameter(self, parameter_name, parameter_value):
"""Prepare the given parameter value."""
if parameter_name == 'subkeys':
if isinstance(parameter_value, dict):
return parameter_value
r... | the_stack_v2_python_sparse | addons/source-python/packages/source-python/messages/types/vguimenu.py | Doldol/Source.Python | train | 0 |
f33491474921323d9182841d1ea478dc790a3a00 | [
"if path_to_monitor is not None:\n self.path_to_monitor = path_to_monitor\nelse:\n self.path_to_monitor = os.getcwd()\nself.disk_io = disk_io\nself.log = logging.getLogger('avalanche')",
"usage = psutil.disk_usage(self.path_to_monitor)\ntotal, used, free, percent = (bytes2human(usage.total), bytes2human(usa... | <|body_start_0|>
if path_to_monitor is not None:
self.path_to_monitor = path_to_monitor
else:
self.path_to_monitor = os.getcwd()
self.disk_io = disk_io
self.log = logging.getLogger('avalanche')
<|end_body_0|>
<|body_start_1|>
usage = psutil.disk_usage(sel... | DiskUsage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiskUsage:
def __init__(self, path_to_monitor=None, disk_io=False):
""":param path_to_monitor (string): a valid path to folder. If None, the current working directory is used. :param disk_io: True to enable monitoring of I/O operations on disk. WARNING: Reports are system-wide, grouping ... | stack_v2_sparse_classes_36k_train_018614 | 14,483 | permissive | [
{
"docstring": ":param path_to_monitor (string): a valid path to folder. If None, the current working directory is used. :param disk_io: True to enable monitoring of I/O operations on disk. WARNING: Reports are system-wide, grouping all disks.",
"name": "__init__",
"signature": "def __init__(self, path_... | 2 | stack_v2_sparse_classes_30k_train_017736 | Implement the Python class `DiskUsage` described below.
Class description:
Implement the DiskUsage class.
Method signatures and docstrings:
- def __init__(self, path_to_monitor=None, disk_io=False): :param path_to_monitor (string): a valid path to folder. If None, the current working directory is used. :param disk_io... | Implement the Python class `DiskUsage` described below.
Class description:
Implement the DiskUsage class.
Method signatures and docstrings:
- def __init__(self, path_to_monitor=None, disk_io=False): :param path_to_monitor (string): a valid path to folder. If None, the current working directory is used. :param disk_io... | 897bde82471ef92ded396aa31d91ec19826d4ce2 | <|skeleton|>
class DiskUsage:
def __init__(self, path_to_monitor=None, disk_io=False):
""":param path_to_monitor (string): a valid path to folder. If None, the current working directory is used. :param disk_io: True to enable monitoring of I/O operations on disk. WARNING: Reports are system-wide, grouping ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiskUsage:
def __init__(self, path_to_monitor=None, disk_io=False):
""":param path_to_monitor (string): a valid path to folder. If None, the current working directory is used. :param disk_io: True to enable monitoring of I/O operations on disk. WARNING: Reports are system-wide, grouping all disks."""
... | the_stack_v2_python_sparse | CL_metrics_CLAIR.py | samuilstoychev/research_project | train | 0 | |
c59b80f05a80003b48a38c784a4cb54c004238d9 | [
"_check_img_dtype(image)\nself.image = image\nself.boxes = boxes\nself.sem_seg = sem_seg",
"self.image = tfm.apply_image(self.image)\nif self.boxes is not None:\n self.boxes = tfm.apply_box(self.boxes)\nif self.sem_seg is not None:\n self.sem_seg = tfm.apply_segmentation(self.sem_seg)"
] | <|body_start_0|>
_check_img_dtype(image)
self.image = image
self.boxes = boxes
self.sem_seg = sem_seg
<|end_body_0|>
<|body_start_1|>
self.image = tfm.apply_image(self.image)
if self.boxes is not None:
self.boxes = tfm.apply_box(self.boxes)
if self.se... | A standard implementation of :class:`AugInput` for the majority of use cases. This class provides the following standard attributes that are common to use by Augmentation (augmentation policies). These are chosen because most :class:`Augmentation` won't need anything more to define a augmentation policy. After applying... | StandardAugInput | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardAugInput:
"""A standard implementation of :class:`AugInput` for the majority of use cases. This class provides the following standard attributes that are common to use by Augmentation (augmentation policies). These are chosen because most :class:`Augmentation` won't need anything more to ... | stack_v2_sparse_classes_36k_train_018615 | 14,222 | permissive | [
{
"docstring": "Args: image: (H,W) or (H,W,C) ndarray of type uint8 in range [0, 255], or floating point in range [0, 1] or [0, 255]. boxes: (N,4) ndarray of float32. It represents the instance bounding boxes of N instances. Each is in XYXY format in unit of absolute coordinates. sem_seg: (H,W) ndarray of type ... | 2 | null | Implement the Python class `StandardAugInput` described below.
Class description:
A standard implementation of :class:`AugInput` for the majority of use cases. This class provides the following standard attributes that are common to use by Augmentation (augmentation policies). These are chosen because most :class:`Aug... | Implement the Python class `StandardAugInput` described below.
Class description:
A standard implementation of :class:`AugInput` for the majority of use cases. This class provides the following standard attributes that are common to use by Augmentation (augmentation policies). These are chosen because most :class:`Aug... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class StandardAugInput:
"""A standard implementation of :class:`AugInput` for the majority of use cases. This class provides the following standard attributes that are common to use by Augmentation (augmentation policies). These are chosen because most :class:`Augmentation` won't need anything more to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StandardAugInput:
"""A standard implementation of :class:`AugInput` for the majority of use cases. This class provides the following standard attributes that are common to use by Augmentation (augmentation policies). These are chosen because most :class:`Augmentation` won't need anything more to define a augm... | the_stack_v2_python_sparse | PyTorch/contrib/cv/detection/RetinaNet/detectron2/data/transforms/augmentation.py | Ascend/ModelZoo-PyTorch | train | 23 |
f83486b74ed8644294ad3dc5eb95d1d58ce3b81c | [
"request = REQUEST\nif request is None:\n request = getattr(self, 'REQUEST', None)\nif request and 'REQUEST_METHOD' in request:\n if request.maybe_webdav_client:\n method = request['REQUEST_METHOD']\n if method in ('PUT',):\n return ReplaceableWrapper(NullResource(self, 'index_html'))... | <|body_start_0|>
request = REQUEST
if request is None:
request = getattr(self, 'REQUEST', None)
if request and 'REQUEST_METHOD' in request:
if request.maybe_webdav_client:
method = request['REQUEST_METHOD']
if method in ('PUT',):
... | Base class for orderable folderish AT Content Types | ATCTOrderedFolder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ATCTOrderedFolder:
"""Base class for orderable folderish AT Content Types"""
def index_html(self, REQUEST=None, RESPONSE=None):
"""Special case index_html"""
<|body_0|>
def manage_renameObject(self, id, new_id, REQUEST=None):
"""Rename a particular sub-object wit... | stack_v2_sparse_classes_36k_train_018616 | 20,087 | no_license | [
{
"docstring": "Special case index_html",
"name": "index_html",
"signature": "def index_html(self, REQUEST=None, RESPONSE=None)"
},
{
"docstring": "Rename a particular sub-object without changing its position.",
"name": "manage_renameObject",
"signature": "def manage_renameObject(self, i... | 2 | null | Implement the Python class `ATCTOrderedFolder` described below.
Class description:
Base class for orderable folderish AT Content Types
Method signatures and docstrings:
- def index_html(self, REQUEST=None, RESPONSE=None): Special case index_html
- def manage_renameObject(self, id, new_id, REQUEST=None): Rename a part... | Implement the Python class `ATCTOrderedFolder` described below.
Class description:
Base class for orderable folderish AT Content Types
Method signatures and docstrings:
- def index_html(self, REQUEST=None, RESPONSE=None): Special case index_html
- def manage_renameObject(self, id, new_id, REQUEST=None): Rename a part... | 9c59626073daa97162c2b1d33a39a043f386cd8e | <|skeleton|>
class ATCTOrderedFolder:
"""Base class for orderable folderish AT Content Types"""
def index_html(self, REQUEST=None, RESPONSE=None):
"""Special case index_html"""
<|body_0|>
def manage_renameObject(self, id, new_id, REQUEST=None):
"""Rename a particular sub-object wit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ATCTOrderedFolder:
"""Base class for orderable folderish AT Content Types"""
def index_html(self, REQUEST=None, RESPONSE=None):
"""Special case index_html"""
request = REQUEST
if request is None:
request = getattr(self, 'REQUEST', None)
if request and 'REQUEST_... | the_stack_v2_python_sparse | Products/ATContentTypes/content/base.py | plone/Products.ATContentTypes | train | 1 |
0843bf18c14e2fc49b139f7786f80294759ebb62 | [
"self.wallx = 400\nself.pineUp = pygame.image.load('pipelineUp.png')\nself.pineDown = pygame.image.load('pipelineDown.png')",
"self.wallx -= 5\nif self.wallx < -80:\n global score\n score += 1\n self.wallx = 400"
] | <|body_start_0|>
self.wallx = 400
self.pineUp = pygame.image.load('pipelineUp.png')
self.pineDown = pygame.image.load('pipelineDown.png')
<|end_body_0|>
<|body_start_1|>
self.wallx -= 5
if self.wallx < -80:
global score
score += 1
self.wallx =... | 定义一个管道类 | Pipline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pipline:
"""定义一个管道类"""
def __init__(self):
"""定义初始化方法"""
<|body_0|>
def updatePipline(self):
"""水平移动"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.wallx = 400
self.pineUp = pygame.image.load('pipelineUp.png')
self.pineDown... | stack_v2_sparse_classes_36k_train_018617 | 5,166 | no_license | [
{
"docstring": "定义初始化方法",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "水平移动",
"name": "updatePipline",
"signature": "def updatePipline(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012598 | Implement the Python class `Pipline` described below.
Class description:
定义一个管道类
Method signatures and docstrings:
- def __init__(self): 定义初始化方法
- def updatePipline(self): 水平移动 | Implement the Python class `Pipline` described below.
Class description:
定义一个管道类
Method signatures and docstrings:
- def __init__(self): 定义初始化方法
- def updatePipline(self): 水平移动
<|skeleton|>
class Pipline:
"""定义一个管道类"""
def __init__(self):
"""定义初始化方法"""
<|body_0|>
def updatePipline(self)... | 5700235cb75a2a0497e47d9c65e043613409fb20 | <|skeleton|>
class Pipline:
"""定义一个管道类"""
def __init__(self):
"""定义初始化方法"""
<|body_0|>
def updatePipline(self):
"""水平移动"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pipline:
"""定义一个管道类"""
def __init__(self):
"""定义初始化方法"""
self.wallx = 400
self.pineUp = pygame.image.load('pipelineUp.png')
self.pineDown = pygame.image.load('pipelineDown.png')
def updatePipline(self):
"""水平移动"""
self.wallx -= 5
if self.wallx ... | the_stack_v2_python_sparse | Python/FlyBird/FlappyBird.py | Wangminjun0207/practice | train | 1 |
69d2c99dbbfbcbfd6f43af97a17e14d4b077d92c | [
"queryset = Materia.objects.filter(anio__carrera__institucion=institucion)\nanio = self.request.query_params.get('anio', None)\nif anio is not None:\n queryset = queryset.filter(anio=anio)\nreturn queryset",
"materia = get_object_or_404(Materia, pk=pk)\nif materia.anio.carrera.institucion != request.user.insti... | <|body_start_0|>
queryset = Materia.objects.filter(anio__carrera__institucion=institucion)
anio = self.request.query_params.get('anio', None)
if anio is not None:
queryset = queryset.filter(anio=anio)
return queryset
<|end_body_0|>
<|body_start_1|>
materia = get_obje... | MateriaViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MateriaViewSet:
def get_queryset(self, institucion):
"""Restringir la busqueda de Materias por un año"""
<|body_0|>
def get(self, request, pk=None):
"""Ver una materia"""
<|body_1|>
def list(self, request, anio_id=None):
"""Listar las materias de... | stack_v2_sparse_classes_36k_train_018618 | 5,481 | no_license | [
{
"docstring": "Restringir la busqueda de Materias por un año",
"name": "get_queryset",
"signature": "def get_queryset(self, institucion)"
},
{
"docstring": "Ver una materia",
"name": "get",
"signature": "def get(self, request, pk=None)"
},
{
"docstring": "Listar las materias de ... | 6 | null | Implement the Python class `MateriaViewSet` described below.
Class description:
Implement the MateriaViewSet class.
Method signatures and docstrings:
- def get_queryset(self, institucion): Restringir la busqueda de Materias por un año
- def get(self, request, pk=None): Ver una materia
- def list(self, request, anio_i... | Implement the Python class `MateriaViewSet` described below.
Class description:
Implement the MateriaViewSet class.
Method signatures and docstrings:
- def get_queryset(self, institucion): Restringir la busqueda de Materias por un año
- def get(self, request, pk=None): Ver una materia
- def list(self, request, anio_i... | be80b2d15f84a8eeba898e753efee348de6ce998 | <|skeleton|>
class MateriaViewSet:
def get_queryset(self, institucion):
"""Restringir la busqueda de Materias por un año"""
<|body_0|>
def get(self, request, pk=None):
"""Ver una materia"""
<|body_1|>
def list(self, request, anio_id=None):
"""Listar las materias de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MateriaViewSet:
def get_queryset(self, institucion):
"""Restringir la busqueda de Materias por un año"""
queryset = Materia.objects.filter(anio__carrera__institucion=institucion)
anio = self.request.query_params.get('anio', None)
if anio is not None:
queryset = quer... | the_stack_v2_python_sparse | curricula/api/views/materia.py | Clear-Education/ontrack_backend | train | 1 | |
8cb832d67cd7ad8670fe37e2f739ca146f4dba92 | [
"self._logger = logger\nself._resource_config = resource_config\nself._service_provider = service_provider",
"deployment = self._service_provider.deployment_service.get_deployment_by_name(deployed_app.namespace, deployed_app.kubernetes_name)\ndeployment.spec.replicas = deployed_app.replicas\ndeployment.spec.templ... | <|body_start_0|>
self._logger = logger
self._resource_config = resource_config
self._service_provider = service_provider
<|end_body_0|>
<|body_start_1|>
deployment = self._service_provider.deployment_service.get_deployment_by_name(deployed_app.namespace, deployed_app.kubernetes_name)
... | PowerFlow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PowerFlow:
def __init__(self, logger, resource_config, service_provider):
"""Init. :param logging.Logger logger: :param cloudshell.cp.kubernetes.resource_config. KubernetesResourceConfig resource_config: :param cloudshell.cp.kubernetes.services.service_provider. ServiceProvider service_p... | stack_v2_sparse_classes_36k_train_018619 | 3,016 | no_license | [
{
"docstring": "Init. :param logging.Logger logger: :param cloudshell.cp.kubernetes.resource_config. KubernetesResourceConfig resource_config: :param cloudshell.cp.kubernetes.services.service_provider. ServiceProvider service_provider:",
"name": "__init__",
"signature": "def __init__(self, logger, resou... | 3 | stack_v2_sparse_classes_30k_train_019621 | Implement the Python class `PowerFlow` described below.
Class description:
Implement the PowerFlow class.
Method signatures and docstrings:
- def __init__(self, logger, resource_config, service_provider): Init. :param logging.Logger logger: :param cloudshell.cp.kubernetes.resource_config. KubernetesResourceConfig res... | Implement the Python class `PowerFlow` described below.
Class description:
Implement the PowerFlow class.
Method signatures and docstrings:
- def __init__(self, logger, resource_config, service_provider): Init. :param logging.Logger logger: :param cloudshell.cp.kubernetes.resource_config. KubernetesResourceConfig res... | 236920b17fdd4d6b80f67c9d8ca9fb27f3763252 | <|skeleton|>
class PowerFlow:
def __init__(self, logger, resource_config, service_provider):
"""Init. :param logging.Logger logger: :param cloudshell.cp.kubernetes.resource_config. KubernetesResourceConfig resource_config: :param cloudshell.cp.kubernetes.services.service_provider. ServiceProvider service_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PowerFlow:
def __init__(self, logger, resource_config, service_provider):
"""Init. :param logging.Logger logger: :param cloudshell.cp.kubernetes.resource_config. KubernetesResourceConfig resource_config: :param cloudshell.cp.kubernetes.services.service_provider. ServiceProvider service_provider:"""
... | the_stack_v2_python_sparse | cloudshell/cp/kubernetes/flows/power.py | QualiSystems/cloudshell-cp-kubernetes | train | 0 | |
4f2dd940e3ceb1f33111c45e38779be1ab6a3187 | [
"self.lambtha = float(lambtha)\nif data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n self.... | <|body_start_0|>
self.lambtha = float(lambtha)
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
else:
if type(data) is not list:
raise TypeError('data must be a list')
if len(data) < 2:
... | Class Exponential | Exponential | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Class Exponential"""
def __init__(self, data=None, lambtha=1.0):
"""Settings for class Expontential"""
<|body_0|>
def pdf(self, x):
"""Method pmf for Exponential dist"""
<|body_1|>
def cdf(self, x):
"""Method CDF for Exponenti... | stack_v2_sparse_classes_36k_train_018620 | 1,041 | permissive | [
{
"docstring": "Settings for class Expontential",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Method pmf for Exponential dist",
"name": "pdf",
"signature": "def pdf(self, x)"
},
{
"docstring": "Method CDF for Exponential Dist",... | 3 | null | Implement the Python class `Exponential` described below.
Class description:
Class Exponential
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Settings for class Expontential
- def pdf(self, x): Method pmf for Exponential dist
- def cdf(self, x): Method CDF for Exponential Dist | Implement the Python class `Exponential` described below.
Class description:
Class Exponential
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Settings for class Expontential
- def pdf(self, x): Method pmf for Exponential dist
- def cdf(self, x): Method CDF for Exponential Dist
<|skel... | eaf23423ec0f412f103f5931d6610fdd67bcc5be | <|skeleton|>
class Exponential:
"""Class Exponential"""
def __init__(self, data=None, lambtha=1.0):
"""Settings for class Expontential"""
<|body_0|>
def pdf(self, x):
"""Method pmf for Exponential dist"""
<|body_1|>
def cdf(self, x):
"""Method CDF for Exponenti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Exponential:
"""Class Exponential"""
def __init__(self, data=None, lambtha=1.0):
"""Settings for class Expontential"""
self.lambtha = float(lambtha)
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
else:
... | the_stack_v2_python_sparse | math/0x03-probability/exponential.py | ledbagholberton/holbertonschool-machine_learning | train | 1 |
16519d217495396819a497ed9b1ae5c740ff72c7 | [
"translated_data = {}\nfor param, value in data.items():\n filterstring = cls.parse_filter_field(param)\n if filterstring:\n translated_data[filterstring] = value\nreturn translated_data",
"match = FILTER_PATTERN.search(param)\nif not match:\n return None\nfield = match.group(1).replace('.', '__')... | <|body_start_0|>
translated_data = {}
for param, value in data.items():
filterstring = cls.parse_filter_field(param)
if filterstring:
translated_data[filterstring] = value
return translated_data
<|end_body_0|>
<|body_start_1|>
match = FILTER_PATTE... | Helper functions used by the FilterSet class. Translate a query dictionary to a standard dictionary. | ParseFiltersMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParseFiltersMixin:
"""Helper functions used by the FilterSet class. Translate a query dictionary to a standard dictionary."""
def parse_filters(cls, data):
"""Retrieve a dictionary of filters from submitted data :param django_filters.filterset.FilterSetMetaclass cls: A class instance... | stack_v2_sparse_classes_36k_train_018621 | 6,183 | permissive | [
{
"docstring": "Retrieve a dictionary of filters from submitted data :param django_filters.filterset.FilterSetMetaclass cls: A class instance :param django.http.request.QueryDict data: Data coming in from an Http request :return: A dictionary of filters requested by the client :rtype: dict",
"name": "parse_... | 2 | stack_v2_sparse_classes_30k_train_021485 | Implement the Python class `ParseFiltersMixin` described below.
Class description:
Helper functions used by the FilterSet class. Translate a query dictionary to a standard dictionary.
Method signatures and docstrings:
- def parse_filters(cls, data): Retrieve a dictionary of filters from submitted data :param django_f... | Implement the Python class `ParseFiltersMixin` described below.
Class description:
Helper functions used by the FilterSet class. Translate a query dictionary to a standard dictionary.
Method signatures and docstrings:
- def parse_filters(cls, data): Retrieve a dictionary of filters from submitted data :param django_f... | fb0e4abb0d5c5daad9f6c89349dbb007f9f5752f | <|skeleton|>
class ParseFiltersMixin:
"""Helper functions used by the FilterSet class. Translate a query dictionary to a standard dictionary."""
def parse_filters(cls, data):
"""Retrieve a dictionary of filters from submitted data :param django_filters.filterset.FilterSetMetaclass cls: A class instance... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParseFiltersMixin:
"""Helper functions used by the FilterSet class. Translate a query dictionary to a standard dictionary."""
def parse_filters(cls, data):
"""Retrieve a dictionary of filters from submitted data :param django_filters.filterset.FilterSetMetaclass cls: A class instance :param djang... | the_stack_v2_python_sparse | drf_jsonapi/filters.py | Vacasa/drf-jsonapi | train | 3 |
ec2afefa0df2c5c2da6685e1aca8f1eb845f2bb1 | [
"i, j = (len(num1) - 1, len(num2) - 1)\nres = []\nt = 0\nwhile i >= 0 and j >= 0:\n k = int(num1[i]) + int(num2[j]) + t\n if k >= 10:\n k -= 10\n t = 1\n else:\n t = 0\n res.append(str(k))\n i -= 1\n j -= 1\nl = -1\nif i >= 0:\n num = num1\n l = i\nelif j >= 0:\n num ... | <|body_start_0|>
i, j = (len(num1) - 1, len(num2) - 1)
res = []
t = 0
while i >= 0 and j >= 0:
k = int(num1[i]) + int(num2[j]) + t
if k >= 10:
k -= 10
t = 1
else:
t = 0
res.append(str(k))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addStrings(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def addStrings2(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_1|>
def addStrings2(self, num1, num2):
""":type n... | stack_v2_sparse_classes_36k_train_018622 | 3,238 | no_license | [
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "addStrings",
"signature": "def addStrings(self, num1, num2)"
},
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "addStrings2",
"signature": "def addStrings2(self, num1, num2)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_002686 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addStrings(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def addStrings2(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def addStrings2(s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addStrings(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def addStrings2(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def addStrings2(s... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def addStrings(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def addStrings2(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_1|>
def addStrings2(self, num1, num2):
""":type n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addStrings(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
i, j = (len(num1) - 1, len(num2) - 1)
res = []
t = 0
while i >= 0 and j >= 0:
k = int(num1[i]) + int(num2[j]) + t
if k >= 10:
k -= 10
... | the_stack_v2_python_sparse | A/AddStrings.py | bssrdf/pyleet | train | 2 | |
c6c55bce48300b6bf426c66e22874ef62a233694 | [
"super(GroverBondVocabPredictor, self).__init__()\nself.linear = nn.Linear(in_features, vocab_size)\nself.linear_rev = nn.Linear(in_features, vocab_size)\nself.logsoftmax = nn.LogSoftmax(dim=1)",
"nm_bonds = embeddings.shape[0]\nids1 = list(range(0, nm_bonds, 2))\nids2 = list(range(1, nm_bonds, 2))\nlogits = self... | <|body_start_0|>
super(GroverBondVocabPredictor, self).__init__()
self.linear = nn.Linear(in_features, vocab_size)
self.linear_rev = nn.Linear(in_features, vocab_size)
self.logsoftmax = nn.LogSoftmax(dim=1)
<|end_body_0|>
<|body_start_1|>
nm_bonds = embeddings.shape[0]
i... | Layer for learning contextual information for bonds. The layer is used in Grover architecture to learn contextual information of a bond by predicting the context of a bond from the bond embedding in a multi-class classification setting. The contextual information of a bond are encoded as strings (ex: '(DOUBLE-STEREONON... | GroverBondVocabPredictor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroverBondVocabPredictor:
"""Layer for learning contextual information for bonds. The layer is used in Grover architecture to learn contextual information of a bond by predicting the context of a bond from the bond embedding in a multi-class classification setting. The contextual information of a... | stack_v2_sparse_classes_36k_train_018623 | 38,432 | permissive | [
{
"docstring": "Initializes GroverBondVocabPredictor Parameters ---------- vocab_size: int Size of vocabulary, used for number of classes in prediction. in_features: int, default: 128 Input feature size of bond embeddings.",
"name": "__init__",
"signature": "def __init__(self, vocab_size: int, in_featur... | 2 | stack_v2_sparse_classes_30k_train_003288 | Implement the Python class `GroverBondVocabPredictor` described below.
Class description:
Layer for learning contextual information for bonds. The layer is used in Grover architecture to learn contextual information of a bond by predicting the context of a bond from the bond embedding in a multi-class classification s... | Implement the Python class `GroverBondVocabPredictor` described below.
Class description:
Layer for learning contextual information for bonds. The layer is used in Grover architecture to learn contextual information of a bond by predicting the context of a bond from the bond embedding in a multi-class classification s... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class GroverBondVocabPredictor:
"""Layer for learning contextual information for bonds. The layer is used in Grover architecture to learn contextual information of a bond by predicting the context of a bond from the bond embedding in a multi-class classification setting. The contextual information of a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroverBondVocabPredictor:
"""Layer for learning contextual information for bonds. The layer is used in Grover architecture to learn contextual information of a bond by predicting the context of a bond from the bond embedding in a multi-class classification setting. The contextual information of a bond are enc... | the_stack_v2_python_sparse | deepchem/models/torch_models/grover_layers.py | deepchem/deepchem | train | 4,876 |
87c34a5ceb0c54dde76385d13c44a47e4f08876a | [
"username = 'test@test.com'\npassword = 'toto'\nself.client.post(reverse(register), {'username': username, 'password': password})\nresponse = self.client.post(reverse(obtain_auth_token), {'username': username, 'password': password}, format='json')\nself.token = json.loads(response.content)['token']\nself.client.get... | <|body_start_0|>
username = 'test@test.com'
password = 'toto'
self.client.post(reverse(register), {'username': username, 'password': password})
response = self.client.post(reverse(obtain_auth_token), {'username': username, 'password': password}, format='json')
self.token = json.l... | Test the Django/Vue interface. | TestDjangoVueInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDjangoVueInterface:
"""Test the Django/Vue interface."""
def setUp(self):
"""Register and log user in."""
<|body_0|>
def test_default_monthly_requests_amount(self):
"""Test that default amount of monthly requests is correct."""
<|body_1|>
def tes... | stack_v2_sparse_classes_36k_train_018624 | 8,751 | no_license | [
{
"docstring": "Register and log user in.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that default amount of monthly requests is correct.",
"name": "test_default_monthly_requests_amount",
"signature": "def test_default_monthly_requests_amount(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_020553 | Implement the Python class `TestDjangoVueInterface` described below.
Class description:
Test the Django/Vue interface.
Method signatures and docstrings:
- def setUp(self): Register and log user in.
- def test_default_monthly_requests_amount(self): Test that default amount of monthly requests is correct.
- def test_de... | Implement the Python class `TestDjangoVueInterface` described below.
Class description:
Test the Django/Vue interface.
Method signatures and docstrings:
- def setUp(self): Register and log user in.
- def test_default_monthly_requests_amount(self): Test that default amount of monthly requests is correct.
- def test_de... | 9c0027b84d8dee6044ff28362e2b2b90c1759b90 | <|skeleton|>
class TestDjangoVueInterface:
"""Test the Django/Vue interface."""
def setUp(self):
"""Register and log user in."""
<|body_0|>
def test_default_monthly_requests_amount(self):
"""Test that default amount of monthly requests is correct."""
<|body_1|>
def tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDjangoVueInterface:
"""Test the Django/Vue interface."""
def setUp(self):
"""Register and log user in."""
username = 'test@test.com'
password = 'toto'
self.client.post(reverse(register), {'username': username, 'password': password})
response = self.client.post(... | the_stack_v2_python_sparse | django_project/api_core/tests.py | juliensalinas/python-django-api-reactjs-frontend-slate-documentation-various-client-libs | train | 3 |
2c0d00c2af7a6273121e53efd372ed4124ae294e | [
"try:\n doc = schemaService.get_by_id(schema_id_or_name)\nexcept SchemaNotFound:\n try:\n doc = schemaService.get_by_name(schema_id_or_name)\n except SchemaNotFound:\n return (\"Requested schema with name/id '{}' not found\".format(schema_id_or_name), 404)\nreturn (doc, 200)",
"try:\n sc... | <|body_start_0|>
try:
doc = schemaService.get_by_id(schema_id_or_name)
except SchemaNotFound:
try:
doc = schemaService.get_by_name(schema_id_or_name)
except SchemaNotFound:
return ("Requested schema with name/id '{}' not found".format(s... | GET/UPDATE/DELETE validation schemas | SchemaController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaController:
"""GET/UPDATE/DELETE validation schemas"""
def get(self, schema_id_or_name):
"""Get a validation schema by ID"""
<|body_0|>
def delete(self, schema_id_or_name):
"""Delete a validation schema from the database"""
<|body_1|>
def put(s... | stack_v2_sparse_classes_36k_train_018625 | 3,102 | permissive | [
{
"docstring": "Get a validation schema by ID",
"name": "get",
"signature": "def get(self, schema_id_or_name)"
},
{
"docstring": "Delete a validation schema from the database",
"name": "delete",
"signature": "def delete(self, schema_id_or_name)"
},
{
"docstring": "Delete a valida... | 3 | stack_v2_sparse_classes_30k_train_006992 | Implement the Python class `SchemaController` described below.
Class description:
GET/UPDATE/DELETE validation schemas
Method signatures and docstrings:
- def get(self, schema_id_or_name): Get a validation schema by ID
- def delete(self, schema_id_or_name): Delete a validation schema from the database
- def put(self,... | Implement the Python class `SchemaController` described below.
Class description:
GET/UPDATE/DELETE validation schemas
Method signatures and docstrings:
- def get(self, schema_id_or_name): Get a validation schema by ID
- def delete(self, schema_id_or_name): Delete a validation schema from the database
- def put(self,... | 4573deec9b8206179ff6e61f37b4ba1847b3dbfb | <|skeleton|>
class SchemaController:
"""GET/UPDATE/DELETE validation schemas"""
def get(self, schema_id_or_name):
"""Get a validation schema by ID"""
<|body_0|>
def delete(self, schema_id_or_name):
"""Delete a validation schema from the database"""
<|body_1|>
def put(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemaController:
"""GET/UPDATE/DELETE validation schemas"""
def get(self, schema_id_or_name):
"""Get a validation schema by ID"""
try:
doc = schemaService.get_by_id(schema_id_or_name)
except SchemaNotFound:
try:
doc = schemaService.get_by_n... | the_stack_v2_python_sparse | esdlvalidator/api/controller/schema.py | ESDLMapEditorESSIM/ESDLValidator | train | 0 |
2e09a5feca96dd3cdb3dae4a0114d5163e9c7261 | [
"memclient = memcache.Client()\ntotal = memclient.get(str(instance))\nif total is None:\n total = 0\n counters = cls.all().filter('instance_key =', instance)\n for counter in counters:\n total += counter.count\n memclient.add(str(instance), str(total), 60)\nreturn int(total)",
"memclient = memc... | <|body_start_0|>
memclient = memcache.Client()
total = memclient.get(str(instance))
if total is None:
total = 0
counters = cls.all().filter('instance_key =', instance)
for counter in counters:
total += counter.count
memclient.add(st... | Contador sharded instance es el key del objeto al que apunta | ShardedCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShardedCounter:
"""Contador sharded instance es el key del objeto al que apunta"""
def get_count(cls, instance):
"""Returns the value of the counter, is counters is not in memcache, counts all the sharded counters"""
<|body_0|>
def increase_counter(cls, instance, count):... | stack_v2_sparse_classes_36k_train_018626 | 5,048 | no_license | [
{
"docstring": "Returns the value of the counter, is counters is not in memcache, counts all the sharded counters",
"name": "get_count",
"signature": "def get_count(cls, instance)"
},
{
"docstring": "Increment the counter of given key",
"name": "increase_counter",
"signature": "def incre... | 2 | stack_v2_sparse_classes_30k_test_001165 | Implement the Python class `ShardedCounter` described below.
Class description:
Contador sharded instance es el key del objeto al que apunta
Method signatures and docstrings:
- def get_count(cls, instance): Returns the value of the counter, is counters is not in memcache, counts all the sharded counters
- def increas... | Implement the Python class `ShardedCounter` described below.
Class description:
Contador sharded instance es el key del objeto al que apunta
Method signatures and docstrings:
- def get_count(cls, instance): Returns the value of the counter, is counters is not in memcache, counts all the sharded counters
- def increas... | d441693eedb32c36fe853895110df808a9959941 | <|skeleton|>
class ShardedCounter:
"""Contador sharded instance es el key del objeto al que apunta"""
def get_count(cls, instance):
"""Returns the value of the counter, is counters is not in memcache, counts all the sharded counters"""
<|body_0|>
def increase_counter(cls, instance, count):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShardedCounter:
"""Contador sharded instance es el key del objeto al que apunta"""
def get_count(cls, instance):
"""Returns the value of the counter, is counters is not in memcache, counts all the sharded counters"""
memclient = memcache.Client()
total = memclient.get(str(instance... | the_stack_v2_python_sparse | src/webapp/georemindme/models_utils.py | GeoRemindMe/GeoRemindMe_Web | train | 8 |
45d8324aaca82661703922b57b515c0a0d68626f | [
"batch_size = lines.size(0)\nintensity_channels = intensities.size(2)\nline_map = torch.zeros(batch_size, intensity_channels, img_size, img_size, dtype=torch.float32, device=device)\nline_index_map = -1 * torch.ones(batch_size, 1, img_size, img_size, dtype=torch.int32, device=device)\nline_weight_map = torch.zeros(... | <|body_start_0|>
batch_size = lines.size(0)
intensity_channels = intensities.size(2)
line_map = torch.zeros(batch_size, intensity_channels, img_size, img_size, dtype=torch.float32, device=device)
line_index_map = -1 * torch.ones(batch_size, 1, img_size, img_size, dtype=torch.int32, devic... | RasterIntensityFunc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RasterIntensityFunc:
def forward(ctx, lines, intensities, img_size=DEFAULT_IMG_SIZE, thickness=DEFAULT_THICKNESS, eps=DEFAULT_EPS, device=DEFAULT_DEVICE):
""":param ctx: :param lines: [batch_size, num_lines, 3] :param intensities: [batch_size, num_lines, channels] :param img_size: :param... | stack_v2_sparse_classes_36k_train_018627 | 4,252 | no_license | [
{
"docstring": ":param ctx: :param lines: [batch_size, num_lines, 3] :param intensities: [batch_size, num_lines, channels] :param img_size: :param thickness: :param eps: :param device: :return:",
"name": "forward",
"signature": "def forward(ctx, lines, intensities, img_size=DEFAULT_IMG_SIZE, thickness=D... | 2 | stack_v2_sparse_classes_30k_train_012671 | Implement the Python class `RasterIntensityFunc` described below.
Class description:
Implement the RasterIntensityFunc class.
Method signatures and docstrings:
- def forward(ctx, lines, intensities, img_size=DEFAULT_IMG_SIZE, thickness=DEFAULT_THICKNESS, eps=DEFAULT_EPS, device=DEFAULT_DEVICE): :param ctx: :param lin... | Implement the Python class `RasterIntensityFunc` described below.
Class description:
Implement the RasterIntensityFunc class.
Method signatures and docstrings:
- def forward(ctx, lines, intensities, img_size=DEFAULT_IMG_SIZE, thickness=DEFAULT_THICKNESS, eps=DEFAULT_EPS, device=DEFAULT_DEVICE): :param ctx: :param lin... | 4cc983fc64fed6b5da0d8e77305ef56d239cbcf9 | <|skeleton|>
class RasterIntensityFunc:
def forward(ctx, lines, intensities, img_size=DEFAULT_IMG_SIZE, thickness=DEFAULT_THICKNESS, eps=DEFAULT_EPS, device=DEFAULT_DEVICE):
""":param ctx: :param lines: [batch_size, num_lines, 3] :param intensities: [batch_size, num_lines, channels] :param img_size: :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RasterIntensityFunc:
def forward(ctx, lines, intensities, img_size=DEFAULT_IMG_SIZE, thickness=DEFAULT_THICKNESS, eps=DEFAULT_EPS, device=DEFAULT_DEVICE):
""":param ctx: :param lines: [batch_size, num_lines, 3] :param intensities: [batch_size, num_lines, channels] :param img_size: :param thickness: :p... | the_stack_v2_python_sparse | neuralline/rasterize.py | Junlin-Yin/Sketch-R2CNN | train | 1 | |
b5371f51b07fe45358efd0dc8ef11e3cf917c67c | [
"bpm = env.job_generator.buffer_processing_matrix\nassert np.all(np.sum(np.where(bpm < 0, -1, 0), axis=0) >= -1), f'Buffer processing matrix not allowed: {bpm}.Current version only works for networks where each activity drains exactly one buffer (i.e., only works for scheduling and/or routing).'\nif weight_per_buff... | <|body_start_0|>
bpm = env.job_generator.buffer_processing_matrix
assert np.all(np.sum(np.where(bpm < 0, -1, 0), axis=0) >= -1), f'Buffer processing matrix not allowed: {bpm}.Current version only works for networks where each activity drains exactly one buffer (i.e., only works for scheduling and/or rou... | MaxWeightAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxWeightAgent:
def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None:
"""MaxWeight policy based on Chapter 6.4 (CTCN book online ... | stack_v2_sparse_classes_36k_train_018628 | 7,371 | permissive | [
{
"docstring": "MaxWeight policy based on Chapter 6.4 (CTCN book online edition). This only works for scheduling and routing problems, where each activity drains only one buffer. NOTE: in case of a buffer managed by multiple resources, the job_conservation_flag has to be True otherwise the buffer may have negat... | 3 | stack_v2_sparse_classes_30k_test_001090 | Implement the Python class `MaxWeightAgent` described below.
Class description:
Implement the MaxWeightAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int... | Implement the Python class `MaxWeightAgent` described below.
Class description:
Implement the MaxWeightAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int... | b067eebaa5b57a96efdaed5796aca9f157d32214 | <|skeleton|>
class MaxWeightAgent:
def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None:
"""MaxWeight policy based on Chapter 6.4 (CTCN book online ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxWeightAgent:
def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None:
"""MaxWeight policy based on Chapter 6.4 (CTCN book online edition). This... | the_stack_v2_python_sparse | src/snc/agents/maxweight_variants/maxweight_agent.py | stochasticnetworkcontrol/snc | train | 9 | |
26fd1620375708d42c0a199aeecb129995def3ba | [
"self.grad_log_q = grad_log_q\nassert proposal_sig > 0\nself.proposal_sig = proposal_sig\nif seed is None:\n seed = np.random.randint(100000)\nself.rng = np.random.default_rng(seed)",
"assert x.shape == gaussian_rvs.shape == uniform_rvs.shape\nz = gaussian_rvs * self.proposal_sig\ngrad_x = self.grad_log_q(x)\n... | <|body_start_0|>
self.grad_log_q = grad_log_q
assert proposal_sig > 0
self.proposal_sig = proposal_sig
if seed is None:
seed = np.random.randint(100000)
self.rng = np.random.default_rng(seed)
<|end_body_0|>
<|body_start_1|>
assert x.shape == gaussian_rvs.shap... | BarkerProposal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarkerProposal:
def __init__(self, grad_log_q, proposal_sig=0.001, seed=None):
"""Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evaluation of proposal density p(y | x) Compared to Langevin proposals, more robust to poor initialization a... | stack_v2_sparse_classes_36k_train_018629 | 1,972 | permissive | [
{
"docstring": "Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evaluation of proposal density p(y | x) Compared to Langevin proposals, more robust to poor initialization and to poor choice of step size. References ---------- [Livingstone, Zanella, 2020] The Bar... | 4 | null | Implement the Python class `BarkerProposal` described below.
Class description:
Implement the BarkerProposal class.
Method signatures and docstrings:
- def __init__(self, grad_log_q, proposal_sig=0.001, seed=None): Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evalu... | Implement the Python class `BarkerProposal` described below.
Class description:
Implement the BarkerProposal class.
Method signatures and docstrings:
- def __init__(self, grad_log_q, proposal_sig=0.001, seed=None): Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evalu... | b853c2d287da0d1c1babb963eaec8fda41539b90 | <|skeleton|>
class BarkerProposal:
def __init__(self, grad_log_q, proposal_sig=0.001, seed=None):
"""Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evaluation of proposal density p(y | x) Compared to Langevin proposals, more robust to poor initialization a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BarkerProposal:
def __init__(self, grad_log_q, proposal_sig=0.001, seed=None):
"""Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evaluation of proposal density p(y | x) Compared to Langevin proposals, more robust to poor initialization and to poor cho... | the_stack_v2_python_sparse | timemachine/md/barker.py | proteneer/timemachine | train | 132 | |
316f1b1f48227f8551522353a6d901a8f3b76edd | [
"super().__init__()\nassert d_model % h == 0, f'd_model={d_model} heads={h}'\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout) if dropout else None",
"if mask is not None:\n mask = mask.unsqueeze(1)\nnbatches = q... | <|body_start_0|>
super().__init__()
assert d_model % h == 0, f'd_model={d_model} heads={h}'
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout) if dropout else None
<|end_b... | MultiHeadedAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
""":param query: (bsz, q_len, dim) :param key: (bsz, seq_len, dim) :param value: (bsz, seq_len... | stack_v2_sparse_classes_36k_train_018630 | 6,126 | no_license | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": ":param query: (bsz, q_len, dim) :param key: (bsz, seq_len, dim) :param value: (bsz, seq_len, dim) :param mask: (bsz, q_len, seq_len) 等于0的位置会... | 2 | null | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): :param query: (bsz... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): :param query: (bsz... | 4bc4a12b0ab44c6847a67cbd7639ce3c025f38f8 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
""":param query: (bsz, q_len, dim) :param key: (bsz, seq_len, dim) :param value: (bsz, seq_len... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
super().__init__()
assert d_model % h == 0, f'd_model={d_model} heads={h}'
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_mode... | the_stack_v2_python_sparse | gaiic2022/nezha/modeling/attentions.py | kelvincjr/shared | train | 6 | |
ec1ba378d88068a091f75b8dfedf5cebb7fbdf5d | [
"pic = self._new_placeholder_pic(image_file)\nself._replace_placeholder_with(pic)\nreturn PlaceholderPicture(pic, self._parent)",
"rId, desc, image_size = self._get_or_add_image(image_file)\nid_, name = (self.id, self.name)\npic = CT_Picture.new_ph_pic(id_, name, desc, rId)\npic.crop_to_fit(image_size, (self.widt... | <|body_start_0|>
pic = self._new_placeholder_pic(image_file)
self._replace_placeholder_with(pic)
return PlaceholderPicture(pic, self._parent)
<|end_body_0|>
<|body_start_1|>
rId, desc, image_size = self._get_or_add_image(image_file)
id_, name = (self.id, self.name)
pic =... | Placeholder shape that can only accept a picture. | PicturePlaceholder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PicturePlaceholder:
"""Placeholder shape that can only accept a picture."""
def insert_picture(self, image_file):
"""Return a |PlaceholderPicture| object depicting the image in *image_file*, which may be either a path (string) or a file-like object. The image is cropped to fill the e... | stack_v2_sparse_classes_36k_train_018631 | 14,749 | permissive | [
{
"docstring": "Return a |PlaceholderPicture| object depicting the image in *image_file*, which may be either a path (string) or a file-like object. The image is cropped to fill the entire space of the placeholder. A |PlaceholderPicture| object has all the properties and methods of a |Picture| shape except that... | 3 | stack_v2_sparse_classes_30k_train_000103 | Implement the Python class `PicturePlaceholder` described below.
Class description:
Placeholder shape that can only accept a picture.
Method signatures and docstrings:
- def insert_picture(self, image_file): Return a |PlaceholderPicture| object depicting the image in *image_file*, which may be either a path (string) ... | Implement the Python class `PicturePlaceholder` described below.
Class description:
Placeholder shape that can only accept a picture.
Method signatures and docstrings:
- def insert_picture(self, image_file): Return a |PlaceholderPicture| object depicting the image in *image_file*, which may be either a path (string) ... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class PicturePlaceholder:
"""Placeholder shape that can only accept a picture."""
def insert_picture(self, image_file):
"""Return a |PlaceholderPicture| object depicting the image in *image_file*, which may be either a path (string) or a file-like object. The image is cropped to fill the e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PicturePlaceholder:
"""Placeholder shape that can only accept a picture."""
def insert_picture(self, image_file):
"""Return a |PlaceholderPicture| object depicting the image in *image_file*, which may be either a path (string) or a file-like object. The image is cropped to fill the entire space o... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/shapes/placeholder.py | ryfeus/lambda-packs | train | 1,283 |
ff298ead63253cd09ab3d43eb3ab8922f1b3e387 | [
"self.key_attrs = {}\nself.val_attrs = {}\nif 'key_attrs' in kwargs:\n self.key_attrs = kwargs.pop('key_attrs')\nif 'val_attrs' in kwargs:\n self.val_attrs = kwargs.pop('val_attrs')\nWidget.__init__(self, *args, **kwargs)",
"if value is None or value.strip() is '':\n value = ('', '')\nret = ''\nctx = {'k... | <|body_start_0|>
self.key_attrs = {}
self.val_attrs = {}
if 'key_attrs' in kwargs:
self.key_attrs = kwargs.pop('key_attrs')
if 'val_attrs' in kwargs:
self.val_attrs = kwargs.pop('val_attrs')
Widget.__init__(self, *args, **kwargs)
<|end_body_0|>
<|body_sta... | A widget that displays JSON Key Value Pairs as a list of text input box pairs Usage (in forms.py) : examplejsonfield = forms.CharField(label = "Example JSON Key Value Field", required = False, widget = JsonPairInputs(val_attrs={'size':35}, key_attrs={'class':'large'})) | AdditionalLink | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdditionalLink:
"""A widget that displays JSON Key Value Pairs as a list of text input box pairs Usage (in forms.py) : examplejsonfield = forms.CharField(label = "Example JSON Key Value Field", required = False, widget = JsonPairInputs(val_attrs={'size':35}, key_attrs={'class':'large'}))"""
... | stack_v2_sparse_classes_36k_train_018632 | 5,886 | permissive | [
{
"docstring": "A widget that displays JSON Key Value Pairs as a list of text input box pairs kwargs: key_attrs -- html attributes applied to the 1st input box pairs val_attrs -- html attributes applied to the 2nd input box pairs",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
... | 3 | stack_v2_sparse_classes_30k_train_003518 | Implement the Python class `AdditionalLink` described below.
Class description:
A widget that displays JSON Key Value Pairs as a list of text input box pairs Usage (in forms.py) : examplejsonfield = forms.CharField(label = "Example JSON Key Value Field", required = False, widget = JsonPairInputs(val_attrs={'size':35},... | Implement the Python class `AdditionalLink` described below.
Class description:
A widget that displays JSON Key Value Pairs as a list of text input box pairs Usage (in forms.py) : examplejsonfield = forms.CharField(label = "Example JSON Key Value Field", required = False, widget = JsonPairInputs(val_attrs={'size':35},... | f570fcc887fd622f958732806863749c66afe772 | <|skeleton|>
class AdditionalLink:
"""A widget that displays JSON Key Value Pairs as a list of text input box pairs Usage (in forms.py) : examplejsonfield = forms.CharField(label = "Example JSON Key Value Field", required = False, widget = JsonPairInputs(val_attrs={'size':35}, key_attrs={'class':'large'}))"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdditionalLink:
"""A widget that displays JSON Key Value Pairs as a list of text input box pairs Usage (in forms.py) : examplejsonfield = forms.CharField(label = "Example JSON Key Value Field", required = False, widget = JsonPairInputs(val_attrs={'size':35}, key_attrs={'class':'large'}))"""
def __init__(... | the_stack_v2_python_sparse | masterinterface/scs_resources/widgets.py | b3c/vphshare | train | 1 |
f58745d2beb252be222b1cf1cf7908bd10aa5d4c | [
"if not matrix:\n return 0\nself.matrix = matrxi\nself.m = len(matrix)\nself.n = len(matrix[0])\nself.visited = [[False for _ in range(n)] for _ in range(m)]\nres = 0\nfor i in range(self.m):\n for j in range(self.n):\n if matrix[i][j] == 1 and (not self.visited[i][j]):\n self.dfs(i, j)\n ... | <|body_start_0|>
if not matrix:
return 0
self.matrix = matrxi
self.m = len(matrix)
self.n = len(matrix[0])
self.visited = [[False for _ in range(n)] for _ in range(m)]
res = 0
for i in range(self.m):
for j in range(self.n):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def group_number(self, matrix):
"""Args: matrix: list[list[int]] Return: int"""
<|body_0|>
def dfs(self, i, j):
"""Args: i: int j: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not matrix:
return 0
self.matrix ... | stack_v2_sparse_classes_36k_train_018633 | 988 | no_license | [
{
"docstring": "Args: matrix: list[list[int]] Return: int",
"name": "group_number",
"signature": "def group_number(self, matrix)"
},
{
"docstring": "Args: i: int j: int",
"name": "dfs",
"signature": "def dfs(self, i, j)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def group_number(self, matrix): Args: matrix: list[list[int]] Return: int
- def dfs(self, i, j): Args: i: int j: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def group_number(self, matrix): Args: matrix: list[list[int]] Return: int
- def dfs(self, i, j): Args: i: int j: int
<|skeleton|>
class Solution:
def group_number(self, mat... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def group_number(self, matrix):
"""Args: matrix: list[list[int]] Return: int"""
<|body_0|>
def dfs(self, i, j):
"""Args: i: int j: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def group_number(self, matrix):
"""Args: matrix: list[list[int]] Return: int"""
if not matrix:
return 0
self.matrix = matrxi
self.m = len(matrix)
self.n = len(matrix[0])
self.visited = [[False for _ in range(n)] for _ in range(m)]
r... | the_stack_v2_python_sparse | 秋招/广联达/广联达_孤岛.py | AiZhanghan/Leetcode | train | 0 | |
acdb5b1748fb3610f90917bfe27b057767a97e5b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn OpenShift()",
"from .change_tracked_entity import ChangeTrackedEntity\nfrom .open_shift_item import OpenShiftItem\nfrom .change_tracked_entity import ChangeTrackedEntity\nfrom .open_shift_item import OpenShiftItem\nfields: Dict[str, Ca... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return OpenShift()
<|end_body_0|>
<|body_start_1|>
from .change_tracked_entity import ChangeTrackedEntity
from .open_shift_item import OpenShiftItem
from .change_tracked_entity import C... | OpenShift | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenShift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift:
"""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: OpenSh... | stack_v2_sparse_classes_36k_train_018634 | 2,856 | 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: OpenShift",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(par... | 3 | null | Implement the Python class `OpenShift` described below.
Class description:
Implement the OpenShift class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift: Creates a new instance of the appropriate class based on discriminator value Args: parse... | Implement the Python class `OpenShift` described below.
Class description:
Implement the OpenShift class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift: Creates a new instance of the appropriate class based on discriminator value Args: parse... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class OpenShift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift:
"""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: OpenSh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenShift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift:
"""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: OpenShift"""
... | the_stack_v2_python_sparse | msgraph/generated/models/open_shift.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b8d2f3a5261369726543744f902bded701a98fd9 | [
"super(ThermoPILE_G, self).__init__(temp, dt, tau, ethermo)\ndself = dd(self)\ndself.pilescale = depend_value(value=scale, name='pilescale')\ndself.pilect = depend_value(value=pilect, name='pilect')\ndself.npilect = depend_value(func=self.get_npilect, name='npilect', dependencies=[dself.pilect])",
"prev_ethermo =... | <|body_start_0|>
super(ThermoPILE_G, self).__init__(temp, dt, tau, ethermo)
dself = dd(self)
dself.pilescale = depend_value(value=scale, name='pilescale')
dself.pilect = depend_value(value=pilect, name='pilect')
dself.npilect = depend_value(func=self.get_npilect, name='npilect', ... | Represents a PILE thermostat with a global centroid thermostat. Simply replaces the Langevin thermostat for the centroid normal mode with a global velocity rescaling thermostat. | ThermoPILE_G | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThermoPILE_G:
"""Represents a PILE thermostat with a global centroid thermostat. Simply replaces the Langevin thermostat for the centroid normal mode with a global velocity rescaling thermostat."""
def __init__(self, temp=1.0, dt=1.0, tau=1.0, ethermo=0.0, scale=1.0, pilect=0.0):
"""... | stack_v2_sparse_classes_36k_train_018635 | 47,974 | no_license | [
{
"docstring": "Initialises ThermoPILE_G. Args: temp: The simulation temperature. Defaults to 1.0. dt: The simulation time step. Defaults to 1.0. tau: The centroid thermostat damping timescale. Defaults to 1.0. ethermo: The initial conserved energy quantity. Defaults to 0.0. Will be non-zero if the thermostat i... | 2 | null | Implement the Python class `ThermoPILE_G` described below.
Class description:
Represents a PILE thermostat with a global centroid thermostat. Simply replaces the Langevin thermostat for the centroid normal mode with a global velocity rescaling thermostat.
Method signatures and docstrings:
- def __init__(self, temp=1.... | Implement the Python class `ThermoPILE_G` described below.
Class description:
Represents a PILE thermostat with a global centroid thermostat. Simply replaces the Langevin thermostat for the centroid normal mode with a global velocity rescaling thermostat.
Method signatures and docstrings:
- def __init__(self, temp=1.... | 57f255266d4668bafef0881d1e7cbf8a27270ddd | <|skeleton|>
class ThermoPILE_G:
"""Represents a PILE thermostat with a global centroid thermostat. Simply replaces the Langevin thermostat for the centroid normal mode with a global velocity rescaling thermostat."""
def __init__(self, temp=1.0, dt=1.0, tau=1.0, ethermo=0.0, scale=1.0, pilect=0.0):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThermoPILE_G:
"""Represents a PILE thermostat with a global centroid thermostat. Simply replaces the Langevin thermostat for the centroid normal mode with a global velocity rescaling thermostat."""
def __init__(self, temp=1.0, dt=1.0, tau=1.0, ethermo=0.0, scale=1.0, pilect=0.0):
"""Initialises T... | the_stack_v2_python_sparse | ipi/engine/thermostats.py | i-pi/i-pi | train | 170 |
7678c0146afcfe24fad1401d4474d098fa05d29c | [
"super(SourceDatasetSearchForm, self).__init__(*args, **kwargs)\nself.helper = FormHelper(self)\nself.helper.form_method = 'get'\nself.helper.form_class = 'form-horizontal'\nself.helper.label_class = 'col-sm-2'\nself.helper.field_class = 'col-sm-10'\nself.helper.layout = Layout(Row(Div(name_checkbox_layout, 'descri... | <|body_start_0|>
super(SourceDatasetSearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_method = 'get'
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-sm-2'
self.helper.field_class = 'col-sm-10'
sel... | Form to handle django-watson searches for SourceDataset objects. | SourceDatasetSearchForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceDatasetSearchForm:
"""Form to handle django-watson searches for SourceDataset objects."""
def __init__(self, *args, **kwargs):
"""Initialize form with formatting and submit button."""
<|body_0|>
def clean(self):
"""Perform additional multi-field cleaning to... | stack_v2_sparse_classes_36k_train_018636 | 19,577 | permissive | [
{
"docstring": "Initialize form with formatting and submit button.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Perform additional multi-field cleaning to make sure that either description or name is entered.",
"name": "clean",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_020618 | Implement the Python class `SourceDatasetSearchForm` described below.
Class description:
Form to handle django-watson searches for SourceDataset objects.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize form with formatting and submit button.
- def clean(self): Perform additional mu... | Implement the Python class `SourceDatasetSearchForm` described below.
Class description:
Form to handle django-watson searches for SourceDataset objects.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize form with formatting and submit button.
- def clean(self): Perform additional mu... | 89ae277f5ba1357580d78c3527f26200686308a6 | <|skeleton|>
class SourceDatasetSearchForm:
"""Form to handle django-watson searches for SourceDataset objects."""
def __init__(self, *args, **kwargs):
"""Initialize form with formatting and submit button."""
<|body_0|>
def clean(self):
"""Perform additional multi-field cleaning to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceDatasetSearchForm:
"""Form to handle django-watson searches for SourceDataset objects."""
def __init__(self, *args, **kwargs):
"""Initialize form with formatting and submit button."""
super(SourceDatasetSearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(sel... | the_stack_v2_python_sparse | trait_browser/forms.py | UW-GAC/pie | train | 0 |
c2da97542ab770c854bd221064294d68c8cb56e3 | [
"Configuration.__init__(self)\nself.isHomoComplex = isHomoComplex\nself.stepName = stepName\nself.averageLRscores = averageLRscores\nif not savedModelsPath is None:\n self.savedModelsPath = savedModelsPath\nself.model = None\nprint(stepName)\nself.savedModelsPath = os.path.join(self.savedModelsPath, 'homo' if se... | <|body_start_0|>
Configuration.__init__(self)
self.isHomoComplex = isHomoComplex
self.stepName = stepName
self.averageLRscores = averageLRscores
if not savedModelsPath is None:
self.savedModelsPath = savedModelsPath
self.model = None
print(stepName)
... | This class is used to predict new pdbs once models have already been computed. | ComplexPredictor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplexPredictor:
"""This class is used to predict new pdbs once models have already been computed."""
def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False):
""":param stepName: str. Must startswith seq_train or struct or mixed (seq_train, mixed_2, ... | stack_v2_sparse_classes_36k_train_018637 | 3,490 | permissive | [
{
"docstring": ":param stepName: str. Must startswith seq_train or struct or mixed (seq_train, mixed_2, structX, seq_train1... are also valid) :param isHomoComplex: boolean. Is the target complex homo or hetero :param savedModelsPath: str. A path to the directory where models have been saved. If None, it will u... | 2 | null | Implement the Python class `ComplexPredictor` described below.
Class description:
This class is used to predict new pdbs once models have already been computed.
Method signatures and docstrings:
- def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False): :param stepName: str. Must star... | Implement the Python class `ComplexPredictor` described below.
Class description:
This class is used to predict new pdbs once models have already been computed.
Method signatures and docstrings:
- def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False): :param stepName: str. Must star... | 1d9801a176323ba238c8d10e673cf2055f83a4b6 | <|skeleton|>
class ComplexPredictor:
"""This class is used to predict new pdbs once models have already been computed."""
def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False):
""":param stepName: str. Must startswith seq_train or struct or mixed (seq_train, mixed_2, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComplexPredictor:
"""This class is used to predict new pdbs once models have already been computed."""
def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False):
""":param stepName: str. Must startswith seq_train or struct or mixed (seq_train, mixed_2, structX, seq_... | the_stack_v2_python_sparse | trainAndTest/predictOneCodifiedComplex.py | rsanchezgarc/BIPSPI | train | 9 |
0eb3040616fa1677aa7ecf0826aa55bf0dcd1de6 | [
"if root == None:\n return '*'\nif root.left == None:\n left = '*'\nelse:\n left = self.serialize(root.left)\nif root.right == None:\n right = '*'\nelse:\n right = self.serialize(root.right)\nreturn str(root.val) + '[' + left + ']' + '(' + right + ')'",
"if data == '*':\n return None\ni = 0\nwhi... | <|body_start_0|>
if root == None:
return '*'
if root.left == None:
left = '*'
else:
left = self.serialize(root.left)
if root.right == None:
right = '*'
else:
right = self.serialize(root.right)
return str(root.val... | 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_018638 | 1,640 | 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:... | 517f5013f9a997923ad22b9728990aab2a7fd10e | <|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 root == None:
return '*'
if root.left == None:
left = '*'
else:
left = self.serialize(root.left)
if root.right == None:
... | the_stack_v2_python_sparse | 297_Serialize_and_Deserialize_Binary_Tree.py | LeeGroups/LeetCode-Questions | train | 0 | |
afe84fc73c846b269eabe5d854b7dfdffe9fc8cf | [
"super(RNNColorbot, self).__init__(name='')\nself.rnn_cell_sizes = rnn_cell_sizes\nself.label_dimension = label_dimension\nself.keep_prob = keep_prob\nself.cells = [keras.layers.LSTMCell(size) for size in rnn_cell_sizes]\nself.relu = keras.layers.Dense(label_dimension, activation=tf.nn.relu)",
"chars, sequence_le... | <|body_start_0|>
super(RNNColorbot, self).__init__(name='')
self.rnn_cell_sizes = rnn_cell_sizes
self.label_dimension = label_dimension
self.keep_prob = keep_prob
self.cells = [keras.layers.LSTMCell(size) for size in rnn_cell_sizes]
self.relu = keras.layers.Dense(label_di... | Multi-layer (LSTM) RNN that regresses on real-valued vector labels. | RNNColorbot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNColorbot:
"""Multi-layer (LSTM) RNN that regresses on real-valued vector labels."""
def __init__(self, rnn_cell_sizes, label_dimension, keep_prob):
"""Constructs an RNNColorbot. Args: rnn_cell_sizes: list of integers denoting the size of each LSTM cell in the RNN; rnn_cell_sizes[i... | stack_v2_sparse_classes_36k_train_018639 | 3,729 | permissive | [
{
"docstring": "Constructs an RNNColorbot. Args: rnn_cell_sizes: list of integers denoting the size of each LSTM cell in the RNN; rnn_cell_sizes[i] is the size of the i-th layer cell label_dimension: the length of the labels on which to regress keep_prob: (1 - dropout probability); dropout is applied to the out... | 2 | stack_v2_sparse_classes_30k_train_007240 | Implement the Python class `RNNColorbot` described below.
Class description:
Multi-layer (LSTM) RNN that regresses on real-valued vector labels.
Method signatures and docstrings:
- def __init__(self, rnn_cell_sizes, label_dimension, keep_prob): Constructs an RNNColorbot. Args: rnn_cell_sizes: list of integers denotin... | Implement the Python class `RNNColorbot` described below.
Class description:
Multi-layer (LSTM) RNN that regresses on real-valued vector labels.
Method signatures and docstrings:
- def __init__(self, rnn_cell_sizes, label_dimension, keep_prob): Constructs an RNNColorbot. Args: rnn_cell_sizes: list of integers denotin... | 8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d | <|skeleton|>
class RNNColorbot:
"""Multi-layer (LSTM) RNN that regresses on real-valued vector labels."""
def __init__(self, rnn_cell_sizes, label_dimension, keep_prob):
"""Constructs an RNNColorbot. Args: rnn_cell_sizes: list of integers denoting the size of each LSTM cell in the RNN; rnn_cell_sizes[i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNColorbot:
"""Multi-layer (LSTM) RNN that regresses on real-valued vector labels."""
def __init__(self, rnn_cell_sizes, label_dimension, keep_prob):
"""Constructs an RNNColorbot. Args: rnn_cell_sizes: list of integers denoting the size of each LSTM cell in the RNN; rnn_cell_sizes[i] is the size... | the_stack_v2_python_sparse | tensorflow_v2/dragen1860/Tutorials/10-ColorBot/model.py | gottaegbert/penter | train | 0 |
3517b4163199387526767f7f9c9fc5ee07ae98cd | [
"try:\n self.assessVers = AssessmentVersion.objects.get(pk=self.kwargs['assessIR'])\nexcept AssessmentVersion.DoesNotExist:\n raise Http404('No asssessment matches the URL.')\nreturn super(SupplementUpload, self).dispatch(request, *args, **kwargs)",
"self.assessVers.supplements.add(self.object)\nself.assess... | <|body_start_0|>
try:
self.assessVers = AssessmentVersion.objects.get(pk=self.kwargs['assessIR'])
except AssessmentVersion.DoesNotExist:
raise Http404('No asssessment matches the URL.')
return super(SupplementUpload, self).dispatch(request, *args, **kwargs)
<|end_body_0|>... | View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` | SupplementUpload | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupplementUpload:
"""View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`"""
def dispatch(self, request, *args, **kwargs):
"""Dispatch view and attach assessment to instance Args: reque... | stack_v2_sparse_classes_36k_train_018640 | 27,436 | no_license | [
{
"docstring": "Dispatch view and attach assessment to instance Args: request (HttpRequest): request to view page Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` Returns: HttpResponse : response of page to request",
"name": "dispatch",
"signa... | 3 | stack_v2_sparse_classes_30k_train_018821 | Implement the Python class `SupplementUpload` described below.
Class description:
View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Di... | Implement the Python class `SupplementUpload` described below.
Class description:
View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Di... | 472a6fd487811002a60a7812ae2eef941e7182cc | <|skeleton|>
class SupplementUpload:
"""View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`"""
def dispatch(self, request, *args, **kwargs):
"""Dispatch view and attach assessment to instance Args: reque... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SupplementUpload:
"""View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`"""
def dispatch(self, request, *args, **kwargs):
"""Dispatch view and attach assessment to instance Args: request (HttpReque... | the_stack_v2_python_sparse | AACForm/makeReports/views/assessment_views.py | jdboyd-github/AAC-Capstone | train | 0 |
577d1948a9c3c7af5b3eb94ae9e7118cf9f120c9 | [
"created = None\npatient_ids = []\nupdated = datetime.now()\nif 'mme_submission' in case_obj and case_obj['mme_submission']:\n created = case_obj['mme_submission']['created_at']\nelse:\n created = updated\npatients = [resp['patient'] for resp in mme_subm_obj.get('server_responses')]\nsubm_obj = {'created_at':... | <|body_start_0|>
created = None
patient_ids = []
updated = datetime.now()
if 'mme_submission' in case_obj and case_obj['mme_submission']:
created = case_obj['mme_submission']['created_at']
else:
created = updated
patients = [resp['patient'] for res... | Class to handle case submissions to MatchMaker Exchange | MMEHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMEHandler:
"""Class to handle case submissions to MatchMaker Exchange"""
def case_mme_update(self, case_obj, user_obj, mme_subm_obj):
"""Updates a case after a submission to MatchMaker Exchange Args: case_obj(dict): a scout case object user_obj(dict): a scout user object mme_subm_ob... | stack_v2_sparse_classes_36k_train_018641 | 3,076 | permissive | [
{
"docstring": "Updates a case after a submission to MatchMaker Exchange Args: case_obj(dict): a scout case object user_obj(dict): a scout user object mme_subm_obj(dict): contains MME submission params and server response Returns: updated_case(dict): the updated scout case",
"name": "case_mme_update",
"... | 2 | stack_v2_sparse_classes_30k_train_008067 | Implement the Python class `MMEHandler` described below.
Class description:
Class to handle case submissions to MatchMaker Exchange
Method signatures and docstrings:
- def case_mme_update(self, case_obj, user_obj, mme_subm_obj): Updates a case after a submission to MatchMaker Exchange Args: case_obj(dict): a scout ca... | Implement the Python class `MMEHandler` described below.
Class description:
Class to handle case submissions to MatchMaker Exchange
Method signatures and docstrings:
- def case_mme_update(self, case_obj, user_obj, mme_subm_obj): Updates a case after a submission to MatchMaker Exchange Args: case_obj(dict): a scout ca... | c9b3ec14f5105abe6066337110145a263320b4c5 | <|skeleton|>
class MMEHandler:
"""Class to handle case submissions to MatchMaker Exchange"""
def case_mme_update(self, case_obj, user_obj, mme_subm_obj):
"""Updates a case after a submission to MatchMaker Exchange Args: case_obj(dict): a scout case object user_obj(dict): a scout user object mme_subm_ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MMEHandler:
"""Class to handle case submissions to MatchMaker Exchange"""
def case_mme_update(self, case_obj, user_obj, mme_subm_obj):
"""Updates a case after a submission to MatchMaker Exchange Args: case_obj(dict): a scout case object user_obj(dict): a scout user object mme_subm_obj(dict): cont... | the_stack_v2_python_sparse | scout/adapter/mongo/matchmaker.py | tapaswenipathak/scout | train | 1 |
9c7e6a029d87ed8ef6beebe95450c5fb7aa3d9bc | [
"n = len(nums)\nres = []\nnums.sort()\n\ndef back_track(nums, index, path, res):\n res.append(path)\n for i in range(index, n):\n if i > index and nums[i] == nums[i - 1]:\n continue\n back_track(nums, i + 1, path + [nums[i]], res)\nback_track(nums, 0, [], res)\nreturn res",
"n = len... | <|body_start_0|>
n = len(nums)
res = []
nums.sort()
def back_track(nums, index, path, res):
res.append(path)
for i in range(index, n):
if i > index and nums[i] == nums[i - 1]:
continue
back_track(nums, i + 1, pa... | Subsets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subsets:
def get_all__(self, nums: int) -> List[List[int]]:
"""Approach: Back tracking Time Complexity: O(N2^N) Space Complexity: O(N2^N) :param nums: :return:"""
<|body_0|>
def get_all_(self, nums: int) -> List[List[int]]:
"""Approach: Lexographic Binary Sorted Time... | stack_v2_sparse_classes_36k_train_018642 | 1,860 | no_license | [
{
"docstring": "Approach: Back tracking Time Complexity: O(N2^N) Space Complexity: O(N2^N) :param nums: :return:",
"name": "get_all__",
"signature": "def get_all__(self, nums: int) -> List[List[int]]"
},
{
"docstring": "Approach: Lexographic Binary Sorted Time Complexity: O(N2^N) Space Complexit... | 3 | null | Implement the Python class `Subsets` described below.
Class description:
Implement the Subsets class.
Method signatures and docstrings:
- def get_all__(self, nums: int) -> List[List[int]]: Approach: Back tracking Time Complexity: O(N2^N) Space Complexity: O(N2^N) :param nums: :return:
- def get_all_(self, nums: int) ... | Implement the Python class `Subsets` described below.
Class description:
Implement the Subsets class.
Method signatures and docstrings:
- def get_all__(self, nums: int) -> List[List[int]]: Approach: Back tracking Time Complexity: O(N2^N) Space Complexity: O(N2^N) :param nums: :return:
- def get_all_(self, nums: int) ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Subsets:
def get_all__(self, nums: int) -> List[List[int]]:
"""Approach: Back tracking Time Complexity: O(N2^N) Space Complexity: O(N2^N) :param nums: :return:"""
<|body_0|>
def get_all_(self, nums: int) -> List[List[int]]:
"""Approach: Lexographic Binary Sorted Time... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subsets:
def get_all__(self, nums: int) -> List[List[int]]:
"""Approach: Back tracking Time Complexity: O(N2^N) Space Complexity: O(N2^N) :param nums: :return:"""
n = len(nums)
res = []
nums.sort()
def back_track(nums, index, path, res):
res.append(path)
... | the_stack_v2_python_sparse | revisited/permutations_combinations_subsets/subsets_ii.py | Shiv2157k/leet_code | train | 1 | |
b4fd9bffee583db8cc45237db4c0604fa3a2c574 | [
"super(ChangeAutoPilot, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._activate = activate",
"self._actor.set_autopilot(self._activate)\nnew_status = py_trees.common.Status.SUCCESS\nself.logger.debug('%s.update()[%s->%s]' % (self.__class__.__name__, ... | <|body_start_0|>
super(ChangeAutoPilot, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._actor = actor
self._activate = activate
<|end_body_0|>
<|body_start_1|>
self._actor.set_autopilot(self._activate)
new_status = py_trees.common.... | This class contains an atomic behavior to disable/enable the use of the autopilot. Important parameters: - actor: CARLA actor to execute the behavior - activate: True (=enable autopilot) or False (=disable autopilot) The behavior terminates after changing the autopilot state | ChangeAutoPilot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeAutoPilot:
"""This class contains an atomic behavior to disable/enable the use of the autopilot. Important parameters: - actor: CARLA actor to execute the behavior - activate: True (=enable autopilot) or False (=disable autopilot) The behavior terminates after changing the autopilot state""... | stack_v2_sparse_classes_36k_train_018643 | 39,839 | permissive | [
{
"docstring": "Setup parameters",
"name": "__init__",
"signature": "def __init__(self, actor, activate, name='ChangeAutoPilot')"
},
{
"docstring": "De/activate autopilot",
"name": "update",
"signature": "def update(self)"
}
] | 2 | null | Implement the Python class `ChangeAutoPilot` described below.
Class description:
This class contains an atomic behavior to disable/enable the use of the autopilot. Important parameters: - actor: CARLA actor to execute the behavior - activate: True (=enable autopilot) or False (=disable autopilot) The behavior terminat... | Implement the Python class `ChangeAutoPilot` described below.
Class description:
This class contains an atomic behavior to disable/enable the use of the autopilot. Important parameters: - actor: CARLA actor to execute the behavior - activate: True (=enable autopilot) or False (=disable autopilot) The behavior terminat... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class ChangeAutoPilot:
"""This class contains an atomic behavior to disable/enable the use of the autopilot. Important parameters: - actor: CARLA actor to execute the behavior - activate: True (=enable autopilot) or False (=disable autopilot) The behavior terminates after changing the autopilot state""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChangeAutoPilot:
"""This class contains an atomic behavior to disable/enable the use of the autopilot. Important parameters: - actor: CARLA actor to execute the behavior - activate: True (=enable autopilot) or False (=disable autopilot) The behavior terminates after changing the autopilot state"""
def __... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_behaviors.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
fd75864686c58be668ffc1684dd95ffcb0299608 | [
"path, user, method = (request.path, request.user, request.method)\nif not path.startswith(API_BASE):\n return True\nif method == 'GET':\n return True\nif method in ['POST', 'PUT', 'DELETE']:\n if not user.is_authenticated():\n if 'HTTP_AUTHORIZATION' in request.META:\n auth = request.MET... | <|body_start_0|>
path, user, method = (request.path, request.user, request.method)
if not path.startswith(API_BASE):
return True
if method == 'GET':
return True
if method in ['POST', 'PUT', 'DELETE']:
if not user.is_authenticated():
if ... | CheckPermissions | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckPermissions:
def user_has_perms(self, request):
"""Check if user has permissions for the URL path and method in the request."""
<|body_0|>
def process_request(self, request):
"""Return None to allow django request to pass through middleware. Return JSON error wi... | stack_v2_sparse_classes_36k_train_018644 | 2,193 | permissive | [
{
"docstring": "Check if user has permissions for the URL path and method in the request.",
"name": "user_has_perms",
"signature": "def user_has_perms(self, request)"
},
{
"docstring": "Return None to allow django request to pass through middleware. Return JSON error with status code 403 if user... | 2 | null | Implement the Python class `CheckPermissions` described below.
Class description:
Implement the CheckPermissions class.
Method signatures and docstrings:
- def user_has_perms(self, request): Check if user has permissions for the URL path and method in the request.
- def process_request(self, request): Return None to ... | Implement the Python class `CheckPermissions` described below.
Class description:
Implement the CheckPermissions class.
Method signatures and docstrings:
- def user_has_perms(self, request): Check if user has permissions for the URL path and method in the request.
- def process_request(self, request): Return None to ... | 708035e8d2299e70a6d3cecce40970242673426c | <|skeleton|>
class CheckPermissions:
def user_has_perms(self, request):
"""Check if user has permissions for the URL path and method in the request."""
<|body_0|>
def process_request(self, request):
"""Return None to allow django request to pass through middleware. Return JSON error wi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckPermissions:
def user_has_perms(self, request):
"""Check if user has permissions for the URL path and method in the request."""
path, user, method = (request.path, request.user, request.method)
if not path.startswith(API_BASE):
return True
if method == 'GET':
... | the_stack_v2_python_sparse | gazetteer/middleware/permissions.py | NYPL/gazetteer | train | 5 | |
9d2be85fcbc878abfcef49e9a6ef17ad071ae8a4 | [
"group = handle.create_group('entry/data_processing')\ngroup.attrs['num_reflections'] = len(reflections)\nfor key, data in reflections.cols():\n self.encode_column(group, key, data)",
"from dials.array_family import flex\nif isinstance(data, flex.shoebox):\n self.encode_shoebox(group, key, data)\nelse:\n ... | <|body_start_0|>
group = handle.create_group('entry/data_processing')
group.attrs['num_reflections'] = len(reflections)
for key, data in reflections.cols():
self.encode_column(group, key, data)
<|end_body_0|>
<|body_start_1|>
from dials.array_family import flex
if is... | Encoder for the reflection data. | ReflectionListEncoder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflectionListEncoder:
"""Encoder for the reflection data."""
def encode(self, reflections, handle):
"""Encode the reflection data."""
<|body_0|>
def encode_column(self, group, key, data):
"""Encode a column of data."""
<|body_1|>
def encode_shoebox(... | stack_v2_sparse_classes_36k_train_018645 | 5,824 | permissive | [
{
"docstring": "Encode the reflection data.",
"name": "encode",
"signature": "def encode(self, reflections, handle)"
},
{
"docstring": "Encode a column of data.",
"name": "encode_column",
"signature": "def encode_column(self, group, key, data)"
},
{
"docstring": "Encode a column ... | 3 | stack_v2_sparse_classes_30k_train_008838 | Implement the Python class `ReflectionListEncoder` described below.
Class description:
Encoder for the reflection data.
Method signatures and docstrings:
- def encode(self, reflections, handle): Encode the reflection data.
- def encode_column(self, group, key, data): Encode a column of data.
- def encode_shoebox(self... | Implement the Python class `ReflectionListEncoder` described below.
Class description:
Encoder for the reflection data.
Method signatures and docstrings:
- def encode(self, reflections, handle): Encode the reflection data.
- def encode_column(self, group, key, data): Encode a column of data.
- def encode_shoebox(self... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class ReflectionListEncoder:
"""Encoder for the reflection data."""
def encode(self, reflections, handle):
"""Encode the reflection data."""
<|body_0|>
def encode_column(self, group, key, data):
"""Encode a column of data."""
<|body_1|>
def encode_shoebox(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReflectionListEncoder:
"""Encoder for the reflection data."""
def encode(self, reflections, handle):
"""Encode the reflection data."""
group = handle.create_group('entry/data_processing')
group.attrs['num_reflections'] = len(reflections)
for key, data in reflections.cols()... | the_stack_v2_python_sparse | src/dials/util/nexus_old.py | dials/dials | train | 71 |
10fabfd281a8860bd1379d066709440578e617ec | [
"if longUrl in self.full2tiny:\n return 'http://tinyurl.com/' + self.full2tiny[longUrl]\nsuffix = ''\ndec = self.global_counter\nif dec == 0:\n suffix += self.letters[0]\nwhile dec:\n suffix += self.letters[dec % 62]\n dec //= 62\nself.full2tiny[longUrl] = suffix\nself.tiny2full[suffix] = longUrl\nself.... | <|body_start_0|>
if longUrl in self.full2tiny:
return 'http://tinyurl.com/' + self.full2tiny[longUrl]
suffix = ''
dec = self.global_counter
if dec == 0:
suffix += self.letters[0]
while dec:
suffix += self.letters[dec % 62]
dec //= 6... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_018646 | 1,390 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str",
"name": "decode",
"signature": "def decode(self,... | 2 | stack_v2_sparse_classes_30k_train_002987 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | bf71ef64a9c6e93e434e9daa99479989cc80cadb | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
if longUrl in self.full2tiny:
return 'http://tinyurl.com/' + self.full2tiny[longUrl]
suffix = ''
dec = self.global_counter
if dec == 0:
suffi... | the_stack_v2_python_sparse | 535_Encode_and_Decode_TinyURL.py | IrisSunshine/leetcode | train | 0 | |
e398a4c41ca22fd2d8a1a12dbcdbba24801f814c | [
"self.table_name = table_name\nself.partition_key_name = partition_key_name\nself.attribute_name = attribute_name\nself.create_table = create_table\nself.partition_keygen = partition_keygen\nself.dynamodb = dynamodb_resource\nself.__create_table_if_not_exists()",
"try:\n table = self.dynamodb.Table(self.table_... | <|body_start_0|>
self.table_name = table_name
self.partition_key_name = partition_key_name
self.attribute_name = attribute_name
self.create_table = create_table
self.partition_keygen = partition_keygen
self.dynamodb = dynamodb_resource
self.__create_table_if_not_e... | Persistence Adapter implementation using Amazon DynamoDb. Amazon DynamoDb based persistence adapter implementation. This internally uses the AWS Python SDK (`boto3`) to process the dynamodb operations. The adapter tries to create the table if ``create_table`` is set, during initialization. :param table_name: Name of th... | DynamoDbAdapter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamoDbAdapter:
"""Persistence Adapter implementation using Amazon DynamoDb. Amazon DynamoDb based persistence adapter implementation. This internally uses the AWS Python SDK (`boto3`) to process the dynamodb operations. The adapter tries to create the table if ``create_table`` is set, during in... | stack_v2_sparse_classes_36k_train_018647 | 10,458 | permissive | [
{
"docstring": "Persistence Adapter implementation using Amazon DynamoDb. Amazon DynamoDb based persistence adapter implementation. This internally uses the AWS Python SDK (`boto3`) to process the dynamodb operations. The adapter tries to create the table if `create_table` is set, during initialization. :param ... | 5 | stack_v2_sparse_classes_30k_train_005255 | Implement the Python class `DynamoDbAdapter` described below.
Class description:
Persistence Adapter implementation using Amazon DynamoDb. Amazon DynamoDb based persistence adapter implementation. This internally uses the AWS Python SDK (`boto3`) to process the dynamodb operations. The adapter tries to create the tabl... | Implement the Python class `DynamoDbAdapter` described below.
Class description:
Persistence Adapter implementation using Amazon DynamoDb. Amazon DynamoDb based persistence adapter implementation. This internally uses the AWS Python SDK (`boto3`) to process the dynamodb operations. The adapter tries to create the tabl... | 7e13ca69b240985584dff6ec633a27598a154ca1 | <|skeleton|>
class DynamoDbAdapter:
"""Persistence Adapter implementation using Amazon DynamoDb. Amazon DynamoDb based persistence adapter implementation. This internally uses the AWS Python SDK (`boto3`) to process the dynamodb operations. The adapter tries to create the table if ``create_table`` is set, during in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamoDbAdapter:
"""Persistence Adapter implementation using Amazon DynamoDb. Amazon DynamoDb based persistence adapter implementation. This internally uses the AWS Python SDK (`boto3`) to process the dynamodb operations. The adapter tries to create the table if ``create_table`` is set, during initialization.... | the_stack_v2_python_sparse | ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py | alexa/alexa-skills-kit-sdk-for-python | train | 560 |
6e09b9348643e6e8cbda2bede42b4579d6b0e20f | [
"sim_scene = MockSimScene(nq=10)\nrobot = DynamixelRobotComponent(sim_scene, groups={'a': {'qpos_indices': [0, 1, 3, 5], 'motor_ids': [10, 20, 12, 21], 'calib_scale': [0.5] * 4, 'calib_offset': [1] * 4}, 'b': {'qpos_indices': [2, 6]}, 'c': {'motor_ids': [22, 24]}}, device_path='test')\ndxl = DynamixelRobotComponent... | <|body_start_0|>
sim_scene = MockSimScene(nq=10)
robot = DynamixelRobotComponent(sim_scene, groups={'a': {'qpos_indices': [0, 1, 3, 5], 'motor_ids': [10, 20, 12, 21], 'calib_scale': [0.5] * 4, 'calib_offset': [1] * 4}, 'b': {'qpos_indices': [2, 6]}, 'c': {'motor_ids': [22, 24]}}, device_path='test')
... | Unit test class for RobotComponent. | RobotComponentTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RobotComponentTest:
"""Unit test class for RobotComponent."""
def test_get_state(self):
"""Tests querying the state of multiple groups."""
<|body_0|>
def test_step(self):
"""Tests stepping with an action for multiple groups."""
<|body_1|>
def test_se... | stack_v2_sparse_classes_36k_train_018648 | 6,907 | permissive | [
{
"docstring": "Tests querying the state of multiple groups.",
"name": "test_get_state",
"signature": "def test_get_state(self)"
},
{
"docstring": "Tests stepping with an action for multiple groups.",
"name": "test_step",
"signature": "def test_step(self)"
},
{
"docstring": "Test... | 4 | stack_v2_sparse_classes_30k_train_000571 | Implement the Python class `RobotComponentTest` described below.
Class description:
Unit test class for RobotComponent.
Method signatures and docstrings:
- def test_get_state(self): Tests querying the state of multiple groups.
- def test_step(self): Tests stepping with an action for multiple groups.
- def test_set_st... | Implement the Python class `RobotComponentTest` described below.
Class description:
Unit test class for RobotComponent.
Method signatures and docstrings:
- def test_get_state(self): Tests querying the state of multiple groups.
- def test_step(self): Tests stepping with an action for multiple groups.
- def test_set_st... | bdba0b58c4a01e0742e97299ce3bd1587ad2aa25 | <|skeleton|>
class RobotComponentTest:
"""Unit test class for RobotComponent."""
def test_get_state(self):
"""Tests querying the state of multiple groups."""
<|body_0|>
def test_step(self):
"""Tests stepping with an action for multiple groups."""
<|body_1|>
def test_se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RobotComponentTest:
"""Unit test class for RobotComponent."""
def test_get_state(self):
"""Tests querying the state of multiple groups."""
sim_scene = MockSimScene(nq=10)
robot = DynamixelRobotComponent(sim_scene, groups={'a': {'qpos_indices': [0, 1, 3, 5], 'motor_ids': [10, 20, 1... | the_stack_v2_python_sparse | adept_envs/components/robot/dynamixel_robot_test.py | google-research/DBAP-simulation | train | 3 |
6b04bb6d719f32a86b1bc83ce357179226385ced | [
"self.kl_weight = 1e-08\nself.num_hypotheses = num_hypotheses\nself.outputs = outputs\nif weights is None:\n self.weights = [1.0] * len(self.outputs)\nelse:\n self.weights = weights\nif stats is not None and len(stats) > 0:\n if len(stats) == 1:\n stats = stats * self.num_hypotheses\n self.st... | <|body_start_0|>
self.kl_weight = 1e-08
self.num_hypotheses = num_hypotheses
self.outputs = outputs
if weights is None:
self.weights = [1.0] * len(self.outputs)
else:
self.weights = weights
if stats is not None and len(stats) > 0:
if le... | This version of the MHP loss assumes that it will receive multiple outputs. | MhpLossWithShape | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MhpLossWithShape:
"""This version of the MHP loss assumes that it will receive multiple outputs."""
def __init__(self, num_hypotheses, outputs, weights=None, loss='mse', avg_weight=0.05, stats=[]):
"""Parameters: ----------- num_hypotheses: number of hypotheses outputs: length of eac... | stack_v2_sparse_classes_36k_train_018649 | 7,780 | permissive | [
{
"docstring": "Parameters: ----------- num_hypotheses: number of hypotheses outputs: length of each output weights: None or vector of weights for each target loss: loss function or vector of loss function names to use (keras) avg_weight: amount of weight to give to average loss across all hypotheses stats: mea... | 2 | stack_v2_sparse_classes_30k_val_000683 | Implement the Python class `MhpLossWithShape` described below.
Class description:
This version of the MHP loss assumes that it will receive multiple outputs.
Method signatures and docstrings:
- def __init__(self, num_hypotheses, outputs, weights=None, loss='mse', avg_weight=0.05, stats=[]): Parameters: ----------- nu... | Implement the Python class `MhpLossWithShape` described below.
Class description:
This version of the MHP loss assumes that it will receive multiple outputs.
Method signatures and docstrings:
- def __init__(self, num_hypotheses, outputs, weights=None, loss='mse', avg_weight=0.05, stats=[]): Parameters: ----------- nu... | be5c12f9d0e9d7078e6a5c283d3be059e7f3d040 | <|skeleton|>
class MhpLossWithShape:
"""This version of the MHP loss assumes that it will receive multiple outputs."""
def __init__(self, num_hypotheses, outputs, weights=None, loss='mse', avg_weight=0.05, stats=[]):
"""Parameters: ----------- num_hypotheses: number of hypotheses outputs: length of eac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MhpLossWithShape:
"""This version of the MHP loss assumes that it will receive multiple outputs."""
def __init__(self, num_hypotheses, outputs, weights=None, loss='mse', avg_weight=0.05, stats=[]):
"""Parameters: ----------- num_hypotheses: number of hypotheses outputs: length of each output weig... | the_stack_v2_python_sparse | costar_models/python/costar_models/mhp_loss.py | lk-greenbird/costar_plan | train | 0 |
d7574f28e4db453db0a88019d12ef1d5568176c6 | [
"super(ModelSelector, self).__init__(None, neg_sample_generator)\nself.models = models\nself.lookup = lookup",
"model_batches = dict()\nfor model_name, _ in list(self.models.items()):\n model_batches[model_name] = dict()\n mask = [self.lookup[elem] == model_name for elem in pra.tolist()]\n model_batches[... | <|body_start_0|>
super(ModelSelector, self).__init__(None, neg_sample_generator)
self.models = models
self.lookup = lookup
<|end_body_0|>
<|body_start_1|>
model_batches = dict()
for model_name, _ in list(self.models.items()):
model_batches[model_name] = dict()
... | Emsemble model with choose model by given relation with performance of model | ModelSelector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelSelector:
"""Emsemble model with choose model by given relation with performance of model"""
def __init__(self, models, neg_sample_generator, lookup):
"""init model selector with list of models and lookup :param models: list of models :param lookup: A dict with (relation id, bes... | stack_v2_sparse_classes_36k_train_018650 | 5,944 | permissive | [
{
"docstring": "init model selector with list of models and lookup :param models: list of models :param lookup: A dict with (relation id, best_performed_model)",
"name": "__init__",
"signature": "def __init__(self, models, neg_sample_generator, lookup)"
},
{
"docstring": "Splits batchs per relat... | 4 | stack_v2_sparse_classes_30k_val_000910 | Implement the Python class `ModelSelector` described below.
Class description:
Emsemble model with choose model by given relation with performance of model
Method signatures and docstrings:
- def __init__(self, models, neg_sample_generator, lookup): init model selector with list of models and lookup :param models: li... | Implement the Python class `ModelSelector` described below.
Class description:
Emsemble model with choose model by given relation with performance of model
Method signatures and docstrings:
- def __init__(self, models, neg_sample_generator, lookup): init model selector with list of models and lookup :param models: li... | 0bf63bf210f506e287f8492e716bb3394137d74b | <|skeleton|>
class ModelSelector:
"""Emsemble model with choose model by given relation with performance of model"""
def __init__(self, models, neg_sample_generator, lookup):
"""init model selector with list of models and lookup :param models: list of models :param lookup: A dict with (relation id, bes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelSelector:
"""Emsemble model with choose model by given relation with performance of model"""
def __init__(self, models, neg_sample_generator, lookup):
"""init model selector with list of models and lookup :param models: list of models :param lookup: A dict with (relation id, best_performed_m... | the_stack_v2_python_sparse | src/models/ensemble/model_selector.py | wang-yuhao/Practical-Big-Data-Science-ADL-AI | train | 0 |
61fb353296b05ae2ce3c47000c2daa3a1f04acc0 | [
"super().__init__(containers=containers, image=pygame.Surface((1, 1)), start=start)\nself.font_size = font_size\nself.color = color\nself.text = text\nself.update_image()",
"font = pygame.font.SysFont('mono', self.font_size)\nimg = font.render(self.text, True, self.color)\nself.set_image(img)",
"if text != self... | <|body_start_0|>
super().__init__(containers=containers, image=pygame.Surface((1, 1)), start=start)
self.font_size = font_size
self.color = color
self.text = text
self.update_image()
<|end_body_0|>
<|body_start_1|>
font = pygame.font.SysFont('mono', self.font_size)
... | A sprite that contains text | TextSprite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextSprite:
"""A sprite that contains text"""
def __init__(self, containers, text, start, font_size=24, color=(255, 255, 255)):
"""Creates the TextSprite"""
<|body_0|>
def update_image(self):
"""Updates the image used for this sprite"""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_018651 | 7,153 | no_license | [
{
"docstring": "Creates the TextSprite",
"name": "__init__",
"signature": "def __init__(self, containers, text, start, font_size=24, color=(255, 255, 255))"
},
{
"docstring": "Updates the image used for this sprite",
"name": "update_image",
"signature": "def update_image(self)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_012559 | Implement the Python class `TextSprite` described below.
Class description:
A sprite that contains text
Method signatures and docstrings:
- def __init__(self, containers, text, start, font_size=24, color=(255, 255, 255)): Creates the TextSprite
- def update_image(self): Updates the image used for this sprite
- def se... | Implement the Python class `TextSprite` described below.
Class description:
A sprite that contains text
Method signatures and docstrings:
- def __init__(self, containers, text, start, font_size=24, color=(255, 255, 255)): Creates the TextSprite
- def update_image(self): Updates the image used for this sprite
- def se... | 8604a243baeecdd393a54c18bf2ff9e003b4b8a0 | <|skeleton|>
class TextSprite:
"""A sprite that contains text"""
def __init__(self, containers, text, start, font_size=24, color=(255, 255, 255)):
"""Creates the TextSprite"""
<|body_0|>
def update_image(self):
"""Updates the image used for this sprite"""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextSprite:
"""A sprite that contains text"""
def __init__(self, containers, text, start, font_size=24, color=(255, 255, 255)):
"""Creates the TextSprite"""
super().__init__(containers=containers, image=pygame.Surface((1, 1)), start=start)
self.font_size = font_size
self.c... | the_stack_v2_python_sparse | src/sprite/sprite_library.py | ZXQYC/random-shooter-game | train | 0 |
1e355e32f09d4aaeb7f755e55e7c95da330b3f70 | [
"try:\n tree = ast.parse(expr)\nexcept SyntaxError:\n raise ValueError(_('Illegal syntax in equation'))\nself.visit(tree)",
"if node.func.id in allowedFunctions:\n super().generic_visit(node)\nelse:\n raise ValueError(_('Illegal function present: {0}').format(node.func.id))",
"if type(node).__name__... | <|body_start_0|>
try:
tree = ast.parse(expr)
except SyntaxError:
raise ValueError(_('Illegal syntax in equation'))
self.visit(tree)
<|end_body_0|>
<|body_start_1|>
if node.func.id in allowedFunctions:
super().generic_visit(node)
else:
... | Class to check that only safe functions are used in an eval expression. Raises a ValueError if unsafe or non-numeric operations are present. Ref. stackoverflow.com questions 10661079 and 12523516 | SafeEvalChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SafeEvalChecker:
"""Class to check that only safe functions are used in an eval expression. Raises a ValueError if unsafe or non-numeric operations are present. Ref. stackoverflow.com questions 10661079 and 12523516"""
def check(self, expr):
"""Check the given expression for non-nume... | stack_v2_sparse_classes_36k_train_018652 | 21,625 | no_license | [
{
"docstring": "Check the given expression for non-numeric operations. Arguments: expr -- the expression string to check",
"name": "check",
"signature": "def check(self, expr)"
},
{
"docstring": "Check for allowed functions only. Arguments: node -- the ast node being checked",
"name": "visit... | 3 | null | Implement the Python class `SafeEvalChecker` described below.
Class description:
Class to check that only safe functions are used in an eval expression. Raises a ValueError if unsafe or non-numeric operations are present. Ref. stackoverflow.com questions 10661079 and 12523516
Method signatures and docstrings:
- def c... | Implement the Python class `SafeEvalChecker` described below.
Class description:
Class to check that only safe functions are used in an eval expression. Raises a ValueError if unsafe or non-numeric operations are present. Ref. stackoverflow.com questions 10661079 and 12523516
Method signatures and docstrings:
- def c... | c9429496e8ed15116746a23f3a90f262cf54f755 | <|skeleton|>
class SafeEvalChecker:
"""Class to check that only safe functions are used in an eval expression. Raises a ValueError if unsafe or non-numeric operations are present. Ref. stackoverflow.com questions 10661079 and 12523516"""
def check(self, expr):
"""Check the given expression for non-nume... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SafeEvalChecker:
"""Class to check that only safe functions are used in an eval expression. Raises a ValueError if unsafe or non-numeric operations are present. Ref. stackoverflow.com questions 10661079 and 12523516"""
def check(self, expr):
"""Check the given expression for non-numeric operation... | the_stack_v2_python_sparse | source/matheval.py | doug-101/TreeLine | train | 121 |
01bf75baf7cb98762e200a8204fb6955182faae5 | [
"res = -1\nc = collections.Counter(arr)\nfor i in c:\n if c[i] == i:\n res = max(res, i)\nreturn res",
"res = -1\ndic = collections.defaultdict(int)\nfor i in arr:\n dic[i] += 1\nfor k in dic.keys():\n if dic[k] == k and k > res:\n res = k\nreturn res",
"res = -1\ndic = {}\nfor i in arr:\... | <|body_start_0|>
res = -1
c = collections.Counter(arr)
for i in c:
if c[i] == i:
res = max(res, i)
return res
<|end_body_0|>
<|body_start_1|>
res = -1
dic = collections.defaultdict(int)
for i in arr:
dic[i] += 1
for... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLucky(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def findLucky(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
def findLucky(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_018653 | 965 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "findLucky",
"signature": "def findLucky(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "findLucky",
"signature": "def findLucky(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLucky(self, arr): :type arr: List[int] :rtype: int
- def findLucky(self, arr): :type arr: List[int] :rtype: int
- def findLucky(self, arr): :type arr: List[int] :rtype: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLucky(self, arr): :type arr: List[int] :rtype: int
- def findLucky(self, arr): :type arr: List[int] :rtype: int
- def findLucky(self, arr): :type arr: List[int] :rtype: i... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findLucky(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def findLucky(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
def findLucky(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLucky(self, arr):
""":type arr: List[int] :rtype: int"""
res = -1
c = collections.Counter(arr)
for i in c:
if c[i] == i:
res = max(res, i)
return res
def findLucky(self, arr):
""":type arr: List[int] :rtype: int... | the_stack_v2_python_sparse | 1394_Find_Lucky_Integer_in_an_Array.py | bingli8802/leetcode | train | 0 | |
c8cfb2de958f6877e8dd000425c5da770cbbec62 | [
"try:\n booster, format = serve_utils.get_loaded_booster(model_dir, serve_utils.is_ensemble_enabled())\nexcept Exception as e:\n raise ModelLoadInferenceError('Unable to load model: {}'.format(str(e)))\nreturn (booster, format)",
"if len(input_data) == 0:\n raise NoContentInferenceError()\ndtest, content... | <|body_start_0|>
try:
booster, format = serve_utils.get_loaded_booster(model_dir, serve_utils.is_ensemble_enabled())
except Exception as e:
raise ModelLoadInferenceError('Unable to load model: {}'.format(str(e)))
return (booster, format)
<|end_body_0|>
<|body_start_1|>
... | DefaultXGBoostAlgoModeInferenceHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultXGBoostAlgoModeInferenceHandler:
def default_model_fn(self, model_dir):
"""Load a model. For XGBoost Framework, a default function to load a model is not provided. Users should provide customized model_fn() in script. Args: model_dir: a directory where model is saved. Returns: A X... | stack_v2_sparse_classes_36k_train_018654 | 6,195 | permissive | [
{
"docstring": "Load a model. For XGBoost Framework, a default function to load a model is not provided. Users should provide customized model_fn() in script. Args: model_dir: a directory where model is saved. Returns: A XGBoost model. XGBoost model format type.",
"name": "default_model_fn",
"signature"... | 4 | stack_v2_sparse_classes_30k_test_000826 | Implement the Python class `DefaultXGBoostAlgoModeInferenceHandler` described below.
Class description:
Implement the DefaultXGBoostAlgoModeInferenceHandler class.
Method signatures and docstrings:
- def default_model_fn(self, model_dir): Load a model. For XGBoost Framework, a default function to load a model is not ... | Implement the Python class `DefaultXGBoostAlgoModeInferenceHandler` described below.
Class description:
Implement the DefaultXGBoostAlgoModeInferenceHandler class.
Method signatures and docstrings:
- def default_model_fn(self, model_dir): Load a model. For XGBoost Framework, a default function to load a model is not ... | d2b7e83038956e158d2b07c809026a8ffb2e832c | <|skeleton|>
class DefaultXGBoostAlgoModeInferenceHandler:
def default_model_fn(self, model_dir):
"""Load a model. For XGBoost Framework, a default function to load a model is not provided. Users should provide customized model_fn() in script. Args: model_dir: a directory where model is saved. Returns: A X... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultXGBoostAlgoModeInferenceHandler:
def default_model_fn(self, model_dir):
"""Load a model. For XGBoost Framework, a default function to load a model is not provided. Users should provide customized model_fn() in script. Args: model_dir: a directory where model is saved. Returns: A XGBoost model. ... | the_stack_v2_python_sparse | src/sagemaker_xgboost_container/algorithm_mode/handler_service.py | aws/sagemaker-xgboost-container | train | 107 | |
7cfcaa264270376d26b5636d418894e47728364c | [
"super(QCILRenderWindowInteractor, self).__init__(parent, **kw)\nself.__saveModifiers = self._QVTKRenderWindowInteractor__saveModifiers\nself.__saveX = self._QVTKRenderWindowInteractor__saveX\nself.__saveY = self._QVTKRenderWindowInteractor__saveY\nself.__saveButtons = self._QVTKRenderWindowInteractor__saveButtons\... | <|body_start_0|>
super(QCILRenderWindowInteractor, self).__init__(parent, **kw)
self.__saveModifiers = self._QVTKRenderWindowInteractor__saveModifiers
self.__saveX = self._QVTKRenderWindowInteractor__saveX
self.__saveY = self._QVTKRenderWindowInteractor__saveY
self.__saveButtons ... | Extends the QVTKRenderWindowInteractor to accept also ALT modifier | QCILRenderWindowInteractor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCILRenderWindowInteractor:
"""Extends the QVTKRenderWindowInteractor to accept also ALT modifier"""
def __init__(self, parent=None, **kw):
"""Constructor"""
<|body_0|>
def _GetCtrlShiftAlt(self, ev):
"""Get CTRL SHIFT ALT key modifiers"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_018655 | 3,441 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent=None, **kw)"
},
{
"docstring": "Get CTRL SHIFT ALT key modifiers",
"name": "_GetCtrlShiftAlt",
"signature": "def _GetCtrlShiftAlt(self, ev)"
},
{
"docstring": "Overload of enterEvent from ba... | 6 | stack_v2_sparse_classes_30k_train_018143 | Implement the Python class `QCILRenderWindowInteractor` described below.
Class description:
Extends the QVTKRenderWindowInteractor to accept also ALT modifier
Method signatures and docstrings:
- def __init__(self, parent=None, **kw): Constructor
- def _GetCtrlShiftAlt(self, ev): Get CTRL SHIFT ALT key modifiers
- def... | Implement the Python class `QCILRenderWindowInteractor` described below.
Class description:
Extends the QVTKRenderWindowInteractor to accept also ALT modifier
Method signatures and docstrings:
- def __init__(self, parent=None, **kw): Constructor
- def _GetCtrlShiftAlt(self, ev): Get CTRL SHIFT ALT key modifiers
- def... | 8c7caca5a78d0f83658a25409abf8291f4a802b7 | <|skeleton|>
class QCILRenderWindowInteractor:
"""Extends the QVTKRenderWindowInteractor to accept also ALT modifier"""
def __init__(self, parent=None, **kw):
"""Constructor"""
<|body_0|>
def _GetCtrlShiftAlt(self, ev):
"""Get CTRL SHIFT ALT key modifiers"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QCILRenderWindowInteractor:
"""Extends the QVTKRenderWindowInteractor to accept also ALT modifier"""
def __init__(self, parent=None, **kw):
"""Constructor"""
super(QCILRenderWindowInteractor, self).__init__(parent, **kw)
self.__saveModifiers = self._QVTKRenderWindowInteractor__sav... | the_stack_v2_python_sparse | Wrappers/Python/ccpi/viewer/QCILRenderWindowInteractor.py | vais-ral/CILViewer | train | 9 |
511c410619dbb944c3caa8ea607d48ffb9496a60 | [
"self.driver = get_ibmcloud_client(username=username, password=password)\nself.node = None\nself._subnet: list = list()\nself._roles: list = list()\nself.root_login: str\nself.osd_scenario: int\nself.keypair: Optional[str] = None",
"LOG.info('Starting to create VM with name %s', node_name)\ntry:\n ibmcloud_cli... | <|body_start_0|>
self.driver = get_ibmcloud_client(username=username, password=password)
self.node = None
self._subnet: list = list()
self._roles: list = list()
self.root_login: str
self.osd_scenario: int
self.keypair: Optional[str] = None
<|end_body_0|>
<|body_s... | Represent the VMNode required for cephci. | CephVMNodeV2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CephVMNodeV2:
"""Represent the VMNode required for cephci."""
def __init__(self, username: str, password: str, **kwargs) -> None:
"""Initialize the instance using the provided information. The co Args: username: The name of the user to be set for the session. password: The password o... | stack_v2_sparse_classes_36k_train_018656 | 4,786 | permissive | [
{
"docstring": "Initialize the instance using the provided information. The co Args: username: The name of the user to be set for the session. password: The password of the provided user. domain_name: The authentication domain to be used. node_name: The name of the node to be retrieved.",
"name": "__init__"... | 2 | null | Implement the Python class `CephVMNodeV2` described below.
Class description:
Represent the VMNode required for cephci.
Method signatures and docstrings:
- def __init__(self, username: str, password: str, **kwargs) -> None: Initialize the instance using the provided information. The co Args: username: The name of the... | Implement the Python class `CephVMNodeV2` described below.
Class description:
Represent the VMNode required for cephci.
Method signatures and docstrings:
- def __init__(self, username: str, password: str, **kwargs) -> None: Initialize the instance using the provided information. The co Args: username: The name of the... | 0691fbaf8fca2a9cd051c5049c83758c65301654 | <|skeleton|>
class CephVMNodeV2:
"""Represent the VMNode required for cephci."""
def __init__(self, username: str, password: str, **kwargs) -> None:
"""Initialize the instance using the provided information. The co Args: username: The name of the user to be set for the session. password: The password o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CephVMNodeV2:
"""Represent the VMNode required for cephci."""
def __init__(self, username: str, password: str, **kwargs) -> None:
"""Initialize the instance using the provided information. The co Args: username: The name of the user to be set for the session. password: The password of the provide... | the_stack_v2_python_sparse | compute/ibmcloud.py | red-hat-storage/cephci | train | 28 |
1bff539b258768f318a099defa4a8f8db36b65f7 | [
"count = 0\nfor i in J:\n for j in S:\n if i == j:\n count += 1\nreturn count",
"nums = 0\nslen = len(s)\nmiddle = ''\nif slen <= 1:\n return slen\nfor i in range(slen):\n if s[i] in middle:\n if len(middle) > nums:\n nums = len(middle)\n middle = middle[1:]\n ... | <|body_start_0|>
count = 0
for i in J:
for j in S:
if i == j:
count += 1
return count
<|end_body_0|>
<|body_start_1|>
nums = 0
slen = len(s)
middle = ''
if slen <= 1:
return slen
for i in range(s... | hash | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""hash"""
def numJewelsInStones(self, J, S):
"""宝石与石头 :type J: str :type S: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring(self, s):
"""无重复字符的最长子串 eg: "abcabcbb" 3 :type s: str :rtype: int"""
<|body_1|>
def titleToNumber(self, ... | stack_v2_sparse_classes_36k_train_018657 | 2,106 | no_license | [
{
"docstring": "宝石与石头 :type J: str :type S: str :rtype: int",
"name": "numJewelsInStones",
"signature": "def numJewelsInStones(self, J, S)"
},
{
"docstring": "无重复字符的最长子串 eg: \"abcabcbb\" 3 :type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSub... | 3 | null | Implement the Python class `Solution` described below.
Class description:
hash
Method signatures and docstrings:
- def numJewelsInStones(self, J, S): 宝石与石头 :type J: str :type S: str :rtype: int
- def lengthOfLongestSubstring(self, s): 无重复字符的最长子串 eg: "abcabcbb" 3 :type s: str :rtype: int
- def titleToNumber(self, s: s... | Implement the Python class `Solution` described below.
Class description:
hash
Method signatures and docstrings:
- def numJewelsInStones(self, J, S): 宝石与石头 :type J: str :type S: str :rtype: int
- def lengthOfLongestSubstring(self, s): 无重复字符的最长子串 eg: "abcabcbb" 3 :type s: str :rtype: int
- def titleToNumber(self, s: s... | 94084e64b1d7582b0b77c785f915ed2218e398e6 | <|skeleton|>
class Solution:
"""hash"""
def numJewelsInStones(self, J, S):
"""宝石与石头 :type J: str :type S: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring(self, s):
"""无重复字符的最长子串 eg: "abcabcbb" 3 :type s: str :rtype: int"""
<|body_1|>
def titleToNumber(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""hash"""
def numJewelsInStones(self, J, S):
"""宝石与石头 :type J: str :type S: str :rtype: int"""
count = 0
for i in J:
for j in S:
if i == j:
count += 1
return count
def lengthOfLongestSubstring(self, s):
... | the_stack_v2_python_sparse | source/mediaTask/leetcode/explore/lc_hash.py | Lewic1201/pythonDemo | train | 3 |
2d405e67146f82aeae513417457fce2635ba3dcb | [
"if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\nm = len(matrix)\nn = len(matrix[0])\ndp = [[0] * n for _ in range(m)]\nans = 0\nfor i in range(m):\n for j in range(n):\n if matrix[i][j] == '1':\n if i == 0 or j == 0:\n dp[i][j] = 1\n else:\n ... | <|body_start_0|>
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
m = len(matrix)
n = len(matrix[0])
dp = [[0] * n for _ in range(m)]
ans = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
if i... | dp(i,j) 表示以 (i, j)(i,j) 为右下角,且只包含 11 的正方形的边长最大值 对于每个位置 (i, j)(i,j),检查在矩阵中该位置的值: 如果该位置的值是 00,则 dp(i, j) = 0dp(i,j)=0,因为当前位置不可能在由 11 组成的正方形中; 如果该位置的值是 11,则 dp(i, j)dp(i,j) 的值由其上方、左方和左上方的三个相邻位置的 dpdp 值决定。具体而言,当前位置的元素值等于三个相邻位置的元素中的最小值加 11,状态转移方程如下: dp(i, j)=min(dp(i−1, j), dp(i−1, j−1), dp(i, j−1))+1 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""dp(i,j) 表示以 (i, j)(i,j) 为右下角,且只包含 11 的正方形的边长最大值 对于每个位置 (i, j)(i,j),检查在矩阵中该位置的值: 如果该位置的值是 00,则 dp(i, j) = 0dp(i,j)=0,因为当前位置不可能在由 11 组成的正方形中; 如果该位置的值是 11,则 dp(i, j)dp(i,j) 的值由其上方、左方和左上方的三个相邻位置的 dpdp 值决定。具体而言,当前位置的元素值等于三个相邻位置的元素中的最小值加 11,状态转移方程如下: dp(i, j)=min(dp(i−1, j), dp(i−1, j−1), ... | stack_v2_sparse_classes_36k_train_018658 | 3,398 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
dp(i,j) 表示以 (i, j)(i,j) 为右下角,且只包含 11 的正方形的边长最大值 对于每个位置 (i, j)(i,j),检查在矩阵中该位置的值: 如果该位置的值是 00,则 dp(i, j) = 0dp(i,j)=0,因为当前位置不可能在由 11 组成的正方形中; 如果该位置的值是 11,则 dp(i, j)dp(i,j) 的值由其上方、左方和左上方的三个相邻位置的 dpdp 值决定。具体而言,当前位置的元素值等于三个相邻位置的元素中的最小值加 11,状态转移方程如下: ... | Implement the Python class `Solution` described below.
Class description:
dp(i,j) 表示以 (i, j)(i,j) 为右下角,且只包含 11 的正方形的边长最大值 对于每个位置 (i, j)(i,j),检查在矩阵中该位置的值: 如果该位置的值是 00,则 dp(i, j) = 0dp(i,j)=0,因为当前位置不可能在由 11 组成的正方形中; 如果该位置的值是 11,则 dp(i, j)dp(i,j) 的值由其上方、左方和左上方的三个相邻位置的 dpdp 值决定。具体而言,当前位置的元素值等于三个相邻位置的元素中的最小值加 11,状态转移方程如下: ... | c162817f717b78997197649c084c27af48c3fd6f | <|skeleton|>
class Solution:
"""dp(i,j) 表示以 (i, j)(i,j) 为右下角,且只包含 11 的正方形的边长最大值 对于每个位置 (i, j)(i,j),检查在矩阵中该位置的值: 如果该位置的值是 00,则 dp(i, j) = 0dp(i,j)=0,因为当前位置不可能在由 11 组成的正方形中; 如果该位置的值是 11,则 dp(i, j)dp(i,j) 的值由其上方、左方和左上方的三个相邻位置的 dpdp 值决定。具体而言,当前位置的元素值等于三个相邻位置的元素中的最小值加 11,状态转移方程如下: dp(i, j)=min(dp(i−1, j), dp(i−1, j−1), ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""dp(i,j) 表示以 (i, j)(i,j) 为右下角,且只包含 11 的正方形的边长最大值 对于每个位置 (i, j)(i,j),检查在矩阵中该位置的值: 如果该位置的值是 00,则 dp(i, j) = 0dp(i,j)=0,因为当前位置不可能在由 11 组成的正方形中; 如果该位置的值是 11,则 dp(i, j)dp(i,j) 的值由其上方、左方和左上方的三个相邻位置的 dpdp 值决定。具体而言,当前位置的元素值等于三个相邻位置的元素中的最小值加 11,状态转移方程如下: dp(i, j)=min(dp(i−1, j), dp(i−1, j−1), dp(i, j−1))+1... | the_stack_v2_python_sparse | Week_06/221.最大正方形.py | dream201188/algorithm017 | train | 1 |
dcbb5323d2dcea15a3658048558a97125e057866 | [
"final_queens = []\n\ndef back(queen_str):\n if len(queen_str) == nums:\n final_queens.append(queen_str)\n return\n for col in range(nums):\n flag = self.valid(queen_str, col)\n if not flag:\n back(queen_str + str(col))\nback(queen_str)\nreturn final_queens",
"rows = l... | <|body_start_0|>
final_queens = []
def back(queen_str):
if len(queen_str) == nums:
final_queens.append(queen_str)
return
for col in range(nums):
flag = self.valid(queen_str, col)
if not flag:
bac... | 回溯法思想 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""回溯法思想"""
def queens(self, nums=8, queen_str=''):
""":param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置"""
<|body_0|>
def valid(self, queen_str, current_queen):
""":param queen_str: 当前皇后以前所存的皇后... | stack_v2_sparse_classes_36k_train_018659 | 2,043 | no_license | [
{
"docstring": ":param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置",
"name": "queens",
"signature": "def queens(self, nums=8, queen_str='')"
},
{
"docstring": ":param queen_str: 当前皇后以前所存的皇后的列的位置 :param current_queen: 当前皇后的位置(列) :return: f... | 2 | stack_v2_sparse_classes_30k_train_011585 | Implement the Python class `Solution` described below.
Class description:
回溯法思想
Method signatures and docstrings:
- def queens(self, nums=8, queen_str=''): :param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置
- def valid(self, queen_str, current_queen): :param q... | Implement the Python class `Solution` described below.
Class description:
回溯法思想
Method signatures and docstrings:
- def queens(self, nums=8, queen_str=''): :param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置
- def valid(self, queen_str, current_queen): :param q... | 14fb97af36c5fb1d69439585adb0db0ce9eae45d | <|skeleton|>
class Solution:
"""回溯法思想"""
def queens(self, nums=8, queen_str=''):
""":param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置"""
<|body_0|>
def valid(self, queen_str, current_queen):
""":param queen_str: 当前皇后以前所存的皇后... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""回溯法思想"""
def queens(self, nums=8, queen_str=''):
""":param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置"""
final_queens = []
def back(queen_str):
if len(queen_str) == nums:
final_que... | the_stack_v2_python_sparse | 八皇后问题.py | zhanvwei/targetoffer | train | 0 |
641123d783fd2d06d63f873908c00dcb757940c5 | [
"super().__init__(*args, **kwargs)\nself.model_dir: str = model_dir\nself.config = Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION))\nself.text_field = IntentBPETextField(self.model_dir, config=self.config)\nself.categories = None\nwith open(os.path.join(self.model_dir, 'categories.json'), 'r'... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.model_dir: str = model_dir
self.config = Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION))
self.text_field = IntentBPETextField(self.model_dir, config=self.config)
self.categories = None
with op... | DialogIntentPredictionPreprocessor | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogIntentPredictionPreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
<|body_0|>
def __call__(self, data: str) -> Dict[str, Any]:
"""process the raw input data Args: data (str): a sentence... | stack_v2_sparse_classes_36k_train_018660 | 2,701 | permissive | [
{
"docstring": "preprocess the data Args: model_dir (str): model path",
"name": "__init__",
"signature": "def __init__(self, model_dir: str, *args, **kwargs)"
},
{
"docstring": "process the raw input data Args: data (str): a sentence Example: 'What do I need to do for the card activation?' Retur... | 2 | null | Implement the Python class `DialogIntentPredictionPreprocessor` described below.
Class description:
Implement the DialogIntentPredictionPreprocessor class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): preprocess the data Args: model_dir (str): model path
- def __call__(self... | Implement the Python class `DialogIntentPredictionPreprocessor` described below.
Class description:
Implement the DialogIntentPredictionPreprocessor class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): preprocess the data Args: model_dir (str): model path
- def __call__(self... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DialogIntentPredictionPreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
<|body_0|>
def __call__(self, data: str) -> Dict[str, Any]:
"""process the raw input data Args: data (str): a sentence... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DialogIntentPredictionPreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
super().__init__(*args, **kwargs)
self.model_dir: str = model_dir
self.config = Config.from_file(os.path.join(self.model_dir, Mod... | the_stack_v2_python_sparse | ai/modelscope/modelscope/preprocessors/nlp/space/dialog_intent_prediction_preprocessor.py | alldatacenter/alldata | train | 774 | |
b390870a2607252dfacbc05252b0b5528dea552f | [
"candles_df = self.get_processed_df()\nlast_candle = candles_df.iloc[-1]\nema_8 = last_candle['EMA_8']\nema_54 = last_candle['EMA_54']\ndistance = ema_8 - ema_54\naverage = (ema_8 + ema_54) / 2\ndistance_pct = distance / average\nif distance_pct > self.distance_pct_threshold:\n signal_value = -1\nelif distance_p... | <|body_start_0|>
candles_df = self.get_processed_df()
last_candle = candles_df.iloc[-1]
ema_8 = last_candle['EMA_8']
ema_54 = last_candle['EMA_54']
distance = ema_8 - ema_54
average = (ema_8 + ema_54) / 2
distance_pct = distance / average
if distance_pct >... | WideningEMABands strategy implementation based on the DirectionalStrategyBase. This strategy uses two EMAs one short and one long to generate trading signals and execute trades based on the percentage of distance between them. Parameters: directional_strategy_name (str): The name of the strategy. trading_pair (str): Th... | WideningEMABands | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WideningEMABands:
"""WideningEMABands strategy implementation based on the DirectionalStrategyBase. This strategy uses two EMAs one short and one long to generate trading signals and execute trades based on the percentage of distance between them. Parameters: directional_strategy_name (str): The ... | stack_v2_sparse_classes_36k_train_018661 | 4,268 | permissive | [
{
"docstring": "Generates the trading signal based on the MACD and Bollinger Bands indicators. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy).",
"name": "get_signal",
"signature": "def get_signal(self)"
},
{
"docstring": "Retrieves the processed dataframe with MACD and Bol... | 3 | null | Implement the Python class `WideningEMABands` described below.
Class description:
WideningEMABands strategy implementation based on the DirectionalStrategyBase. This strategy uses two EMAs one short and one long to generate trading signals and execute trades based on the percentage of distance between them. Parameters... | Implement the Python class `WideningEMABands` described below.
Class description:
WideningEMABands strategy implementation based on the DirectionalStrategyBase. This strategy uses two EMAs one short and one long to generate trading signals and execute trades based on the percentage of distance between them. Parameters... | c3f101759ab7e7a2165cd23a3a3e94c90c642a9b | <|skeleton|>
class WideningEMABands:
"""WideningEMABands strategy implementation based on the DirectionalStrategyBase. This strategy uses two EMAs one short and one long to generate trading signals and execute trades based on the percentage of distance between them. Parameters: directional_strategy_name (str): The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WideningEMABands:
"""WideningEMABands strategy implementation based on the DirectionalStrategyBase. This strategy uses two EMAs one short and one long to generate trading signals and execute trades based on the percentage of distance between them. Parameters: directional_strategy_name (str): The name of the s... | the_stack_v2_python_sparse | scripts/directional_strategy_widening_ema_bands.py | CoinAlpha/hummingbot | train | 135 |
08383286f37f34f683898e2b0b196b1cc9d8de5a | [
"if len(chordProgression) < 4:\n print('ERROR IN ChordProgression 2')\n return None\nelse:\n keysForReturn = []\n tempChords = []\n for chord in chordProgression:\n tempChords.append(chord[0])\n tempChords = np.array(tempChords)\n chords = [[tempChords[0], tempChords[1]], [tempChords[2],... | <|body_start_0|>
if len(chordProgression) < 4:
print('ERROR IN ChordProgression 2')
return None
else:
keysForReturn = []
tempChords = []
for chord in chordProgression:
tempChords.append(chord[0])
tempChords = np.arra... | SubMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
<|body_0|>
def cherryB(self, keyProgression, chordProgression):
"""サビで使われているメソッド"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(chordProgression) < 4... | stack_v2_sparse_classes_36k_train_018662 | 12,440 | no_license | [
{
"docstring": "INTROで使われているメソッド",
"name": "cherryIntro",
"signature": "def cherryIntro(self, keyProgression, chordProgression)"
},
{
"docstring": "サビで使われているメソッド",
"name": "cherryB",
"signature": "def cherryB(self, keyProgression, chordProgression)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007223 | Implement the Python class `SubMethods` described below.
Class description:
Implement the SubMethods class.
Method signatures and docstrings:
- def cherryIntro(self, keyProgression, chordProgression): INTROで使われているメソッド
- def cherryB(self, keyProgression, chordProgression): サビで使われているメソッド | Implement the Python class `SubMethods` described below.
Class description:
Implement the SubMethods class.
Method signatures and docstrings:
- def cherryIntro(self, keyProgression, chordProgression): INTROで使われているメソッド
- def cherryB(self, keyProgression, chordProgression): サビで使われているメソッド
<|skeleton|>
class SubMethods:... | 172f486048825d989aac69945c463dd150b84a88 | <|skeleton|>
class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
<|body_0|>
def cherryB(self, keyProgression, chordProgression):
"""サビで使われているメソッド"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
if len(chordProgression) < 4:
print('ERROR IN ChordProgression 2')
return None
else:
keysForReturn = []
tempChords = []
for chord in c... | the_stack_v2_python_sparse | SongGenerator/mikakunin/Composer/ChordProgression.py | ku70t6h1k6r1/auto_music | train | 0 | |
69cced6a40f1ab605316883c24466efcb4abcb3b | [
"if self.public:\n return self.PUBLIC_URI_TEMPLATE.format(registry_alias=self.alias)\nreturn self.URI_TEMPLATE.format(aws_account_id=self.account_id, aws_region=self.region)",
"values.setdefault('public', bool(values.get('alias')))\nif not values['public']:\n account_id = values.get('account_id')\n ctx: ... | <|body_start_0|>
if self.public:
return self.PUBLIC_URI_TEMPLATE.format(registry_alias=self.alias)
return self.URI_TEMPLATE.format(aws_account_id=self.account_id, aws_region=self.region)
<|end_body_0|>
<|body_start_1|>
values.setdefault('public', bool(values.get('alias')))
i... | AWS Elastic Container Registry. | ElasticContainerRegistry | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticContainerRegistry:
"""AWS Elastic Container Registry."""
def fqn(self) -> str:
"""Fully qualified ECR name."""
<|body_0|>
def _set_defaults(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Set default values based on other values."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_018663 | 4,059 | permissive | [
{
"docstring": "Fully qualified ECR name.",
"name": "fqn",
"signature": "def fqn(self) -> str"
},
{
"docstring": "Set default values based on other values.",
"name": "_set_defaults",
"signature": "def _set_defaults(cls, values: Dict[str, Any]) -> Dict[str, Any]"
}
] | 2 | stack_v2_sparse_classes_30k_train_007552 | Implement the Python class `ElasticContainerRegistry` described below.
Class description:
AWS Elastic Container Registry.
Method signatures and docstrings:
- def fqn(self) -> str: Fully qualified ECR name.
- def _set_defaults(cls, values: Dict[str, Any]) -> Dict[str, Any]: Set default values based on other values. | Implement the Python class `ElasticContainerRegistry` described below.
Class description:
AWS Elastic Container Registry.
Method signatures and docstrings:
- def fqn(self) -> str: Fully qualified ECR name.
- def _set_defaults(cls, values: Dict[str, Any]) -> Dict[str, Any]: Set default values based on other values.
<... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class ElasticContainerRegistry:
"""AWS Elastic Container Registry."""
def fqn(self) -> str:
"""Fully qualified ECR name."""
<|body_0|>
def _set_defaults(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Set default values based on other values."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticContainerRegistry:
"""AWS Elastic Container Registry."""
def fqn(self) -> str:
"""Fully qualified ECR name."""
if self.public:
return self.PUBLIC_URI_TEMPLATE.format(registry_alias=self.alias)
return self.URI_TEMPLATE.format(aws_account_id=self.account_id, aws_r... | the_stack_v2_python_sparse | runway/cfngin/hooks/docker/data_models.py | onicagroup/runway | train | 156 |
f6f4c0d0004ae143068f6edd39b83b25cf58ae48 | [
"CONTENTS = 'manifest contents'\nsrc_manifest = os.path.join(self.tempdir, 'src_manifest')\ngit_repo = os.path.join(self.tempdir, 'git_repo')\ndst_manifest = os.path.join(git_repo, 'default.xml')\nosutils.WriteFile(src_manifest, CONTENTS)\nrepository.PrepManifestForRepo(git_repo, src_manifest)\nself.assertEqual(CON... | <|body_start_0|>
CONTENTS = 'manifest contents'
src_manifest = os.path.join(self.tempdir, 'src_manifest')
git_repo = os.path.join(self.tempdir, 'git_repo')
dst_manifest = os.path.join(git_repo, 'default.xml')
osutils.WriteFile(src_manifest, CONTENTS)
repository.PrepManife... | Tests for our ability to init from a local repository. | PrepManifestForRepoTests | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrepManifestForRepoTests:
"""Tests for our ability to init from a local repository."""
def testCreateManifestRepo(self):
"""Test we can create a local git repository with a local manifest."""
<|body_0|>
def testUpdatingManifestRepo(self):
"""Test we can update ma... | stack_v2_sparse_classes_36k_train_018664 | 6,078 | permissive | [
{
"docstring": "Test we can create a local git repository with a local manifest.",
"name": "testCreateManifestRepo",
"signature": "def testCreateManifestRepo(self)"
},
{
"docstring": "Test we can update manifest in a local git repository.",
"name": "testUpdatingManifestRepo",
"signature"... | 2 | null | Implement the Python class `PrepManifestForRepoTests` described below.
Class description:
Tests for our ability to init from a local repository.
Method signatures and docstrings:
- def testCreateManifestRepo(self): Test we can create a local git repository with a local manifest.
- def testUpdatingManifestRepo(self): ... | Implement the Python class `PrepManifestForRepoTests` described below.
Class description:
Tests for our ability to init from a local repository.
Method signatures and docstrings:
- def testCreateManifestRepo(self): Test we can create a local git repository with a local manifest.
- def testUpdatingManifestRepo(self): ... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class PrepManifestForRepoTests:
"""Tests for our ability to init from a local repository."""
def testCreateManifestRepo(self):
"""Test we can create a local git repository with a local manifest."""
<|body_0|>
def testUpdatingManifestRepo(self):
"""Test we can update ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrepManifestForRepoTests:
"""Tests for our ability to init from a local repository."""
def testCreateManifestRepo(self):
"""Test we can create a local git repository with a local manifest."""
CONTENTS = 'manifest contents'
src_manifest = os.path.join(self.tempdir, 'src_manifest')
... | the_stack_v2_python_sparse | third_party/chromite/cbuildbot/repository_unittest.py | metux/chromium-suckless | train | 5 |
397440cbf4f73d62861284650f2dd12beda24df2 | [
"ss = SparqlSearch()\nquery = 'select ?s, ?p, ?o where {?s ?p ?o .} limit 2'\nresult, error = ss.executeQuery(query)\nself.assertEqual(error, None)",
"ss = SparqlSearch()\nquery = 'select ?s, ?p, ?o here {?s ?p ?o .} limit 2'\nresult, error = ss.executeQuery(query)\nself.assertNotEqual(error.code, 200)"
] | <|body_start_0|>
ss = SparqlSearch()
query = 'select ?s, ?p, ?o where {?s ?p ?o .} limit 2'
result, error = ss.executeQuery(query)
self.assertEqual(error, None)
<|end_body_0|>
<|body_start_1|>
ss = SparqlSearch()
query = 'select ?s, ?p, ?o here {?s ?p ?o .} limit 2'
... | SparlSearchTests | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparlSearchTests:
def test_sparql_query_ok(self):
"""Test query against sparql endpoint :return: 200: OK"""
<|body_0|>
def test_sparql_query_notok(self):
"""Test query against sparql endpoint :return: 400 and error message"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_018665 | 820 | permissive | [
{
"docstring": "Test query against sparql endpoint :return: 200: OK",
"name": "test_sparql_query_ok",
"signature": "def test_sparql_query_ok(self)"
},
{
"docstring": "Test query against sparql endpoint :return: 400 and error message",
"name": "test_sparql_query_notok",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_014083 | Implement the Python class `SparlSearchTests` described below.
Class description:
Implement the SparlSearchTests class.
Method signatures and docstrings:
- def test_sparql_query_ok(self): Test query against sparql endpoint :return: 200: OK
- def test_sparql_query_notok(self): Test query against sparql endpoint :retur... | Implement the Python class `SparlSearchTests` described below.
Class description:
Implement the SparlSearchTests class.
Method signatures and docstrings:
- def test_sparql_query_ok(self): Test query against sparql endpoint :return: 200: OK
- def test_sparql_query_notok(self): Test query against sparql endpoint :retur... | 7be2b33c22b9c2e2f0f3bbcf6004d20be6e15572 | <|skeleton|>
class SparlSearchTests:
def test_sparql_query_ok(self):
"""Test query against sparql endpoint :return: 200: OK"""
<|body_0|>
def test_sparql_query_notok(self):
"""Test query against sparql endpoint :return: 400 and error message"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparlSearchTests:
def test_sparql_query_ok(self):
"""Test query against sparql endpoint :return: 200: OK"""
ss = SparqlSearch()
query = 'select ?s, ?p, ?o where {?s ?p ?o .} limit 2'
result, error = ss.executeQuery(query)
self.assertEqual(error, None)
def test_spar... | the_stack_v2_python_sparse | proapi/api_v1/tests.py | PROconsortium/PRoteinOntology | train | 11 | |
96e68d825b1e5d873f2d22b5ab79d661ccdf56c2 | [
"self._hass = hass\nself._store = Store[dict[str, dict[str, Union[bool, int]]]](hass, STORAGE_VERSION, STORAGE_KEY)\nself._prefs: dict[str, dict[str, bool | int]] | None = None",
"if (prefs := (await self._store.async_load())) is None:\n prefs = {}\nself._prefs = prefs",
"if preload_stream is not UNDEFINED:\... | <|body_start_0|>
self._hass = hass
self._store = Store[dict[str, dict[str, Union[bool, int]]]](hass, STORAGE_VERSION, STORAGE_KEY)
self._prefs: dict[str, dict[str, bool | int]] | None = None
<|end_body_0|>
<|body_start_1|>
if (prefs := (await self._store.async_load())) is None:
... | Handle camera preferences. | CameraPreferences | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CameraPreferences:
"""Handle camera preferences."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize camera prefs."""
<|body_0|>
async def async_initialize(self) -> None:
"""Finish initializing the preferences."""
<|body_1|>
async def a... | stack_v2_sparse_classes_36k_train_018666 | 3,632 | permissive | [
{
"docstring": "Initialize camera prefs.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant) -> None"
},
{
"docstring": "Finish initializing the preferences.",
"name": "async_initialize",
"signature": "async def async_initialize(self) -> None"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_val_000495 | Implement the Python class `CameraPreferences` described below.
Class description:
Handle camera preferences.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize camera prefs.
- async def async_initialize(self) -> None: Finish initializing the preferences.
- async def async... | Implement the Python class `CameraPreferences` described below.
Class description:
Handle camera preferences.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize camera prefs.
- async def async_initialize(self) -> None: Finish initializing the preferences.
- async def async... | dcf68d768e4f628d038f1fdd6e40bad713fbc222 | <|skeleton|>
class CameraPreferences:
"""Handle camera preferences."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize camera prefs."""
<|body_0|>
async def async_initialize(self) -> None:
"""Finish initializing the preferences."""
<|body_1|>
async def a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CameraPreferences:
"""Handle camera preferences."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize camera prefs."""
self._hass = hass
self._store = Store[dict[str, dict[str, Union[bool, int]]]](hass, STORAGE_VERSION, STORAGE_KEY)
self._prefs: dict[str, dict... | the_stack_v2_python_sparse | homeassistant/components/camera/prefs.py | Adminiuga/home-assistant | train | 5 |
b4f8836e3f900777b69125134be2b320fb524eb4 | [
"if 'gateway' not in os.popen('jps').read():\n os.system('java gateway &')\n delay(0.5)\n LOGGER.debug('Started Java gateway')\nLOGGER.debug('Connecting to gateway from py4j')\ngate = JavaGateway()\nreturn gate",
"gate = Authentication.create_gateway()\njava_import(gate.jvm, 'com.splicemachine.shiro.Spli... | <|body_start_0|>
if 'gateway' not in os.popen('jps').read():
os.system('java gateway &')
delay(0.5)
LOGGER.debug('Started Java gateway')
LOGGER.debug('Connecting to gateway from py4j')
gate = JavaGateway()
return gate
<|end_body_0|>
<|body_start_1|>
... | Utilities to assist with Authentication | Authentication | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Authentication:
"""Utilities to assist with Authentication"""
def create_gateway():
"""Starts the java gateway server if it doesn't exist and creates the gateway :return: (Gateway) java gateway object"""
<|body_0|>
def validate_auth(username: str, password: str) -> Optio... | stack_v2_sparse_classes_36k_train_018667 | 2,895 | permissive | [
{
"docstring": "Starts the java gateway server if it doesn't exist and creates the gateway :return: (Gateway) java gateway object",
"name": "create_gateway",
"signature": "def create_gateway()"
},
{
"docstring": "This function uses the Shiro authentication API and retrieves whether or not the us... | 2 | stack_v2_sparse_classes_30k_train_009082 | Implement the Python class `Authentication` described below.
Class description:
Utilities to assist with Authentication
Method signatures and docstrings:
- def create_gateway(): Starts the java gateway server if it doesn't exist and creates the gateway :return: (Gateway) java gateway object
- def validate_auth(userna... | Implement the Python class `Authentication` described below.
Class description:
Utilities to assist with Authentication
Method signatures and docstrings:
- def create_gateway(): Starts the java gateway server if it doesn't exist and creates the gateway :return: (Gateway) java gateway object
- def validate_auth(userna... | 2f9a0d3d2814941c6bd78f9dcc019870a4e8c2da | <|skeleton|>
class Authentication:
"""Utilities to assist with Authentication"""
def create_gateway():
"""Starts the java gateway server if it doesn't exist and creates the gateway :return: (Gateway) java gateway object"""
<|body_0|>
def validate_auth(username: str, password: str) -> Optio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Authentication:
"""Utilities to assist with Authentication"""
def create_gateway():
"""Starts the java gateway server if it doesn't exist and creates the gateway :return: (Gateway) java gateway object"""
if 'gateway' not in os.popen('jps').read():
os.system('java gateway &')
... | the_stack_v2_python_sparse | shared/shared/services/authentication.py | myles-novick/ml-workflow | train | 0 |
096fa67184f166a645b1501aa3bcc073d8501c52 | [
"errors = {}\nsab_api = await get_client(self.hass, user_input)\nif not sab_api:\n errors['base'] = 'cannot_connect'\nreturn errors",
"errors = {}\nif user_input is not None:\n errors = await self._async_validate_input(user_input)\n if not errors:\n return self.async_create_entry(title=user_input[... | <|body_start_0|>
errors = {}
sab_api = await get_client(self.hass, user_input)
if not sab_api:
errors['base'] = 'cannot_connect'
return errors
<|end_body_0|>
<|body_start_1|>
errors = {}
if user_input is not None:
errors = await self._async_valida... | Sabnzbd config flow. | SABnzbdConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SABnzbdConfigFlow:
"""Sabnzbd config flow."""
async def _async_validate_input(self, user_input):
"""Validate the user input allows us to connect."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle a flow... | stack_v2_sparse_classes_36k_train_018668 | 1,995 | permissive | [
{
"docstring": "Validate the user input allows us to connect.",
"name": "_async_validate_input",
"signature": "async def _async_validate_input(self, user_input)"
},
{
"docstring": "Handle a flow initialized by the user.",
"name": "async_step_user",
"signature": "async def async_step_user... | 3 | null | Implement the Python class `SABnzbdConfigFlow` described below.
Class description:
Sabnzbd config flow.
Method signatures and docstrings:
- async def _async_validate_input(self, user_input): Validate the user input allows us to connect.
- async def async_step_user(self, user_input: dict[str, Any] | None=None) -> Flow... | Implement the Python class `SABnzbdConfigFlow` described below.
Class description:
Sabnzbd config flow.
Method signatures and docstrings:
- async def _async_validate_input(self, user_input): Validate the user input allows us to connect.
- async def async_step_user(self, user_input: dict[str, Any] | None=None) -> Flow... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SABnzbdConfigFlow:
"""Sabnzbd config flow."""
async def _async_validate_input(self, user_input):
"""Validate the user input allows us to connect."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle a flow... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SABnzbdConfigFlow:
"""Sabnzbd config flow."""
async def _async_validate_input(self, user_input):
"""Validate the user input allows us to connect."""
errors = {}
sab_api = await get_client(self.hass, user_input)
if not sab_api:
errors['base'] = 'cannot_connect'
... | the_stack_v2_python_sparse | homeassistant/components/sabnzbd/config_flow.py | home-assistant/core | train | 35,501 |
f505fb7fb8031af3ef4bf60a52df08165a467262 | [
"self.asteroid_list = []\ni = 0\nwhile i < 100:\n self.asteroid_list.append(Asteroid(random.randint(1, 4), [random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)], [random.randint(-5, 5), random.randint(-5, 5), random.randint(-5, 5)], datetime.now()))\n i += 1",
"i = 0\nwhile i < int(second... | <|body_start_0|>
self.asteroid_list = []
i = 0
while i < 100:
self.asteroid_list.append(Asteroid(random.randint(1, 4), [random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)], [random.randint(-5, 5), random.randint(-5, 5), random.randint(-5, 5)], datetime.now()))
... | A controller that controls asteroids | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
"""A controller that controls asteroids"""
def __init__(self):
"""Initialization of a controller Creates 100 Asteroids."""
<|body_0|>
def simulate(self, seconds):
"""Simulates the movements for asteroids. Accepts a number of seconds and move all aster... | stack_v2_sparse_classes_36k_train_018669 | 1,600 | no_license | [
{
"docstring": "Initialization of a controller Creates 100 Asteroids.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Simulates the movements for asteroids. Accepts a number of seconds and move all asteroids every second Prints resultant information :param seconds: an ... | 2 | stack_v2_sparse_classes_30k_train_003651 | Implement the Python class `Controller` described below.
Class description:
A controller that controls asteroids
Method signatures and docstrings:
- def __init__(self): Initialization of a controller Creates 100 Asteroids.
- def simulate(self, seconds): Simulates the movements for asteroids. Accepts a number of secon... | Implement the Python class `Controller` described below.
Class description:
A controller that controls asteroids
Method signatures and docstrings:
- def __init__(self): Initialization of a controller Creates 100 Asteroids.
- def simulate(self, seconds): Simulates the movements for asteroids. Accepts a number of secon... | ec79fbccd6cab95192ba8ab0cb42aa3b52a8af99 | <|skeleton|>
class Controller:
"""A controller that controls asteroids"""
def __init__(self):
"""Initialization of a controller Creates 100 Asteroids."""
<|body_0|>
def simulate(self, seconds):
"""Simulates the movements for asteroids. Accepts a number of seconds and move all aster... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Controller:
"""A controller that controls asteroids"""
def __init__(self):
"""Initialization of a controller Creates 100 Asteroids."""
self.asteroid_list = []
i = 0
while i < 100:
self.asteroid_list.append(Asteroid(random.randint(1, 4), [random.randint(0, 100),... | the_stack_v2_python_sparse | Labs/Lab 1/controller.py | a01037479/Python_OOP_Projects | train | 0 |
e93e366ca062494ce59a1196eb02a3ae4e63152c | [
"super(ReactorEnumerate, self).__init__(achem, mols)\nself.maxmols = len(mols)\nself.mols = []\nself.tested = []\nself.untested = []\nfor mol in mols:\n self.add_mol(mol)",
"if mol not in self.mols:\n self.mols.append(mol)\n noreactants = self.achem.noreactants\n try:\n noreactants = set(noreac... | <|body_start_0|>
super(ReactorEnumerate, self).__init__(achem, mols)
self.maxmols = len(mols)
self.mols = []
self.tested = []
self.untested = []
for mol in mols:
self.add_mol(mol)
<|end_body_0|>
<|body_start_1|>
if mol not in self.mols:
se... | Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear. | ReactorEnumerate | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReactorEnumerate:
"""Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear."""
def __init__(self, achem, mols):
""":param achem: :py:class:`achemkit.achem.AChem` object or equivalent. :param mols: ... | stack_v2_sparse_classes_36k_train_018670 | 7,950 | permissive | [
{
"docstring": ":param achem: :py:class:`achemkit.achem.AChem` object or equivalent. :param mols: Initial molecular species.",
"name": "__init__",
"signature": "def __init__(self, achem, mols)"
},
{
"docstring": "Internal utility function used to ensure molecular species have the relevant reacti... | 3 | stack_v2_sparse_classes_30k_train_000322 | Implement the Python class `ReactorEnumerate` described below.
Class description:
Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear.
Method signatures and docstrings:
- def __init__(self, achem, mols): :param achem: :py:class:`... | Implement the Python class `ReactorEnumerate` described below.
Class description:
Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear.
Method signatures and docstrings:
- def __init__(self, achem, mols): :param achem: :py:class:`... | 4800044693fdf8a228430eae5ee8b0283fde9920 | <|skeleton|>
class ReactorEnumerate:
"""Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear."""
def __init__(self, achem, mols):
""":param achem: :py:class:`achemkit.achem.AChem` object or equivalent. :param mols: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReactorEnumerate:
"""Reactor object designed to exaustively enumerate all possible reactant collections, adding new reactant collections as novel products appear."""
def __init__(self, achem, mols):
""":param achem: :py:class:`achemkit.achem.AChem` object or equivalent. :param mols: Initial molec... | the_stack_v2_python_sparse | achemkit/sim/simple.py | afaulconbridge/PyAChemKit | train | 2 |
f4efbece647e5b9a29e18533458bb62b47c830bd | [
"if self.creator is not None:\n kwargs.pop('creator', None)\nsuper().save(*args, **kwargs)",
"result = self.updater.get_full_name()\nif not result:\n result = self.updater.username\nreturn result",
"result = self.creator.get_full_name()\nif not result:\n result = self.creator.username\nreturn result"
] | <|body_start_0|>
if self.creator is not None:
kwargs.pop('creator', None)
super().save(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
result = self.updater.get_full_name()
if not result:
result = self.updater.username
return result
<|end_body_1|>
<|bod... | Abstract model mixin used in the model classes to provide user and creator fields. | UserModelMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserModelMixin:
"""Abstract model mixin used in the model classes to provide user and creator fields."""
def save(self, *args, **kwargs):
"""Save is here to assure that save is executed throughout the MRO. :param args: Positional arguments. :param kwargs: Keyword arguments."""
... | stack_v2_sparse_classes_36k_train_018671 | 5,231 | permissive | [
{
"docstring": "Save is here to assure that save is executed throughout the MRO. :param args: Positional arguments. :param kwargs: Keyword arguments.",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
},
{
"docstring": "Primary use is in an admin class to supply the updater's full ... | 3 | null | Implement the Python class `UserModelMixin` described below.
Class description:
Abstract model mixin used in the model classes to provide user and creator fields.
Method signatures and docstrings:
- def save(self, *args, **kwargs): Save is here to assure that save is executed throughout the MRO. :param args: Position... | Implement the Python class `UserModelMixin` described below.
Class description:
Abstract model mixin used in the model classes to provide user and creator fields.
Method signatures and docstrings:
- def save(self, *args, **kwargs): Save is here to assure that save is executed throughout the MRO. :param args: Position... | 44a8f151652640306bd6112c9838db99f5fc5c38 | <|skeleton|>
class UserModelMixin:
"""Abstract model mixin used in the model classes to provide user and creator fields."""
def save(self, *args, **kwargs):
"""Save is here to assure that save is executed throughout the MRO. :param args: Positional arguments. :param kwargs: Keyword arguments."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserModelMixin:
"""Abstract model mixin used in the model classes to provide user and creator fields."""
def save(self, *args, **kwargs):
"""Save is here to assure that save is executed throughout the MRO. :param args: Positional arguments. :param kwargs: Keyword arguments."""
if self.cre... | the_stack_v2_python_sparse | inventory/common/model_mixins.py | cnobile2012/inventory | train | 14 |
cef2b5861fa3e232f5a6574246b28a99cd53136e | [
"assert revision in self.blame_list\nfor i in range(0, len(self.blame_list)):\n if revision == self.blame_list[i]:\n return i + self.previous_build_commit_position + 1",
"length = len(self.blame_list)\nassert commit_position > self.commit_position - length and commit_position <= self.commit_position\nre... | <|body_start_0|>
assert revision in self.blame_list
for i in range(0, len(self.blame_list)):
if revision == self.blame_list[i]:
return i + self.previous_build_commit_position + 1
<|end_body_0|>
<|body_start_1|>
length = len(self.blame_list)
assert commit_posi... | DataPoint | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataPoint:
def GetCommitPosition(self, revision):
"""Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int): The calculated commit position of revision."""
<|body_0|>
def GetRevisionAtCommitP... | stack_v2_sparse_classes_36k_train_018672 | 11,733 | permissive | [
{
"docstring": "Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int): The calculated commit position of revision.",
"name": "GetCommitPosition",
"signature": "def GetCommitPosition(self, revision)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_018565 | Implement the Python class `DataPoint` described below.
Class description:
Implement the DataPoint class.
Method signatures and docstrings:
- def GetCommitPosition(self, revision): Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int... | Implement the Python class `DataPoint` described below.
Class description:
Implement the DataPoint class.
Method signatures and docstrings:
- def GetCommitPosition(self, revision): Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int... | 09064105713603f7bf75c772e8354800a1bfa256 | <|skeleton|>
class DataPoint:
def GetCommitPosition(self, revision):
"""Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int): The calculated commit position of revision."""
<|body_0|>
def GetRevisionAtCommitP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataPoint:
def GetCommitPosition(self, revision):
"""Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int): The calculated commit position of revision."""
assert revision in self.blame_list
for i in ra... | the_stack_v2_python_sparse | appengine/findit/model/flake/master_flake_analysis.py | mcgreevy/chromium-infra | train | 1 | |
22da4b02a550dfe725e5d5dfe30029c09932cfd4 | [
"self.low = low\nself.high = high\nself.dist = dist\nif dist == None:\n self.u = torch.distributions.uniform.Uniform(low=low, high=high)\n vol = torch.prod(torch.abs(high - low)).float()\n self.pdf = torch.ones(batch_size, dtype=torch.float, device=ddevice) / vol\n self.logpdf = torch.log(self.pdf)\neli... | <|body_start_0|>
self.low = low
self.high = high
self.dist = dist
if dist == None:
self.u = torch.distributions.uniform.Uniform(low=low, high=high)
vol = torch.prod(torch.abs(high - low)).float()
self.pdf = torch.ones(batch_size, dtype=torch.float, dev... | Prior | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Prior:
def __init__(self, dist=None, low=None, high=None, mean=None, cov=None):
"""Defines some priors. Uniform and normal. dist: str, distribution name. low: array or list (ndim), uniform low limit. high: array or list (ndim), uniform high limit. mean: array or list (ndim), normal dist.... | stack_v2_sparse_classes_36k_train_018673 | 13,126 | no_license | [
{
"docstring": "Defines some priors. Uniform and normal. dist: str, distribution name. low: array or list (ndim), uniform low limit. high: array or list (ndim), uniform high limit. mean: array or list (ndim), normal dist. mean. cov: array or list (ndim, ndim), normal dist. covariance. USE ONLY UNIFORM, NORMAL N... | 4 | stack_v2_sparse_classes_30k_train_001308 | Implement the Python class `Prior` described below.
Class description:
Implement the Prior class.
Method signatures and docstrings:
- def __init__(self, dist=None, low=None, high=None, mean=None, cov=None): Defines some priors. Uniform and normal. dist: str, distribution name. low: array or list (ndim), uniform low l... | Implement the Python class `Prior` described below.
Class description:
Implement the Prior class.
Method signatures and docstrings:
- def __init__(self, dist=None, low=None, high=None, mean=None, cov=None): Defines some priors. Uniform and normal. dist: str, distribution name. low: array or list (ndim), uniform low l... | 8789f692d81c5435a5888b6b151ccf6187d5a064 | <|skeleton|>
class Prior:
def __init__(self, dist=None, low=None, high=None, mean=None, cov=None):
"""Defines some priors. Uniform and normal. dist: str, distribution name. low: array or list (ndim), uniform low limit. high: array or list (ndim), uniform high limit. mean: array or list (ndim), normal dist.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Prior:
def __init__(self, dist=None, low=None, high=None, mean=None, cov=None):
"""Defines some priors. Uniform and normal. dist: str, distribution name. low: array or list (ndim), uniform low limit. high: array or list (ndim), uniform high limit. mean: array or list (ndim), normal dist. mean. cov: ar... | the_stack_v2_python_sparse | p18/mcmc.py | fluowhy/MCMC-methods | train | 1 | |
cc48219ae676b8797c3d154c08b32e8f6449c184 | [
"node = TreeNode.byname(taxon)\nparents = [node.canon_name.name]\nwhile node.parent.canon_name.name != 'root':\n parents.append(node.parent.canon_name.name)\n node = node.parent\nreturn parents",
"node = TreeNode.byname(taxon)\nparents = {node.rank: node.canon_name.name}\nwhile node.parent.canon_name.name !... | <|body_start_0|>
node = TreeNode.byname(taxon)
parents = [node.canon_name.name]
while node.parent.canon_name.name != 'root':
parents.append(node.parent.canon_name.name)
node = node.parent
return parents
<|end_body_0|>
<|body_start_1|>
node = TreeNode.byna... | TaxaTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaxaTree:
def ancestors(taxon):
"""Return a list of all ancestors of the taxon starting with the taxon itself."""
<|body_0|>
def ranked_ancestors(taxon):
"""Return a dict of all ancestors of the taxon starting with the taxon itself. Keys of the dict are taxon ranks""... | stack_v2_sparse_classes_36k_train_018674 | 3,036 | permissive | [
{
"docstring": "Return a list of all ancestors of the taxon starting with the taxon itself.",
"name": "ancestors",
"signature": "def ancestors(taxon)"
},
{
"docstring": "Return a dict of all ancestors of the taxon starting with the taxon itself. Keys of the dict are taxon ranks",
"name": "ra... | 4 | stack_v2_sparse_classes_30k_train_020043 | Implement the Python class `TaxaTree` described below.
Class description:
Implement the TaxaTree class.
Method signatures and docstrings:
- def ancestors(taxon): Return a list of all ancestors of the taxon starting with the taxon itself.
- def ranked_ancestors(taxon): Return a dict of all ancestors of the taxon start... | Implement the Python class `TaxaTree` described below.
Class description:
Implement the TaxaTree class.
Method signatures and docstrings:
- def ancestors(taxon): Return a list of all ancestors of the taxon starting with the taxon itself.
- def ranked_ancestors(taxon): Return a dict of all ancestors of the taxon start... | 630551dded7f9e38f95eda8c36039e0de46961e7 | <|skeleton|>
class TaxaTree:
def ancestors(taxon):
"""Return a list of all ancestors of the taxon starting with the taxon itself."""
<|body_0|>
def ranked_ancestors(taxon):
"""Return a dict of all ancestors of the taxon starting with the taxon itself. Keys of the dict are taxon ranks""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaxaTree:
def ancestors(taxon):
"""Return a list of all ancestors of the taxon starting with the taxon itself."""
node = TreeNode.byname(taxon)
parents = [node.canon_name.name]
while node.parent.canon_name.name != 'root':
parents.append(node.parent.canon_name.name)
... | the_stack_v2_python_sparse | pangea/contrib/treeoflife/taxa_tree.py | jtnedoctor/pangea-django | train | 0 | |
2b32f409c37ceb571d94250ed2e9104991c4f984 | [
"self.discs = []\nfor i, c in enumerate(config):\n tok = c.split()\n total = int(tok[3])\n start = int(tok[-1].strip('.'))\n div = total - (i + 1 + start) % total\n self.discs.append((total, start, div))",
"time = 0\ninc = 1\nwhile True:\n for i, d in enumerate(self.discs):\n if (time + i... | <|body_start_0|>
self.discs = []
for i, c in enumerate(config):
tok = c.split()
total = int(tok[3])
start = int(tok[-1].strip('.'))
div = total - (i + 1 + start) % total
self.discs.append((total, start, div))
<|end_body_0|>
<|body_start_1|>
... | DiscStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscStack:
def __init__(self, config):
"""read in the config"""
<|body_0|>
def find_min_time(self):
"""find the minimum time where the capsule would fall through"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.discs = []
for i, c in enu... | stack_v2_sparse_classes_36k_train_018675 | 1,366 | no_license | [
{
"docstring": "read in the config",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "find the minimum time where the capsule would fall through",
"name": "find_min_time",
"signature": "def find_min_time(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013869 | Implement the Python class `DiscStack` described below.
Class description:
Implement the DiscStack class.
Method signatures and docstrings:
- def __init__(self, config): read in the config
- def find_min_time(self): find the minimum time where the capsule would fall through | Implement the Python class `DiscStack` described below.
Class description:
Implement the DiscStack class.
Method signatures and docstrings:
- def __init__(self, config): read in the config
- def find_min_time(self): find the minimum time where the capsule would fall through
<|skeleton|>
class DiscStack:
def __i... | b1688431de1c5ab60659bc632c1a7131c3c7aad5 | <|skeleton|>
class DiscStack:
def __init__(self, config):
"""read in the config"""
<|body_0|>
def find_min_time(self):
"""find the minimum time where the capsule would fall through"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscStack:
def __init__(self, config):
"""read in the config"""
self.discs = []
for i, c in enumerate(config):
tok = c.split()
total = int(tok[3])
start = int(tok[-1].strip('.'))
div = total - (i + 1 + start) % total
self.disc... | the_stack_v2_python_sparse | 2016/15_02.py | yknot/adventOfCode | train | 0 | |
ed92b882459bb173298447219338286e8d89f537 | [
"self._bytes_per_callback = start_bytes_per_callback\nself._callback_func = callback_func\nself._calls_per_exponent = calls_per_exponent\nself._max_bytes_per_callback = max_bytes_per_callback\nself._total_size = total_size\nself._bytes_processed_since_callback = 0\nself._callbacks_made = 0\nself._total_bytes_proces... | <|body_start_0|>
self._bytes_per_callback = start_bytes_per_callback
self._callback_func = callback_func
self._calls_per_exponent = calls_per_exponent
self._max_bytes_per_callback = max_bytes_per_callback
self._total_size = total_size
self._bytes_processed_since_callback ... | Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output. | ProgressCallbackWithBackoff | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressCallbackWithBackoff:
"""Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output."""
def __init__(self, total_size, callback_func, start_bytes_per_callback=_START_BYTES_PER_CALLBACK, max_bytes_per_callback=_MAX_BYTES_PER_CALLBAC... | stack_v2_sparse_classes_36k_train_018676 | 7,111 | permissive | [
{
"docstring": "Initializes the callback with backoff. Args: total_size: Total bytes to process. If this is None, size is not known at the outset. callback_func: Func of (int: processed_so_far, int: total_bytes) used to make callbacks. start_bytes_per_callback: Lower bound of bytes per callback. max_bytes_per_c... | 2 | stack_v2_sparse_classes_30k_train_003142 | Implement the Python class `ProgressCallbackWithBackoff` described below.
Class description:
Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output.
Method signatures and docstrings:
- def __init__(self, total_size, callback_func, start_bytes_per_callback=_STA... | Implement the Python class `ProgressCallbackWithBackoff` described below.
Class description:
Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output.
Method signatures and docstrings:
- def __init__(self, total_size, callback_func, start_bytes_per_callback=_STA... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class ProgressCallbackWithBackoff:
"""Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output."""
def __init__(self, total_size, callback_func, start_bytes_per_callback=_START_BYTES_PER_CALLBACK, max_bytes_per_callback=_MAX_BYTES_PER_CALLBAC... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgressCallbackWithBackoff:
"""Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output."""
def __init__(self, total_size, callback_func, start_bytes_per_callback=_START_BYTES_PER_CALLBACK, max_bytes_per_callback=_MAX_BYTES_PER_CALLBACK, calls_per_... | the_stack_v2_python_sparse | third_party/catapult/third_party/gsutil/gslib/progress_callback.py | metux/chromium-suckless | train | 5 |
6e340765469ba9b764db4cd0bb19c1f5867fe135 | [
"self = object.__new__(cls)\nself.name = cls.DEFAULT_NAME\nself.value = value\nself.metadata_type = InteractionMetadataBase\nreturn self",
"self.value = value\nself.name = name\nself.metadata_type = metadata_type\nself.INSTANCES[value] = self"
] | <|body_start_0|>
self = object.__new__(cls)
self.name = cls.DEFAULT_NAME
self.value = value
self.metadata_type = InteractionMetadataBase
return self
<|end_body_0|>
<|body_start_1|>
self.value = value
self.name = name
self.metadata_type = metadata_type
... | The type of an interaction. Attributes ---------- name : `str` The name of the interaction type. value : `int` The identifier value the interaction type. metadata_type : `type<InteractionMetadataBase>` The interaction's respective metadata type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``Interact... | InteractionType | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractionType:
"""The type of an interaction. Attributes ---------- name : `str` The name of the interaction type. value : `int` The identifier value the interaction type. metadata_type : `type<InteractionMetadataBase>` The interaction's respective metadata type. Class Attributes --------------... | stack_v2_sparse_classes_36k_train_018677 | 5,118 | permissive | [
{
"docstring": "Creates a new interaction type with the given value. Parameters ---------- value : `int` The interaction type's identifier value. Returns ------- self : ``InteractionType`` The created instance.",
"name": "_from_value",
"signature": "def _from_value(cls, value)"
},
{
"docstring":... | 2 | null | Implement the Python class `InteractionType` described below.
Class description:
The type of an interaction. Attributes ---------- name : `str` The name of the interaction type. value : `int` The identifier value the interaction type. metadata_type : `type<InteractionMetadataBase>` The interaction's respective metadat... | Implement the Python class `InteractionType` described below.
Class description:
The type of an interaction. Attributes ---------- name : `str` The name of the interaction type. value : `int` The identifier value the interaction type. metadata_type : `type<InteractionMetadataBase>` The interaction's respective metadat... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class InteractionType:
"""The type of an interaction. Attributes ---------- name : `str` The name of the interaction type. value : `int` The identifier value the interaction type. metadata_type : `type<InteractionMetadataBase>` The interaction's respective metadata type. Class Attributes --------------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InteractionType:
"""The type of an interaction. Attributes ---------- name : `str` The name of the interaction type. value : `int` The identifier value the interaction type. metadata_type : `type<InteractionMetadataBase>` The interaction's respective metadata type. Class Attributes ---------------- INSTANCES ... | the_stack_v2_python_sparse | hata/discord/interaction/interaction_event/preinstanced.py | HuyaneMatsu/hata | train | 3 |
0fe63b5ffccfdb9d5e28600ae4433cbb4357112b | [
"review = get_object_or_404(Review, pk=review_pk)\nreview.delete()\nreturn Response()",
"kindergarten = get_object_or_404(Kindergarten, pk=kindergarten_pk)\nreview = get_object_or_404(Review, pk=review_pk)\nserializer = ReviewCreateSerializer(review, data=request.data)\nif serializer.is_valid(raise_exception=True... | <|body_start_0|>
review = get_object_or_404(Review, pk=review_pk)
review.delete()
return Response()
<|end_body_0|>
<|body_start_1|>
kindergarten = get_object_or_404(Kindergarten, pk=kindergarten_pk)
review = get_object_or_404(Review, pk=review_pk)
serializer = ReviewCrea... | ReviewDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewDetail:
def delete(self, request, kindergarten_pk, review_pk):
"""리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다."""
<|body_0|>
def put(self, request, kindergarten_pk, review_pk):
"""리뷰 수정 ## 리뷰 수정 - 리뷰를 수정할 수 있습니다. - 로그인한 사용자만 요청할 수 있습니다."""
<|body... | stack_v2_sparse_classes_36k_train_018678 | 26,419 | no_license | [
{
"docstring": "리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다.",
"name": "delete",
"signature": "def delete(self, request, kindergarten_pk, review_pk)"
},
{
"docstring": "리뷰 수정 ## 리뷰 수정 - 리뷰를 수정할 수 있습니다. - 로그인한 사용자만 요청할 수 있습니다.",
"name": "put",
"signature": "def put(self, request, k... | 2 | stack_v2_sparse_classes_30k_train_008795 | Implement the Python class `ReviewDetail` described below.
Class description:
Implement the ReviewDetail class.
Method signatures and docstrings:
- def delete(self, request, kindergarten_pk, review_pk): 리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다.
- def put(self, request, kindergarten_pk, review_pk): 리뷰 수정 ## ... | Implement the Python class `ReviewDetail` described below.
Class description:
Implement the ReviewDetail class.
Method signatures and docstrings:
- def delete(self, request, kindergarten_pk, review_pk): 리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다.
- def put(self, request, kindergarten_pk, review_pk): 리뷰 수정 ## ... | 7ab42320f71c06f21644accb42e0296eaa2042c0 | <|skeleton|>
class ReviewDetail:
def delete(self, request, kindergarten_pk, review_pk):
"""리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다."""
<|body_0|>
def put(self, request, kindergarten_pk, review_pk):
"""리뷰 수정 ## 리뷰 수정 - 리뷰를 수정할 수 있습니다. - 로그인한 사용자만 요청할 수 있습니다."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewDetail:
def delete(self, request, kindergarten_pk, review_pk):
"""리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다."""
review = get_object_or_404(Review, pk=review_pk)
review.delete()
return Response()
def put(self, request, kindergarten_pk, review_pk):
"""... | the_stack_v2_python_sparse | backend/kindergartens/views.py | YongjoonSeo/Children-ZIP | train | 1 | |
c04aab7a1510901dcc9538a5920c7743e5d7b097 | [
"self.pageId = pageId\nself.sortBy = sortBy\nself.sortValue = sortValue",
"params = {'pageId': self.pageId}\nif self.sortBy is not None:\n params['sortBy'] = self.sortBy\nif self.sortValue is not None:\n params['sortValue'] = self.sortValue\nreturn params"
] | <|body_start_0|>
self.pageId = pageId
self.sortBy = sortBy
self.sortValue = sortValue
<|end_body_0|>
<|body_start_1|>
params = {'pageId': self.pageId}
if self.sortBy is not None:
params['sortBy'] = self.sortBy
if self.sortValue is not None:
params... | ListAllPickupsRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListAllPickupsRequest:
def __init__(self, pageId, sortBy=None, sortValue=None):
"""Initialize new instance from ListAllPickupsRequest class Parameters: pageId (int) sortBy (str) sortValue (str) Returns: New instance from ListAllPickupsRequest class"""
<|body_0|>
def toQueryP... | stack_v2_sparse_classes_36k_train_018679 | 788 | permissive | [
{
"docstring": "Initialize new instance from ListAllPickupsRequest class Parameters: pageId (int) sortBy (str) sortValue (str) Returns: New instance from ListAllPickupsRequest class",
"name": "__init__",
"signature": "def __init__(self, pageId, sortBy=None, sortValue=None)"
},
{
"docstring": "Re... | 2 | stack_v2_sparse_classes_30k_train_017538 | Implement the Python class `ListAllPickupsRequest` described below.
Class description:
Implement the ListAllPickupsRequest class.
Method signatures and docstrings:
- def __init__(self, pageId, sortBy=None, sortValue=None): Initialize new instance from ListAllPickupsRequest class Parameters: pageId (int) sortBy (str) ... | Implement the Python class `ListAllPickupsRequest` described below.
Class description:
Implement the ListAllPickupsRequest class.
Method signatures and docstrings:
- def __init__(self, pageId, sortBy=None, sortValue=None): Initialize new instance from ListAllPickupsRequest class Parameters: pageId (int) sortBy (str) ... | df3f48dafac49b2577669fd4d74a5e5e9d28f2c1 | <|skeleton|>
class ListAllPickupsRequest:
def __init__(self, pageId, sortBy=None, sortValue=None):
"""Initialize new instance from ListAllPickupsRequest class Parameters: pageId (int) sortBy (str) sortValue (str) Returns: New instance from ListAllPickupsRequest class"""
<|body_0|>
def toQueryP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListAllPickupsRequest:
def __init__(self, pageId, sortBy=None, sortValue=None):
"""Initialize new instance from ListAllPickupsRequest class Parameters: pageId (int) sortBy (str) sortValue (str) Returns: New instance from ListAllPickupsRequest class"""
self.pageId = pageId
self.sortBy =... | the_stack_v2_python_sparse | bostaSDK/pickup/list/ListAllPickupsRequest.py | bostaapp/bosta-python | train | 0 | |
b83b1d97af812e578b42147c208a50ddd82ce6cb | [
"mLen = len(nums) + 1\nmSum = 0\nleft, right = (0, 1)\nfor right in range(1, len(nums) + 1):\n mSum = max(mSum, sum(nums[left:right]))\n if sum(nums[left:right]) >= target:\n while sum(nums[left:right]) >= target and left <= right:\n left += 1\n mLen = min(mLen, right - left + 1)\nif ... | <|body_start_0|>
mLen = len(nums) + 1
mSum = 0
left, right = (0, 1)
for right in range(1, len(nums) + 1):
mSum = max(mSum, sum(nums[left:right]))
if sum(nums[left:right]) >= target:
while sum(nums[left:right]) >= target and left <= right:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubArrayLen_ver1(self, target, nums):
""":type target: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen_ver2(self, target, nums):
""":type target: int :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_018680 | 1,398 | no_license | [
{
"docstring": ":type target: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen_ver1",
"signature": "def minSubArrayLen_ver1(self, target, nums)"
},
{
"docstring": ":type target: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen_ver2",
"signature": "def minSub... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen_ver1(self, target, nums): :type target: int :type nums: List[int] :rtype: int
- def minSubArrayLen_ver2(self, target, nums): :type target: int :type nums: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen_ver1(self, target, nums): :type target: int :type nums: List[int] :rtype: int
- def minSubArrayLen_ver2(self, target, nums): :type target: int :type nums: List... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def minSubArrayLen_ver1(self, target, nums):
""":type target: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen_ver2(self, target, nums):
""":type target: int :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minSubArrayLen_ver1(self, target, nums):
""":type target: int :type nums: List[int] :rtype: int"""
mLen = len(nums) + 1
mSum = 0
left, right = (0, 1)
for right in range(1, len(nums) + 1):
mSum = max(mSum, sum(nums[left:right]))
if s... | the_stack_v2_python_sparse | 21. SLIDING_WINDOW/209_Minimum_size_subarray_sum/solution.py | kimmyoo/python_leetcode | train | 1 | |
7971ae69eec593041f3bb59c11e8855bb4f0e8ff | [
"for row in matrix:\n if not is_distinct_row(row):\n return False\nreturn True",
"rows = []\nfor _ in range(self.num_rows):\n random_permutation = random_state.permutation(self.num_atoms)\n rows.append(random_permutation[:self.num_cols])\nreturn np.array(rows)"
] | <|body_start_0|>
for row in matrix:
if not is_distinct_row(row):
return False
return True
<|end_body_0|>
<|body_start_1|>
rows = []
for _ in range(self.num_rows):
random_permutation = random_state.permutation(self.num_atoms)
rows.appen... | Relation where elements in a matrix row are distinct. | DistinctRelation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistinctRelation:
"""Relation where elements in a matrix row are distinct."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
<|body_0|>
def sample(self, random_state):
"""Samples a matrix consistent with the relation."""
... | stack_v2_sparse_classes_36k_train_018681 | 10,947 | permissive | [
{
"docstring": "Checks whether the matrix satisfies the relation.",
"name": "is_consistent",
"signature": "def is_consistent(matrix)"
},
{
"docstring": "Samples a matrix consistent with the relation.",
"name": "sample",
"signature": "def sample(self, random_state)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003521 | Implement the Python class `DistinctRelation` described below.
Class description:
Relation where elements in a matrix row are distinct.
Method signatures and docstrings:
- def is_consistent(matrix): Checks whether the matrix satisfies the relation.
- def sample(self, random_state): Samples a matrix consistent with th... | Implement the Python class `DistinctRelation` described below.
Class description:
Relation where elements in a matrix row are distinct.
Method signatures and docstrings:
- def is_consistent(matrix): Checks whether the matrix satisfies the relation.
- def sample(self, random_state): Samples a matrix consistent with th... | 73d4b995e88efdd5ffbe98a72e48a620c58f4dc7 | <|skeleton|>
class DistinctRelation:
"""Relation where elements in a matrix row are distinct."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
<|body_0|>
def sample(self, random_state):
"""Samples a matrix consistent with the relation."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DistinctRelation:
"""Relation where elements in a matrix row are distinct."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
for row in matrix:
if not is_distinct_row(row):
return False
return True
def sample(sel... | the_stack_v2_python_sparse | disentanglement_lib/evaluation/abstract_reasoning/pgm_utils.py | travers-rhodes/disentanglement_lib | train | 0 |
956fe9ded2b82c8b6d60d7b308fd15866bde4d81 | [
"if not envelopes:\n return 0\nresult = 1\nnums = sorted(envelopes, key=lambda x: x)\ndp = [1] * len(nums)\nfor i in range(1, len(nums)):\n for j in range(i):\n if nums[i][0] > nums[j][0] and nums[i][1] > nums[j][1]:\n dp[i] = max(dp[i], dp[j] + 1)\n result = max(result, dp[i])\nreturn re... | <|body_start_0|>
if not envelopes:
return 0
result = 1
nums = sorted(envelopes, key=lambda x: x)
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i][0] > nums[j][0] and nums[i][1] > nums[j][1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not env... | stack_v2_sparse_classes_36k_train_018682 | 3,206 | no_license | [
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "_maxEnvelopes",
"signature": "def _maxEnvelopes(self, envelopes)"
},
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes",
"signature": "def maxEnvelopes(self, envelopes)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
<|skeleton|>
c... | b7e3b02c50d54515e584cb18dff83109224245d0 | <|skeleton|>
class Solution:
def _maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
if not envelopes:
return 0
result = 1
nums = sorted(envelopes, key=lambda x: x)
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in r... | the_stack_v2_python_sparse | Python/LeetCode/ByteDance/354_max_envelopes.py | shouliang/Development | train | 0 | |
ab653e3f647c9968115427fbb054d85039a08226 | [
"tmp = []\nwhile head:\n tmp.append(head.val)\n head = head.next\nreturn tmp == tmp[::-1]",
"tmp = []\nmove = head\nwhile move:\n tmp.append(move.val)\n move = move.next\nreturn tmp == tmp[::-1]"
] | <|body_start_0|>
tmp = []
while head:
tmp.append(head.val)
head = head.next
return tmp == tmp[::-1]
<|end_body_0|>
<|body_start_1|>
tmp = []
move = head
while move:
tmp.append(move.val)
move = move.next
return tmp =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""复杂度分析: 时间复杂度:遍历链表并将值复制到数组中 O(n) 空间复杂度:O(n),其中n指的是链表元素个数,我们使用一个数组列表存放链表的元素值"""
<|body_0|>
def isPalindrome1(self, head: ListNode) -> bool:
"""最简单的方法就是将值复制到数组中,然后使用双指针法 确定数组列表是否回文很简单,我们可以用双指针来比较两端的元素,并向中间移动。 ... | stack_v2_sparse_classes_36k_train_018683 | 1,836 | no_license | [
{
"docstring": "复杂度分析: 时间复杂度:遍历链表并将值复制到数组中 O(n) 空间复杂度:O(n),其中n指的是链表元素个数,我们使用一个数组列表存放链表的元素值",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head: ListNode) -> bool"
},
{
"docstring": "最简单的方法就是将值复制到数组中,然后使用双指针法 确定数组列表是否回文很简单,我们可以用双指针来比较两端的元素,并向中间移动。 一个指针从起点向中间移动,另一个指针从终点向中间移动,这需要 O(... | 2 | stack_v2_sparse_classes_30k_train_002302 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: 复杂度分析: 时间复杂度:遍历链表并将值复制到数组中 O(n) 空间复杂度:O(n),其中n指的是链表元素个数,我们使用一个数组列表存放链表的元素值
- def isPalindrome1(self, head: ListNode) -> bool: 最简单的... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: 复杂度分析: 时间复杂度:遍历链表并将值复制到数组中 O(n) 空间复杂度:O(n),其中n指的是链表元素个数,我们使用一个数组列表存放链表的元素值
- def isPalindrome1(self, head: ListNode) -> bool: 最简单的... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""复杂度分析: 时间复杂度:遍历链表并将值复制到数组中 O(n) 空间复杂度:O(n),其中n指的是链表元素个数,我们使用一个数组列表存放链表的元素值"""
<|body_0|>
def isPalindrome1(self, head: ListNode) -> bool:
"""最简单的方法就是将值复制到数组中,然后使用双指针法 确定数组列表是否回文很简单,我们可以用双指针来比较两端的元素,并向中间移动。 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""复杂度分析: 时间复杂度:遍历链表并将值复制到数组中 O(n) 空间复杂度:O(n),其中n指的是链表元素个数,我们使用一个数组列表存放链表的元素值"""
tmp = []
while head:
tmp.append(head.val)
head = head.next
return tmp == tmp[::-1]
def isPalindrome1(self, hea... | the_stack_v2_python_sparse | LCCI/02_06_PalindromeLinkedList.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
6c0a459f65c134ce7d64fe56d7ef856a7c919a73 | [
"self.color = color\nself.data_set = quandl_data_set_name\nself.dates, self.prices = self.get_quandl_data(self.data_set, quandl_settings)\nif statsmodels_settings.confidence:\n self.regression, self.lower, self.upper = self.run_ordinary_least_squares(self.dates, self.prices, statsmodels_settings)\nelse:\n sel... | <|body_start_0|>
self.color = color
self.data_set = quandl_data_set_name
self.dates, self.prices = self.get_quandl_data(self.data_set, quandl_settings)
if statsmodels_settings.confidence:
self.regression, self.lower, self.upper = self.run_ordinary_least_squares(self.dates, se... | This class contain the logic for calculating the regression analysis given a Quandl data-set name, a QuandlSettings object, and a StatsModelsSettings object. The resulting regression analysis is returned. | RegressionAnalysis | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegressionAnalysis:
"""This class contain the logic for calculating the regression analysis given a Quandl data-set name, a QuandlSettings object, and a StatsModelsSettings object. The resulting regression analysis is returned."""
def __init__(self, quandl_data_set_name, quandl_settings, sta... | stack_v2_sparse_classes_36k_train_018684 | 8,530 | permissive | [
{
"docstring": "This initialization method constructs a new RegressionAnalysis object",
"name": "__init__",
"signature": "def __init__(self, quandl_data_set_name, quandl_settings, statsmodels_settings, color='r')"
},
{
"docstring": "This method retrieves the quandl data set given the settings sp... | 3 | null | Implement the Python class `RegressionAnalysis` described below.
Class description:
This class contain the logic for calculating the regression analysis given a Quandl data-set name, a QuandlSettings object, and a StatsModelsSettings object. The resulting regression analysis is returned.
Method signatures and docstri... | Implement the Python class `RegressionAnalysis` described below.
Class description:
This class contain the logic for calculating the regression analysis given a Quandl data-set name, a QuandlSettings object, and a StatsModelsSettings object. The resulting regression analysis is returned.
Method signatures and docstri... | 408f3fa3d36542d8fc1236ba1cac804de6f14b0c | <|skeleton|>
class RegressionAnalysis:
"""This class contain the logic for calculating the regression analysis given a Quandl data-set name, a QuandlSettings object, and a StatsModelsSettings object. The resulting regression analysis is returned."""
def __init__(self, quandl_data_set_name, quandl_settings, sta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegressionAnalysis:
"""This class contain the logic for calculating the regression analysis given a Quandl data-set name, a QuandlSettings object, and a StatsModelsSettings object. The resulting regression analysis is returned."""
def __init__(self, quandl_data_set_name, quandl_settings, statsmodels_sett... | the_stack_v2_python_sparse | hard-gists/0d9745f39a034758e51e/snippet.py | dockerizeme/dockerizeme | train | 24 |
95c82addde9a37044f1ca314017a74cd486dea12 | [
"if len(array) == 0:\n return False\nrownum = len(array)\ncolnum = len(array[0])\ni = colnum - 1\nj = 0\nwhile i >= 0 and j < rownum:\n if array[j][i] < target:\n j += 1\n elif array[j][i] > target:\n i -= 1\n else:\n return True\nreturn False",
"if not matrix or len(matrix) == 0:... | <|body_start_0|>
if len(array) == 0:
return False
rownum = len(array)
colnum = len(array[0])
i = colnum - 1
j = 0
while i >= 0 and j < rownum:
if array[j][i] < target:
j += 1
elif array[j][i] > target:
i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def Find(self, array, target):
"""是否存在"""
<|body_0|>
def searchMatrix(self, matrix, target):
"""输出个数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(array) == 0:
return False
rownum = len(array)
colnum = ... | stack_v2_sparse_classes_36k_train_018685 | 2,335 | no_license | [
{
"docstring": "是否存在",
"name": "Find",
"signature": "def Find(self, array, target)"
},
{
"docstring": "输出个数",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001785 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Find(self, array, target): 是否存在
- def searchMatrix(self, matrix, target): 输出个数 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Find(self, array, target): 是否存在
- def searchMatrix(self, matrix, target): 输出个数
<|skeleton|>
class Solution:
def Find(self, array, target):
"""是否存在"""
<|... | ae191a449619418e3eba23f18574c7841e7ba52a | <|skeleton|>
class Solution:
def Find(self, array, target):
"""是否存在"""
<|body_0|>
def searchMatrix(self, matrix, target):
"""输出个数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def Find(self, array, target):
"""是否存在"""
if len(array) == 0:
return False
rownum = len(array)
colnum = len(array[0])
i = colnum - 1
j = 0
while i >= 0 and j < rownum:
if array[j][i] < target:
j += 1
... | the_stack_v2_python_sparse | target_offer/two_dimensions_search.py | zealfory/dive_python | train | 0 | |
75971c7aecda5cbda87112a436c52f9dc4bbfa2a | [
"gtk.ComboBox.__init__(self, gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING))\ncell = gtk.CellRendererText()\nself.pack_start(cell, True)\nself.add_attribute(cell, 'text', 0)\nself.set_size_request(width, heigth)\nself.set_border_width(margin)\nself.set_items(items)",
"p_tree_model = self.get_model()\np_t... | <|body_start_0|>
gtk.ComboBox.__init__(self, gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING))
cell = gtk.CellRendererText()
self.pack_start(cell, True)
self.add_attribute(cell, 'text', 0)
self.set_size_request(width, heigth)
self.set_border_width(margin)
s... | Simple GTK ComboBox using a fullfilled GtkTree, with 2 columns - first columns is used to display the human-readable value, - second to stock the non-readable value. Methods: LbxComboBox(self, list): instantiate a ComboBox using the given list set_items(self, list): display list in the ComboBox | LbxComboBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LbxComboBox:
"""Simple GTK ComboBox using a fullfilled GtkTree, with 2 columns - first columns is used to display the human-readable value, - second to stock the non-readable value. Methods: LbxComboBox(self, list): instantiate a ComboBox using the given list set_items(self, list): display list i... | stack_v2_sparse_classes_36k_train_018686 | 13,120 | no_license | [
{
"docstring": "Instantiate a new LbxComboBox Returns a new LbxComboBox pre-filled with list ComboBox geometry default to 200x30 + 10 margin list should be a list of tuples",
"name": "__init__",
"signature": "def __init__(self, items=None, width=200, heigth=30, margin=10)"
},
{
"docstring": "Fil... | 2 | stack_v2_sparse_classes_30k_train_011840 | Implement the Python class `LbxComboBox` described below.
Class description:
Simple GTK ComboBox using a fullfilled GtkTree, with 2 columns - first columns is used to display the human-readable value, - second to stock the non-readable value. Methods: LbxComboBox(self, list): instantiate a ComboBox using the given lis... | Implement the Python class `LbxComboBox` described below.
Class description:
Simple GTK ComboBox using a fullfilled GtkTree, with 2 columns - first columns is used to display the human-readable value, - second to stock the non-readable value. Methods: LbxComboBox(self, list): instantiate a ComboBox using the given lis... | 53c26e3c03c5054fb9d5730cf98716442a07464a | <|skeleton|>
class LbxComboBox:
"""Simple GTK ComboBox using a fullfilled GtkTree, with 2 columns - first columns is used to display the human-readable value, - second to stock the non-readable value. Methods: LbxComboBox(self, list): instantiate a ComboBox using the given list set_items(self, list): display list i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LbxComboBox:
"""Simple GTK ComboBox using a fullfilled GtkTree, with 2 columns - first columns is used to display the human-readable value, - second to stock the non-readable value. Methods: LbxComboBox(self, list): instantiate a ComboBox using the given list set_items(self, list): display list in the ComboBo... | the_stack_v2_python_sparse | lbx_gtk_widgets.py | mandriva-management-console/beam | train | 0 |
924b381c83b753d2581a92e1a78614a528044e40 | [
"super().__init__()\nself.self_attn = self_attn\nself.feed_forward = feed_forward\nself.norm1 = nn.LayerNorm(size, eps=1e-05)\nself.norm2 = nn.LayerNorm(size, eps=1e-05)\nself.dropout = nn.Dropout(dropout_rate)\nself.size = size\nself.normalize_before = normalize_before",
"residual = x\nif self.normalize_before:\... | <|body_start_0|>
super().__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.norm1 = nn.LayerNorm(size, eps=1e-05)
self.norm2 = nn.LayerNorm(size, eps=1e-05)
self.dropout = nn.Dropout(dropout_rate)
self.size = size
self.normalize_be... | Encoder layer module. Args: size (int): Input dimension. self_attn (torch.nn.Module): Self-attention module instance. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance can be used as the argument. feed_forward (torch.nn.Module): Feed-forward module instance. `PositionwiseFeedForward`, instance can be... | TransformerEncoderLayer | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoderLayer:
"""Encoder layer module. Args: size (int): Input dimension. self_attn (torch.nn.Module): Self-attention module instance. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance can be used as the argument. feed_forward (torch.nn.Module): Feed-forward module i... | stack_v2_sparse_classes_36k_train_018687 | 9,600 | permissive | [
{
"docstring": "Construct an EncoderLayer object.",
"name": "__init__",
"signature": "def __init__(self, size: int, self_attn: torch.nn.Module, feed_forward: torch.nn.Module, dropout_rate: float, normalize_before: bool=True)"
},
{
"docstring": "Compute encoded features. Args: x (torch.Tensor): (... | 2 | null | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
Encoder layer module. Args: size (int): Input dimension. self_attn (torch.nn.Module): Self-attention module instance. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance can be used as the argument. feed_forward (... | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
Encoder layer module. Args: size (int): Input dimension. self_attn (torch.nn.Module): Self-attention module instance. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance can be used as the argument. feed_forward (... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class TransformerEncoderLayer:
"""Encoder layer module. Args: size (int): Input dimension. self_attn (torch.nn.Module): Self-attention module instance. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance can be used as the argument. feed_forward (torch.nn.Module): Feed-forward module i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerEncoderLayer:
"""Encoder layer module. Args: size (int): Input dimension. self_attn (torch.nn.Module): Self-attention module instance. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance can be used as the argument. feed_forward (torch.nn.Module): Feed-forward module instance. `Pos... | the_stack_v2_python_sparse | PyTorch/built-in/audio/Wenet_Conformer_for_Pytorch/wenet/transformer/encoder_layer.py | Ascend/ModelZoo-PyTorch | train | 23 |
1b689b2234a1121ee3b55b601df0ce4e849c804f | [
"s = list(str(num))\nd = sorted(s, reverse=True)\nl = len(s)\nis_Swap = False\nfor i in range(l):\n if d[i] != s[i]:\n is_Swap = True\n end = i\n target = d[i]\n break\nif not is_Swap:\n return num\nfor i in range(l - 1, end, -1):\n if s[i] == target:\n s[end], s[i] = (s[... | <|body_start_0|>
s = list(str(num))
d = sorted(s, reverse=True)
l = len(s)
is_Swap = False
for i in range(l):
if d[i] != s[i]:
is_Swap = True
end = i
target = d[i]
break
if not is_Swap:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximumSwap(self, num):
""":type num: int :rtype: int 49ms"""
<|body_0|>
def maximumSwap_1(self, num):
""":type num: int :rtype: int 29ms"""
<|body_1|>
def maximumSwap_2(self, num):
""":type num: int :rtype: int 38ms"""
<|bo... | stack_v2_sparse_classes_36k_train_018688 | 2,489 | no_license | [
{
"docstring": ":type num: int :rtype: int 49ms",
"name": "maximumSwap",
"signature": "def maximumSwap(self, num)"
},
{
"docstring": ":type num: int :rtype: int 29ms",
"name": "maximumSwap_1",
"signature": "def maximumSwap_1(self, num)"
},
{
"docstring": ":type num: int :rtype: i... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumSwap(self, num): :type num: int :rtype: int 49ms
- def maximumSwap_1(self, num): :type num: int :rtype: int 29ms
- def maximumSwap_2(self, num): :type num: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumSwap(self, num): :type num: int :rtype: int 49ms
- def maximumSwap_1(self, num): :type num: int :rtype: int 29ms
- def maximumSwap_2(self, num): :type num: int :rtype:... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def maximumSwap(self, num):
""":type num: int :rtype: int 49ms"""
<|body_0|>
def maximumSwap_1(self, num):
""":type num: int :rtype: int 29ms"""
<|body_1|>
def maximumSwap_2(self, num):
""":type num: int :rtype: int 38ms"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximumSwap(self, num):
""":type num: int :rtype: int 49ms"""
s = list(str(num))
d = sorted(s, reverse=True)
l = len(s)
is_Swap = False
for i in range(l):
if d[i] != s[i]:
is_Swap = True
end = i
... | the_stack_v2_python_sparse | MaximumSwap_MID_670.py | 953250587/leetcode-python | train | 2 | |
c3ab16220b5902f75045e7bbb8d1a43f0bd8deb9 | [
"super(TextLineInputter, self).__init__(dataset, batch_size)\nif self._batch_size is None:\n raise ValueError('batch_size should be provided.')\nif not hasattr(dataset, data_field_name):\n raise ValueError('dataset object has no attribute named \"{}\"'.format(data_field_name))\nself._data_files = getattr(data... | <|body_start_0|>
super(TextLineInputter, self).__init__(dataset, batch_size)
if self._batch_size is None:
raise ValueError('batch_size should be provided.')
if not hasattr(dataset, data_field_name):
raise ValueError('dataset object has no attribute named "{}"'.format(data... | Class for reading in source side lines or target side lines. | TextLineInputter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextLineInputter:
"""Class for reading in source side lines or target side lines."""
def __init__(self, dataset, data_field_name, batch_size):
"""Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. data_field_name: The attribute name of dataset that has a... | stack_v2_sparse_classes_36k_train_018689 | 29,753 | permissive | [
{
"docstring": "Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. data_field_name: The attribute name of dataset that has access to a data file. batch_size: An integer value indicating the number of sentences passed into one step. Sentences will be padded by EOS. Raises: ValueErro... | 3 | stack_v2_sparse_classes_30k_train_004578 | Implement the Python class `TextLineInputter` described below.
Class description:
Class for reading in source side lines or target side lines.
Method signatures and docstrings:
- def __init__(self, dataset, data_field_name, batch_size): Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. ... | Implement the Python class `TextLineInputter` described below.
Class description:
Class for reading in source side lines or target side lines.
Method signatures and docstrings:
- def __init__(self, dataset, data_field_name, batch_size): Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. ... | 01155c740705f1641ebf3134829cea0e212f2d28 | <|skeleton|>
class TextLineInputter:
"""Class for reading in source side lines or target side lines."""
def __init__(self, dataset, data_field_name, batch_size):
"""Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. data_field_name: The attribute name of dataset that has a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextLineInputter:
"""Class for reading in source side lines or target side lines."""
def __init__(self, dataset, data_field_name, batch_size):
"""Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. data_field_name: The attribute name of dataset that has access to a da... | the_stack_v2_python_sparse | njunmt/data/text_inputter.py | zhaocq-nlp/NJUNMT-tf | train | 114 |
d7617960c534c0db6652d15dc0e1b79b696c1625 | [
"checkTypeDescription = type(accionDescription) == str\ncheckTypeId = type(idBacklog) == int\nif checkTypeDescription and checkTypeId:\n checkLongAccionDescription = MIN_ACCION_DESCRIPTION <= len(accionDescription) <= MAX_ACCION_DESCRIPTION\n checkLongId = MIN_ID <= idBacklog\n if checkLongAccionDescriptio... | <|body_start_0|>
checkTypeDescription = type(accionDescription) == str
checkTypeId = type(idBacklog) == int
if checkTypeDescription and checkTypeId:
checkLongAccionDescription = MIN_ACCION_DESCRIPTION <= len(accionDescription) <= MAX_ACCION_DESCRIPTION
checkLongId = MIN_I... | Clase que permite manejar las acciones de manera persistente | accions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class accions:
"""Clase que permite manejar las acciones de manera persistente"""
def insertAccion(self, accionDescription, idBacklog):
"""Permite insertar una Accion asociada a un producto"""
<|body_0|>
def searchAccion(self, accionDescription, idBacklog):
"""Permite ... | stack_v2_sparse_classes_36k_train_018690 | 5,147 | no_license | [
{
"docstring": "Permite insertar una Accion asociada a un producto",
"name": "insertAccion",
"signature": "def insertAccion(self, accionDescription, idBacklog)"
},
{
"docstring": "Permite buscar acciones por su descripcion",
"name": "searchAccion",
"signature": "def searchAccion(self, ac... | 5 | stack_v2_sparse_classes_30k_val_000343 | Implement the Python class `accions` described below.
Class description:
Clase que permite manejar las acciones de manera persistente
Method signatures and docstrings:
- def insertAccion(self, accionDescription, idBacklog): Permite insertar una Accion asociada a un producto
- def searchAccion(self, accionDescription,... | Implement the Python class `accions` described below.
Class description:
Clase que permite manejar las acciones de manera persistente
Method signatures and docstrings:
- def insertAccion(self, accionDescription, idBacklog): Permite insertar una Accion asociada a un producto
- def searchAccion(self, accionDescription,... | ade66ad90588712045dca7b9b8d8c64e2a24f141 | <|skeleton|>
class accions:
"""Clase que permite manejar las acciones de manera persistente"""
def insertAccion(self, accionDescription, idBacklog):
"""Permite insertar una Accion asociada a un producto"""
<|body_0|>
def searchAccion(self, accionDescription, idBacklog):
"""Permite ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class accions:
"""Clase que permite manejar las acciones de manera persistente"""
def insertAccion(self, accionDescription, idBacklog):
"""Permite insertar una Accion asociada a un producto"""
checkTypeDescription = type(accionDescription) == str
checkTypeId = type(idBacklog) == int
... | the_stack_v2_python_sparse | app/scrum/accions.py | WhosTheMark/APMwSc | train | 1 |
1e2f83db3e18f1d88da6bbcdf6826330be2b86fd | [
"serialized: dict = vars(self)\nserialize = lambda value: value.to_dict() if hasattr(value, 'to_dict') else value\nfor key, value in serialized.items():\n if type(value) in [tuple, list]:\n serialized[key] = [serialize(x) for x in value]\n else:\n serialized[key] = serialize(value)\nreturn seria... | <|body_start_0|>
serialized: dict = vars(self)
serialize = lambda value: value.to_dict() if hasattr(value, 'to_dict') else value
for key, value in serialized.items():
if type(value) in [tuple, list]:
serialized[key] = [serialize(x) for x in value]
else:
... | BaseModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModel:
def to_dict(self) -> dict:
"""Convert the current class into a dictionnary"""
<|body_0|>
def resolve(cls, instance: dict):
"""Resolve a dictionnary into an object"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
serialized: dict = vars(sel... | stack_v2_sparse_classes_36k_train_018691 | 1,183 | no_license | [
{
"docstring": "Convert the current class into a dictionnary",
"name": "to_dict",
"signature": "def to_dict(self) -> dict"
},
{
"docstring": "Resolve a dictionnary into an object",
"name": "resolve",
"signature": "def resolve(cls, instance: dict)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010261 | Implement the Python class `BaseModel` described below.
Class description:
Implement the BaseModel class.
Method signatures and docstrings:
- def to_dict(self) -> dict: Convert the current class into a dictionnary
- def resolve(cls, instance: dict): Resolve a dictionnary into an object | Implement the Python class `BaseModel` described below.
Class description:
Implement the BaseModel class.
Method signatures and docstrings:
- def to_dict(self) -> dict: Convert the current class into a dictionnary
- def resolve(cls, instance: dict): Resolve a dictionnary into an object
<|skeleton|>
class BaseModel:
... | 18a6dfc63a2a6b709391d9e0a0265dc46da71c8b | <|skeleton|>
class BaseModel:
def to_dict(self) -> dict:
"""Convert the current class into a dictionnary"""
<|body_0|>
def resolve(cls, instance: dict):
"""Resolve a dictionnary into an object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseModel:
def to_dict(self) -> dict:
"""Convert the current class into a dictionnary"""
serialized: dict = vars(self)
serialize = lambda value: value.to_dict() if hasattr(value, 'to_dict') else value
for key, value in serialized.items():
if type(value) in [tuple, l... | the_stack_v2_python_sparse | app/models/other/abc.py | Madscientiste/OpenClassrooms_P4 | train | 0 | |
a3747727ffef7616ecc15b3479137a0315395dd5 | [
"shift_values_str = self._hparams.get('shift_values', '')\nshift_values = [int(x) for x in shift_values_str.split(',')]\ntf.logging.info('Computing auxiliary losses for the following shifts: %s', shift_values)\nreturn shift_values",
"assert isinstance(shift, int) and shift != 0\nname = 'reconst_%d' % shift if shi... | <|body_start_0|>
shift_values_str = self._hparams.get('shift_values', '')
shift_values = [int(x) for x in shift_values_str.split(',')]
tf.logging.info('Computing auxiliary losses for the following shifts: %s', shift_values)
return shift_values
<|end_body_0|>
<|body_start_1|>
ass... | Attention net. See file docstring. | TransformerAux | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerAux:
"""Attention net. See file docstring."""
def _extract_shift_values(self):
"""Parses the shift string. The hparams should contain the key shift_values, which maps to a comma-separated string of integers. These integers specify the number of timesteps to predict/reconst... | stack_v2_sparse_classes_36k_train_018692 | 5,658 | permissive | [
{
"docstring": "Parses the shift string. The hparams should contain the key shift_values, which maps to a comma-separated string of integers. These integers specify the number of timesteps to predict/reconstruct to compute auxiliary losses. For instance, \"-4,2,6\" means to reconstruct the target 4 steps before... | 3 | null | Implement the Python class `TransformerAux` described below.
Class description:
Attention net. See file docstring.
Method signatures and docstrings:
- def _extract_shift_values(self): Parses the shift string. The hparams should contain the key shift_values, which maps to a comma-separated string of integers. These in... | Implement the Python class `TransformerAux` described below.
Class description:
Attention net. See file docstring.
Method signatures and docstrings:
- def _extract_shift_values(self): Parses the shift string. The hparams should contain the key shift_values, which maps to a comma-separated string of integers. These in... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class TransformerAux:
"""Attention net. See file docstring."""
def _extract_shift_values(self):
"""Parses the shift string. The hparams should contain the key shift_values, which maps to a comma-separated string of integers. These integers specify the number of timesteps to predict/reconst... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerAux:
"""Attention net. See file docstring."""
def _extract_shift_values(self):
"""Parses the shift string. The hparams should contain the key shift_values, which maps to a comma-separated string of integers. These integers specify the number of timesteps to predict/reconstruct to compu... | the_stack_v2_python_sparse | t2t_bert/utils/tensor2tensor/models/research/transformer_aux.py | yyht/BERT | train | 37 |
51fa3f79818f18be6814bc9664ff9ab5ce080def | [
"self.partner_id = partner_id\nself.borrowers = borrowers\nself.redirect_uri = redirect_uri\nself.webhook = webhook\nself.webhook_content_type = webhook_content_type\nself.webhook_data = webhook_data\nself.webhook_headers = webhook_headers\nself.institution_settings = institution_settings\nself.email = email\nself.... | <|body_start_0|>
self.partner_id = partner_id
self.borrowers = borrowers
self.redirect_uri = redirect_uri
self.webhook = webhook
self.webhook_content_type = webhook_content_type
self.webhook_data = webhook_data
self.webhook_headers = webhook_headers
self.i... | Implementation of the 'V2 Connect Email Request - Joint Borrower' model. TODO: type model description here. Attributes: partner_id (string): Your partner id from the [Finicity Developer Portal](https://signup.finicity.com/). borrowers (list of Borrowers): (MVS) Array of borrowers to pass the primary and joint borrower’... | V2ConnectEmailRequestJointBorrower | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class V2ConnectEmailRequestJointBorrower:
"""Implementation of the 'V2 Connect Email Request - Joint Borrower' model. TODO: type model description here. Attributes: partner_id (string): Your partner id from the [Finicity Developer Portal](https://signup.finicity.com/). borrowers (list of Borrowers): (M... | stack_v2_sparse_classes_36k_train_018693 | 9,443 | permissive | [
{
"docstring": "Constructor for the V2ConnectEmailRequestJointBorrower class",
"name": "__init__",
"signature": "def __init__(self, partner_id=None, borrowers=None, email=None, experience=None, redirect_uri=None, webhook=None, webhook_content_type='application/json', webhook_data=None, webhook_headers=N... | 2 | stack_v2_sparse_classes_30k_train_014325 | Implement the Python class `V2ConnectEmailRequestJointBorrower` described below.
Class description:
Implementation of the 'V2 Connect Email Request - Joint Borrower' model. TODO: type model description here. Attributes: partner_id (string): Your partner id from the [Finicity Developer Portal](https://signup.finicity.c... | Implement the Python class `V2ConnectEmailRequestJointBorrower` described below.
Class description:
Implementation of the 'V2 Connect Email Request - Joint Borrower' model. TODO: type model description here. Attributes: partner_id (string): Your partner id from the [Finicity Developer Portal](https://signup.finicity.c... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class V2ConnectEmailRequestJointBorrower:
"""Implementation of the 'V2 Connect Email Request - Joint Borrower' model. TODO: type model description here. Attributes: partner_id (string): Your partner id from the [Finicity Developer Portal](https://signup.finicity.com/). borrowers (list of Borrowers): (M... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class V2ConnectEmailRequestJointBorrower:
"""Implementation of the 'V2 Connect Email Request - Joint Borrower' model. TODO: type model description here. Attributes: partner_id (string): Your partner id from the [Finicity Developer Portal](https://signup.finicity.com/). borrowers (list of Borrowers): (MVS) Array of ... | the_stack_v2_python_sparse | finicityapi/models/v_2_connect_email_request_joint_borrower.py | monarchmoney/finicity-python | train | 0 |
cb860dd0ae2eb70cac8d187185fa3b03cf2e9f05 | [
"if obj.is_expression:\n dims = {}\n for var in obj.variable_names:\n dim_data = dict(units=obj.variable_units[var])\n dim = obj._symbol_dims.get(var)\n if dim is not None and dim != var:\n dim_data['symbol'] = var\n else:\n dim = var\n dims[dim] = Gene... | <|body_start_0|>
if obj.is_expression:
dims = {}
for var in obj.variable_names:
dim_data = dict(units=obj.variable_units[var])
dim = obj._symbol_dims.get(var)
if dim is not None and dim != var:
dim_data['symbol'] = var
... | Serialization class for weldx.core.GenericSeries | GenericSeriesConverter | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericSeriesConverter:
"""Serialization class for weldx.core.GenericSeries"""
def to_yaml_tree(self, obj: GenericSeries, tag: str, ctx) -> dict:
"""Convert to python dict."""
<|body_0|>
def from_yaml_tree(self, node: dict, tag: str, ctx):
"""Construct from tree.... | stack_v2_sparse_classes_36k_train_018694 | 2,696 | permissive | [
{
"docstring": "Convert to python dict.",
"name": "to_yaml_tree",
"signature": "def to_yaml_tree(self, obj: GenericSeries, tag: str, ctx) -> dict"
},
{
"docstring": "Construct from tree.",
"name": "from_yaml_tree",
"signature": "def from_yaml_tree(self, node: dict, tag: str, ctx)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015609 | Implement the Python class `GenericSeriesConverter` described below.
Class description:
Serialization class for weldx.core.GenericSeries
Method signatures and docstrings:
- def to_yaml_tree(self, obj: GenericSeries, tag: str, ctx) -> dict: Convert to python dict.
- def from_yaml_tree(self, node: dict, tag: str, ctx):... | Implement the Python class `GenericSeriesConverter` described below.
Class description:
Serialization class for weldx.core.GenericSeries
Method signatures and docstrings:
- def to_yaml_tree(self, obj: GenericSeries, tag: str, ctx) -> dict: Convert to python dict.
- def from_yaml_tree(self, node: dict, tag: str, ctx):... | 7bc16a196ee669822f3663f3c7a08f6bbd0c76d5 | <|skeleton|>
class GenericSeriesConverter:
"""Serialization class for weldx.core.GenericSeries"""
def to_yaml_tree(self, obj: GenericSeries, tag: str, ctx) -> dict:
"""Convert to python dict."""
<|body_0|>
def from_yaml_tree(self, node: dict, tag: str, ctx):
"""Construct from tree.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericSeriesConverter:
"""Serialization class for weldx.core.GenericSeries"""
def to_yaml_tree(self, obj: GenericSeries, tag: str, ctx) -> dict:
"""Convert to python dict."""
if obj.is_expression:
dims = {}
for var in obj.variable_names:
dim_data =... | the_stack_v2_python_sparse | weldx/tags/core/generic_series.py | BAMWelDX/weldx | train | 20 |
83f51190bd723f02e0b48277f8b71f571f342d07 | [
"load_file = LoadFileValidator(self.value)\nis_file_loaded = load_file.validate()\nself.append_report(load_file)\nif not is_file_loaded:\n return False\nload_yaml = LoadYamlValidator(load_file)\nis_yaml_loaded = load_yaml.validate()\nself.append_report(load_yaml)\nif not is_yaml_loaded:\n return False\nconfig... | <|body_start_0|>
load_file = LoadFileValidator(self.value)
is_file_loaded = load_file.validate()
self.append_report(load_file)
if not is_file_loaded:
return False
load_yaml = LoadYamlValidator(load_file)
is_yaml_loaded = load_yaml.validate()
self.appen... | Validator for an API Map file. Validator for validating a given configuration file. Consists of a FileLoadValidator, a YamlLoadValidator and an ConfigYamlValidator. Attributes: value: The file name or file path as Text. | ConfigFileValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFileValidator:
"""Validator for an API Map file. Validator for validating a given configuration file. Consists of a FileLoadValidator, a YamlLoadValidator and an ConfigYamlValidator. Attributes: value: The file name or file path as Text."""
def validate(self) -> bool:
"""Valida... | stack_v2_sparse_classes_36k_train_018695 | 13,405 | no_license | [
{
"docstring": "Validates the value. Validates the value attribute while generating a validation Report. @return: Whether further Validators may continue validating.",
"name": "validate",
"signature": "def validate(self) -> bool"
},
{
"docstring": "TODO: Fill out",
"name": "result",
"sig... | 2 | stack_v2_sparse_classes_30k_train_003541 | Implement the Python class `ConfigFileValidator` described below.
Class description:
Validator for an API Map file. Validator for validating a given configuration file. Consists of a FileLoadValidator, a YamlLoadValidator and an ConfigYamlValidator. Attributes: value: The file name or file path as Text.
Method signat... | Implement the Python class `ConfigFileValidator` described below.
Class description:
Validator for an API Map file. Validator for validating a given configuration file. Consists of a FileLoadValidator, a YamlLoadValidator and an ConfigYamlValidator. Attributes: value: The file name or file path as Text.
Method signat... | 09e970944f8bc07dc565576cb798c6db4f17b347 | <|skeleton|>
class ConfigFileValidator:
"""Validator for an API Map file. Validator for validating a given configuration file. Consists of a FileLoadValidator, a YamlLoadValidator and an ConfigYamlValidator. Attributes: value: The file name or file path as Text."""
def validate(self) -> bool:
"""Valida... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFileValidator:
"""Validator for an API Map file. Validator for validating a given configuration file. Consists of a FileLoadValidator, a YamlLoadValidator and an ConfigYamlValidator. Attributes: value: The file name or file path as Text."""
def validate(self) -> bool:
"""Validates the value... | the_stack_v2_python_sparse | open_crypto/model/validating/config_file_validator.py | SergejUschakow/open-crypto | train | 0 |
b123aacf1549581d2b000ad0970e28531c40e5ec | [
"sig = (dividend > 0) ^ (divisor > 0)\ndividend, divisor = (abs(dividend), abs(divisor))\nif divisor == 1:\n result = dividend\nelse:\n result = len(range(0, dividend + 1, divisor)) - 1\nif sig:\n return max(-result, -2 ** 31)\nelse:\n return min(result, 2 ** 31 - 1)",
"sig = (dividend > 0) ^ (divisor... | <|body_start_0|>
sig = (dividend > 0) ^ (divisor > 0)
dividend, divisor = (abs(dividend), abs(divisor))
if divisor == 1:
result = dividend
else:
result = len(range(0, dividend + 1, divisor)) - 1
if sig:
return max(-result, -2 ** 31)
els... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def divide1(self, dividend: int, divisor: int) -> int:
"""Using stepwise range()"""
<|body_0|>
def divide2(self, dividend: int, divisor: int) -> int:
"""Bitwise Operation"""
<|body_1|>
def _bit_size(self, dividend: int, divisor: int):
"... | stack_v2_sparse_classes_36k_train_018696 | 2,040 | permissive | [
{
"docstring": "Using stepwise range()",
"name": "divide1",
"signature": "def divide1(self, dividend: int, divisor: int) -> int"
},
{
"docstring": "Bitwise Operation",
"name": "divide2",
"signature": "def divide2(self, dividend: int, divisor: int) -> int"
},
{
"docstring": "To fi... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divide1(self, dividend: int, divisor: int) -> int: Using stepwise range()
- def divide2(self, dividend: int, divisor: int) -> int: Bitwise Operation
- def _bit_size(self, div... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divide1(self, dividend: int, divisor: int) -> int: Using stepwise range()
- def divide2(self, dividend: int, divisor: int) -> int: Bitwise Operation
- def _bit_size(self, div... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def divide1(self, dividend: int, divisor: int) -> int:
"""Using stepwise range()"""
<|body_0|>
def divide2(self, dividend: int, divisor: int) -> int:
"""Bitwise Operation"""
<|body_1|>
def _bit_size(self, dividend: int, divisor: int):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def divide1(self, dividend: int, divisor: int) -> int:
"""Using stepwise range()"""
sig = (dividend > 0) ^ (divisor > 0)
dividend, divisor = (abs(dividend), abs(divisor))
if divisor == 1:
result = dividend
else:
result = len(range(0, di... | the_stack_v2_python_sparse | leetcode/0029_divide_two_integers.py | chaosWsF/Python-Practice | train | 1 | |
ac1034028c8499681321515eb904e8dd1f60571c | [
"m = len(matrix)\nif m == 0:\n return 0\nn = len(matrix[0])\nheight = [[0] * n for row in range(m)]\nfor i in range(m):\n for j in range(n):\n k = ord(matrix[i][j]) - ord('0')\n height[i][j] = (height[i - 1][j] + 1) * k\nmaximum = 0\nfor i in range(m):\n maximum = max(maximum, self.largestRec... | <|body_start_0|>
m = len(matrix)
if m == 0:
return 0
n = len(matrix[0])
height = [[0] * n for row in range(m)]
for i in range(m):
for j in range(n):
k = ord(matrix[i][j]) - ord('0')
height[i][j] = (height[i - 1][j] + 1) * k
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
"""Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area."""
<|body_0|>
def largestRectangleArea(self, height):
"""Given n non-negative integers representing ... | stack_v2_sparse_classes_36k_train_018697 | 1,688 | no_license | [
{
"docstring": "Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
},
{
"docstring": "Given n non-negative integers representing the histogram's bar ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
- def largestRectangleAr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
- def largestRectangleAr... | d16e4724ee34a0046cb2a8b0b13139b43d284e83 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
"""Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area."""
<|body_0|>
def largestRectangleArea(self, height):
"""Given n non-negative integers representing ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalRectangle(self, matrix):
"""Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area."""
m = len(matrix)
if m == 0:
return 0
n = len(matrix[0])
height = [[0] * n for row in rang... | the_stack_v2_python_sparse | Maximal Rectangle.py | KnightChan/LeetCode-Python | train | 0 | |
10b004d7e3063e1db2599848bc6c1de807c0cecc | [
"if obj is None:\n return getattr(self, 'model', None)\nreturn obj.__class__",
"excluded_fields = super().get_exclude(request, obj=obj)\nif self.admin_integration_enabled:\n model_cls = self.get_model_cls(obj)\n if model_cls:\n excluded_fields = list({*model_cls.Moderation.excluded_fields, *exclud... | <|body_start_0|>
if obj is None:
return getattr(self, 'model', None)
return obj.__class__
<|end_body_0|>
<|body_start_1|>
excluded_fields = super().get_exclude(request, obj=obj)
if self.admin_integration_enabled:
model_cls = self.get_model_cls(obj)
if... | Admin for models requiring moderation. | ModeratedModelAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModeratedModelAdmin:
"""Admin for models requiring moderation."""
def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]:
"""Return the class of the moderated model."""
<|body_0|>
def get_exclude(self, request: 'HttpRequest', ob... | stack_v2_sparse_classes_36k_train_018698 | 6,185 | no_license | [
{
"docstring": "Return the class of the moderated model.",
"name": "get_model_cls",
"signature": "def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]"
},
{
"docstring": "Return the fields to be excluded from the admin form.",
"name": "get_exclude... | 5 | stack_v2_sparse_classes_30k_train_001670 | Implement the Python class `ModeratedModelAdmin` described below.
Class description:
Admin for models requiring moderation.
Method signatures and docstrings:
- def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]: Return the class of the moderated model.
- def get_exclude(... | Implement the Python class `ModeratedModelAdmin` described below.
Class description:
Admin for models requiring moderation.
Method signatures and docstrings:
- def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]: Return the class of the moderated model.
- def get_exclude(... | 8bbdc8eec3622af22c17214051c34e36bea8e05a | <|skeleton|>
class ModeratedModelAdmin:
"""Admin for models requiring moderation."""
def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]:
"""Return the class of the moderated model."""
<|body_0|>
def get_exclude(self, request: 'HttpRequest', ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModeratedModelAdmin:
"""Admin for models requiring moderation."""
def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]:
"""Return the class of the moderated model."""
if obj is None:
return getattr(self, 'model', None)
retur... | the_stack_v2_python_sparse | apps/moderation/admin/moderated_model/admin.py | abdulwahed-mansour/modularhistory | train | 1 |
452c12ce53d32f0c8f52832cbaf41efe4167b3a6 | [
"self.wait_for_daemon_start()\noriginal_active, = self.fs.get_active_names()\noriginal_standbys = self.mds_cluster.get_standby_daemons()\nself.fs.mds_stop(original_active)\ngrace = float(self.fs.get_config('mds_beacon_grace', service_type='mon'))\n\ndef promoted():\n active = self.fs.get_active_names()\n retu... | <|body_start_0|>
self.wait_for_daemon_start()
original_active, = self.fs.get_active_names()
original_standbys = self.mds_cluster.get_standby_daemons()
self.fs.mds_stop(original_active)
grace = float(self.fs.get_config('mds_beacon_grace', service_type='mon'))
def promoted... | TestFailover | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFailover:
def test_simple(self):
"""That when the active MDS is killed, a standby MDS is promoted into its rank after the grace period. This is just a simple unit test, the harder cases are covered in thrashing tests."""
<|body_0|>
def test_client_abort(self):
""... | stack_v2_sparse_classes_36k_train_018699 | 23,165 | permissive | [
{
"docstring": "That when the active MDS is killed, a standby MDS is promoted into its rank after the grace period. This is just a simple unit test, the harder cases are covered in thrashing tests.",
"name": "test_simple",
"signature": "def test_simple(self)"
},
{
"docstring": "That a client wil... | 4 | stack_v2_sparse_classes_30k_train_008706 | Implement the Python class `TestFailover` described below.
Class description:
Implement the TestFailover class.
Method signatures and docstrings:
- def test_simple(self): That when the active MDS is killed, a standby MDS is promoted into its rank after the grace period. This is just a simple unit test, the harder cas... | Implement the Python class `TestFailover` described below.
Class description:
Implement the TestFailover class.
Method signatures and docstrings:
- def test_simple(self): That when the active MDS is killed, a standby MDS is promoted into its rank after the grace period. This is just a simple unit test, the harder cas... | 6a0747b6b79f5ca814afca6cefeb45f52fb9a509 | <|skeleton|>
class TestFailover:
def test_simple(self):
"""That when the active MDS is killed, a standby MDS is promoted into its rank after the grace period. This is just a simple unit test, the harder cases are covered in thrashing tests."""
<|body_0|>
def test_client_abort(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFailover:
def test_simple(self):
"""That when the active MDS is killed, a standby MDS is promoted into its rank after the grace period. This is just a simple unit test, the harder cases are covered in thrashing tests."""
self.wait_for_daemon_start()
original_active, = self.fs.get_a... | the_stack_v2_python_sparse | qa/tasks/cephfs/test_failover.py | SrinivasaBharath/ceph-1 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.