body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def _trusted_commit(self, committer_id, commit_type, commit_message, commit_cmds): 'Record the event to the commit log after the model commit.\n\n Note that this extends the superclass method.\n\n Args:\n committer_id: str. The user_id of the user who committed the\n change.\...
8,086,757,080,571,136,000
Record the event to the commit log after the model commit. Note that this extends the superclass method. Args: committer_id: str. The user_id of the user who committed the change. commit_type: str. The type of commit. Possible values are in core.storage.base_models.COMMIT_TYPE_CHOICES. com...
core/domain/activity_jobs_one_off_test.py
_trusted_commit
AnanyaNegi/oppia
python
def _trusted_commit(self, committer_id, commit_type, commit_message, commit_cmds): 'Record the event to the commit log after the model commit.\n\n Note that this extends the superclass method.\n\n Args:\n committer_id: str. The user_id of the user who committed the\n change.\...
def _trusted_commit(self, committer_id, commit_type, commit_message, commit_cmds): 'Record the event to the commit log after the model commit.\n\n Note that this extends the superclass method.\n\n Args:\n committer_id: str. The user_id of the user who committed the\n change.\...
3,609,551,769,068,114,400
Record the event to the commit log after the model commit. Note that this extends the superclass method. Args: committer_id: str. The user_id of the user who committed the change. commit_type: str. The type of commit. Possible values are in core.storage.base_models.COMMIT_TYPE_CHOICES. com...
core/domain/activity_jobs_one_off_test.py
_trusted_commit
AnanyaNegi/oppia
python
def _trusted_commit(self, committer_id, commit_type, commit_message, commit_cmds): 'Record the event to the commit log after the model commit.\n\n Note that this extends the superclass method.\n\n Args:\n committer_id: str. The user_id of the user who committed the\n change.\...
def _run_one_off_job(self): 'Runs the one-off MapReduce job.' job_id = activity_jobs_one_off.AddContentUserIdsContentJob.create_new() activity_jobs_one_off.AddContentUserIdsContentJob.enqueue(job_id) self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1) ...
-5,408,814,941,831,667,000
Runs the one-off MapReduce job.
core/domain/activity_jobs_one_off_test.py
_run_one_off_job
AnanyaNegi/oppia
python
def _run_one_off_job(self): job_id = activity_jobs_one_off.AddContentUserIdsContentJob.create_new() activity_jobs_one_off.AddContentUserIdsContentJob.enqueue(job_id) self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1) self.process_and_flush_pendin...
def _run_one_off_job(self): 'Runs the one-off MapReduce job.' job_id = activity_jobs_one_off.AddCommitCmdsUserIdsMetadataJob.create_new() activity_jobs_one_off.AddCommitCmdsUserIdsMetadataJob.enqueue(job_id) self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JO...
5,209,690,579,846,129,000
Runs the one-off MapReduce job.
core/domain/activity_jobs_one_off_test.py
_run_one_off_job
AnanyaNegi/oppia
python
def _run_one_off_job(self): job_id = activity_jobs_one_off.AddCommitCmdsUserIdsMetadataJob.create_new() activity_jobs_one_off.AddCommitCmdsUserIdsMetadataJob.enqueue(job_id) self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1) self.process_and_flus...
def _run_one_off_job(self): 'Runs the one-off MapReduce job.' job_id = activity_jobs_one_off.AuditSnapshotMetadataModelsJob.create_new() activity_jobs_one_off.AuditSnapshotMetadataModelsJob.enqueue(job_id) self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS...
-3,907,230,091,904,724,000
Runs the one-off MapReduce job.
core/domain/activity_jobs_one_off_test.py
_run_one_off_job
AnanyaNegi/oppia
python
def _run_one_off_job(self): job_id = activity_jobs_one_off.AuditSnapshotMetadataModelsJob.create_new() activity_jobs_one_off.AuditSnapshotMetadataModelsJob.enqueue(job_id) self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1) self.process_and_flush_...
def _run_one_off_job(self): 'Runs the one-off MapReduce job.' job_class = activity_jobs_one_off.ValidateSnapshotMetadataModelsJob job_id = job_class.create_new() activity_jobs_one_off.ValidateSnapshotMetadataModelsJob.enqueue(job_id) self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_...
9,207,150,648,411,642,000
Runs the one-off MapReduce job.
core/domain/activity_jobs_one_off_test.py
_run_one_off_job
AnanyaNegi/oppia
python
def _run_one_off_job(self): job_class = activity_jobs_one_off.ValidateSnapshotMetadataModelsJob job_id = job_class.create_new() activity_jobs_one_off.ValidateSnapshotMetadataModelsJob.enqueue(job_id) self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS)...
def clean_str(string): '\n Tokenization/string cleaning for all datasets except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n ' string = re.sub("[^A-Za-z0-9(),!?\\'\\`]", ' ', string) string = re.sub("\\'s", " 's", string) string = re.sub("...
6,380,898,887,572,334,000
Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
data_helpers.py
clean_str
pychuang/ist557-data-mining-cnn
python
def clean_str(string): '\n Tokenization/string cleaning for all datasets except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n ' string = re.sub("[^A-Za-z0-9(),!?\\'\\`]", ' ', string) string = re.sub("\\'s", " 's", string) string = re.sub("...
def load_data_and_labels(data_file): '\n Loads MR polarity data from files, splits the data into words and generates labels.\n Returns split sentences and labels.\n ' datapoints = load_datapoints(data_file) x_text = extract_phrases_in_datapoints(datapoints) y = [int(dp.Sentiment) for dp in data...
4,745,854,949,447,349,000
Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels.
data_helpers.py
load_data_and_labels
pychuang/ist557-data-mining-cnn
python
def load_data_and_labels(data_file): '\n Loads MR polarity data from files, splits the data into words and generates labels.\n Returns split sentences and labels.\n ' datapoints = load_datapoints(data_file) x_text = extract_phrases_in_datapoints(datapoints) y = [int(dp.Sentiment) for dp in data...
def batch_iter(data, batch_size, num_epochs, shuffle=True): '\n Generates a batch iterator for a dataset.\n ' data = np.array(data) data_size = len(data) num_batches_per_epoch = (int((len(data) / batch_size)) + 1) for epoch in range(num_epochs): if shuffle: shuffle_indices ...
6,353,081,854,038,388,000
Generates a batch iterator for a dataset.
data_helpers.py
batch_iter
pychuang/ist557-data-mining-cnn
python
def batch_iter(data, batch_size, num_epochs, shuffle=True): '\n \n ' data = np.array(data) data_size = len(data) num_batches_per_epoch = (int((len(data) / batch_size)) + 1) for epoch in range(num_epochs): if shuffle: shuffle_indices = np.random.permutation(np.arange(data_si...
def test_tabs(self): 'Test tabs functionality' text = '\t\tHello' expected = '\t\t' got = get_leading_whitespace(text) assert (expected == got)
-2,184,680,040,339,133,400
Test tabs functionality
tests/test_utils.py
test_tabs
lukerm48/dyc
python
def test_tabs(self): text = '\t\tHello' expected = '\t\t' got = get_leading_whitespace(text) assert (expected == got)
def test_whitespace(self): 'Test whitespace functionality' space = ' ' text = '{space}Such a long whitespace'.format(space=space) expected = space got = get_leading_whitespace(text) assert (expected == got)
4,380,228,456,149,272,600
Test whitespace functionality
tests/test_utils.py
test_whitespace
lukerm48/dyc
python
def test_whitespace(self): space = ' ' text = '{space}Such a long whitespace'.format(space=space) expected = space got = get_leading_whitespace(text) assert (expected == got)
def test_valid_comments(self): 'Testing valid comments' text = '# Hello World' assert (is_comment(text, ['#']) == True)
-3,741,295,515,058,425,000
Testing valid comments
tests/test_utils.py
test_valid_comments
lukerm48/dyc
python
def test_valid_comments(self): text = '# Hello World' assert (is_comment(text, ['#']) == True)
def test_invalid_comments(self): 'Testing invalid comments' text = '# Hello World' assert (is_comment(text, ['//']) == False)
-2,414,815,970,119,370,000
Testing invalid comments
tests/test_utils.py
test_invalid_comments
lukerm48/dyc
python
def test_invalid_comments(self): text = '# Hello World' assert (is_comment(text, ['//']) == False)
def load_preprocessed_data(self): '\n raw_data is a list that has three components\n component1) trajectory data for training\n component2) trajectory data for validation and visualization\n ' f = open(self.dataset_path, 'rb') raw_data = pickle.load(f) f.close() counter =...
-470,723,059,986,581,900
raw_data is a list that has three components component1) trajectory data for training component2) trajectory data for validation and visualization
kitti_utils.py
load_preprocessed_data
d1024choi/trajpred_irl
python
def load_preprocessed_data(self): '\n raw_data is a list that has three components\n component1) trajectory data for training\n component2) trajectory data for validation and visualization\n ' f = open(self.dataset_path, 'rb') raw_data = pickle.load(f) f.close() counter =...
def preprocess_sequence(self, seq, isValid, isDiff): '\n dataset id (0)\n object id (1)\n target pose (2~3)\n neighbor pose (4~63)\n ' seq_len = seq.shape[0] seq_tpose = np.copy(seq[:, 2:4]) seq_npose = np.copy(seq[:, 4:64]).reshape(seq_len, 30, 2) dataset_index = ...
4,740,553,938,265,372,000
dataset id (0) object id (1) target pose (2~3) neighbor pose (4~63)
kitti_utils.py
preprocess_sequence
d1024choi/trajpred_irl
python
def preprocess_sequence(self, seq, isValid, isDiff): '\n dataset id (0)\n object id (1)\n target pose (2~3)\n neighbor pose (4~63)\n ' seq_len = seq.shape[0] seq_tpose = np.copy(seq[:, 2:4]) seq_npose = np.copy(seq[:, 4:64]).reshape(seq_len, 30, 2) dataset_index = ...
def next_batch(self): '\n Read a batch randomly\n :x_batch: <batch size x seq_length x input_dim>\n :y_batch: <batch size x seq_length x input_dim>\n :d_batch: <batch size x seq_length>\n ' x_batch = [] y_batch = [] sg_batch = [] map_batch = [] d_batch = [] ...
-7,187,001,706,206,327,000
Read a batch randomly :x_batch: <batch size x seq_length x input_dim> :y_batch: <batch size x seq_length x input_dim> :d_batch: <batch size x seq_length>
kitti_utils.py
next_batch
d1024choi/trajpred_irl
python
def next_batch(self): '\n Read a batch randomly\n :x_batch: <batch size x seq_length x input_dim>\n :y_batch: <batch size x seq_length x input_dim>\n :d_batch: <batch size x seq_length>\n ' x_batch = [] y_batch = [] sg_batch = [] map_batch = [] d_batch = [] ...
def next_batch_valid(self): '\n Read a batch randomly for validation during training\n :x_batch: <batch size x seq_length x input_dim>\n :y_batch: <batch size x seq_length x input_dim>\n :d_batch: <batch size x seq_length>\n ' x_batch = [] y_batch = [] sg_batch = [] ...
-2,475,856,481,739,356,000
Read a batch randomly for validation during training :x_batch: <batch size x seq_length x input_dim> :y_batch: <batch size x seq_length x input_dim> :d_batch: <batch size x seq_length>
kitti_utils.py
next_batch_valid
d1024choi/trajpred_irl
python
def next_batch_valid(self): '\n Read a batch randomly for validation during training\n :x_batch: <batch size x seq_length x input_dim>\n :y_batch: <batch size x seq_length x input_dim>\n :d_batch: <batch size x seq_length>\n ' x_batch = [] y_batch = [] sg_batch = [] ...
def next_sequence_valid(self): '\n\n dataset id (0)\n object id (1)\n target pose (2~3)\n neighbor pose (4~63)\n\n Read a batch randomly for validation and visualization\n :x_batch: <batch size x seq_length x input_dim>\n :y_batch: <batch size x seq_length x input_di...
7,151,321,459,105,572,000
dataset id (0) object id (1) target pose (2~3) neighbor pose (4~63) Read a batch randomly for validation and visualization :x_batch: <batch size x seq_length x input_dim> :y_batch: <batch size x seq_length x input_dim> :d_batch: <batch size x seq_length>
kitti_utils.py
next_sequence_valid
d1024choi/trajpred_irl
python
def next_sequence_valid(self): '\n\n dataset id (0)\n object id (1)\n target pose (2~3)\n neighbor pose (4~63)\n\n Read a batch randomly for validation and visualization\n :x_batch: <batch size x seq_length x input_dim>\n :y_batch: <batch size x seq_length x input_di...
def _load_from_socket(port, auth_secret): '\n Load data from a given socket, this is a blocking method thus only return when the socket\n connection has been closed.\n ' (sockfile, sock) = local_connect_and_auth(port, auth_secret) sock.settimeout(None) write_int(BARRIER_FUNCTION, sockfile) ...
4,420,216,276,343,981,000
Load data from a given socket, this is a blocking method thus only return when the socket connection has been closed.
python/pyspark/taskcontext.py
_load_from_socket
2RedSquares/spark
python
def _load_from_socket(port, auth_secret): '\n Load data from a given socket, this is a blocking method thus only return when the socket\n connection has been closed.\n ' (sockfile, sock) = local_connect_and_auth(port, auth_secret) sock.settimeout(None) write_int(BARRIER_FUNCTION, sockfile) ...
def __new__(cls): 'Even if users construct TaskContext instead of using get, give them the singleton.' taskContext = cls._taskContext if (taskContext is not None): return taskContext cls._taskContext = taskContext = object.__new__(cls) return taskContext
3,980,086,144,201,819,600
Even if users construct TaskContext instead of using get, give them the singleton.
python/pyspark/taskcontext.py
__new__
2RedSquares/spark
python
def __new__(cls): taskContext = cls._taskContext if (taskContext is not None): return taskContext cls._taskContext = taskContext = object.__new__(cls) return taskContext
@classmethod def _getOrCreate(cls): 'Internal function to get or create global TaskContext.' if (cls._taskContext is None): cls._taskContext = TaskContext() return cls._taskContext
6,418,743,054,464,887,000
Internal function to get or create global TaskContext.
python/pyspark/taskcontext.py
_getOrCreate
2RedSquares/spark
python
@classmethod def _getOrCreate(cls): if (cls._taskContext is None): cls._taskContext = TaskContext() return cls._taskContext
@classmethod def get(cls): '\n Return the currently active TaskContext. This can be called inside of\n user functions to access contextual information about running tasks.\n\n .. note:: Must be called on the worker, not the driver. Returns None if not initialized.\n ' return cls._tas...
1,419,744,605,024,734,200
Return the currently active TaskContext. This can be called inside of user functions to access contextual information about running tasks. .. note:: Must be called on the worker, not the driver. Returns None if not initialized.
python/pyspark/taskcontext.py
get
2RedSquares/spark
python
@classmethod def get(cls): '\n Return the currently active TaskContext. This can be called inside of\n user functions to access contextual information about running tasks.\n\n .. note:: Must be called on the worker, not the driver. Returns None if not initialized.\n ' return cls._tas...
def stageId(self): 'The ID of the stage that this task belong to.' return self._stageId
-8,501,152,381,933,950,000
The ID of the stage that this task belong to.
python/pyspark/taskcontext.py
stageId
2RedSquares/spark
python
def stageId(self): return self._stageId
def partitionId(self): '\n The ID of the RDD partition that is computed by this task.\n ' return self._partitionId
4,923,525,649,721,193,000
The ID of the RDD partition that is computed by this task.
python/pyspark/taskcontext.py
partitionId
2RedSquares/spark
python
def partitionId(self): '\n \n ' return self._partitionId
def attemptNumber(self): '"\n How many times this task has been attempted. The first task attempt will be assigned\n attemptNumber = 0, and subsequent attempts will have increasing attempt numbers.\n ' return self._attemptNumber
8,904,765,901,230,001,000
" How many times this task has been attempted. The first task attempt will be assigned attemptNumber = 0, and subsequent attempts will have increasing attempt numbers.
python/pyspark/taskcontext.py
attemptNumber
2RedSquares/spark
python
def attemptNumber(self): '"\n How many times this task has been attempted. The first task attempt will be assigned\n attemptNumber = 0, and subsequent attempts will have increasing attempt numbers.\n ' return self._attemptNumber
def taskAttemptId(self): "\n An ID that is unique to this task attempt (within the same SparkContext, no two task\n attempts will share the same attempt ID). This is roughly equivalent to Hadoop's\n TaskAttemptID.\n " return self._taskAttemptId
-2,749,768,595,232,958,500
An ID that is unique to this task attempt (within the same SparkContext, no two task attempts will share the same attempt ID). This is roughly equivalent to Hadoop's TaskAttemptID.
python/pyspark/taskcontext.py
taskAttemptId
2RedSquares/spark
python
def taskAttemptId(self): "\n An ID that is unique to this task attempt (within the same SparkContext, no two task\n attempts will share the same attempt ID). This is roughly equivalent to Hadoop's\n TaskAttemptID.\n " return self._taskAttemptId
def getLocalProperty(self, key): '\n Get a local property set upstream in the driver, or None if it is missing.\n ' return self._localProperties.get(key, None)
-8,642,961,275,192,264,000
Get a local property set upstream in the driver, or None if it is missing.
python/pyspark/taskcontext.py
getLocalProperty
2RedSquares/spark
python
def getLocalProperty(self, key): '\n \n ' return self._localProperties.get(key, None)
def resources(self): '\n Resources allocated to the task. The key is the resource name and the value is information\n about the resource.\n ' return self._resources
-8,342,268,450,500,635,000
Resources allocated to the task. The key is the resource name and the value is information about the resource.
python/pyspark/taskcontext.py
resources
2RedSquares/spark
python
def resources(self): '\n Resources allocated to the task. The key is the resource name and the value is information\n about the resource.\n ' return self._resources
@classmethod def _getOrCreate(cls): '\n Internal function to get or create global BarrierTaskContext. We need to make sure\n BarrierTaskContext is returned from here because it is needed in python worker reuse\n scenario, see SPARK-25921 for more details.\n ' if (not isinstance(cls._...
2,762,703,837,966,486,500
Internal function to get or create global BarrierTaskContext. We need to make sure BarrierTaskContext is returned from here because it is needed in python worker reuse scenario, see SPARK-25921 for more details.
python/pyspark/taskcontext.py
_getOrCreate
2RedSquares/spark
python
@classmethod def _getOrCreate(cls): '\n Internal function to get or create global BarrierTaskContext. We need to make sure\n BarrierTaskContext is returned from here because it is needed in python worker reuse\n scenario, see SPARK-25921 for more details.\n ' if (not isinstance(cls._...
@classmethod def get(cls): '\n .. note:: Experimental\n\n Return the currently active :class:`BarrierTaskContext`.\n This can be called inside of user functions to access contextual information about\n running tasks.\n\n .. note:: Must be called on the worker, not the driver. Retu...
8,051,729,507,975,203,000
.. note:: Experimental Return the currently active :class:`BarrierTaskContext`. This can be called inside of user functions to access contextual information about running tasks. .. note:: Must be called on the worker, not the driver. Returns None if not initialized.
python/pyspark/taskcontext.py
get
2RedSquares/spark
python
@classmethod def get(cls): '\n .. note:: Experimental\n\n Return the currently active :class:`BarrierTaskContext`.\n This can be called inside of user functions to access contextual information about\n running tasks.\n\n .. note:: Must be called on the worker, not the driver. Retu...
@classmethod def _initialize(cls, port, secret): '\n Initialize BarrierTaskContext, other methods within BarrierTaskContext can only be called\n after BarrierTaskContext is initialized.\n ' cls._port = port cls._secret = secret
-1,927,426,430,799,265,000
Initialize BarrierTaskContext, other methods within BarrierTaskContext can only be called after BarrierTaskContext is initialized.
python/pyspark/taskcontext.py
_initialize
2RedSquares/spark
python
@classmethod def _initialize(cls, port, secret): '\n Initialize BarrierTaskContext, other methods within BarrierTaskContext can only be called\n after BarrierTaskContext is initialized.\n ' cls._port = port cls._secret = secret
def barrier(self): '\n .. note:: Experimental\n\n Sets a global barrier and waits until all tasks in this stage hit this barrier.\n Similar to `MPI_Barrier` function in MPI, this function blocks until all tasks\n in the same stage have reached this routine.\n\n .. warning:: In a b...
-5,306,368,122,698,499,000
.. note:: Experimental Sets a global barrier and waits until all tasks in this stage hit this barrier. Similar to `MPI_Barrier` function in MPI, this function blocks until all tasks in the same stage have reached this routine. .. warning:: In a barrier stage, each task much have the same number of `barrier()` cal...
python/pyspark/taskcontext.py
barrier
2RedSquares/spark
python
def barrier(self): '\n .. note:: Experimental\n\n Sets a global barrier and waits until all tasks in this stage hit this barrier.\n Similar to `MPI_Barrier` function in MPI, this function blocks until all tasks\n in the same stage have reached this routine.\n\n .. warning:: In a b...
def getTaskInfos(self): '\n .. note:: Experimental\n\n Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage,\n ordered by partition ID.\n\n .. versionadded:: 2.4.0\n ' if ((self._port is None) or (self._secret is None)): raise Exception(('Not supported ...
855,620,321,117,693,600
.. note:: Experimental Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage, ordered by partition ID. .. versionadded:: 2.4.0
python/pyspark/taskcontext.py
getTaskInfos
2RedSquares/spark
python
def getTaskInfos(self): '\n .. note:: Experimental\n\n Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage,\n ordered by partition ID.\n\n .. versionadded:: 2.4.0\n ' if ((self._port is None) or (self._secret is None)): raise Exception(('Not supported ...
def run_test(self): 'Main test logic' cli_response = self.nodes[0].cli('-version').send_cli() assert ('Deepcoin Core RPC client version' in cli_response) self.log.info('Compare responses from gewalletinfo RPC and `deepcoin-cli getwalletinfo`') cli_response = self.nodes[0].cli.getwalletinfo() rpc...
1,788,795,389,587,930,000
Main test logic
test/functional/interface_deepcoin_cli.py
run_test
deepcoindev2/Deepcoin
python
def run_test(self): cli_response = self.nodes[0].cli('-version').send_cli() assert ('Deepcoin Core RPC client version' in cli_response) self.log.info('Compare responses from gewalletinfo RPC and `deepcoin-cli getwalletinfo`') cli_response = self.nodes[0].cli.getwalletinfo() rpc_response = self....
def __init__(self): 'FlatLocales - a model defined in OpenAPI' self.discriminator = None
2,601,218,367,010,354,000
FlatLocales - a model defined in OpenAPI
flat_api/models/flat_locales.py
__init__
FlatIO/api-client-python
python
def __init__(self): self.discriminator = None
def to_dict(self): 'Returns the model properties as a dict' result = {} for (attr, _) in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) e...
8,442,519,487,048,767,000
Returns the model properties as a dict
flat_api/models/flat_locales.py
to_dict
FlatIO/api-client-python
python
def to_dict(self): result = {} for (attr, _) in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): ...
def to_str(self): 'Returns the string representation of the model' return pprint.pformat(self.to_dict())
5,849,158,643,760,736,000
Returns the string representation of the model
flat_api/models/flat_locales.py
to_str
FlatIO/api-client-python
python
def to_str(self): return pprint.pformat(self.to_dict())
def __repr__(self): 'For `print` and `pprint`' return self.to_str()
-8,960,031,694,814,905,000
For `print` and `pprint`
flat_api/models/flat_locales.py
__repr__
FlatIO/api-client-python
python
def __repr__(self): return self.to_str()
def __eq__(self, other): 'Returns true if both objects are equal' if (not isinstance(other, FlatLocales)): return False return (self.__dict__ == other.__dict__)
8,377,921,118,189,592,000
Returns true if both objects are equal
flat_api/models/flat_locales.py
__eq__
FlatIO/api-client-python
python
def __eq__(self, other): if (not isinstance(other, FlatLocales)): return False return (self.__dict__ == other.__dict__)
def __ne__(self, other): 'Returns true if both objects are not equal' return (not (self == other))
7,764,124,047,908,058,000
Returns true if both objects are not equal
flat_api/models/flat_locales.py
__ne__
FlatIO/api-client-python
python
def __ne__(self, other): return (not (self == other))
def child(self, index): 'Returns the child HDPrivateKey at a particular index.\n Hardened children return for indices >= 0x8000000.\n ' if (index >= 2147483648): data = (int_to_big_endian(self.private_key.secret, 33) + int_to_big_endian(index, 4)) else: data = (self.private_key...
7,838,682,160,407,161,000
Returns the child HDPrivateKey at a particular index. Hardened children return for indices >= 0x8000000.
session6/hd.py
child
jimmysong/pw-exercises
python
def child(self, index): 'Returns the child HDPrivateKey at a particular index.\n Hardened children return for indices >= 0x8000000.\n ' if (index >= 2147483648): data = (int_to_big_endian(self.private_key.secret, 33) + int_to_big_endian(index, 4)) else: data = (self.private_key...
def traverse(self, path): "Returns the HDPrivateKey at the path indicated.\n Path should be in the form of m/x/y/z where x' means\n hardened" current = self components = path.split('/')[1:] for child in components: if child.endswith("'"): index = (int(child[:(- 1)]) + 2...
924,929,705,790,682,600
Returns the HDPrivateKey at the path indicated. Path should be in the form of m/x/y/z where x' means hardened
session6/hd.py
traverse
jimmysong/pw-exercises
python
def traverse(self, path): "Returns the HDPrivateKey at the path indicated.\n Path should be in the form of m/x/y/z where x' means\n hardened" current = self components = path.split('/')[1:] for child in components: if child.endswith("'"): index = (int(child[:(- 1)]) + 2...
def _prv(self, version): 'Returns the base58-encoded x/y/z prv.\n Expects a 4-byte version.' raw = self.raw_serialize(version) return encode_base58_checksum(raw)
2,242,973,465,055,090,200
Returns the base58-encoded x/y/z prv. Expects a 4-byte version.
session6/hd.py
_prv
jimmysong/pw-exercises
python
def _prv(self, version): 'Returns the base58-encoded x/y/z prv.\n Expects a 4-byte version.' raw = self.raw_serialize(version) return encode_base58_checksum(raw)
@classmethod def parse(cls, s): 'Returns a HDPrivateKey from an extended key string' raw = raw_decode_base58(s) if (len(raw) != 78): raise ValueError('Not a proper extended key') stream = BytesIO(raw) return cls.raw_parse(stream)
-3,830,092,010,722,180,600
Returns a HDPrivateKey from an extended key string
session6/hd.py
parse
jimmysong/pw-exercises
python
@classmethod def parse(cls, s): raw = raw_decode_base58(s) if (len(raw) != 78): raise ValueError('Not a proper extended key') stream = BytesIO(raw) return cls.raw_parse(stream)
@classmethod def raw_parse(cls, s): 'Returns a HDPrivateKey from a stream' version = s.read(4) if (version in (TESTNET_XPRV, TESTNET_YPRV, TESTNET_ZPRV)): testnet = True elif (version in (MAINNET_XPRV, MAINNET_YPRV, MAINNET_ZPRV)): testnet = False else: raise ValueError('not ...
1,832,675,882,951,446,000
Returns a HDPrivateKey from a stream
session6/hd.py
raw_parse
jimmysong/pw-exercises
python
@classmethod def raw_parse(cls, s): version = s.read(4) if (version in (TESTNET_XPRV, TESTNET_YPRV, TESTNET_ZPRV)): testnet = True elif (version in (MAINNET_XPRV, MAINNET_YPRV, MAINNET_ZPRV)): testnet = False else: raise ValueError('not an xprv, yprv or zprv: {}'.format(vers...
def _get_address(self, purpose, account=0, external=True, address=0): "Returns the proper address among purposes 44', 49' and 84'.\n p2pkh for 44', p2sh-p2wpkh for 49' and p2wpkh for 84'." if (purpose not in ("44'", "49'", "84'")): raise ValueError('Cannot create an address without a proper purpo...
5,953,938,896,022,769,000
Returns the proper address among purposes 44', 49' and 84'. p2pkh for 44', p2sh-p2wpkh for 49' and p2wpkh for 84'.
session6/hd.py
_get_address
jimmysong/pw-exercises
python
def _get_address(self, purpose, account=0, external=True, address=0): "Returns the proper address among purposes 44', 49' and 84'.\n p2pkh for 44', p2sh-p2wpkh for 49' and p2wpkh for 84'." if (purpose not in ("44'", "49'", "84'")): raise ValueError('Cannot create an address without a proper purpo...
@classmethod def from_mnemonic(cls, mnemonic, password=b'', path='m', testnet=False): 'Returns a HDPrivateKey object from the mnemonic.' words = mnemonic.split() if (len(words) not in (12, 15, 18, 21, 24)): raise ValueError('you need 12, 15, 18, 21, or 24 words') number = 0 for word in words...
5,686,827,912,756,427,000
Returns a HDPrivateKey object from the mnemonic.
session6/hd.py
from_mnemonic
jimmysong/pw-exercises
python
@classmethod def from_mnemonic(cls, mnemonic, password=b, path='m', testnet=False): words = mnemonic.split() if (len(words) not in (12, 15, 18, 21, 24)): raise ValueError('you need 12, 15, 18, 21, or 24 words') number = 0 for word in words: index = WORD_LOOKUP[word] number =...
def fingerprint(self): "Fingerprint is the hash160's first 4 bytes" return self.hash160()[:4]
2,325,837,346,603,048,000
Fingerprint is the hash160's first 4 bytes
session6/hd.py
fingerprint
jimmysong/pw-exercises
python
def fingerprint(self): return self.hash160()[:4]
def child(self, index): 'Returns the child HDPrivateKey at a particular index.\n Raises ValueError for indices >= 0x8000000.\n ' if (index >= 2147483648): raise ValueError('child number should always be less than 2^31') data = (self.point.sec() + int_to_big_endian(index, 4)) h = hm...
2,450,639,498,486,831,000
Returns the child HDPrivateKey at a particular index. Raises ValueError for indices >= 0x8000000.
session6/hd.py
child
jimmysong/pw-exercises
python
def child(self, index): 'Returns the child HDPrivateKey at a particular index.\n Raises ValueError for indices >= 0x8000000.\n ' if (index >= 2147483648): raise ValueError('child number should always be less than 2^31') data = (self.point.sec() + int_to_big_endian(index, 4)) h = hm...
def traverse(self, path): 'Returns the HDPublicKey at the path indicated.\n Path should be in the form of m/x/y/z.' current = self components = path.split('/')[1:] for child in components: if (child[(- 1):] == "'"): raise ValueError('HDPublicKey cannot get hardened child') ...
-492,497,757,683,349,200
Returns the HDPublicKey at the path indicated. Path should be in the form of m/x/y/z.
session6/hd.py
traverse
jimmysong/pw-exercises
python
def traverse(self, path): 'Returns the HDPublicKey at the path indicated.\n Path should be in the form of m/x/y/z.' current = self components = path.split('/')[1:] for child in components: if (child[(- 1):] == "'"): raise ValueError('HDPublicKey cannot get hardened child') ...
def _pub(self, version): 'Returns the base58-encoded x/y/z pub.\n Expects a 4-byte version.' raw = self._serialize(version) return encode_base58_checksum(raw)
-8,777,945,254,099,310,000
Returns the base58-encoded x/y/z pub. Expects a 4-byte version.
session6/hd.py
_pub
jimmysong/pw-exercises
python
def _pub(self, version): 'Returns the base58-encoded x/y/z pub.\n Expects a 4-byte version.' raw = self._serialize(version) return encode_base58_checksum(raw)
@classmethod def parse(cls, s): 'Returns a HDPublicKey from an extended key string' raw = raw_decode_base58(s) if (len(raw) != 78): raise ValueError('Not a proper extended key') stream = BytesIO(raw) return cls.raw_parse(stream)
-348,898,283,253,583,100
Returns a HDPublicKey from an extended key string
session6/hd.py
parse
jimmysong/pw-exercises
python
@classmethod def parse(cls, s): raw = raw_decode_base58(s) if (len(raw) != 78): raise ValueError('Not a proper extended key') stream = BytesIO(raw) return cls.raw_parse(stream)
@classmethod def raw_parse(cls, s): 'Returns a HDPublicKey from a stream' version = s.read(4) if (version in (TESTNET_XPUB, TESTNET_YPUB, TESTNET_ZPUB)): testnet = True elif (version in (MAINNET_XPUB, MAINNET_YPUB, MAINNET_ZPUB)): testnet = False else: raise ValueError('not a...
7,748,026,601,330,876,000
Returns a HDPublicKey from a stream
session6/hd.py
raw_parse
jimmysong/pw-exercises
python
@classmethod def raw_parse(cls, s): version = s.read(4) if (version in (TESTNET_XPUB, TESTNET_YPUB, TESTNET_ZPUB)): testnet = True elif (version in (MAINNET_XPUB, MAINNET_YPUB, MAINNET_ZPUB)): testnet = False else: raise ValueError('not an xpub, ypub or zpub: {} {}'.format(s...
@cached_property def additional_properties_type(): '\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n ' lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type)
1,702,168,743,392,494,600
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
cryptoapis/model/list_assets_details_e400.py
additional_properties_type
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
python
@cached_property def additional_properties_type(): '\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n ' lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type)
@cached_property def openapi_types(): '\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ...
-5,576,899,373,819,436,000
This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type.
cryptoapis/model/list_assets_details_e400.py
openapi_types
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
python
@cached_property def openapi_types(): '\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ...
@classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): 'ListAssetsDetailsE400 - a model defined in OpenAPI\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeErr...
2,020,670,956,389,146,600
ListAssetsDetailsE400 - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_...
cryptoapis/model/list_assets_details_e400.py
_from_openapi_data
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
python
@classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): 'ListAssetsDetailsE400 - a model defined in OpenAPI\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeErr...
@convert_js_args_to_python_args def __init__(self, *args, **kwargs): 'ListAssetsDetailsE400 - a model defined in OpenAPI\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n ...
-423,784,295,900,482,900
ListAssetsDetailsE400 - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_...
cryptoapis/model/list_assets_details_e400.py
__init__
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
python
@convert_js_args_to_python_args def __init__(self, *args, **kwargs): 'ListAssetsDetailsE400 - a model defined in OpenAPI\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n ...
def __init__(self): '\n Creates the himesis graph representing the AToM3 model HMM10_then1_IsolatedLHS.\n ' self.is_compiled = True super(HMM10_then1_IsolatedLHS, self).__init__(name='HMM10_then1_IsolatedLHS', num_nodes=0, edges=[]) self.add_edges([]) self['mm__'] = ['MT_pre__F...
8,705,714,719,552,520,000
Creates the himesis graph representing the AToM3 model HMM10_then1_IsolatedLHS.
UMLRT2Kiltera_MM/Properties/from_thesis/HMM10_then1_IsolatedLHS.py
__init__
levilucio/SyVOLT
python
def __init__(self): '\n \n ' self.is_compiled = True super(HMM10_then1_IsolatedLHS, self).__init__(name='HMM10_then1_IsolatedLHS', num_nodes=0, edges=[]) self.add_edges([]) self['mm__'] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self['MT_constraint__'] = "#=============...
def constraint(self, PreNode, graph): '\n Executable constraint code.\n @param PreNode: Function taking an integer as parameter\n and returns the node corresponding to that label.\n ' return True
-9,135,366,208,570,063,000
Executable constraint code. @param PreNode: Function taking an integer as parameter and returns the node corresponding to that label.
UMLRT2Kiltera_MM/Properties/from_thesis/HMM10_then1_IsolatedLHS.py
constraint
levilucio/SyVOLT
python
def constraint(self, PreNode, graph): '\n Executable constraint code.\n @param PreNode: Function taking an integer as parameter\n and returns the node corresponding to that label.\n ' return True
def read_symbols(executable, imports=True): '\n Parse an ELF executable and return a list of (symbol,version) tuples\n for dynamic, imported symbols.\n ' p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdou...
-1,495,590,509,076,206,600
Parse an ELF executable and return a list of (symbol,version) tuples for dynamic, imported symbols.
contrib/devtools/symbol-check.py
read_symbols
bitcoinemxmx/GCX
python
def read_symbols(executable, imports=True): '\n Parse an ELF executable and return a list of (symbol,version) tuples\n for dynamic, imported symbols.\n ' p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdou...
def build(classifier, X, y=None): '\n Inner build function that builds a single model.\n ' if isinstance(classifier, type): classifier = classifier() model = Pipeline([('preprocessor', NLTKPreprocessor()), ('vectorizer', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=...
4,710,342,378,621,694,000
Inner build function that builds a single model.
analyzer/build.py
build
shobhitagarwal1612/Emotion-Analysis
python
def build(classifier, X, y=None): '\n \n ' if isinstance(classifier, type): classifier = classifier() model = Pipeline([('preprocessor', NLTKPreprocessor()), ('vectorizer', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)), ('classifier', classifier)]) model....
def test_toolchains(self): 'Try each toolchain' for toolchain in fpgaperf.toolchains.keys(): (device, package) = def_devpack(toolchain) fpgaperf.run(family='ice40', device=device, package=package, toolchain=toolchain, project=fpgaperf.get_project('oneblink'), verbose=self.verbose)
8,048,555,090,105,903,000
Try each toolchain
test/test_all.py
test_toolchains
arn4ud/fpga-tool-perf
python
def test_toolchains(self): for toolchain in fpgaperf.toolchains.keys(): (device, package) = def_devpack(toolchain) fpgaperf.run(family='ice40', device=device, package=package, toolchain=toolchain, project=fpgaperf.get_project('oneblink'), verbose=self.verbose)
def test_pcf(self): 'Try each toolchain with a pcf' for toolchain in fpgaperf.toolchains.keys(): (device, package) = def_devpack(toolchain) if ('radiant' in toolchain): pcf = (fpgaperf.root_dir + '/project/FIXME.pcf') else: pcf = (fpgaperf.root_dir + '/project/one...
-8,995,371,934,689,438,000
Try each toolchain with a pcf
test/test_all.py
test_pcf
arn4ud/fpga-tool-perf
python
def test_pcf(self): for toolchain in fpgaperf.toolchains.keys(): (device, package) = def_devpack(toolchain) if ('radiant' in toolchain): pcf = (fpgaperf.root_dir + '/project/FIXME.pcf') else: pcf = (fpgaperf.root_dir + '/project/oneblink_lp8k-cm81.pcf') f...
def test_seed(self): 'Try seeding, where possible' random.seed(1234) for toolchain in fpgaperf.get_seedable(): seed = random.randint(1, 2147483647) (device, package) = def_devpack(toolchain) fpgaperf.run(family='ice40', device=device, package=package, toolchain=toolchain, project=fpg...
6,710,430,323,428,870,000
Try seeding, where possible
test/test_all.py
test_seed
arn4ud/fpga-tool-perf
python
def test_seed(self): random.seed(1234) for toolchain in fpgaperf.get_seedable(): seed = random.randint(1, 2147483647) (device, package) = def_devpack(toolchain) fpgaperf.run(family='ice40', device=device, package=package, toolchain=toolchain, project=fpgaperf.get_project('oneblink')...
def __init__(self, config, wsas_params, tmp_dir, nonstandard_residue_files, nonstandard_residue, ligand_topology, options=None, parameters=None): 'Wrapper for freesasa\n\n config: str\n Path to configuration file containing residue composition\n and atomic parameters - freesasa format.\...
4,610,078,083,853,016,600
Wrapper for freesasa config: str Path to configuration file containing residue composition and atomic parameters - freesasa format. options: dict, optional Options to change how PDBs are parsed by freesasa. parameters: dict, optional Parameters to alter how freesasa computes surface area.
bac/analyse/wsas/freesasa_utils.py
__init__
UCL-CCS/BAC2
python
def __init__(self, config, wsas_params, tmp_dir, nonstandard_residue_files, nonstandard_residue, ligand_topology, options=None, parameters=None): 'Wrapper for freesasa\n\n config: str\n Path to configuration file containing residue composition\n and atomic parameters - freesasa format.\...
def run(self, pdb): 'Run freesasa on provided PDB file\n\n Parameters\n ----------\n\n pdb: str\n Path to input PDB file\n\n Returns\n -------\n list\n SASA values for each atom of every model in the input PDB.\n\n ' structure_array = freesa...
2,183,696,454,969,197,300
Run freesasa on provided PDB file Parameters ---------- pdb: str Path to input PDB file Returns ------- list SASA values for each atom of every model in the input PDB.
bac/analyse/wsas/freesasa_utils.py
run
UCL-CCS/BAC2
python
def run(self, pdb): 'Run freesasa on provided PDB file\n\n Parameters\n ----------\n\n pdb: str\n Path to input PDB file\n\n Returns\n -------\n list\n SASA values for each atom of every model in the input PDB.\n\n ' structure_array = freesa...
def _update_sasa_config(self, config, parameters, tmp_dir, nonstandard_residue_files, nonstandard_residue, ligand_topology): '\n Add non-standard residues (including the ligand if a topology is\n provided for it) to the freesasa config file.\n\n Parameters\n ----------\n\n Notes\n...
-3,815,972,230,154,587,000
Add non-standard residues (including the ligand if a topology is provided for it) to the freesasa config file. Parameters ---------- Notes ----- Edited config files is saved in self.tmp_dir and self.freesasa_config_file is updated to reflect this. Returns -------
bac/analyse/wsas/freesasa_utils.py
_update_sasa_config
UCL-CCS/BAC2
python
def _update_sasa_config(self, config, parameters, tmp_dir, nonstandard_residue_files, nonstandard_residue, ligand_topology): '\n Add non-standard residues (including the ligand if a topology is\n provided for it) to the freesasa config file.\n\n Parameters\n ----------\n\n Notes\n...
@staticmethod def _create_freesasa_section_text(new_residues, sasa_atom_params): '\n Create text to add to freesasa configuration file to incorporate new residue.\n\n Parameters\n ----------\n new_residues : dict\n Non-standard residues to add to the freesasa config file.\n ...
8,965,076,196,579,469,000
Create text to add to freesasa configuration file to incorporate new residue. Parameters ---------- new_residues : dict Non-standard residues to add to the freesasa config file. keys = residue names, values = atom name to type mapping (dict). sasa_atom_params: dict Maps atom type to properties needed by fr...
bac/analyse/wsas/freesasa_utils.py
_create_freesasa_section_text
UCL-CCS/BAC2
python
@staticmethod def _create_freesasa_section_text(new_residues, sasa_atom_params): '\n Create text to add to freesasa configuration file to incorporate new residue.\n\n Parameters\n ----------\n new_residues : dict\n Non-standard residues to add to the freesasa config file.\n ...
def _add_residues_freesasa_config_file(self, new_residues, new_filename, atom_params, orig_filename): '\n Create a new freesasa config file that adds specified residue to the\n content of an existing copy.\n\n Parameters\n ----------\n new_residues : dict\n Non-standard...
3,335,320,457,434,036,700
Create a new freesasa config file that adds specified residue to the content of an existing copy. Parameters ---------- new_residues : dict Non-standard residues to add to the freesasa config file. keys = residue names, values = atom name to type mapping (dict). new_filename: str Filename to be used for th...
bac/analyse/wsas/freesasa_utils.py
_add_residues_freesasa_config_file
UCL-CCS/BAC2
python
def _add_residues_freesasa_config_file(self, new_residues, new_filename, atom_params, orig_filename): '\n Create a new freesasa config file that adds specified residue to the\n content of an existing copy.\n\n Parameters\n ----------\n new_residues : dict\n Non-standard...
def splitlines_parser(data): 'A test parser that returns the input data, split by line.' return data.splitlines()
8,821,445,958,649,442,000
A test parser that returns the input data, split by line.
tests/integrations/subprocess/test_Subprocess__parse_output.py
splitlines_parser
pybee/briefcase
python
def splitlines_parser(data): return data.splitlines()
def second_line_parser(data): 'A test parser that returns the second line of input.' try: return data.splitlines()[1] except IndexError: raise ParseError('Input does not contain 2 lines')
5,938,198,887,935,977,000
A test parser that returns the second line of input.
tests/integrations/subprocess/test_Subprocess__parse_output.py
second_line_parser
pybee/briefcase
python
def second_line_parser(data): try: return data.splitlines()[1] except IndexError: raise ParseError('Input does not contain 2 lines')
def third_line_parser(data): 'A test parser that returns the third line of input.' try: return data.splitlines()[2] except IndexError: raise ParseError('Input does not contain 3 lines')
1,768,642,836,130,958,300
A test parser that returns the third line of input.
tests/integrations/subprocess/test_Subprocess__parse_output.py
third_line_parser
pybee/briefcase
python
def third_line_parser(data): try: return data.splitlines()[2] except IndexError: raise ParseError('Input does not contain 3 lines')
def test_call(mock_sub, capsys): 'A simple call to check_output will be invoked.' output = mock_sub.parse_output(splitlines_parser, ['hello', 'world']) mock_sub._subprocess.check_output.assert_called_with(['hello', 'world'], text=True) assert (capsys.readouterr().out == '') assert (output == ['some ...
-9,145,021,900,062,871,000
A simple call to check_output will be invoked.
tests/integrations/subprocess/test_Subprocess__parse_output.py
test_call
pybee/briefcase
python
def test_call(mock_sub, capsys): output = mock_sub.parse_output(splitlines_parser, ['hello', 'world']) mock_sub._subprocess.check_output.assert_called_with(['hello', 'world'], text=True) assert (capsys.readouterr().out == ) assert (output == ['some output line 1', 'more output line 2'])
def test_call_with_arg(mock_sub, capsys): 'Any extra keyword arguments are passed through as-is to check_output.' output = mock_sub.parse_output(splitlines_parser, ['hello', 'world'], extra_arg='asdf') mock_sub._subprocess.check_output.assert_called_with(['hello', 'world'], extra_arg='asdf', text=True) ...
-6,034,261,138,534,564,000
Any extra keyword arguments are passed through as-is to check_output.
tests/integrations/subprocess/test_Subprocess__parse_output.py
test_call_with_arg
pybee/briefcase
python
def test_call_with_arg(mock_sub, capsys): output = mock_sub.parse_output(splitlines_parser, ['hello', 'world'], extra_arg='asdf') mock_sub._subprocess.check_output.assert_called_with(['hello', 'world'], extra_arg='asdf', text=True) assert (capsys.readouterr().out == ) assert (output == ['some outpu...
def test_call_with_parser_success(mock_sub, capsys): "Parser returns expected portion of check_output's output." output = mock_sub.parse_output(second_line_parser, ['hello', 'world']) mock_sub._subprocess.check_output.assert_called_with(['hello', 'world'], text=True) assert (output == 'more output line ...
-8,240,593,146,039,259,000
Parser returns expected portion of check_output's output.
tests/integrations/subprocess/test_Subprocess__parse_output.py
test_call_with_parser_success
pybee/briefcase
python
def test_call_with_parser_success(mock_sub, capsys): output = mock_sub.parse_output(second_line_parser, ['hello', 'world']) mock_sub._subprocess.check_output.assert_called_with(['hello', 'world'], text=True) assert (output == 'more output line 2')
def test_call_with_parser_error(mock_sub, capsys): 'Parser errors on output from check_output.' with pytest.raises(CommandOutputParseError, match='Unable to parse command output: Input does not contain 3 lines'): mock_sub.parse_output(third_line_parser, ['hello', 'world']) mock_sub._subprocess.check...
-4,493,378,662,148,309,000
Parser errors on output from check_output.
tests/integrations/subprocess/test_Subprocess__parse_output.py
test_call_with_parser_error
pybee/briefcase
python
def test_call_with_parser_error(mock_sub, capsys): with pytest.raises(CommandOutputParseError, match='Unable to parse command output: Input does not contain 3 lines'): mock_sub.parse_output(third_line_parser, ['hello', 'world']) mock_sub._subprocess.check_output.assert_called_with(['hello', 'world'...
@pytest.mark.parametrize('in_kwargs, kwargs', [({}, {'text': True}), ({'text': True}, {'text': True}), ({'text': False}, {'text': False}), ({'universal_newlines': False}, {'universal_newlines': False}), ({'universal_newlines': True}, {'universal_newlines': True})]) def test_text_eq_true_default_overriding(mock_sub, in_...
-8,395,795,399,331,432,000
if text or universal_newlines is explicitly provided, those should override text=true default.
tests/integrations/subprocess/test_Subprocess__parse_output.py
test_text_eq_true_default_overriding
pybee/briefcase
python
@pytest.mark.parametrize('in_kwargs, kwargs', [({}, {'text': True}), ({'text': True}, {'text': True}), ({'text': False}, {'text': False}), ({'universal_newlines': False}, {'universal_newlines': False}), ({'universal_newlines': True}, {'universal_newlines': True})]) def test_text_eq_true_default_overriding(mock_sub, in_...
def _execute(self, state: GlobalState) -> None: '\n\n :param state:\n :return:\n ' if (state.get_current_instruction()['address'] in self.cache): return issues = self._analyze_state(state) for issue in issues: self.cache.add(issue.address) self.issues.extend(issu...
-3,896,410,076,598,750,000
:param state: :return:
mythril/analysis/module/modules/dependence_on_predictable_vars.py
_execute
marcuswin/mythril
python
def _execute(self, state: GlobalState) -> None: '\n\n :param state:\n :return:\n ' if (state.get_current_instruction()['address'] in self.cache): return issues = self._analyze_state(state) for issue in issues: self.cache.add(issue.address) self.issues.extend(issu...
@staticmethod def _analyze_state(state: GlobalState) -> list: '\n\n :param state:\n :return:\n ' issues = [] if is_prehook(): opcode = state.get_current_instruction()['opcode'] if (opcode in final_ops): for annotation in state.annotations: if ...
-7,975,389,300,939,921,000
:param state: :return:
mythril/analysis/module/modules/dependence_on_predictable_vars.py
_analyze_state
marcuswin/mythril
python
@staticmethod def _analyze_state(state: GlobalState) -> list: '\n\n :param state:\n :return:\n ' issues = [] if is_prehook(): opcode = state.get_current_instruction()['opcode'] if (opcode in final_ops): for annotation in state.annotations: if ...
def test_sksurgerytextoverlay(): ' Basic test to run the widget and make sure everything loads OK.' if (sys.platform == 'darwin'): pytest.skip('Test not working on Mac runner') input_file = 'tests/data/test_video.avi' gui = TextOverlayDemo(input_file) gui.start()
6,263,612,313,655,906,000
Basic test to run the widget and make sure everything loads OK.
tests/test_sksurgerytextoverlay.py
test_sksurgerytextoverlay
SciKit-Surgery/scikit-surgeryutils
python
def test_sksurgerytextoverlay(): ' ' if (sys.platform == 'darwin'): pytest.skip('Test not working on Mac runner') input_file = 'tests/data/test_video.avi' gui = TextOverlayDemo(input_file) gui.start()
@skipIf((PSYCOPG2_VERSION < (2, 7)), 'SQL string composition not available in psycopg2<2.7') def test_composed_query(self): 'Checks whether execution of composed SQL string is traced' query = SQL(' union all ').join([SQL('select {} as x').format(Literal('one')), SQL('select {} as x').format(Literal('two'))]) ...
4,491,225,874,725,807,600
Checks whether execution of composed SQL string is traced
tests/contrib/psycopg/test_psycopg.py
test_composed_query
discord/dd-trace-py
python
@skipIf((PSYCOPG2_VERSION < (2, 7)), 'SQL string composition not available in psycopg2<2.7') def test_composed_query(self): query = SQL(' union all ').join([SQL('select {} as x').format(Literal('one')), SQL('select {} as x').format(Literal('two'))]) db = self._get_conn() with db.cursor() as cur: ...
@skipIf((PSYCOPG2_VERSION < (2, 7)), 'SQL string composition not available in psycopg2<2.7') def test_composed_query_identifier(self): 'Checks whether execution of composed SQL string is traced' db = self._get_conn() with db.cursor() as cur: cur.execute('CREATE TEMP TABLE test (id serial PRIMARY KEY...
6,862,115,182,421,737,000
Checks whether execution of composed SQL string is traced
tests/contrib/psycopg/test_psycopg.py
test_composed_query_identifier
discord/dd-trace-py
python
@skipIf((PSYCOPG2_VERSION < (2, 7)), 'SQL string composition not available in psycopg2<2.7') def test_composed_query_identifier(self): db = self._get_conn() with db.cursor() as cur: cur.execute('CREATE TEMP TABLE test (id serial PRIMARY KEY, name varchar(12) NOT NULL UNIQUE);') cur.execute(...
@snapshot() @skipIf((PSYCOPG2_VERSION < (2, 7)), 'SQL string composition not available in psycopg2<2.7') def test_composed_query_encoding(self): 'Checks whether execution of composed SQL string is traced' import logging logger = logging.getLogger() logger.level = logging.DEBUG query = SQL(' union al...
8,238,151,430,507,487,000
Checks whether execution of composed SQL string is traced
tests/contrib/psycopg/test_psycopg.py
test_composed_query_encoding
discord/dd-trace-py
python
@snapshot() @skipIf((PSYCOPG2_VERSION < (2, 7)), 'SQL string composition not available in psycopg2<2.7') def test_composed_query_encoding(self): import logging logger = logging.getLogger() logger.level = logging.DEBUG query = SQL(' union all ').join([SQL("select 'one' as x"), SQL("select 'two' as x...
@TracerTestCase.run_in_subprocess(env_overrides=dict(DD_SERVICE='mysvc')) def test_user_specified_app_service(self): '\n When a user specifies a service for the app\n The psycopg integration should not use it.\n ' from ddtrace import config assert (config.service == 'mysvc') con...
4,316,217,354,407,632,400
When a user specifies a service for the app The psycopg integration should not use it.
tests/contrib/psycopg/test_psycopg.py
test_user_specified_app_service
discord/dd-trace-py
python
@TracerTestCase.run_in_subprocess(env_overrides=dict(DD_SERVICE='mysvc')) def test_user_specified_app_service(self): '\n When a user specifies a service for the app\n The psycopg integration should not use it.\n ' from ddtrace import config assert (config.service == 'mysvc') con...
def dcan2fmriprepx(dcan_dir, out_dir, sub_id): '\n dcan2fmriprep(dcan_dir,out_dir)\n ' sess = glob.glob((((dcan_dir + '/') + sub_id) + '/s*')) ses_id = [] ses_id = [j.split('ses-')[1] for j in sess] for ses in ses_id: anat_dirx = (((((dcan_dir + '/') + sub_id) + '/ses-') + ses) + '/fil...
8,666,387,277,339,448,000
dcan2fmriprep(dcan_dir,out_dir)
xcp_abcd/utils/dcan2fmriprep.py
dcan2fmriprepx
PennLINC/xcp_abcd
python
def dcan2fmriprepx(dcan_dir, out_dir, sub_id): '\n \n ' sess = glob.glob((((dcan_dir + '/') + sub_id) + '/s*')) ses_id = [] ses_id = [j.split('ses-')[1] for j in sess] for ses in ses_id: anat_dirx = (((((dcan_dir + '/') + sub_id) + '/ses-') + ses) + '/files/MNINonLinear/') anat...
def copyfileobj_example(source, dest, buffer_size=((1024 * 1024) * 1024)): ' \n Copy a file from source to dest. source and dest\n must be file-like objects, i.e. any object with a read or\n write method, like for example StringIO.\n ' while True: copy_buffer = source.read(buffer_size) ...
-4,312,684,828,816,021,500
Copy a file from source to dest. source and dest must be file-like objects, i.e. any object with a read or write method, like for example StringIO.
xcp_abcd/utils/dcan2fmriprep.py
copyfileobj_example
PennLINC/xcp_abcd
python
def copyfileobj_example(source, dest, buffer_size=((1024 * 1024) * 1024)): ' \n Copy a file from source to dest. source and dest\n must be file-like objects, i.e. any object with a read or\n write method, like for example StringIO.\n ' while True: copy_buffer = source.read(buffer_size) ...
def forward(self, imgs, bboxes, labels, scale): 'Forward Faster R-CNN and calculate losses.\n\n Here are notations used.\n\n * :math:`N` is the batch size.\n * :math:`R` is the number of bounding boxes per image.\n\n Currently, only :math:`N=1` is supported.\n\n Args:\n ...
-7,758,097,655,763,915,000
Forward Faster R-CNN and calculate losses. Here are notations used. * :math:`N` is the batch size. * :math:`R` is the number of bounding boxes per image. Currently, only :math:`N=1` is supported. Args: imgs (~torch.autograd.Variable): A variable with a batch of images. bboxes (~torch.autograd.Variable): A b...
baseline/fast_rcnn/trainer.py
forward
ITMO-NSS-team/LightObjRecEnsembler
python
def forward(self, imgs, bboxes, labels, scale): 'Forward Faster R-CNN and calculate losses.\n\n Here are notations used.\n\n * :math:`N` is the batch size.\n * :math:`R` is the number of bounding boxes per image.\n\n Currently, only :math:`N=1` is supported.\n\n Args:\n ...
def save(self, save_optimizer=False, save_path=None, **kwargs): "serialize models include optimizer and other info\n return path where the model-file is stored.\n\n Args:\n save_optimizer (bool): whether save optimizer.state_dict().\n save_path (string): where to save model, if i...
-2,786,790,712,384,780,000
serialize models include optimizer and other info return path where the model-file is stored. Args: save_optimizer (bool): whether save optimizer.state_dict(). save_path (string): where to save model, if it's None, save_path is generate using time str and info from kwargs. Returns: save_path(str):...
baseline/fast_rcnn/trainer.py
save
ITMO-NSS-team/LightObjRecEnsembler
python
def save(self, save_optimizer=False, save_path=None, **kwargs): "serialize models include optimizer and other info\n return path where the model-file is stored.\n\n Args:\n save_optimizer (bool): whether save optimizer.state_dict().\n save_path (string): where to save model, if i...
def get_object(self): '\n retrieve auhtenticated user\n ' return self.request.user
-7,649,043,722,026,112,000
retrieve auhtenticated user
app/user/views.py
get_object
xemperforya/recipe-app-api
python
def get_object(self): '\n \n ' return self.request.user
@distributed_trace def list(self, **kwargs: Any) -> Iterable['_models.ManagedClusterSnapshotListResult']: 'Gets a list of managed cluster snapshots in the specified subscription.\n\n Gets a list of managed cluster snapshots in the specified subscription.\n\n :keyword callable cls: A custom type or fun...
-806,864,483,680,052,100
Gets a list of managed cluster snapshots in the specified subscription. Gets a list of managed cluster snapshots in the specified subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedClusterSnapshotListResult or the ...
src/aks-preview/azext_aks_preview/vendored_sdks/azure_mgmt_preview_aks/v2022_03_02_preview/operations/_managed_cluster_snapshots_operations.py
list
Hamster-Huey/azure-cli-extensions
python
@distributed_trace def list(self, **kwargs: Any) -> Iterable['_models.ManagedClusterSnapshotListResult']: 'Gets a list of managed cluster snapshots in the specified subscription.\n\n Gets a list of managed cluster snapshots in the specified subscription.\n\n :keyword callable cls: A custom type or fun...
@distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable['_models.ManagedClusterSnapshotListResult']: 'Lists managed cluster snapshots in the specified subscription and resource group.\n\n Lists managed cluster snapshots in the specified subscription and resour...
6,987,555,572,338,603,000
Lists managed cluster snapshots in the specified subscription and resource group. Lists managed cluster snapshots in the specified subscription and resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :keyword callable cls: A custom t...
src/aks-preview/azext_aks_preview/vendored_sdks/azure_mgmt_preview_aks/v2022_03_02_preview/operations/_managed_cluster_snapshots_operations.py
list_by_resource_group
Hamster-Huey/azure-cli-extensions
python
@distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable['_models.ManagedClusterSnapshotListResult']: 'Lists managed cluster snapshots in the specified subscription and resource group.\n\n Lists managed cluster snapshots in the specified subscription and resour...
@distributed_trace def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> '_models.ManagedClusterSnapshot': 'Gets a managed cluster snapshot.\n\n Gets a managed cluster snapshot.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n ...
3,540,760,310,827,036,000
Gets a managed cluster snapshot. Gets a managed cluster snapshot. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param resource_name: The name of the managed cluster resource. :type resource_name: str :keyword callable cls: A custom type or fu...
src/aks-preview/azext_aks_preview/vendored_sdks/azure_mgmt_preview_aks/v2022_03_02_preview/operations/_managed_cluster_snapshots_operations.py
get
Hamster-Huey/azure-cli-extensions
python
@distributed_trace def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> '_models.ManagedClusterSnapshot': 'Gets a managed cluster snapshot.\n\n Gets a managed cluster snapshot.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n ...
@distributed_trace def create_or_update(self, resource_group_name: str, resource_name: str, parameters: '_models.ManagedClusterSnapshot', **kwargs: Any) -> '_models.ManagedClusterSnapshot': 'Creates or updates a managed cluster snapshot.\n\n Creates or updates a managed cluster snapshot.\n\n :param re...
3,594,859,589,582,269,400
Creates or updates a managed cluster snapshot. Creates or updates a managed cluster snapshot. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param resource_name: The name of the managed cluster resource. :type resource_name: str :param paramet...
src/aks-preview/azext_aks_preview/vendored_sdks/azure_mgmt_preview_aks/v2022_03_02_preview/operations/_managed_cluster_snapshots_operations.py
create_or_update
Hamster-Huey/azure-cli-extensions
python
@distributed_trace def create_or_update(self, resource_group_name: str, resource_name: str, parameters: '_models.ManagedClusterSnapshot', **kwargs: Any) -> '_models.ManagedClusterSnapshot': 'Creates or updates a managed cluster snapshot.\n\n Creates or updates a managed cluster snapshot.\n\n :param re...
@distributed_trace def update_tags(self, resource_group_name: str, resource_name: str, parameters: '_models.TagsObject', **kwargs: Any) -> '_models.ManagedClusterSnapshot': 'Updates tags on a managed cluster snapshot.\n\n Updates tags on a managed cluster snapshot.\n\n :param resource_group_name: The ...
-3,153,889,745,219,867,000
Updates tags on a managed cluster snapshot. Updates tags on a managed cluster snapshot. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param resource_name: The name of the managed cluster resource. :type resource_name: str :param parameters: P...
src/aks-preview/azext_aks_preview/vendored_sdks/azure_mgmt_preview_aks/v2022_03_02_preview/operations/_managed_cluster_snapshots_operations.py
update_tags
Hamster-Huey/azure-cli-extensions
python
@distributed_trace def update_tags(self, resource_group_name: str, resource_name: str, parameters: '_models.TagsObject', **kwargs: Any) -> '_models.ManagedClusterSnapshot': 'Updates tags on a managed cluster snapshot.\n\n Updates tags on a managed cluster snapshot.\n\n :param resource_group_name: The ...
@distributed_trace def delete(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> None: 'Deletes a managed cluster snapshot.\n\n Deletes a managed cluster snapshot.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_g...
-6,312,127,759,750,229,000
Deletes a managed cluster snapshot. Deletes a managed cluster snapshot. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param resource_name: The name of the managed cluster resource. :type resource_name: str :keyword callable cls: A custom type...
src/aks-preview/azext_aks_preview/vendored_sdks/azure_mgmt_preview_aks/v2022_03_02_preview/operations/_managed_cluster_snapshots_operations.py
delete
Hamster-Huey/azure-cli-extensions
python
@distributed_trace def delete(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> None: 'Deletes a managed cluster snapshot.\n\n Deletes a managed cluster snapshot.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_g...
@property def is_terminal(self) -> bool: 'True if the current state is a terminal state.' if (self.life_cycle_state not in RUN_LIFE_CYCLE_STATES): raise AirflowException('Unexpected life cycle state: {}: If the state has been introduced recently, please check the Databricks user guide for troubleshootin...
358,714,069,093,355,900
True if the current state is a terminal state.
airflow/providers/databricks/hooks/databricks.py
is_terminal
AMS-Kepler/airflow
python
@property def is_terminal(self) -> bool: if (self.life_cycle_state not in RUN_LIFE_CYCLE_STATES): raise AirflowException('Unexpected life cycle state: {}: If the state has been introduced recently, please check the Databricks user guide for troubleshooting information'.format(self.life_cycle_state)) ...
@property def is_successful(self) -> bool: 'True if the result state is SUCCESS' return (self.result_state == 'SUCCESS')
4,436,874,940,241,474,000
True if the result state is SUCCESS
airflow/providers/databricks/hooks/databricks.py
is_successful
AMS-Kepler/airflow
python
@property def is_successful(self) -> bool: return (self.result_state == 'SUCCESS')
def run_now(self, json: dict) -> int: '\n Utility function to call the ``api/2.0/jobs/run-now`` endpoint.\n\n :param json: The data used in the body of the request to the ``run-now`` endpoint.\n :return: the run_id as an int\n :rtype: str\n ' response = self._do_api_call(RUN_N...
-1,929,148,863,777,814,500
Utility function to call the ``api/2.0/jobs/run-now`` endpoint. :param json: The data used in the body of the request to the ``run-now`` endpoint. :return: the run_id as an int :rtype: str
airflow/providers/databricks/hooks/databricks.py
run_now
AMS-Kepler/airflow
python
def run_now(self, json: dict) -> int: '\n Utility function to call the ``api/2.0/jobs/run-now`` endpoint.\n\n :param json: The data used in the body of the request to the ``run-now`` endpoint.\n :return: the run_id as an int\n :rtype: str\n ' response = self._do_api_call(RUN_N...
def submit_run(self, json: dict) -> int: '\n Utility function to call the ``api/2.0/jobs/runs/submit`` endpoint.\n\n :param json: The data used in the body of the request to the ``submit`` endpoint.\n :return: the run_id as an int\n :rtype: str\n ' response = self._do_api_call...
6,492,600,274,998,970,000
Utility function to call the ``api/2.0/jobs/runs/submit`` endpoint. :param json: The data used in the body of the request to the ``submit`` endpoint. :return: the run_id as an int :rtype: str
airflow/providers/databricks/hooks/databricks.py
submit_run
AMS-Kepler/airflow
python
def submit_run(self, json: dict) -> int: '\n Utility function to call the ``api/2.0/jobs/runs/submit`` endpoint.\n\n :param json: The data used in the body of the request to the ``submit`` endpoint.\n :return: the run_id as an int\n :rtype: str\n ' response = self._do_api_call...
def list_jobs(self, limit: int=25, offset: int=0, expand_tasks: bool=False) -> List[Dict[(str, Any)]]: '\n Lists the jobs in the Databricks Job Service.\n\n :param limit: The limit/batch size used to retrieve jobs.\n :param offset: The offset of the first job to return, relative to the most rec...
-2,245,901,606,107,715,300
Lists the jobs in the Databricks Job Service. :param limit: The limit/batch size used to retrieve jobs. :param offset: The offset of the first job to return, relative to the most recently created job. :param expand_tasks: Whether to include task and cluster details in the response. :return: A list of jobs.
airflow/providers/databricks/hooks/databricks.py
list_jobs
AMS-Kepler/airflow
python
def list_jobs(self, limit: int=25, offset: int=0, expand_tasks: bool=False) -> List[Dict[(str, Any)]]: '\n Lists the jobs in the Databricks Job Service.\n\n :param limit: The limit/batch size used to retrieve jobs.\n :param offset: The offset of the first job to return, relative to the most rec...