_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q252600 | ClientJobsDAO.jobInsert | validation | def jobInsert(self, client, cmdLine, clientInfo='', clientKey='', params='',
alreadyRunning=False, minimumWorkers=0, maximumWorkers=0,
jobType='', priority=DEFAULT_JOB_PRIORITY):
""" Add an entry to the jobs table for a new job request. This is called by
clients that wish to star... | python | {
"resource": ""
} |
q252601 | ClientJobsDAO._startJobWithRetries | validation | def _startJobWithRetries(self, jobID):
""" Place the given job in STATUS_RUNNING mode; the job is expected to be
STATUS_NOTSTARTED.
NOTE: this function was factored out of jobStartNext because it's also
needed for testing (e.g., test_client_jobs_dao.py)
"""
with ConnectionFactory.get() as conn... | python | {
"resource": ""
} |
q252602 | ClientJobsDAO.jobReactivateRunningJobs | validation | def jobReactivateRunningJobs(self):
""" Look through the jobs table and reactivate all that are already in the
running state by setting their _eng_allocate_new_workers fields to True;
used by Nupic Scheduler as part of its failure-recovery procedure.
| python | {
"resource": ""
} |
q252603 | ClientJobsDAO.jobGetDemand | validation | def jobGetDemand(self,):
""" Look through the jobs table and get the demand - minimum and maximum
number of workers requested, if new workers are to be allocated, if there
are any untended dead workers, for all running jobs.
Parameters:
--------------------------------------------------------------... | python | {
"resource": ""
} |
q252604 | ClientJobsDAO.jobCancelAllRunningJobs | validation | def jobCancelAllRunningJobs(self):
""" Set cancel field of all currently-running jobs to true.
"""
# Get a database connection and cursor
with ConnectionFactory.get() as conn:
query = 'UPDATE | python | {
"resource": ""
} |
q252605 | ClientJobsDAO.jobCountCancellingJobs | validation | def jobCountCancellingJobs(self,):
""" Look through the jobs table and count the running jobs whose
cancel field is true.
Parameters:
----------------------------------------------------------------
retval: A count of running jobs with the cancel | python | {
"resource": ""
} |
q252606 | ClientJobsDAO.jobGetCancellingJobs | validation | def jobGetCancellingJobs(self,):
""" Look through the jobs table and get the list of running jobs whose
cancel field is true.
Parameters:
----------------------------------------------------------------
retval: A (possibly empty) sequence of running job IDs with cancel field
... | python | {
"resource": ""
} |
q252607 | ClientJobsDAO.partitionAtIntervals | validation | def partitionAtIntervals(data, intervals):
""" Generator to allow iterating slices at dynamic intervals
Parameters:
----------------------------------------------------------------
data: Any data structure that supports slicing (i.e. list or tuple)
*intervals: Iterable of intervals. The sum ... | python | {
"resource": ""
} |
q252608 | ClientJobsDAO.jobInfoWithModels | validation | def jobInfoWithModels(self, jobID):
""" Get all info about a job, with model details, if available.
Parameters:
----------------------------------------------------------------
job: jobID of the job to query
retval: A sequence of two-tuples if the jobID exists in the jobs
table (exe... | python | {
"resource": ""
} |
q252609 | ClientJobsDAO.jobInfo | validation | def jobInfo(self, jobID):
""" Get all info about a job
Parameters:
----------------------------------------------------------------
job: jobID of the job to query
retval: namedtuple containing the job info.
"""
row = self._getOneMatchingRowWithRetries(
self._jobs, dict(job_id=job... | python | {
"resource": ""
} |
q252610 | ClientJobsDAO.jobSetStatus | validation | def jobSetStatus(self, jobID, status, useConnectionID=True,):
""" Change the status on the given job
Parameters:
----------------------------------------------------------------
job: jobID of the job to change status
status: new status string (ClientJobsDAO.STATUS_xxxxx)
useConnecti... | python | {
"resource": ""
} |
q252611 | ClientJobsDAO.jobSetCompleted | validation | def jobSetCompleted(self, jobID, completionReason, completionMsg,
useConnectionID = True):
""" Change the status on the given job to completed
Parameters:
----------------------------------------------------------------
job: jobID of the job to mark as completed
... | python | {
"resource": ""
} |
q252612 | ClientJobsDAO.jobCancel | validation | def jobCancel(self, jobID):
""" Cancel the given job. This will update the cancel field in the
jobs table and will result in the job being cancelled.
Parameters:
----------------------------------------------------------------
jobID: jobID of the job to mark as completed
to Fal... | python | {
"resource": ""
} |
q252613 | ClientJobsDAO.jobGetModelIDs | validation | def jobGetModelIDs(self, jobID):
"""Fetch all the modelIDs that correspond to a given jobID; empty sequence
if none"""
rows = self._getMatchingRowsWithRetries(self._models, | python | {
"resource": ""
} |
q252614 | ClientJobsDAO.getActiveJobCountForClientInfo | validation | def getActiveJobCountForClientInfo(self, clientInfo):
""" Return the number of jobs for the given clientInfo and a status that is
not completed.
"""
with ConnectionFactory.get() as conn:
query = | python | {
"resource": ""
} |
q252615 | ClientJobsDAO.getActiveJobCountForClientKey | validation | def getActiveJobCountForClientKey(self, clientKey):
""" Return the number of jobs for the given clientKey and a status that is
not completed.
"""
with ConnectionFactory.get() as conn:
query = 'SELECT | python | {
"resource": ""
} |
q252616 | ClientJobsDAO.getActiveJobsForClientInfo | validation | def getActiveJobsForClientInfo(self, clientInfo, fields=[]):
""" Fetch jobIDs for jobs in the table with optional fields given a
specific clientInfo """
# Form the sequence of field name strings that will go into the
# request
dbFields = [self._jobs.pubToDBNameDict[x] for x in fields]
dbFields... | python | {
"resource": ""
} |
q252617 | ClientJobsDAO.jobUpdateResults | validation | def jobUpdateResults(self, jobID, results):
""" Update the results string and last-update-time fields of a model.
Parameters:
----------------------------------------------------------------
jobID: job ID of model to modify
results: new results (json dict string)
"""
with Connection... | python | {
"resource": ""
} |
q252618 | ClientJobsDAO.modelsClearAll | validation | def modelsClearAll(self):
""" Delete all models from the models table
Parameters:
----------------------------------------------------------------
"""
self._logger.info('Deleting all rows from models table %r',
self.modelsTableName) | python | {
"resource": ""
} |
q252619 | ClientJobsDAO.modelsInfo | validation | def modelsInfo(self, modelIDs):
""" Get ALL info for a set of models
WARNING!!!: The order of the results are NOT necessarily in the same order as
the order of the model IDs passed in!!!
Parameters:
----------------------------------------------------------------
modelIDs: list of model IDs... | python | {
"resource": ""
} |
q252620 | ClientJobsDAO.modelsGetFieldsForJob | validation | def modelsGetFieldsForJob(self, jobID, fields, ignoreKilled=False):
""" Gets the specified fields for all the models for a single job. This is
similar to modelsGetFields
Parameters:
----------------------------------------------------------------
jobID: jobID for the models to be searc... | python | {
"resource": ""
} |
q252621 | ClientJobsDAO.modelsGetFieldsForCheckpointed | validation | def modelsGetFieldsForCheckpointed(self, jobID, fields):
"""
Gets fields from all models in a job that have been checkpointed. This is
used to figure out whether or not a new model should be checkpointed.
Parameters:
-----------------------------------------------------------------------
jobID:... | python | {
"resource": ""
} |
q252622 | ClientJobsDAO.modelsGetParams | validation | def modelsGetParams(self, modelIDs):
""" Get the params and paramsHash for a set of models.
WARNING!!!: The order of the results are NOT necessarily in the same order as
the order of the model IDs passed in!!!
Parameters:
----------------------------------------------------------------
modelID... | python | {
"resource": ""
} |
q252623 | ClientJobsDAO.modelsGetResultAndStatus | validation | def modelsGetResultAndStatus(self, modelIDs):
""" Get the results string and other status fields for a set of models.
WARNING!!!: The order of the results are NOT necessarily in the same order
as the order of the model IDs passed in!!!
For each model, this returns a tuple containing:
(modelID, re... | python | {
"resource": ""
} |
q252624 | ClientJobsDAO.modelAdoptNextOrphan | validation | def modelAdoptNextOrphan(self, jobId, maxUpdateInterval):
""" Look through the models table for an orphaned model, which is a model
that is not completed yet, whose _eng_last_update_time is more than
maxUpdateInterval seconds ago.
If one is found, change its _eng_worker_conn_id to the current worker's
... | python | {
"resource": ""
} |
q252625 | KNNClassifierRegion._initEphemerals | validation | def _initEphemerals(self):
"""
Initialize attributes that are not saved with the checkpoint.
"""
self._firstComputeCall = True
self._accuracy = None
self._protoScores = None
self._categoryDistances = None
self._knn = knn_classifier.KNNClassifier(**self.knnParams)
| python | {
"resource": ""
} |
q252626 | KNNClassifierRegion.enableTap | validation | def enableTap(self, tapPath):
"""
Begin writing output tap files.
:param tapPath: (string) base name of the output tap files to write.
"""
| python | {
"resource": ""
} |
q252627 | KNNClassifierRegion.disableTap | validation | def disableTap(self):
"""
Disable writing of output tap files.
"""
if self._tapFileIn is not None:
self._tapFileIn.close()
self._tapFileIn = None
| python | {
"resource": ""
} |
q252628 | KNNClassifierRegion.handleLogOutput | validation | def handleLogOutput(self, output):
"""
Write outputs to output tap file.
:param outputs: (iter) some outputs.
"""
#raise Exception('MULTI-LINE DUMMY\nMULTI-LINE DUMMY')
if self._tapFileOut is not None:
| python | {
"resource": ""
} |
q252629 | KNNClassifierRegion._storeSample | validation | def _storeSample(self, inputVector, trueCatIndex, partition=0):
"""
Store a training sample and associated category label
"""
# If this is the first sample, then allocate a numpy array
# of the appropriate size in which to store all samples.
if self._samples is None:
self._samples = numpy... | python | {
"resource": ""
} |
q252630 | KNNClassifierRegion._finishLearning | validation | def _finishLearning(self):
"""Does nothing. Kept here for API compatibility """
if self._doSphering:
self._finishSphering()
| python | {
"resource": ""
} |
q252631 | generateStats | validation | def generateStats(filename, statsInfo, maxSamples = None, filters=[], cache=True):
"""Generate requested statistics for a dataset and cache to a file.
If filename is None, then don't cache to a file"""
# Sanity checking
if not isinstance(statsInfo, dict):
raise RuntimeError("statsInfo must be a dict -- "
... | python | {
"resource": ""
} |
q252632 | _fixupRandomEncoderParams | validation | def _fixupRandomEncoderParams(params, minVal, maxVal, minResolution):
"""
Given model params, figure out the correct parameters for the
RandomDistributed encoder. Modifies params in place.
"""
encodersDict = (
params["modelConfig"]["modelParams"]["sensorParams"]["encoders"]
| python | {
"resource": ""
} |
q252633 | MonitoredTemporalMemory.read | validation | def read(cls, proto):
"""
Intercepts TemporalMemory deserialization request in order to initialize
`TemporalMemoryMonitorMixin` state
@param proto (DynamicStructBuilder) Proto object
@return (TemporalMemory) TemporalMemory shim instance
"""
tm = super(TemporalMemoryMonitorMixin, cls).read(... | python | {
"resource": ""
} |
q252634 | pickByDistribution | validation | def pickByDistribution(distribution, r=None):
"""
Pick a value according to the provided distribution.
Example:
::
pickByDistribution([.2, .1])
Returns 0 two thirds of the time and 1 one third of the time.
| python | {
"resource": ""
} |
q252635 | Indicator | validation | def Indicator(pos, size, dtype):
"""
Returns an array of length size and type dtype that is everywhere 0,
except in the index in pos.
:param pos: (int) specifies the position of the one entry that will be set.
:param size: (int) The total size of the array to be returned.
:param dtype: The element type (co... | python | {
"resource": ""
} |
q252636 | MultiIndicator | validation | def MultiIndicator(pos, size, dtype):
"""
Returns an array of length size and type dtype that is everywhere 0,
except in the indices listed in sequence pos.
:param pos: A single integer or sequence of integers that specify
the position of ones to be set.
:param size: The total size of the array t... | python | {
"resource": ""
} |
q252637 | Distribution | validation | def Distribution(pos, size, counts, dtype):
"""
Returns an array of length size and type dtype that is everywhere 0,
except in the indices listed in sequence pos. The non-zero indices
contain a normalized distribution based on the counts.
:param pos: A single integer or sequence of integers that specify... | python | {
"resource": ""
} |
q252638 | ConditionalProbabilityTable2D.grow | validation | def grow(self, rows, cols):
"""
Grows the histogram to have rows rows and cols columns.
Must not have been initialized before, or already have the same
number of columns.
If rows is smaller than the current number of rows,
does not shrink.
Also updates the sizes of the row and column sums.
... | python | {
"resource": ""
} |
q252639 | ConditionalProbabilityTable2D.updateRow | validation | def updateRow(self, row, distribution):
"""
Add distribution to row row.
Distribution should be an array of probabilities or counts.
:param row: Integer index of the row to add to.
May be larger than the current number of rows, in which case
the histogram grows.
... | python | {
"resource": ""
} |
q252640 | importAndRunFunction | validation | def importAndRunFunction(
path,
moduleName,
funcName,
**keywords
):
"""
Run a named function specified by a filesystem path, module name
and function name.
Returns the value returned by the imported function.
Use this when access is needed to code that has
not been added to a package acc... | python | {
"resource": ""
} |
q252641 | MovingAverage.compute | validation | def compute(slidingWindow, total, newVal, windowSize):
"""Routine for computing a moving average.
@param slidingWindow a list of previous values to use in computation that
will be modified and returned
@param total the sum of the values in slidingWindow to be used in the
calculation of the ... | python | {
"resource": ""
} |
q252642 | MovingAverage.next | validation | def next(self, newValue):
"""Instance method wrapper around compute."""
newAverage, self.slidingWindow, self.total = self.compute(
| python | {
"resource": ""
} |
q252643 | MetricPassThruPrediction.addInstance | validation | def addInstance(self, groundTruth, prediction, record = None, result = None):
"""Compute and store | python | {
"resource": ""
} |
q252644 | CustomErrorMetric.mostLikely | validation | def mostLikely(self, pred):
""" Helper function to return a scalar value representing the most
likely outcome given a probability distribution
"""
if len(pred) == 1:
return pred.keys()[0]
mostLikelyOutcome = None
maxProbability = 0
for prediction, probability in pred.items():
| python | {
"resource": ""
} |
q252645 | CustomErrorMetric.expValue | validation | def expValue(self, pred):
""" Helper function to return a scalar value representing the expected
value of a probability distribution
""" | python | {
"resource": ""
} |
q252646 | Encoder.getScalarNames | validation | def getScalarNames(self, parentFieldName=''):
"""
Return the field names for each of the scalar values returned by
getScalars.
:param parentFieldName: The name of the encoder which is our parent. This
name is prefixed to each of the field names within this encoder to
form the keys of th... | python | {
"resource": ""
} |
q252647 | Encoder._getInputValue | validation | def _getInputValue(self, obj, fieldName):
"""
Gets the value of a given field from the input record
"""
if isinstance(obj, dict):
if not fieldName in obj:
knownFields = ", ".join(
key for key in obj.keys() if not key.startswith("_")
| python | {
"resource": ""
} |
q252648 | Encoder.getFieldDescription | validation | def getFieldDescription(self, fieldName):
"""
Return the offset and length of a given field within the encoded output.
:param fieldName: Name of the field
:return: tuple(``offset``, ``width``) of the field within the encoded output
"""
# Find which field it's in
description = self.getDescr... | python | {
"resource": ""
} |
q252649 | Encoder.encodedBitDescription | validation | def encodedBitDescription(self, bitOffset, formatted=False):
"""
Return a description of the given bit in the encoded output.
This will include the field name and the offset within the field.
:param bitOffset: Offset of the bit to get the description of
:param formatted: If True, the bitO... | python | {
"resource": ""
} |
q252650 | Encoder.pprint | validation | def pprint(self, output, prefix=""):
"""
Pretty-print the encoded output using ascii art.
:param output: to print
:param prefix: printed before the header if specified
| python | {
"resource": ""
} |
q252651 | Encoder.decode | validation | def decode(self, encoded, parentFieldName=''):
"""
Takes an encoded output and does its best to work backwards and generate
the input that would have generated it.
In cases where the encoded output contains more ON bits than an input
would have generated, this routine will return one or more ranges... | python | {
"resource": ""
} |
q252652 | drawFile | validation | def drawFile(dataset, matrix, patterns, cells, w, fnum):
'''The similarity of two patterns in the bit-encoding space is displayed alongside
their similarity in the sp-coinc space.'''
score=0
count = 0
assert len(patterns)==len(cells)
for p in xrange(len(patterns)-1):
matrix[p+1:,p] = [len(set(patterns[p... | python | {
"resource": ""
} |
q252653 | Example.createInput | validation | def createInput(self):
"""create a random input vector"""
print "-" * 70 + "Creating a random input vector" + "-" * 70
#clear the inputArray to zero before creating a new input vector
self.inputArray[0:] = 0
| python | {
"resource": ""
} |
q252654 | Example.run | validation | def run(self):
"""Run the spatial pooler with the input vector"""
print "-" * 80 + "Computing the SDR" + "-" * 80
#activeArray[column]=1 if column is active after spatial pooling
| python | {
"resource": ""
} |
q252655 | KNNClassifier.clear | validation | def clear(self):
"""Clears the state of the KNNClassifier."""
self._Memory = None
self._numPatterns = 0
self._M = None
self._categoryList = []
self._partitionIdList = []
self._partitionIdMap = {}
self._finishedLearning = False
self._iterationIdx = -1
# Fixed capacity KNN
if ... | python | {
"resource": ""
} |
q252656 | KNNClassifier._removeRows | validation | def _removeRows(self, rowsToRemove):
"""
A list of row indices to remove. There are two caveats. First, this is
a potentially slow operation. Second, pattern indices will shift if
patterns before them are removed.
"""
# Form a numpy array of row indices to be removed
removalArray = numpy.arr... | python | {
"resource": ""
} |
q252657 | KNNClassifier.getDistances | validation | def getDistances(self, inputPattern):
"""Return the distances between the input pattern and all other
stored patterns.
:param inputPattern: pattern to check distance with
:returns: (distances, categories) | python | {
"resource": ""
} |
q252658 | KNNClassifier.infer | validation | def infer(self, inputPattern, computeScores=True, overCategories=True,
partitionId=None):
"""Finds the category that best matches the input pattern. Returns the
winning category index as well as a distribution over all categories.
:param inputPattern: (list or array) The pattern to be classifie... | python | {
"resource": ""
} |
q252659 | KNNClassifier.getClosest | validation | def getClosest(self, inputPattern, topKCategories=3):
"""Returns the index of the pattern that is closest to inputPattern,
the distances of all patterns to inputPattern, and the indices of the k
closest categories.
"""
inferenceResult = numpy.zeros(max(self._categoryList)+1)
dist = self._getDist... | python | {
"resource": ""
} |
q252660 | KNNClassifier.closestTrainingPattern | validation | def closestTrainingPattern(self, inputPattern, cat):
"""Returns the closest training pattern to inputPattern that belongs to
category "cat".
:param inputPattern: The pattern whose closest neighbor is sought
:param cat: The required category of closest neighbor
:returns: A dense version of the clo... | python | {
"resource": ""
} |
q252661 | KNNClassifier.getPattern | validation | def getPattern(self, idx, sparseBinaryForm=False, cat=None):
"""Gets a training pattern either by index or category number.
:param idx: Index of the training pattern
:param sparseBinaryForm: If true, returns a list of the indices of the
non-zero bits in the training pattern
:param cat: If not... | python | {
"resource": ""
} |
q252662 | KNNClassifier.getPartitionId | validation | def getPartitionId(self, i):
"""
Gets the partition id given an index.
:param i: index of partition
:returns: the partition id associated with pattern i. Returns None if no id
is associated with it.
"""
if (i < 0) or (i >= self._numPatterns):
| python | {
"resource": ""
} |
q252663 | KNNClassifier._addPartitionId | validation | def _addPartitionId(self, index, partitionId=None):
"""
Adds partition id for pattern index
"""
if partitionId is None:
self._partitionIdList.append(numpy.inf)
else:
self._partitionIdList.append(partitionId)
| python | {
"resource": ""
} |
q252664 | KNNClassifier._rebuildPartitionIdMap | validation | def _rebuildPartitionIdMap(self, partitionIdList):
"""
Rebuilds the partition Id map using the given partitionIdList
"""
self._partitionIdMap = {}
for row, partitionId in enumerate(partitionIdList):
indices | python | {
"resource": ""
} |
q252665 | KNNClassifier._calcDistance | validation | def _calcDistance(self, inputPattern, distanceNorm=None):
"""Calculate the distances from inputPattern to all stored patterns. All
distances are between 0.0 and 1.0
:param inputPattern The pattern from which distances to all other patterns
are calculated
:param distanceNorm Degree of the dista... | python | {
"resource": ""
} |
q252666 | KNNClassifier._getDistances | validation | def _getDistances(self, inputPattern, partitionId=None):
"""Return the distances from inputPattern to all stored patterns.
:param inputPattern The pattern from which distances to all other patterns
are returned
:param partitionId If provided, ignore all training vectors with this
partition... | python | {
"resource": ""
} |
q252667 | KNNClassifier.remapCategories | validation | def remapCategories(self, mapping):
"""Change the category indices.
Used by the Network Builder to keep the category indices in sync with the
ImageSensor categoryInfo when the user renames or removes categories.
:param mapping: List of new category indices. For example, mapping=[2,0,1]
would c... | python | {
"resource": ""
} |
q252668 | RecordSensor._convertNonNumericData | validation | def _convertNonNumericData(self, spatialOutput, temporalOutput, output):
"""
Converts all of the non-numeric fields from spatialOutput and temporalOutput
into their scalar equivalents and records them in the output dictionary.
:param spatialOutput: The results of topDownCompute() for the spatial input.... | python | {
"resource": ""
} |
q252669 | RecordSensor.getOutputElementCount | validation | def getOutputElementCount(self, name):
"""
Computes the width of dataOut.
Overrides
:meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
"""
if name == "resetOut":
print ("WARNING: getOutputElementCount should not have been called with "
"resetOut")
... | python | {
"resource": ""
} |
q252670 | RecordSensor.setParameter | validation | def setParameter(self, parameterName, index, parameterValue):
"""
Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are explicitly handled here.
"""
if parameterName == 'topDownMode':
... | python | {
"resource": ""
} |
q252671 | FileRecordStream.rewind | validation | def rewind(self):
"""
Put us back at the beginning of the file again.
"""
# Superclass rewind
super(FileRecordStream, self).rewind()
self.close()
self._file = open(self._filename, self._mode)
self._reader = csv.reader(self._file, dialect="excel")
| python | {
"resource": ""
} |
q252672 | FileRecordStream.getNextRecord | validation | def getNextRecord(self, useCache=True):
""" Returns next available data record from the file.
:returns: a data row (a list or tuple) if available; None, if no more
records in the table (End of Stream - EOS); empty sequence (list
or tuple) when timing out while waiting for the next r... | python | {
"resource": ""
} |
q252673 | FileRecordStream.appendRecord | validation | def appendRecord(self, record):
"""
Saves the record in the underlying csv file.
:param record: a list of Python objects that will be string-ified
"""
assert self._file is not None
assert self._mode == self._FILE_WRITE_MODE
assert isinstance(record, (list, tuple)), \
"unexpected reco... | python | {
"resource": ""
} |
q252674 | FileRecordStream.appendRecords | validation | def appendRecords(self, records, progressCB=None):
"""
Saves multiple records in the underlying storage.
:param records: array of records as in
:meth:`~.FileRecordStream.appendRecord`
| python | {
"resource": ""
} |
q252675 | FileRecordStream.getBookmark | validation | def getBookmark(self):
"""
Gets a bookmark or anchor to the current position.
:returns: an anchor to the current position in the data. Passing this
anchor to a constructor makes the current position to be the first
returned record.
"""
if self._write | python | {
"resource": ""
} |
q252676 | FileRecordStream.seekFromEnd | validation | def seekFromEnd(self, numRecords):
"""
Seeks to ``numRecords`` from the end and returns a bookmark to the new
position.
:param numRecords: how far to seek from end of file.
| python | {
"resource": ""
} |
q252677 | FileRecordStream._updateSequenceInfo | validation | def _updateSequenceInfo(self, r):
"""Keep track of sequence and make sure time goes forward
Check if the current record is the beginning of a new sequence
A new sequence starts in 2 cases:
1. The sequence id changed (if there is a sequence id field)
2. The reset field is 1 (if there is a reset fie... | python | {
"resource": ""
} |
q252678 | FileRecordStream._getStartRow | validation | def _getStartRow(self, bookmark):
""" Extracts start row from the bookmark information
"""
bookMarkDict = json.loads(bookmark)
realpath = os.path.realpath(self._filename)
bookMarkFile = bookMarkDict.get('filepath', None)
if bookMarkFile != realpath:
print ("Ignoring bookmark due to mism... | python | {
"resource": ""
} |
q252679 | InferenceElement.isTemporal | validation | def isTemporal(inferenceElement):
""" Returns True if the inference from this timestep is predicted the input
for the NEXT timestep.
NOTE: This should only be checked IF THE MODEL'S INFERENCE TYPE IS ALSO
TEMPORAL. That is, a temporal model CAN have non-temporal inference elements,
but a non-tempor... | python | {
"resource": ""
} |
q252680 | InferenceElement.getTemporalDelay | validation | def getTemporalDelay(inferenceElement, key=None):
""" Returns the number of records that elapse between when an inference is
made and when the corresponding input record will appear. For example, a
multistep prediction for 3 timesteps out will have a delay of 3
Parameters:
------------------------... | python | {
"resource": ""
} |
q252681 | InferenceElement.getMaxDelay | validation | def getMaxDelay(inferences):
"""
Returns the maximum delay for the InferenceElements in the inference
dictionary
Parameters:
-----------------------------------------------------------------------
inferences: A dictionary where the keys are InferenceElements
"""
maxDelay = 0
for i... | python | {
"resource": ""
} |
q252682 | InferenceType.isTemporal | validation | def isTemporal(inferenceType):
""" Returns True if the inference type is 'temporal', i.e. requires a
temporal memory in the network.
"""
if InferenceType.__temporalInferenceTypes is None:
InferenceType.__temporalInferenceTypes = \
set([InferenceType.TemporalNextStep... | python | {
"resource": ""
} |
q252683 | Enum | validation | def Enum(*args, **kwargs):
"""
Utility function for creating enumerations in python
Example Usage:
>> Color = Enum("Red", "Green", "Blue", "Magenta")
>> print Color.Red
>> 0
>> print Color.Green
>> 1
>> print Color.Blue
>> 2
>> print Color.Magenta
>> 3
>> Color.Violet
... | python | {
"resource": ""
} |
q252684 | makeDirectoryFromAbsolutePath | validation | def makeDirectoryFromAbsolutePath(absDirPath):
""" Makes directory for the given directory path with default permissions.
If the directory already exists, it is treated as success.
absDirPath: absolute path of the directory to create.
Returns: absDirPath arg
Exceptions: OSError if directory ... | python | {
"resource": ""
} |
q252685 | ConfigurationBase._readConfigFile | validation | def _readConfigFile(cls, filename, path=None):
""" Parse the given XML file and return a dict describing the file.
Parameters:
----------------------------------------------------------------
filename: name of XML file to parse (no path)
path: path of the XML file. If None, then use the stand... | python | {
"resource": ""
} |
q252686 | Configuration.setCustomProperties | validation | def setCustomProperties(cls, properties):
""" Set multiple custom properties and persist them to the custom
configuration store.
Parameters:
----------------------------------------------------------------
properties: a dict of property name/value pairs to set
"""
_getLogger().info("Setting... | python | {
"resource": ""
} |
q252687 | Configuration.clear | validation | def clear(cls):
""" Clear all configuration properties from in-memory cache, but do NOT
alter the custom configuration file. Used in unit-testing.
"""
# Clear the in-memory settings cache, forcing reload upon subsequent "get"
| python | {
"resource": ""
} |
q252688 | Configuration.resetCustomConfig | validation | def resetCustomConfig(cls):
""" Clear all custom configuration settings and delete the persistent
custom configuration store.
"""
_getLogger().info("Resetting all custom configuration properties; "
| python | {
"resource": ""
} |
q252689 | _CustomConfigurationFileWrapper.clear | validation | def clear(cls, persistent=False):
""" If persistent is True, delete the temporary file
Parameters:
----------------------------------------------------------------
persistent: if True, custom configuration file is deleted
"""
if persistent:
try:
os.unlink(cls.getPath())
exce... | python | {
"resource": ""
} |
q252690 | _CustomConfigurationFileWrapper.getCustomDict | validation | def getCustomDict(cls):
""" Returns a dict of all temporary values in custom configuration file
"""
if not os.path.exists(cls.getPath()):
return dict()
properties = Configuration._readConfigFile(os.path.basename(
cls.getPath()), os.path.dirname(cls.getPath()))
values = dict() | python | {
"resource": ""
} |
q252691 | _CustomConfigurationFileWrapper.edit | validation | def edit(cls, properties):
""" Edits the XML configuration file with the parameters specified by
properties
Parameters:
----------------------------------------------------------------
properties: dict of settings to be applied to the custom configuration store
(key is property nam... | python | {
"resource": ""
} |
q252692 | _CustomConfigurationFileWrapper._setPath | validation | def _setPath(cls):
""" Sets the path of the custom configuration file
"""
| python | {
"resource": ""
} |
q252693 | Particle.getState | validation | def getState(self):
"""Get the particle state as a dict. This is enough information to
instantiate this particle on another worker."""
varStates = dict()
for varName, var in self.permuteVars.iteritems():
varStates[varName] = var.getState() | python | {
"resource": ""
} |
q252694 | Particle.initStateFrom | validation | def initStateFrom(self, particleId, particleState, newBest):
"""Init all of our variable positions, velocities, and optionally the best
result and best position from the given particle.
If newBest is true, we get the best result and position for this new
generation from the resultsDB, This is used when... | python | {
"resource": ""
} |
q252695 | Particle.copyVarStatesFrom | validation | def copyVarStatesFrom(self, particleState, varNames):
"""Copy specific variables from particleState into this particle.
Parameters:
--------------------------------------------------------------
particleState: dict produced by a particle's getState() method
varNames: which variab... | python | {
"resource": ""
} |
q252696 | Particle.getPositionFromState | validation | def getPositionFromState(pState):
"""Return the position of a particle given its state dict.
Parameters:
--------------------------------------------------------------
retval: dict() of particle position, keys are the variable names,
| python | {
"resource": ""
} |
q252697 | Particle.agitate | validation | def agitate(self):
"""Agitate this particle so that it is likely to go to a new position.
Every time agitate is called, the particle is jiggled an even greater
amount.
Parameters:
--------------------------------------------------------------
| python | {
"resource": ""
} |
q252698 | Particle.newPosition | validation | def newPosition(self, whichVars=None):
# TODO: incorporate data from choice variables....
# TODO: make sure we're calling this when appropriate.
"""Choose a new position based on results obtained so far from all other
particles.
Parameters:
------------------------------------------------------... | python | {
"resource": ""
} |
q252699 | ModelFactory.__getLogger | validation | def __getLogger(cls):
""" Get the logger for this object.
:returns: (Logger) A Logger object.
"""
if cls.__logger is None:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.