def Func(arg_0, arg_1, arg_2):
    """Instantiates a _HyperSearchJob instance from info saved in file

    Parameters:
    ----------------------------------------------------------------------
    permWorkDir: Directory path for saved jobID file
    outputLabel: Label string for incorporating into file name for saved jobID
    retval:      _HyperSearchJob instance; raises exception if not found
    """
    arg_3 = arg_0.__loadHyperSearchJobID(arg_1=arg_1,
                                       arg_2=arg_2)

    arg_4 = _HyperSearchJob(nupicJobID=arg_3)
    return arg_4


def Func(arg_0, arg_1, arg_2):
    """Loads a saved jobID from file

    Parameters:
    ----------------------------------------------------------------------
    permWorkDir:  Directory path for saved jobID file
    outputLabel:  Label string for incorporating into file name for saved jobID
    retval:       HyperSearch jobID; raises exception if not found.
    """
    arg_3 = arg_0.__getHyperSearchJobIDFilePath(arg_1=arg_1,
                                                 arg_2=arg_2)

    arg_4 = None
    with open(arg_3, "r") as jobIdPickleFile:
      arg_5 = pickle.load(jobIdPickleFile)
      arg_4 = arg_5["hyperSearchJobID"]

    return arg_4


def Func(arg_0, arg_1):
    """Emit model info to csv file

    Parameters:
    ----------------------------------------------------------------------
    modelInfo:      _NupicModelInfo instance
    retval:         nothing
    """
    # Open/init csv file, if needed
    if arg_0.__csvFileObj is None:
      # sets up self.__sortedVariableNames and self.__csvFileObj
      arg_0.__openAndInitCSVFile(arg_1)

    arg_2 = arg_0.__csvFileObj

    # Emit model info row to report.csv
    print >> arg_2, "%s, " % (arg_0.__searchJobID),
    print >> arg_2, "%s, " % (arg_1.getModelID()),
    print >> arg_2, "%s, " % (arg_1.statusAsString()),
    if arg_1.isFinished():
      print >> arg_2, "%s, " % (arg_1.getCompletionReason()),
    else:
      print >> arg_2, "NA, ",
    if not arg_1.isWaitingToStart():
      print >> arg_2, "%s, " % (arg_1.getStartTime()),
    else:
      print >> arg_2, "NA, ",
    if arg_1.isFinished():
      arg_3 = "%Y-%m-%d %H:%M:%S"
      arg_4 = arg_1.getStartTime()
      arg_5 = arg_1.getEndTime()
      print >> arg_2, "%s, " % arg_5,
      arg_6 = datetime.strptime(arg_4, arg_3)
      arg_7 = datetime.strptime(arg_5, arg_3)
      print >> arg_2, "%s, " % (str((arg_7 - arg_6).seconds)),
    else:
      print >> arg_2, "NA, ",
      print >> arg_2, "NA, ",
    print >> arg_2, "%s, " % str(arg_1.getModelDescription()),
    print >> arg_2, "%s, " % str(arg_1.getNumRecords()),
    arg_8 = arg_1.getParamLabels()
    for arg_9 in arg_0.__sortedVariableNames:
      # Some values are complex structures,.. which need to be represented as
      # strings
      if arg_9 in arg_8:
        print >> arg_2, "%s, " % (arg_8[arg_9]),
      else:
        print >> arg_2, "None, ",
    arg_10 = arg_1.getReportMetrics()
    for arg_9 in arg_0.__sortedMetricsKeys:
      arg_11 = arg_10.get(arg_9, "NA")
      arg_11 = str(arg_11)
      arg_11 = arg_11.replace("\n", " ")
      print >> arg_2, "%s, " % (arg_11),

    print >> arg_2


def Func(arg_0):
    """Queuries DB for model IDs of all currently instantiated models
    associated with this HyperSearch job.

    See also: _iterModels()

    Parameters:
    ----------------------------------------------------------------------
    retval:         A sequence of Nupic modelIDs
    """
    arg_1 = arg_0.getJobID()
    arg_2 = _clientJobsDB().modelsGetUpdateCounters(arg_1)
    arg_3 = tuple(x[0] for x in arg_2)

    return arg_3


def Func(arg_0, arg_1):
    """Retrives the optimization key name and optimization function.

    Parameters:
    ---------------------------------------------------------
    searchJobParams:
                    Parameter for passing as the searchParams arg to
                    Hypersearch constructor.
    retval:       (optimizationMetricKey, maximize)
                  optimizationMetricKey: which report key to optimize for
                  maximize: True if we should try and maximize the optimizeKey
                    metric. False if we should minimize it.
    """
    if arg_1["hsVersion"] == "v2":
      arg_2 = HypersearchV2(searchParams=arg_1)
    else:
      raise RuntimeError("Unsupported hypersearch version \"%s\"" % \
                         (arg_1["hsVersion"]))

    arg_3 = arg_2.Func()
    return arg_3


def Func(arg_0):
    """Retrives a dictionary of metrics that combines all report and
    optimization metrics

    Parameters:
    ----------------------------------------------------------------------
    retval:         a dictionary of optimization metrics that were collected
                    for the model; an empty dictionary if there aren't any.
    """
    arg_1 = arg_0.getReportMetrics()
    arg_1.update(arg_0.getOptimizationMetrics())
    return arg_1


def Func(arg_0, arg_1):
    """ Returns the periodic checks to see if the model should
    continue running.

    Parameters:
    -----------------------------------------------------------------------
    terminationFunc:  The function that will be called in the model main loop
                      as a wrapper around this function. Must have a parameter
                      called 'index'

    Returns:          A list of PeriodicActivityRequest objects.
    """
    arg_2 = [None] * len(ModelTerminator._MILESTONES)
    for arg_3, (arg_4, arg_5) in enumerate(ModelTerminator._MILESTONES):
      arg_6 = functools.partial(arg_1, arg_3=arg_3)
      arg_2[arg_3] = PeriodicActivityRequest(repeating =False,
                                                  period = arg_4,
                                                  arg_6=arg_6)


def Func(arg_0):
    """
    Iterates through stream to calculate total records after aggregation.
    This will alter the bookmark state.
    """
    arg_1 = 0
    while True:
      arg_2 = arg_0.getNextRecord()
      if arg_2 is None:
        return arg_1
      arg_1 += 1

      if arg_1 > 10000:
        raise RuntimeError('No end of datastream found.')


def Func(arg_0, arg_1):
    """
    Return a pattern for a number.

    @param number (int) Number of pattern

    @return (set) Indices of on bits
    """
    if not arg_1 in arg_0._patterns:
      raise IndexError("Invalid number")

    return arg_0._patterns[arg_1]


def Func(arg_0, arg_1, arg_2):
    """
    Add noise to pattern.

    @param bits   (set)   Indices of on bits
    @param amount (float) Probability of switching an on bit with a random bit

    @return (set) Indices of on bits in noisy pattern
    """
    arg_3 = set()

    for arg_4 in arg_1:
      if arg_0._random.getReal64() < arg_2:
        arg_3.add(arg_0._random.getUInt32(arg_0._n))
      else:
        arg_3.add(arg_4)

    return arg_3


def Func(arg_0, arg_1):
    """
    Return the set of pattern numbers that match a bit.

    @param bit (int) Index of bit

    @return (set) Indices of numbers
    """
    if arg_1 >= arg_0._n:
      raise IndexError("Invalid bit")

    arg_2 = set()

    for arg_3, arg_4 in arg_0._patterns.iteritems():
      if arg_1 in arg_4:
        arg_2.add(arg_3)

    return arg_2


def Func(arg_0, arg_1):
    """
    Return a map from number to matching on bits,
    for all numbers that match a set of bits.

    @param bits (set) Indices of bits

    @return (dict) Mapping from number => on bits.
    """
    arg_2 = dict()

    for arg_3 in arg_1:
      arg_4 = arg_0.numbersForBit(arg_3)

      for arg_5 in arg_4:
        if not arg_5 in arg_2:
          arg_2[arg_5] = set()

        arg_2[arg_5].add(arg_3)

    return arg_2


def Func(arg_0, arg_1, arg_2=1):
    """
    Pretty print a pattern.

    @param bits      (set) Indices of on bits
    @param verbosity (int) Verbosity level

    @return (string) Pretty-printed text
    """
    arg_3 = arg_0.numberMapForBits(arg_1)
    arg_4 = ""

    arg_5 = []
    arg_6 = sorted(arg_3.iteritems(),
                         key=lambda (arg_7, arg_1): len(arg_1),
                         reverse=True)

    for arg_7, arg_1 in arg_6:

      if arg_2 > 2:
        arg_8 = [str(n) for n in arg_1]
        arg_9 = "{0} (bits: {1})".format(arg_7, ",".join(arg_8))
      elif arg_2 > 1:
        arg_9 = "{0} ({1} bits)".format(arg_7, len(arg_1))
      else:
        arg_9 = str(arg_7)

      arg_5.append(arg_9)

    arg_4 += "[{0}]".format(", ".join(arg_5))

    return arg_4


def Func(arg_0):
    """
    Generates set of random patterns.
    """
    arg_1 = np.array(range(arg_0._n), np.uint32)
    for arg_2 in xrange(arg_0._num):
      arg_0._random.shuffle(arg_1)
      arg_3 = arg_1[0:arg_0._getW()]
      arg_0._patterns[arg_2] = set(arg_3)


def Func(arg_0):
    """
    Generates set of consecutive patterns.
    """
    arg_1 = arg_0._n
    arg_2 = arg_0._w

    assert type(arg_2) is int, "List for w not supported"

    for arg_3 in xrange(arg_1 / arg_2):
      arg_4 = set(xrange(arg_3 * arg_2, (arg_3+1) * arg_2))
      arg_0._patterns[arg_3] = arg_4


def Func(arg_0, arg_1, arg_2):
    """
    Calculate error signal

    :param bucketIdxList: list of encoder buckets

    :return: dict containing error. The key is the number of steps
             The value is a numpy array of error at the output layer
    """
    arg_3 = dict()
    arg_4 = numpy.zeros(arg_0._maxBucketIdx + 1)
    arg_5 = len(arg_2)
    for arg_6 in arg_2:
      arg_4[arg_6] = 1.0/arg_5

    for (arg_7, arg_8) in arg_0._patternNZHistory:
      arg_9 = arg_1 - arg_7
      if arg_9 in arg_0.steps:
        arg_10 = arg_0.inferSingleStep(arg_8,
                                           arg_0._weightMatrix[arg_9])
        arg_3[arg_9] = arg_4 - arg_10

    return arg_3


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=1024 * 1024 * 100):
  """Sort a potentially big file

  filename - the input file (standard File format)
  key - a list of field names to Func by
  outputFile - the name of the output file
  fields - a list of fields that should be included (all fields if None)
  watermark - when available memory goes bellow the watermark create a new chunk

  Func() works by reading as records from the file into memory
  and calling _FuncChunk() on each chunk. In the process it gets
  rid of unneeded fields if any. Once all the chunks have been Funced and
  written to chunk files it calls _merge() to merge all the chunks into a
  single Funced file.

  Note, that Func() gets a key that contains field names, which it converts
  into field indices for _FuncChunk() becuase _FuncChunk() doesn't need to know
  the field name.

  Func() figures out by itself how many chunk files to use by reading records
  from the file until the low watermark value of availabel memory is hit and
  then it Funcs the current records, generates a chunk file, clears the Funced
  records and starts on a new chunk.

  The key field names are turned into indices
  """
  if arg_3 is not None:
    assert set(arg_1).issubset(set([arg_5[0] for arg_5 in arg_3]))

  with FileRecordStream(arg_0) as arg_5:

    # Find the indices of the requested fields
    if arg_3:
      arg_6 = [ff[0] for ff in arg_3]
      arg_7 = [arg_5.getFieldNames().index(name) for name in arg_6]
      assert len(arg_7) == len(arg_3)
    else:
      arg_8 = arg_5.getFields()
      arg_6 = arg_5.getFieldNames()
      arg_7 = None

    # turn key fields to key indices
    arg_1 = [arg_6.index(name) for name in arg_1]

    arg_9 = 0
    arg_10 = []
    for arg_11, arg_12 in enumerate(arg_5):
      # Select requested fields only
      if arg_7:
        arg_13 = []
        for arg_11 in arg_7:
          arg_13.append(arg_12[arg_11])
        arg_12 = arg_13
      # Store processed record
      arg_10.append(arg_12)

      # Check memory
      arg_14 = psutil.avail_phymem()

      # If bellow the watermark create a new chunk, reset and keep going
      if arg_14 < arg_4:
        _FuncChunk(arg_10, arg_1, arg_9, arg_3)
        arg_10 = []
        arg_9 += 1

    # Sort and write the remainder
    if len(arg_10) > 0:
      _FuncChunk(arg_10, arg_1, arg_9, arg_3)
      arg_9 += 1

    # Marge all the files
    _mergeFiles(arg_1, arg_9, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
  """Sort in memory chunk of records

  records - a list of records read from the original dataset
  key - a list of indices to sort the records by
  chunkIndex - the index of the current chunk

  The records contain only the fields requested by the user.

  Func() will write the sorted records to a standard File
  named "chunk_<chunk index>.csv" (chunk_0.csv, chunk_1.csv,...).
  """
  title(additional='(key=%s, chunkIndex=%d)' % (str(arg_1), arg_2))

  assert len(arg_0) > 0

  # Sort the current records
  arg_0.sort(arg_1=itemgetter(*arg_1))

  # Write to a chunk file
  if arg_2 is not None:
    arg_4 = 'chunk_%d.csv' % arg_2
    with FileRecordStream(arg_4, write=True, arg_3=arg_3) as o:
      for arg_5 in arg_0:
        o.appendRecord(arg_5)

    assert os.path.getsize(arg_4) > 0

  return arg_0


def Func(arg_0, arg_1, arg_2=True):
    """
    Feeds input record through TM, performing inference and learning.
    Updates member variables with new state.

    @param activeColumns (set) Indices of active columns in `t`
    """
    arg_3 = numpy.zeros(arg_0.numberOfCols, dtype=dtype)
    arg_3[arg_4(arg_1)] = 1
    super(TemporalMemoryShim, arg_0).Func(arg_3,
                                            enableLearn=arg_2,
                                            enableInference=True)

    arg_5 = arg_0.getPredictedState()
    arg_0.predictiveCells = set(numpy.flatnonzero(arg_5))


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
    """Print a message to the console.

    Prints only if level <= self.consolePrinterVerbosity
    Printing with level 0 is equivalent to using a print statement,
    and should normally be avoided.

    :param level: (int) indicating the urgency of the message with
           lower values meaning more urgent (messages at level 0  are the most
           urgent and are always printed)

    :param message: (string) possibly with format specifiers

    :param args: specifies the values for any format specifiers in message

    :param kw: newline is the only keyword argument. True (default) if a newline
           should be printed
    """

    if arg_1 > arg_0.consolePrinterVerbosity:
      return

    if len(arg_4) > 1:
      raise KeyError("Invalid keywords for Func: %s" % str(arg_4.keys()))

    arg_5 = arg_4.get("newline", True)
    if len(arg_4) == 1 and 'newline' not in arg_4:
      raise KeyError("Invalid keyword for Func: %s" % arg_4.keys()[0])

    if len(arg_3) == 0:
      if arg_5:
        print arg_2
      else:
        print arg_2,
    else:
      if arg_5:
        print arg_2 % arg_3
      else:
        print arg_2 % arg_3,


def Func(arg_0, arg_1):
    """
    Returns radius for given speed.

    Tries to get the encodings of consecutive readings to be
    adjacent with some overlap.

    :param: speed (float) Speed (in meters per second)
    :returns: (int) Radius for given speed
    """
    arg_2 = 1.5
    arg_3 = arg_1 * arg_0.timestep / arg_0.scale
    arg_4 = int(round(float(arg_3) / 2 * arg_2))
    arg_5 = int(math.ceil((math.sqrt(arg_0.w) - 1) / 2))
    return max(arg_4, arg_5)


def Func(arg_0, arg_1, arg_2=True):
    """
    Write serialized object to file.

    :param f: output file
    :param packed: If true, will pack contents.
    """
    # Get capnproto schema from instance
    arg_3 = arg_0.getSchema()

    # Construct new message, otherwise refered to as `proto`
    arg_4 = arg_3.new_message()

    # Populate message w/ `write()` instance method
    arg_0.write(arg_4)

    # Finally, write to file
    if arg_2:
      arg_4.write_packed(arg_1)
    else:
      arg_4.write(arg_1)


def Func(arg_0):
  """
  Decorator for functions that require anomaly models.
  """
  @wraps(arg_0)
  def _decorator(arg_1, *arg_2, **arg_3):
    if not arg_1.getInferenceType() == InferenceType.TemporalAnomaly:
      raise RuntimeError("Method required a TemporalAnomaly model.")
    if arg_1._getAnomalyClassifier() is None:
      raise RuntimeError("Model does not support this command. Model must"
          "be an active anomalyDetector model.")
    return arg_0(arg_1, *arg_2, **arg_3)
  return _decorator


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Remove labels from the anomaly classifier within this model. Removes all
    records if ``labelFilter==None``, otherwise only removes the labels equal to
    ``labelFilter``.

    :param start: (int) index to start removing labels
    :param end: (int) index to end removing labels
    :param labelFilter: (string) If specified, only removes records that match
    """
    arg_0._getAnomalyClassifier().getSelf().removeLabels(arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Add labels from the anomaly classifier within this model.

    :param start: (int) index to start label
    :param end: (int) index to end label
    :param labelName: (string) name of label
    """
    arg_0._getAnomalyClassifier().getSelf().addLabel(arg_1, arg_2, arg_3)


def Func(arg_0):
    """
    Compute Anomaly score, if required
    """
    arg_1 = arg_0.getInferenceType()

    arg_2 = {}
    arg_3 = arg_0._getSPRegion()
    arg_4 = None
    if arg_1 == InferenceType.NontemporalAnomaly:
      arg_4 = arg_3.getOutputData("anomalyScore")[0] #TODO move from SP to Anomaly ?

    elif arg_1 == InferenceType.TemporalAnomaly:
      arg_5 = arg_0._getTPRegion()

      if arg_3 is not None:
        arg_6 = arg_3.getOutputData("bottomUpOut").nonzero()[0]
      else:
        arg_7 = arg_0._getSensorRegion()
        arg_6 = arg_7.getOutputData('dataOut').nonzero()[0]

      if not arg_0._predictedFieldName in arg_0._input:
        raise ValueError(
          "Expected predicted field '%s' in input row, but was not found!"
          % arg_0._predictedFieldName
        )
      # Calculate the anomaly score using the active columns
      # and previous predicted columns.
      arg_4 = arg_5.getOutputData("anomalyScore")[0]

      # Calculate the classifier's output and use the result as the anomaly
      # label. Stores as string of results.

      # TODO: make labels work with non-SP models
      if arg_3 is not None:
        arg_0._getAnomalyClassifier().setParameter(
            "activeColumnCount", len(arg_6))
        arg_0._getAnomalyClassifier().prepareInputs()
        arg_0._getAnomalyClassifier().compute()

        arg_8 = arg_0._getAnomalyClassifier().getSelf().getLabelResults()
        arg_2[arg_9.anomalyLabel] = "%s" % arg_8

    arg_2[arg_9.anomalyScore] = arg_4
    return arg_2


def Func(arg_0):
    """
    Returns reference to the network's Classifier region
    """
    if (arg_0._netInfo.net is not None and
        "Classifier" in arg_0._netInfo.net.regions):
      return arg_0._netInfo.net.regions["Classifier"]
    else:
      return None


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """
    Attaches an 'AnomalyClassifier' region to the network. Will remove current
    'AnomalyClassifier' region if it exists.

    Parameters
    -----------
    network - network to add the AnomalyClassifier region
    params - parameters to pass to the region
    spEnable - True if network has an SP region
    tmEnable - True if network has a TM region; Currently requires True
    """

    arg_5 = copy.deepcopy(arg_2)
    arg_6 = dict(k=1,
                     distanceMethod='rawOverlap',
                     distanceNorm=1,
                     doBinarization=1,
                     replaceDuplicates=0,
                     maxStoredPatterns=1000)
    arg_5.update(arg_6)

    # Set defaults if not set
    if arg_5['trainRecords'] is None:
      arg_5['trainRecords'] = DEFAULT_ANOMALY_TRAINRECORDS

    if arg_5['cacheSize'] is None:
      arg_5['cacheSize'] = DEFAULT_ANOMALY_CACHESIZE

    # Remove current instance if already created (used for deserializing)
    if arg_0._netInfo is not None and arg_0._netInfo.net is not None \
              and arg_0._getAnomalyClassifier() is not None:
      arg_0._netInfo.net.removeRegion('AnomalyClassifier')

    arg_1.addRegion("AnomalyClassifier",
                      "py.KNNAnomalyClassifierRegion",
                      json.dumps(arg_5))

    # Attach link to SP
    if arg_3:
      arg_1.link("SP", "AnomalyClassifier", "UniformLink", "",
          srcOutput="bottomUpOut", destInput="spBottomUpOut")
    else:
      arg_1.link("sensor", "AnomalyClassifier", "UniformLink", "",
          srcOutput="dataOut", destInput="spBottomUpOut")

    # Attach link to TM
    if arg_4:
      arg_1.link("TM", "AnomalyClassifier", "UniformLink", "",
              srcOutput="topDownOut", destInput="tpTopDownOut")
      arg_1.link("TM", "AnomalyClassifier", "UniformLink", "",
              srcOutput="lrnActiveStateT", destInput="tpLrnActiveStateT")
    else:
      raise RuntimeError("TemporalAnomaly models require a TM region.")


def Func(arg_0, arg_1):
    """ Tell the writer which metrics should be written

    Parameters:
    -----------------------------------------------------------------------
    metricsNames: A list of metric lables to be written
    """
    if arg_1 is None:
      arg_0.__metricNames = set([])
    else:
      arg_0.__metricNames = set(arg_1)


def Func(arg_0, arg_1, arg_2):
    """Get field metadate information for inferences that are of dict type"""
    arg_3 = []
    arg_4 = InferenceElement.getLabel(arg_1)

    if InferenceElement.getInputElement(arg_1):
      arg_3.append(FieldMetaInfo(name=arg_4+".actual",
                                         type=FieldMetaType.string,
                                         special = ''))

    arg_5 = sorted(arg_2.keys())
    for arg_6 in arg_5:
      arg_3.append(FieldMetaInfo(name=arg_4+"."+str(arg_6),
                                         type=FieldMetaType.string,
                                         special=''))

    return arg_3


def Func(arg_0, arg_1):
    """ Creates the inference output directory for the given experiment

    experimentDir:  experiment directory path that contains description.py

    Returns:  path of the inference output directory
    """
    arg_2 = arg_0.getExperimentInferenceDirPath(arg_1)

    arg_0.makeDirectory(arg_2)

    return arg_2


def Func(arg_0):
  """A decorator that maintains the attribute lock state of an object

  It coperates with the LockAttributesMetaclass (see bellow) that replaces
  the __setattr__ method with a custom one that checks the _canAddAttributes
  counter and allows setting new attributes only if _canAddAttributes > 0.

  New attributes can be set only from methods decorated
  with this decorator (should be only __init__ and __setstate__ normally)

  The decorator is reentrant (e.g. if from inside a decorated function another
  decorated function is invoked). Before invoking the target function it
  increments the counter (or sets it to 1). After invoking the target function
  it decrements the counter and if it's 0 it removed the counter.
  """
  def arg_7(arg_1, *arg_2, **arg_3):
    """The decorated function that replaces __init__() or __setstate__()

    """
    # Run the original function
    if not hasattr(arg_1, '_canAddAttributes'):
      arg_1.__dict__['_canAddAttributes'] = 1
    else:
      arg_1._canAddAttributes += 1
    assert arg_1._canAddAttributes >= 1

    # Save add attribute counter
    arg_5 = arg_1._canAddAttributes
    arg_0(arg_1, *arg_2, **arg_3)

    # Restore _CanAddAttributes if deleted from dict (can happen in __setstte__)
    if hasattr(arg_1, '_canAddAttributes'):
      arg_1._canAddAttributes -= 1
    else:
      arg_1._canAddAttributes = arg_5 - 1

    assert arg_1._canAddAttributes >= 0
    if arg_1._canAddAttributes == 0:
      del arg_1._canAddAttributes

  arg_7.__doc__ = arg_0.__doc__
  arg_7.__name__ = arg_0.__name__
  return arg_7


def Func(arg_0, arg_1 = 10):
  """ Creates a neighboring record for each record in the inputs and adds
  new records at the end of the inputs list
  """
  arg_2 = len(arg_0)
  arg_3 = False
  for arg_4 in xrange(arg_2):
    arg_5 = arg_0[arg_4]
    arg_6 = 0
    arg_7 = copy.deepcopy(arg_5)
    for arg_8 in xrange(len(arg_5)-1):
      if arg_3:
        arg_3 = False
        continue
      if arg_5[arg_8] == 1 and arg_5[arg_8+1] == 0:
        arg_7[arg_8] = 0
        arg_7[arg_8+1] = 1
        arg_0.append(arg_7)
        arg_7 = copy.deepcopy(arg_7)
        #print input
        #print newInput
        arg_6 += 1
        arg_3 = True
        if arg_6 == arg_1:
          break


def Func(arg_0, arg_1):
  """ Modifies up to maxChanges number of bits in the inputVal
  """
  arg_2 = np.random.random_integers(0, arg_1, 1)[0]

  if arg_2 == 0:
    return arg_0

  arg_3 = len(arg_0)

  arg_4 = np.random.random_integers(0, 41, arg_2)

  arg_5 = -1
  arg_6 = 0
  for arg_7 in xrange(arg_3):
    if arg_6 >= arg_2:
      break
    if arg_0[arg_7] == 1:
      arg_5 += 1
      if arg_5 in arg_4:
        if arg_7 != 0 and arg_0[arg_7-1] == 0:
          arg_0[arg_7-1] = 1
          arg_0[arg_7] = 0

  return arg_0


def Func(arg_0, arg_1):
  """ Returns a random selection from the inputSpace with randomly modified
  up to maxChanges number of bits.
  """
  arg_2 = len(arg_0)
  arg_3 = np.random.random_integers(0, arg_2-1, 1)[0]

  arg_4 = copy.deepcopy(arg_0[arg_3])

  if arg_1 == 0:
    return arg_4

  return modifyBits(arg_4, arg_1)


def Func(arg_0):
  """Creates and returns a new Network with a sensor region reading data from
  'dataSource'. There are two hierarchical levels, each with one SP and one TM.
  @param dataSource - A RecordStream containing the input data
  @returns a Network ready to run
  """
  arg_1 = Network()

  # Create and add a record sensor and a SP region
  arg_2 = createRecordSensor(arg_1, name=_RECORD_SENSOR,
                              arg_0=arg_0)
  createSpatialPooler(arg_1, name=_L1_SPATIAL_POOLER,
                      inputWidth=arg_2.encoder.getWidth())

  # Link the SP region to the sensor input
  arg_3 = "UniformLink"
  arg_4 = ""
  arg_1.link(_RECORD_SENSOR, _L1_SPATIAL_POOLER, arg_3, arg_4)

  # Create and add a TM region
  arg_5 = createTemporalMemory(arg_1, _L1_TEMPORAL_MEMORY)

  # Link SP region to TM region in the feedforward direction
  arg_1.link(_L1_SPATIAL_POOLER, _L1_TEMPORAL_MEMORY, arg_3, arg_4)

  # Add a classifier
  arg_6 = {  # Learning rate. Higher values make it adapt faster.
                        'alpha': 0.005,

                        # A comma separated list of the number of steps the
                        # classifier predicts in the future. The classifier will
                        # learn predictions of each order specified.
                        'steps': '1',

                        # The specific implementation of the classifier to use
                        # See SDRClassifierFactory#create for options
                        'implementation': 'py',

                        # Diagnostic output verbosity control;
                        # 0: silent; [1..6]: increasing levels of verbosity
                        'verbosity': 0}

  arg_7 = arg_1.addRegion(_L1_CLASSIFIER, "py.SDRClassifierRegion",
                                   json.dumps(arg_6))
  arg_7.setParameter('inferenceMode', True)
  arg_7.setParameter('learningMode', True)
  arg_1.link(_L1_TEMPORAL_MEMORY, _L1_CLASSIFIER, arg_3, arg_4,
               srcOutput="bottomUpOut", destInput="bottomUpIn")
  arg_1.link(_RECORD_SENSOR, _L1_CLASSIFIER, arg_3, arg_4,
               srcOutput="categoryOut", destInput="categoryIn")
  arg_1.link(_RECORD_SENSOR, _L1_CLASSIFIER, arg_3, arg_4,
               srcOutput="bucketIdxOut", destInput="bucketIdxIn")
  arg_1.link(_RECORD_SENSOR, _L1_CLASSIFIER, arg_3, arg_4,
               srcOutput="actValueOut", destInput="actValueIn")

  # Second Level
  arg_8 = arg_5.getSelf().getOutputElementCount("bottomUpOut")
  createSpatialPooler(arg_1, name=_L2_SPATIAL_POOLER, inputWidth=arg_8)
  arg_1.link(_L1_TEMPORAL_MEMORY, _L2_SPATIAL_POOLER, arg_3, arg_4)

  createTemporalMemory(arg_1, _L2_TEMPORAL_MEMORY)
  arg_1.link(_L2_SPATIAL_POOLER, _L2_TEMPORAL_MEMORY, arg_3, arg_4)

  arg_9 = arg_1.addRegion(_L2_CLASSIFIER, "py.SDRClassifierRegion",
                                   json.dumps(arg_6))
  arg_9.setParameter('inferenceMode', True)
  arg_9.setParameter('learningMode', True)
  arg_1.link(_L2_TEMPORAL_MEMORY, _L2_CLASSIFIER, arg_3, arg_4,
               srcOutput="bottomUpOut", destInput="bottomUpIn")
  arg_1.link(_RECORD_SENSOR, _L2_CLASSIFIER, arg_3, arg_4,
               srcOutput="categoryOut", destInput="categoryIn")
  arg_1.link(_RECORD_SENSOR, _L2_CLASSIFIER, arg_3, arg_4,
               srcOutput="bucketIdxOut", destInput="bucketIdxIn")
  arg_1.link(_RECORD_SENSOR, _L2_CLASSIFIER, arg_3, arg_4,
               srcOutput="actValueOut", destInput="actValueIn")
  return arg_1


def Func(arg_0, arg_1, arg_2):
  """
  Runs specified Network writing the ensuing anomaly
  scores to writer.

  @param network: The Network instance to be run
  @param writer: A csv.writer used to write to output file.
  """
  arg_3 = arg_0.regions[_RECORD_SENSOR]
  arg_4 = arg_0.regions[_L1_SPATIAL_POOLER]
  arg_5 = arg_0.regions[_L1_TEMPORAL_MEMORY]
  arg_6 = arg_0.regions[_L1_CLASSIFIER]

  arg_7 = arg_0.regions[_L2_SPATIAL_POOLER]
  arg_8 = arg_0.regions[_L2_TEMPORAL_MEMORY]
  arg_9 = arg_0.regions[_L2_CLASSIFIER]

  arg_10 = []
  arg_11 = []

  arg_12 = None
  arg_13 = None
  arg_14 = 0.0
  arg_15 = 0.0
  for arg_16 in xrange(arg_1):
    # Run the network for a single iteration
    arg_0.run(1)

    arg_17 = float(arg_3.getOutputData("actValueOut")[0])

    arg_18 = arg_6.getOutputData("actualValues")
    arg_19 = arg_6.getOutputData("probabilities")
    arg_20 = arg_18[arg_19.argmax()]
    if arg_12 is not None:
      arg_14 += math.fabs(arg_12 - arg_17)
    arg_12 = arg_20

    arg_21 = arg_9.getOutputData("actualValues")
    arg_22 = arg_9.getOutputData("probabilities")
    arg_23 = arg_21[arg_22.argmax()]
    if arg_13 is not None:
      arg_15 += math.fabs(arg_13 - arg_17)
    arg_13 = arg_23

    arg_24 = arg_5.getOutputData("anomalyScore")[0]
    arg_25 = arg_8.getOutputData("anomalyScore")[0]

    # Write record number, actualInput, and anomaly scores
    arg_2.writerow((arg_16, arg_17, arg_12, arg_24, arg_13, arg_25))

    # Store the predicted columns for the next timestep
    arg_26 = arg_5.getOutputData("topDownOut").nonzero()[0]
    arg_10 = copy.deepcopy(arg_26)
    #
    arg_27 = arg_8.getOutputData("topDownOut").nonzero()[0]
    arg_11 = copy.deepcopy(arg_27)

  # Output absolute average error for each level
  if arg_1 > 1:
    print "L1 ave abs class. error: %f" % (arg_14 / (arg_1 - 1))
    print "L2 ave abs class. error: %f" % (arg_15 / (arg_1 - 1))


def Func(arg_0):
  """Removes trailing whitespace on each line."""
  arg_1 = [l.rstrip() for l in arg_0.split('\n')]
  return '\n'.join(arg_1)


def Func(arg_0):
    """
    Gets the current metric values

    :returns: (dict) where each key is the metric-name, and the values are
              it scalar value. Same as the output of
              :meth:`~nupic.frameworks.opf.prediction_metrics_manager.MetricsManager.update`
    """

    arg_1 = {}

    for arg_2, arg_3 in zip(arg_0.__metrics, arg_0.__metricLabels):
      arg_4 = arg_2.getMetric()
      arg_1[arg_3] = arg_4['value']

    return arg_1


def Func(arg_0, arg_1):
    """
    Gets detailed info about a given metric, in addition to its value. This
    may including any statistics or auxilary data that are computed for a given
    metric.

    :param metricLabel: (string) label of the given metric (see
           :class:`~nupic.frameworks.opf.metrics.MetricSpec`)

    :returns: (dict) of metric information, as returned by
             :meth:`nupic.frameworks.opf.metrics.MetricsIface.getMetric`.
    """
    try:
      arg_2 = arg_0.__metricLabels.index(arg_1)
    except IndexError:
      return None

    return arg_0.__metrics[arg_2].getMetric()


def Func(arg_0, arg_1):
    """
    Stores the current model results in the manager's internal store

    Parameters:
    -----------------------------------------------------------------------
    results:  A ModelResults object that contains the current timestep's
              input/inferences
    """
    # -----------------------------------------------------------------------
    # If the model potentially has temporal inferences.
    if arg_0.__isTemporal:
      arg_2 = arg_0.__inferenceShifter.shift(arg_1).inferences
      arg_0.__currentResult = copy.deepcopy(arg_1)
      arg_0.__currentResult.inferences = arg_2
      arg_0.__currentInference = arg_2

    # -----------------------------------------------------------------------
    # The current model has no temporal inferences.
    else:
      arg_0.__currentResult = copy.deepcopy(arg_1)
      arg_0.__currentInference = copy.deepcopy(arg_1.inferences)

    # -----------------------------------------------------------------------
    # Save the current ground-truth results
    arg_0.__currentGroundTruth = copy.deepcopy(arg_1)


def Func(arg_0, arg_1):
    """
    Get the actual value for this field

    Parameters:
    -----------------------------------------------------------------------
    sensorInputElement:       The inference element (part of the inference) that
                            is being used for this metric
    """
    arg_2 = InferenceElement.getInputElement(arg_1)
    if arg_2 is None:
      return None
    return getattr(arg_0.__currentGroundTruth.sensorInput, arg_2)


def Func(arg_0, arg_1):
  """ Abbreviate the given text to threshold chars and append an ellipsis if its
  length exceeds threshold; used for logging;

  NOTE: the resulting text could be longer than threshold due to the ellipsis
  """
  if arg_0 is not None and len(arg_0) > arg_1:
    arg_0 = arg_0[:arg_1] + "..."

  return arg_0


def Func(arg_0, arg_1):
    """ Generates the ClientJobs database name for the given version of the
    database

    Parameters:
    ----------------------------------------------------------------
    dbVersion:      ClientJobs database version number

    retval:         the ClientJobs database name for the given DB version
    """

    # DB Name prefix for the given version
    arg_2 = arg_0.__getDBNamePrefixForVersion(arg_1)

    # DB Name suffix
    arg_3 = Configuration.get('nupic.cluster.database.nameSuffix')

    # Replace dash and dot with underscore (e.g. 'ec2-user' or ec2.user will break SQL)
    arg_3 = arg_3.replace("-", "_")
    arg_3 = arg_3.replace(".", "_")

    # Create the name of the database for the given DB version
    arg_4 = '%s_%s' % (arg_2, arg_3)

    return arg_4


def Func(arg_0, arg_1=False, arg_2=False):
    """ Locate the current version of the jobs DB or create a new one, and
    optionally delete old versions laying around. If desired, this method
    can be called at any time to re-create the tables from scratch, delete
    old versions of the database, etc.

    Parameters:
    ----------------------------------------------------------------
    deleteOldVersions:   if true, delete any old versions of the DB left
                          on the server
    recreate:            if true, recreate the database from scratch even
                          if it already exists.
    """

    # Initialize tables, if needed
    with ConnectionFactory.get() as conn:
      # Initialize tables
      arg_0._initTables(cursor=conn.cursor, arg_1=arg_1,
                       arg_2=arg_2)

      # Save our Funcion id
      conn.cursor.execute('SELECT CONNECTION_ID()')
      arg_0._FuncionID = conn.cursor.fetchall()[0][0]
      arg_0._logger.info("clientJobsConnectionID=%r", arg_0._FuncionID)

    return


def Func(arg_0, arg_1, arg_2, arg_3,
                                arg_4, arg_5=None):
    """ Return a sequence of matching rows with the requested field values from
    a table or empty sequence if nothing matched.

    tableInfo:       Table information: a ClientJobsDAO._TableInfoBase  instance
    conn:            Owned connection acquired from ConnectionFactory.get()
    fieldsToMatch:   Dictionary of internal fieldName/value mappings that
                     identify the desired rows. If a value is an instance of
                     ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the
                     operator 'IN' will be used in the corresponding SQL
                     predicate; if the value is bool: "IS TRUE/FALSE"; if the
                     value is None: "IS NULL"; '=' will be used for all other
                     cases.
    selectFieldNames:
                     list of fields to return, using internal field names
    maxRows:         maximum number of rows to return; unlimited if maxRows
                      is None

    retval:          A sequence of matching rows, each row consisting of field
                      values in the order of the requested field names.  Empty
                      sequence is returned when not match exists.
    """

    assert arg_3, repr(arg_3)
    assert all(arg_6 in arg_1.dbFieldNames
               for arg_6 in arg_3.iterkeys()), repr(arg_3)

    assert arg_4, repr(arg_4)
    assert all(arg_7 in arg_1.dbFieldNames for arg_7 in arg_4), repr(
      arg_4)

    # NOTE: make sure match expressions and values are in the same order
    arg_8 = arg_3.items()
    arg_9 = (
      p[0] +
      (' IS ' + {True:'TRUE', False:'FALSE'}[p[1]] if isinstance(p[1], bool)
       else ' IS NULL' if p[1] is None
       else ' IN %s' if isinstance(p[1], arg_0._SEQUENCE_TYPES)
       else '=%s')
      for p in arg_8)
    arg_10 = [p[1] for p in arg_8
                        if (not isinstance(p[1], (bool)) and p[1] is not None)]

    arg_11 = 'SELECT %s FROM %s WHERE (%s)' % (
      ','.join(arg_4), arg_1.tableName,
      ' AND '.join(arg_9))
    arg_12 = arg_10
    if arg_5 is not None:
      arg_11 += ' LIMIT %s'
      arg_12.append(arg_5)

    arg_2.cursor.execute(arg_11, arg_12)
    arg_13 = arg_2.cursor.fetchall()

    if arg_13:
      assert arg_5 is None or len(arg_13) <= arg_5, "%d !<= %d" % (
        len(arg_13), arg_5)
      assert len(arg_13[0]) == len(arg_4), "%d != %d" % (
        len(arg_13[0]), len(arg_4))
    else:
      arg_13 = tuple()

    return arg_13


def Func(arg_0, arg_1, arg_2, arg_3,
                                  arg_4):
    """ Return a single matching row with the requested field values from the
    the requested table or None if nothing matched.

    tableInfo:       Table information: a ClientJobsDAO._TableInfoBase  instance
    conn:            Owned connection acquired from ConnectionFactory.get()
    fieldsToMatch:   Dictionary of internal fieldName/value mappings that
                     identify the desired rows. If a value is an instance of
                     ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the
                     operator 'IN' will be used in the corresponding SQL
                     predicate; if the value is bool: "IS TRUE/FALSE"; if the
                     value is None: "IS NULL"; '=' will be used for all other
                     cases.
    selectFieldNames:
                     list of fields to return, using internal field names

    retval:          A sequence of field values of the matching row in the order
                      of the given field names; or None if there was no match.
    """
    arg_5 = arg_0._getMatchingRowsNoRetries(arg_1, arg_2, arg_3,
                                          arg_4, maxRows=1)
    if arg_5:
      assert len(arg_5) == 1, repr(len(arg_5))
      arg_6 = arg_5[0]
    else:
      arg_6 = None

    return arg_6


def Func(arg_0, arg_1):
    """ 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:
      arg_2 = 'UPDATE %s SET status=%%s, ' \
                '            _eng_cjm_conn_id=%%s, ' \
                '            start_time=UTC_TIMESTAMP(), ' \
                '            _eng_last_update_time=UTC_TIMESTAMP() ' \
                '          WHERE (job_id=%%s AND status=%%s)' \
                % (arg_0.jobsTableName,)
      arg_3 = [arg_0.STATUS_RUNNING, arg_0._connectionID,
                   arg_1, arg_0.STATUS_NOTSTARTED]
      arg_4 = conn.cursor.execute(arg_2, arg_3)
      if arg_4 != 1:
        arg_0._logger.warn('jobStartNext: numRowsUpdated=%r instead of 1; '
                          'likely side-effect of transient connection '
                          'failure', arg_4)
    return


def Func(arg_0):
    """ Set cancel field of all currently-running jobs to true.
    """

    # Get a database connection and cursor
    with ConnectionFactory.get() as conn:

      arg_1 = 'UPDATE %s SET cancel=TRUE WHERE status<>%%s ' \
              % (arg_0.jobsTableName,)
      conn.cursor.execute(arg_1, [arg_0.STATUS_COMPLETED])

    return


def Func(arg_0,):
    """ 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 field set to true.
    """
    with ConnectionFactory.get() as conn:
      arg_1 = 'SELECT COUNT(job_id) '\
              'FROM %s ' \
              'WHERE (status<>%%s AND cancel is TRUE)' \
              % (arg_0.jobsTableName,)

      conn.cursor.execute(arg_1, [arg_0.STATUS_COMPLETED])
      arg_2 = conn.cursor.fetchall()

    return arg_2[0][0]


def Func(arg_0, arg_1):
    """ 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 of intervals should be less
                than, or equal to the length of data.

    """
    assert sum(arg_1) <= len(arg_0)

    arg_2 = 0
    for arg_3 in arg_1:
      arg_4 = arg_2 + arg_3
      yield arg_0[arg_2:arg_4]
      arg_2 = arg_4

    raise StopIteration


def Func(arg_0, arg_1):
    """ 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 (exeption is raised if it doesn't exist). Each two-tuple
             contains an instance of jobInfoNamedTuple as the first element and
             an instance of modelInfoNamedTuple as the second element. NOTE: In
             the case where there are no matching model rows, a sequence of one
             two-tuple will still be returned, but the modelInfoNamedTuple
             fields will be None, and the jobInfoNamedTuple fields will be
             populated.
    """

    # Get a database connection and cursor
    arg_2 = None

    with ConnectionFactory.get() as conn:
      # NOTE: Since we're using a LEFT JOIN on the models table, there need not
      # be a matching row in the models table, but the matching row from the
      # jobs table will still be returned (along with all fields from the models
      # table with values of None in case there were no matchings models)
      arg_3 = ' '.join([
        'SELECT %s.*, %s.*' % (arg_0.jobsTableName, arg_0.modelsTableName),
        'FROM %s' % arg_0.jobsTableName,
        'LEFT JOIN %s USING(job_id)' % arg_0.modelsTableName,
        'WHERE job_id=%s'])

      conn.cursor.execute(arg_3, (arg_1,))

      if conn.cursor.rowcount > 0:
        arg_2 = [
          ClientJobsDAO._combineResults(
            result, arg_0._jobs.jobInfoNamedTuple,
            arg_0._models.modelInfoNamedTuple
          ) for result in conn.cursor.fetchall()]

    if arg_2 is not None:
      return arg_2

    raise RuntimeError("jobID=%s not found within the jobs table" % (arg_1))


def Func(arg_0, arg_1):
    """ Get all info about a job

    Parameters:
    ----------------------------------------------------------------
    job:    jobID of the job to query
    retval:  namedtuple containing the job info.

    """
    arg_2 = arg_0._getOneMatchingRowWithRetries(
      arg_0._jobs, dict(job_id=arg_1),
      [arg_0._jobs.pubToDBNameDict[n]
       for n in arg_0._jobs.FuncNamedTuple._fields])

    if arg_2 is None:
      raise RuntimeError("jobID=%s not found within the jobs table" % (arg_1))

    # Create a namedtuple with the names to values
    return arg_0._jobs.FuncNamedTuple._make(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3=True,):
    """ Change the status on the given job

    Parameters:
    ----------------------------------------------------------------
    job:        jobID of the job to change status
    status:     new status string (ClientJobsDAO.STATUS_xxxxx)

    useConnectionID: True if the connection id of the calling function
    must be the same as the connection that created the job. Set
    to False for hypersearch workers
    """
    # Get a database connection and cursor
    with ConnectionFactory.get() as conn:
      arg_4 = 'UPDATE %s SET status=%%s, ' \
              '              _eng_last_update_time=UTC_TIMESTAMP() ' \
              '          WHERE job_id=%%s' \
              % (arg_0.jobsTableName,)
      arg_5 = [arg_2, arg_1]

      if arg_3:
        arg_4 += ' AND _eng_cjm_conn_id=%s'
        arg_5.append(arg_0._connectionID)

      arg_6 = conn.cursor.execute(arg_4, arg_5)

      if arg_6 != 1:
        raise RuntimeError("Tried to change the status of job %d to %s, but "
                           "this job belongs to some other CJM" % (
                            arg_1, arg_2))


def Func(arg_0, arg_1, arg_2, arg_3,
                      arg_4 = True):
    """ Change the status on the given job to completed

    Parameters:
    ----------------------------------------------------------------
    job:                 jobID of the job to mark as completed
    completionReason:    completionReason string
    completionMsg:       completionMsg string

    useConnectionID: True if the connection id of the calling function
    must be the same as the connection that created the job. Set
    to False for hypersearch workers
    """

    # Get a database connection and cursor
    with ConnectionFactory.get() as conn:
      arg_5 = 'UPDATE %s SET status=%%s, ' \
              '              completion_reason=%%s, ' \
              '              completion_msg=%%s, ' \
              '              end_time=UTC_TIMESTAMP(), ' \
              '              _eng_last_update_time=UTC_TIMESTAMP() ' \
              '          WHERE job_id=%%s' \
              % (arg_0.jobsTableName,)
      arg_6 = [arg_0.STATUS_COMPLETED, arg_2, arg_3,
                   arg_1]

      if arg_4:
        arg_5 += ' AND _eng_cjm_conn_id=%s'
        arg_6.append(arg_0._connectionID)

      arg_7 = conn.cursor.execute(arg_5, arg_6)

      if arg_7 != 1:
        raise RuntimeError("Tried to change the status of jobID=%s to "
                           "completed, but this job could not be found or "
                           "belongs to some other CJM" % (arg_1))


def Func(arg_0, arg_1):
    """ 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 False for hypersearch workers
    """
    arg_0._logger.info('Canceling jobID=%s', arg_1)
    # NOTE: jobSetFields does retries on transient mysql failures
    arg_0.jobSetFields(arg_1, {"cancel" : True}, useConnectionID=False)


def Func(arg_0, arg_1):
    """Fetch all the modelIDs that correspond to a given jobID; empty sequence
    if none"""

    arg_2 = arg_0._getMatchingRowsWithRetries(arg_0._models, dict(job_id=arg_1),
                                            ['model_id'])
    return [arg_3[0] for arg_3 in arg_2]


def Func(arg_0, arg_1):
    """ Return the number of jobs for the given clientKey and a status that is
    not completed.
    """
    with ConnectionFactory.get() as conn:
      arg_2 = 'SELECT count(job_id) ' \
              'FROM %s ' \
              'WHERE client_key = %%s ' \
              ' AND status != %%s' %  arg_0.jobsTableName
      conn.cursor.execute(arg_2, [arg_1, arg_0.STATUS_COMPLETED])
      arg_3 = conn.cursor.fetchone()[0]

    return arg_3


def Func(arg_0):
    """ Delete all models from the models table

    Parameters:
    ----------------------------------------------------------------
    """
    arg_0._logger.info('Deleting all rows from models table %r',
                      arg_0.modelsTableName)
    with ConnectionFactory.get() as conn:
      arg_1 = 'DELETE FROM %s' % (arg_0.modelsTableName)
      conn.cursor.execute(arg_1)


def Func(arg_0, arg_1):
    """ 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
    retval:      list of nametuples containing all the fields stored for each
                    model.
    """
    assert isinstance(arg_1, arg_0._SEQUENCE_TYPES), (
      "wrong modelIDs type: %s") % (type(arg_1),)
    assert arg_1, "modelIDs is empty"

    arg_2 = arg_0._getMatchingRowsWithRetries(
      arg_0._models, dict(model_id=arg_1),
      [arg_0._models.pubToDBNameDict[f]
       for f in arg_0._models.modelInfoNamedTuple._fields])

    arg_3 = [arg_0._models.modelInfoNamedTuple._make(arg_4) for arg_4 in arg_2]

    # NOTE: assetion will also fail if modelIDs contains duplicates
    assert len(arg_3) == len(arg_1), "modelIDs not found: %s" % (
      set(arg_1) - set(arg_4.modelId for arg_4 in arg_3))

    return arg_3


def Func(arg_0, arg_1, arg_2, arg_3=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 searched
    fields:             A list  of fields to return
    ignoreKilled:       (True/False). If True, this will ignore models that
                        have been killed

    Returns: a (possibly empty) list of tuples as follows
      [
        (model_id1, [field1, ..., fieldn]),
        (model_id2, [field1, ..., fieldn]),
        (model_id3, [field1, ..., fieldn])
                    ...
      ]

    NOTE: since there is a window of time between a job getting inserted into
     jobs table and the job's worker(s) starting up and creating models, an
     empty-list result is one of the normal outcomes.
    """

    assert len(arg_2) >= 1, 'fields is empty'

    # Form the sequence of field name strings that will go into the
    #  request
    arg_4 = [arg_0._models.pubToDBNameDict[x] for x in arg_2]
    arg_5 = ','.join(arg_4)

    arg_6 = 'SELECT model_id, %s FROM %s ' \
              '          WHERE job_id=%%s ' \
              % (arg_5, arg_0.modelsTableName)
    arg_7 = [arg_1]

    if arg_3:
      arg_6 += ' AND (completion_reason IS NULL OR completion_reason != %s)'
      arg_7.append(arg_0.CMPL_REASON_KILLED)

    # Get a database connection and cursor
    with ConnectionFactory.get() as conn:
      conn.cursor.execute(arg_6, arg_7)
      arg_8 = conn.cursor.fetchall()

    if arg_8 is None:
      # fetchall is defined to return a (possibly-empty) sequence of
      # sequences; however, we occasionally see None returned and don't know
      # why...
      arg_0._logger.error("Unexpected None result from cursor.fetchall; "
                         "query=%r; Traceback=%r",
                         arg_6, traceback.format_exc())

    return [(arg_9[0], list(arg_9[1:])) for arg_9 in arg_8]


def Func(arg_0, arg_1):
    """ 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:
    ----------------------------------------------------------------
    modelIDs:    list of model IDs
    retval:      list of result namedtuples defined in
                  ClientJobsDAO._models.getParamsNamedTuple. Each tuple
                  contains: (modelId, params, engParamsHash)
    """
    assert isinstance(arg_1, arg_0._SEQUENCE_TYPES), (
      "Wrong modelIDs type: %r") % (type(arg_1),)
    assert len(arg_1) >= 1, "modelIDs is empty"

    arg_2 = arg_0._getMatchingRowsWithRetries(
      arg_0._models, {'model_id' : arg_1},
      [arg_0._models.pubToDBNameDict[f]
       for f in arg_0._models.getParamsNamedTuple._fields])

    # NOTE: assertion will also fail when modelIDs contains duplicates
    assert len(arg_2) == len(arg_1), "Didn't find modelIDs: %r" % (
      (set(arg_1) - set(arg_3[0] for arg_3 in arg_2)),)

    # Return the params and params hashes as a namedtuple
    return [arg_0._models.getParamsNamedTuple._make(arg_3) for arg_3 in arg_2]


def Func(arg_0, arg_1):
    """ 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, results, status, updateCounter, numRecords, completionReason,
         completionMsg, engParamsHash

    Parameters:
    ----------------------------------------------------------------
    modelIDs:    list of model IDs
    retval:      list of result tuples. Each tuple contains:
                    (modelID, results, status, updateCounter, numRecords,
                      completionReason, completionMsg, engParamsHash)
    """
    assert isinstance(arg_1, arg_0._SEQUENCE_TYPES), (
      "Wrong modelIDs type: %r") % type(arg_1)
    assert len(arg_1) >= 1, "modelIDs is empty"

    arg_2 = arg_0._getMatchingRowsWithRetries(
      arg_0._models, {'model_id' : arg_1},
      [arg_0._models.pubToDBNameDict[f]
       for f in arg_0._models.getResultAndStatusNamedTuple._fields])

    # NOTE: assertion will also fail when modelIDs contains duplicates
    assert len(arg_2) == len(arg_1), "Didn't find modelIDs: %r" % (
      (set(arg_1) - set(arg_3[0] for arg_3 in arg_2)),)

    # Return the results as a list of namedtuples
    return [arg_0._models.getResultAndStatusNamedTuple._make(arg_3) for arg_3 in arg_2]


def Func(arg_0):
    """
    Disable writing of output tap files.
    """

    if arg_0._tapFileIn is not None:
      arg_0._tapFileIn.close()
      arg_0._tapFileIn = None
    if arg_0._tapFileOut is not None:
      arg_0._tapFileOut.close()
      arg_0._tapFileOut = None


def Func(arg_0):
    """Does nothing. Kept here for API compatibility """
    if arg_0._doSphering:
      arg_0._finishSphering()

    arg_0._knn.finishLearning()

    # Compute leave-one-out validation accuracy if
    # we actually received non-trivial partition info
    arg_0._accuracy = None


def Func(arg_0, arg_1):
    """
    Intercepts TemporalMemory deserialization request in order to initialize
    `TemporalMemoryMonitorMixin` state

    @param proto (DynamicStructBuilder) Proto object

    @return (TemporalMemory) TemporalMemory shim instance
    """
    arg_2 = super(TemporalMemoryMonitorMixin, arg_0).Func(arg_1)

    # initialize `TemporalMemoryMonitorMixin` attributes
    arg_2.mmName = None
    arg_2._mmTraces = None
    arg_2._mmData = None
    arg_2.mmClearHistory()
    arg_2._mmResetActive = True
    return arg_2


def Func(arg_0, arg_1=None):
  """
  Pick a value according to the provided distribution.

  Example:

  ::

    Func([.2, .1])

  Returns 0 two thirds of the time and 1 one third of the time.

  :param distribution: Probability distribution. Need not be normalized.
  :param r: Instance of random.Random. Uses the system instance if one is
         not provided.
  """

  if arg_1 is None:
    arg_1 = random

  arg_2 = arg_1.uniform(0, sum(arg_0))
  for arg_3, arg_4 in enumerate(arg_0):
    if arg_2 <= arg_4:
      return arg_3
    arg_2 -= arg_4


def Func(arg_0, arg_1, arg_2):
  """
  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 to be returned.
  :param dtype: The element type (compatible with NumPy array())
         of the array to be returned.
  :returns: An array of length size and element type dtype.
  """
  arg_3 = numpy.zeros(arg_1, arg_2=arg_2)
  if hasattr(arg_0, '__iter__'):
    for arg_4 in arg_0: arg_3[arg_4] = 1
  else: arg_3[arg_0] = 1
  return arg_3


def Func(arg_0, arg_1, arg_2):
    """
    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.
    :param distribution: Array of length equal to the number of columns.
    """
    arg_0.grow(arg_1+1, len(arg_2))
    arg_0.hist_.axby(arg_1, 1, 1, arg_2)
    arg_0.rowSums_[arg_1] += arg_2.sum()
    arg_0.colSums_ += arg_2
    arg_0.hack_ = None


def Func(
    arg_0,
    arg_1,
    arg_2,
    **arg_3
  ):
  """
  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 accessible from the ordinary Python
  path. Encapsulates the multiple lines usually needed to
  safely manipulate and restore the Python path.

  Parameters
  ----------
  path: filesystem path
  Path to the directory where the desired module is stored.
  This will be used to temporarily augment the Python path.

  moduleName: basestring
  Name of the module, without trailing extension, where the desired
  function is stored. This module should be in the directory specified
  with path.

  funcName: basestring
  Name of the function to import and call.

  keywords:
  Keyword arguments to be passed to the imported function.
  """
  import arg_6
  arg_4 = arg_6.path
  try:
    arg_5 = [arg_0] + arg_6.path
    arg_6.path = arg_5
    arg_7 = getattr(__import__(arg_1, fromlist=[arg_2]), arg_2)
    arg_6.path = arg_4
  except:
    # Restore the original path in case of an exception.
    arg_6.path = arg_4
    raise
  return arg_7(**arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
    """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 moving average
    @param newVal a new number Func the new windowed average
    @param windowSize how many values to use in the moving window

    @returns an updated windowed average, the modified input slidingWindow list,
        and the new total sum of the sliding window
    """
    if len(arg_0) == arg_3:
      arg_1 -= arg_0.pop(0)

    arg_0.append(arg_2)
    arg_1 += arg_2
    return float(arg_1) / len(arg_0), arg_0, arg_1


def Func(arg_0, arg_1):
    """Instance method wrapper around compute."""
    arg_2, arg_0.slidingWindow, arg_0.total = arg_0.compute(
        arg_0.slidingWindow, arg_0.total, arg_1, arg_0.windowSize)
    return arg_2


def Func(arg_0, arg_1):
    """ Helper function to return a scalar value representing the most
        likely outcome given a probability distribution
    """
    if len(arg_1) == 1:
      return arg_1.keys()[0]

    arg_2 = None
    arg_3 = 0

    for arg_4, arg_5 in arg_1.items():
      if arg_5 > arg_3:
        arg_2 = arg_4
        arg_3 = arg_5

    return arg_2


def Func(arg_0, arg_1):
    """ Helper function to return a scalar value representing the expected
        value of a probability distribution
    """
    if len(arg_1) == 1:
      return arg_1.keys()[0]

    return sum([arg_2*arg_3 for arg_2,arg_3 in arg_1.items()])


def Func(arg_0, arg_1=''):
    """
    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 the dict() in the retval.

    :return: array of field names
    """
    arg_2 = []

    if arg_0.encoders is not None:
      for (arg_3, arg_4, arg_5) in arg_0.encoders:
        arg_6 = arg_4.Func(arg_1=arg_3)
        if arg_1 != '':
          arg_6 = ['%s.%s' % (arg_1, arg_3) for arg_3 in arg_6]
        arg_2.extend(arg_6)
    else:
      if arg_1 != '':
        arg_2.append(arg_1)
      else:
        arg_2.append(arg_0.name)

    return arg_2


def Func(arg_0, arg_1, arg_2):
    """
    Gets the value of a given field from the input record
    """
    if isinstance(arg_1, dict):
      if not arg_2 in arg_1:
        arg_3 = ", ".join(
          key for key in arg_1.keys() if not key.startswith("_")
        )
        raise ValueError(
          "Unknown field name '%s' in input record. Known fields are '%s'.\n"
          "This could be because input headers are mislabeled, or because "
          "input data rows do not contain a value for '%s'." % (
            arg_2, arg_3, arg_2
          )
        )
      return arg_1[arg_2]
    else:
      return getattr(arg_1, arg_2)


def Func(arg_0, arg_1):
    """
    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
    arg_2 = arg_0.getDescription() + [("end", arg_0.getWidth())]
    for arg_3 in xrange(len(arg_2)):
      (arg_4, arg_5) = arg_2[arg_3]
      if (arg_4 == arg_1):
        break

    if arg_3 >= len(arg_2)-1:
      raise RuntimeError("Field name %s not found in this encoder" % arg_1)

    # Return the offset and width
    return (arg_5, arg_2[arg_3+1][1] - arg_5)


def Func(arg_0, arg_1, arg_2=''):
    """
    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 of inputs
    which, if their encoded outputs were ORed together, would produce the
    target output. This behavior makes this method suitable for doing things
    like generating a description of a learned coincidence in the SP, which
    in many cases might be a union of one or more inputs.

    If instead, you want to figure the *most likely* single input scalar value
    that would have generated a specific encoded output, use the
    :meth:`.topDownCompute` method.

    If you want to pretty print the return value from this method, use the
    :meth:`.FuncdToStr` method.

    :param encoded:      The encoded output that you want Func
    :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 the dict() in the retval.

    :return: tuple(``fieldsDict``, ``fieldOrder``)

              ``fieldsDict`` is a dict() where the keys represent field names
              (only 1 if this is a simple encoder, > 1 if this is a multi
              or date encoder) and the values are the result of decoding each
              field. If there are  no bits in encoded that would have been
              generated by a field, it won't be present in the dict. The
              key of each entry in the dict is formed by joining the passed in
              parentFieldName with the child encoder name using a '.'.

              Each 'value' in ``fieldsDict`` consists of (ranges, desc), where
              ranges is a list of one or more (minVal, maxVal) ranges of
              input that would generate bits in the encoded output and 'desc'
              is a pretty print description of the ranges. For encoders like
              the category encoder, the 'desc' will contain the category
              names that correspond to the scalar values included in the
              ranges.

              ``fieldOrder`` is a list of the keys from ``fieldsDict``, in the
              same order as the fields appear in the encoded output.

              TODO: when we switch to Python 2.7 or 3.x, use OrderedDict

    Example retvals for a scalar encoder:

    .. code-block:: python

       {'amount':  ( [[1,3], [7,10]], '1-3, 7-10' )}
       {'amount':  ( [[2.5,2.5]],     '2.5'       )}

    Example retval for a category encoder:

    .. code-block:: python

       {'country': ( [[1,1], [5,6]], 'US, GB, ES' )}

    Example retval for a multi encoder:

    .. code-block:: python

       {'amount':  ( [[2.5,2.5]],     '2.5'       ),
        'country': ( [[1,1], [5,6]],  'US, GB, ES' )}

    """

    arg_3 = dict()
    arg_4 = []

    # What is the effective parent name?
    if arg_2 == '':
      arg_5 = arg_0.name
    else:
      arg_5 = "%s.%s" % (arg_2, arg_0.name)

    if arg_0.encoders is not None:
      # Merge decodings of all child encoders together
      for arg_6 in xrange(len(arg_0.encoders)):

        # Get the encoder and the encoded output
        (arg_7, arg_8, arg_9) = arg_0.encoders[arg_6]
        if arg_6 < len(arg_0.encoders)-1:
          arg_10 = arg_0.encoders[arg_6+1][2]
        else:
          arg_10 = arg_0.width
        arg_11 = arg_1[arg_9:arg_10]
        (arg_12, arg_13) = arg_8.Func(arg_11,
                                              arg_2=arg_5)

        arg_3.update(arg_12)
        arg_4.extend(arg_13)

    return (arg_3, arg_4)


def Func(arg_0):
    """create a random input vector"""

    print "-" * 70 + "Creating a random input vector" + "-" * 70

    #clear the inputArray to zero before creating a new input vector
    arg_0.inputArray[0:] = 0

    for arg_2 in range(arg_0.inputSize):
      #randrange returns 0 or 1
      arg_0.inputArray[arg_2] = random.randrange(2)


def Func(arg_0, arg_1, arg_2=True, arg_3=True,
            arg_4=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 classified. This
        must be a dense representation of the array (e.g. [0, 0, 1, 1, 0, 1]).

    :param computeScores: NO EFFECT

    :param overCategories: NO EFFECT

    :param partitionId: (int) If provided, all training vectors with partitionId
        equal to that of the input pattern are ignored.
        For example, this may be used to perform k-fold cross validation
        without repopulating the classifier. First partition all the data into
        k equal partitions numbered 0, 1, 2, ... and then call learn() for each
        vector passing in its partitionId. Then, during Funcence, by passing
        in the partition ID in the call to Func(), all other vectors with the
        same partitionId are ignored simulating the effect of repopulating the
        classifier while ommitting the training vectors in the same partition.

    :returns: 4-tuple with these keys:

      - ``winner``: The category with the greatest number of nearest neighbors
          within the kth nearest neighbors. If the FuncenceResult contains no
          neighbors, the value of winner is None. This can happen, for example,
          in cases of exact matching, if there are no stored vectors, or if
          minSparsity is not met.
      - ``FuncenceResult``: A list of length numCategories, each entry contains
          the number of neighbors within the top k neighbors that are in that
          category.
      - ``dist``: A list of length numPrototypes. Each entry is the distance
          from the unknown to that prototype. All distances are between 0.0 and
          1.0.
      - ``categoryDist``: A list of length numCategories. Each entry is the
                        distance from the unknown to the nearest prototype of
                        that category. All distances are between 0 and 1.0.
    """

    # Calculate sparsity. If sparsity is too low, we do not want to run
    # Funcence with this vector
    arg_5 = 0.0
    if arg_0.minSparsity > 0.0:
      arg_5 = ( float(len(arg_1.nonzero()[0])) /
                   len(arg_1) )

    if len(arg_0._categoryList) == 0 or arg_5 < arg_0.minSparsity:
      # No categories learned yet; i.e. first Funcence w/ online learning or
      # insufficient sparsity
      arg_6 = None
      arg_7 = numpy.zeros(1)
      arg_8 = numpy.ones(1)
      arg_9 = numpy.ones(1)

    else:
      arg_10 = max(arg_0._categoryList)
      arg_7 = numpy.zeros(arg_10+1)
      arg_8 = arg_0._getDistances(arg_1, arg_4=arg_4)
      arg_11 = len(arg_0._categoryList) - arg_0._categoryList.count(-1)

      # Loop through the indices of the nearest neighbors.
      if arg_0.exact:
        # Is there an exact match in the distances?
        arg_12 = numpy.where(arg_8<0.00001)[0]
        if len(arg_12) > 0:
          for arg_13 in arg_12[:min(arg_0.k, arg_11)]:
            arg_7[arg_0._categoryList[arg_13]] += 1.0
      else:
        arg_14 = arg_8.argsort()
        for arg_15 in arg_14[:min(arg_0.k, arg_11)]:
          arg_7[arg_0._categoryList[arg_15]] += 1.0

      # Prepare Funcence results.
      if arg_7.any():
        arg_6 = arg_7.argmax()
        arg_7 /= arg_7.sum()
      else:
        arg_6 = None
      arg_9 = min_score_per_category(arg_10,
                                            arg_0._categoryList, arg_8)
      arg_9.clip(0, 1.0, arg_9)

    if arg_0.verbosity >= 1:
      print "%s Func:" % (g_debugPrefix)
      print "  active inputs:",  _labeledInput(arg_1,
                                               cellsPerCol=arg_0.cellsPerCol)
      print "  winner category:", arg_6
      print "  pct neighbors of each category:", arg_7
      print "  dist of each prototype:", arg_8
      print "  dist of each category:", arg_9

    arg_16 = (arg_6, arg_7, arg_8, arg_9)
    return arg_16


def Func(arg_0, arg_1, arg_2=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.
    """
    arg_3 = numpy.zeros(max(arg_0._categoryList)+1)
    arg_4 = arg_0._getDistances(arg_1)

    arg_5 = arg_4.argsort()

    arg_6 = len(arg_0._categoryList) - arg_0._categoryList.count(-1)
    for arg_7 in arg_5[:min(arg_0.k, arg_6)]:
      arg_3[arg_0._categoryList[arg_7]] += 1.0

    arg_8 = arg_3.argmax()

    arg_9 = []
    for arg_10 in range(arg_2):
      arg_9.append((arg_0._categoryList[arg_5[arg_10]], arg_4[arg_5[arg_10]] ))

    return arg_8, arg_4, arg_9


def Func(arg_0, arg_1, arg_2):
    """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 closest training pattern, or None if no
        such patterns exist
    """
    arg_3 = arg_0._getDistances(arg_1)
    arg_4 = arg_3.argsort()

    for arg_5 in arg_4:
      arg_6 = arg_0._categoryList[arg_5]

      # If closest pattern belongs to desired category, return it
      if arg_6 == arg_2:
        if arg_0.useSparseMemory:
          arg_7 = arg_0._Memory.getRow(int(arg_5))
        else:
          arg_7 = arg_0._M[arg_5]

        return arg_7

    # No patterns were found!
    return None


def Func(arg_0, arg_1, arg_2=False, arg_3=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 None, get the first pattern belonging to category cat. If
        this is specified, idx must be None.

    :returns: The training pattern with specified index
    """
    if arg_3 is not None:
      assert arg_1 is None
      arg_1 = arg_0._categoryList.index(arg_3)

    if not arg_0.useSparseMemory:
      arg_4 = arg_0._Memory[arg_1]
      if arg_2:
        arg_4 = arg_4.nonzero()[0]

    else:
      (arg_5, arg_6) = arg_0._Memory.rowNonZeros(arg_1)
      if not arg_2:
        arg_4 = numpy.zeros(arg_0._Memory.nCols())
        numpy.put(arg_4, arg_5, 1)
      else:
        arg_4 = arg_5

    return arg_4


def Func(arg_0, arg_1):
    """
    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 (arg_1 < 0) or (arg_1 >= arg_0._numPatterns):
      raise RuntimeError("index out of bounds")
    arg_2 = arg_0._partitionIdList[arg_1]
    if arg_2 == numpy.inf:
      return None
    else:
      return arg_2


def Func(arg_0, arg_1, arg_2=None):
    """
    Adds partition id for pattern index
    """
    if arg_2 is None:
      arg_0._partitionIdList.append(numpy.inf)
    else:
      arg_0._partitionIdList.append(arg_2)
      arg_3 = arg_0._partitionIdMap.get(arg_2, [])
      arg_3.append(arg_1)
      arg_0._partitionIdMap[arg_2] = arg_3


def Func(arg_0, arg_1):
    """
    Rebuilds the partition Id map using the given partitionIdList
    """
    arg_0._partitionIdMap = {}
    for arg_3, arg_4 in enumerate(arg_1):
      arg_5 = arg_0._partitionIdMap.get(arg_4, [])
      arg_5.append(arg_3)
      arg_0._partitionIdMap[arg_4] = arg_5


def Func(arg_0, arg_1, arg_2=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 distance norm
    """
    if arg_2 is None:
      arg_2 = arg_0.distanceNorm

    # Sparse memory
    if arg_0.useSparseMemory:
      if arg_0._protoSizes is None:
        arg_0._protoSizes = arg_0._Memory.rowSums()
      arg_4 = arg_0._Memory.rightVecSumAtNZ(arg_1)
      arg_5 = arg_1.sum()

      if arg_0.distanceMethod == "rawOverlap":
        arg_6 = arg_1.sum() - arg_4
      elif arg_0.distanceMethod == "pctOverlapOfInput":
        arg_6 = arg_5 - arg_4
        if arg_5 > 0:
          arg_6 /= arg_5
      elif arg_0.distanceMethod == "pctOverlapOfProto":
        arg_4 /= arg_0._protoSizes
        arg_6 = 1.0 - arg_4
      elif arg_0.distanceMethod == "pctOverlapOfLarger":
        arg_7 = numpy.maximum(arg_0._protoSizes, arg_5)
        if arg_7.all() > 0:
          arg_4 /= arg_7
        arg_6 = 1.0 - arg_4
      elif arg_0.distanceMethod == "norm":
        arg_6 = arg_0._Memory.vecLpDist(arg_0.distanceNorm, arg_1)
        arg_8 = arg_6.max()
        if arg_8 > 0:
          arg_6 /= arg_8
      else:
        raise RuntimeError("Unimplemented distance method %s" %
          arg_0.distanceMethod)

    # Dense memory
    else:
      if arg_0.distanceMethod == "norm":
        arg_6 = numpy.power(numpy.abs(arg_0._M - arg_1), arg_0.distanceNorm)
        arg_6 = arg_6.sum(1)
        arg_6 = numpy.power(arg_6, 1.0/arg_0.distanceNorm)
        arg_6 /= arg_6.max()
      else:
        raise RuntimeError ("Not implemented yet for dense storage....")

    return arg_6


def Func(arg_0, arg_1, arg_2=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
        partitionId.
    """
    if not arg_0._finishedLearning:
      arg_0.finishLearning()
      arg_0._finishedLearning = True

    if arg_0._vt is not None and len(arg_0._vt) > 0:
      arg_1 = arg_6.dot(arg_0._vt, arg_1 - arg_0._mean)

    arg_4 = arg_0._sparsifyVector(arg_1)

    # Compute distances
    arg_5 = arg_0._calcDistance(arg_4)
    # Invalidate results where category is -1
    if arg_0._specificIndexTraining:
      arg_5[arg_6.array(arg_0._categoryList) == -1] = arg_6.inf

    # Ignore vectors with this partition id by setting their distances to inf
    if arg_2 is not None:
      arg_5[arg_0._partitionIdMap.get(arg_2, [])] = arg_6.inf

    return arg_5


def Func(arg_0, arg_1):
    """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 change all vectors of category 0 to be category 2, category 1 to
        0, and category 2 to 1
    """
    arg_2 = numpy.array(arg_0._categoryList)
    arg_3 = numpy.zeros(arg_2.shape[0])
    arg_3.fill(-1)
    for arg_4 in xrange(len(arg_1)):
      arg_3[arg_2==arg_4] = arg_1[arg_4]
    arg_0._categoryList = list(arg_3)


def Func(arg_0, arg_1):
    """
    Computes the width of dataOut.

    Overrides
    :meth:`nupic.bindings.regions.PyRegion.PyRegion.Func`.
    """

    if arg_1 == "resetOut":
      print ("WARNING: Func should not have been called with "
             "resetOut")
      return 1

    elif arg_1 == "sequenceIdOut":
      print ("WARNING: Func should not have been called with "
             "sequenceIdOut")
      return 1

    elif arg_1 == "dataOut":
      if arg_0.encoder is None:
        raise Exception("NuPIC requested output element count for 'dataOut' "
                        "on a RecordSensor node, but the encoder has not "
                        "been set")
      return arg_0.encoder.getWidth()

    elif arg_1 == "sourceOut":
      if arg_0.encoder is None:
        raise Exception("NuPIC requested output element count for 'sourceOut' "
                        "on a RecordSensor node, "
                        "but the encoder has not been set")
      return len(arg_0.encoder.getDescription())

    elif arg_1 == "bucketIdxOut":
      return 1

    elif arg_1 == "actValueOut":
      return 1

    elif arg_1 == "categoryOut":
      return arg_0.numCategories

    elif arg_1 == 'spatialTopDownOut' or arg_1 == 'temporalTopDownOut':
      if arg_0.encoder is None:
        raise Exception("NuPIC requested output element count for 'sourceOut' "
                        "on a RecordSensor node, "
                        "but the encoder has not been set")
      return len(arg_0.encoder.getDescription())
    else:
      raise Exception("Unknown output %s" % arg_1)


def Func(arg_0, arg_1, arg_2, arg_3):
    """
      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 arg_1 == 'topDownMode':
      arg_0.topDownMode = arg_3
    elif arg_1 == 'predictedField':
      arg_0.predictedField = arg_3
    else:
      raise Exception('Unknown parameter: ' + arg_1)


def Func(arg_0, arg_1):
    """
    Saves the record in the underlying csv file.

    :param record: a list of Python objects that will be string-ified
    """

    assert arg_0._file is not None
    assert arg_0._mode == arg_0._FILE_WRITE_MODE
    assert isinstance(arg_1, (list, tuple)), \
      "unexpected record type: " + repr(type(arg_1))

    assert len(arg_1) == arg_0._fieldCount, \
      "len(record): %s, fieldCount: %s" % (len(arg_1), arg_0._fieldCount)

    # Write header if needed
    if arg_0._recordCount == 0:
      # Write the header
      arg_2, arg_3, arg_4 = zip(*arg_0.getFields())
      for arg_5 in arg_2, arg_3, arg_4:
        arg_0._writer.writerow(arg_5)

    # Keep track of sequences, make sure time flows forward
    arg_0._updateSequenceInfo(arg_1)

    arg_5 = [arg_0._adapters[i](f) for i, f in enumerate(arg_1)]

    arg_0._writer.writerow(arg_5)
    arg_0._recordCount += 1


def Func(arg_0, arg_1, arg_2=None):
    """
    Saves multiple records in the underlying storage.

    :param records: array of records as in
                    :meth:`~.FileRecordStream.appendRecord`
    :param progressCB: (function) callback to report progress
    """

    for arg_3 in arg_1:
      arg_0.appendRecord(arg_3)
      if arg_2 is not None:
        arg_2()


def Func(arg_0):
    """
    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 arg_0._write and arg_0._recordCount==0:
      return None

    arg_1 = dict(filepath=os.path.realpath(arg_0._filename),
                   currentRow=arg_0._recordCount)
    return json.dumps(arg_1)


def Func(arg_0, arg_1):
    """
    Seeks to ``numRecords`` from the end and returns a bookmark to the new
    position.

    :param numRecords: how far to seek from end of file.
    :return: bookmark to desired location.
    """
    arg_0._file.seek(arg_0._getTotalLineCount() - arg_1)
    return arg_0.getBookmark()


def Func(arg_0, arg_1):
    """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 field)

    Note that if there is no sequenceId field or resetId field then the entire
    dataset is technically one big sequence. The function will not return True
    for the first record in this case. This is Ok because it is important to
    detect new sequences only when there are multiple sequences in the file.
    """

    # Get current sequence id (if any)
    arg_2 = False
    arg_3 = (arg_1[arg_0._sequenceIdIdx]
                  if arg_0._sequenceIdIdx is not None else None)
    if arg_3 != arg_0._currSequence:
      # verify that the new sequence didn't show up before
      if arg_3 in arg_0._sequences:
        raise Exception('Broken sequence: %s, record: %s' % \
                        (arg_3, arg_1))

      # add the finished sequence to the set of sequence
      arg_0._sequences.add(arg_0._currSequence)
      arg_0._currSequence = arg_3

      # Verify that the reset is consistent (if there is one)
      if arg_0._resetIdx:
        assert arg_1[arg_0._resetIdx] == 1
      arg_2 = True

    else:
      # Check the reset
      arg_5 = False
      if arg_0._resetIdx:
        arg_5 = arg_1[arg_0._resetIdx]
        if arg_5 == 1:
          arg_2 = True

    # If it's still the same old sequence make sure the time flows forward
    if not arg_2:
      if arg_0._timeStampIdx and arg_0._currTime is not None:
        arg_6 = arg_1[arg_0._timeStampIdx]
        if arg_6 < arg_0._currTime:
          raise Exception('No time travel. Early timestamp for record: %s' % arg_1)

    if arg_0._timeStampIdx:
      arg_0._currTime = arg_1[arg_0._timeStampIdx]


def Func(arg_0, arg_1=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:
    -----------------------------------------------------------------------

    inferenceElement:   The InferenceElement value being delayed
    key:                If the inference is a dictionary type, this specifies
                        key for the sub-inference that is being delayed
    """
    # -----------------------------------------------------------------------
    # For next step prediction, we shift by 1
    if arg_0 in (InferenceElement.prediction,
                            InferenceElement.encodings):
      return 1
    # -----------------------------------------------------------------------
    # For classification, anomaly scores, the inferences immediately succeed the
    # inputs
    if arg_0 in (InferenceElement.anomalyScore,
                            InferenceElement.anomalyLabel,
                            InferenceElement.classification,
                            InferenceElement.classConfidences):
      return 0
    # -----------------------------------------------------------------------
    # For multistep prediction, the delay is based on the key in the inference
    # dictionary
    if arg_0 in (InferenceElement.multiStepPredictions,
                            InferenceElement.multiStepBestPredictions):
      return int(arg_1)

    # -----------------------------------------------------------------------
    # default: return 0
    return 0


def Func(arg_0):
    """ Returns True if the inference type is 'temporal', i.e. requires a
    temporal memory in the network.
    """
    if arg_1.__temporalInferenceTypes is None:
      arg_1.__temporalInferenceTypes = \
                                set([arg_1.TemporalNextStep,
                                     arg_1.TemporalClassification,
                                     arg_1.TemporalAnomaly,
                                     arg_1.TemporalMultiStep,
                                     arg_1.NontemporalMultiStep])

    return arg_0 in arg_1.__temporalInferenceTypes


def Func(arg_0):
  """ 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 creation fails
  """

  assert os.path.isabs(arg_0)

  try:
    os.makedirs(arg_0)
  except OSError, e:
    if e.errno != os.errno.EEXIST:
      raise

  return arg_0


def Func(arg_0, arg_1, arg_2=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 standard
                  configuration search path.
    retval:    returns a dict with each property as a key and a dict of all
               the property's attributes as value
    """

    arg_3 = dict()

    # Get the path to the config files.
    if arg_2 is None:
      arg_4 = arg_0.findConfigFile(arg_1)
    else:
      arg_4 = os.path.join(arg_2, arg_1)

    # ------------------------------------------------------------------
    # Read in the config file
    try:
      if arg_4 is not None:
        try:
          # Use warn since console log level is set to warning
          _getLoggerBase().debug("Loading config file: %s", arg_4)
          with open(arg_4, 'r') as inp:
            arg_5 = inp.read()
        except Exception:
          raise RuntimeError("Expected configuration file at %s" % arg_4)
      else:
        # If the file was not found in the normal search paths, which includes
        # checking the NTA_CONF_PATH, we'll try loading it from pkg_resources.
        try:
          arg_5 = resource_string("nupic.support", arg_1)
        except Exception as resourceException:
          # We expect these to be read, and if they don't exist we'll just use
          # an empty configuration string.
          if arg_1 in [USER_CONFIG, CUSTOM_CONFIG]:
            arg_5 = '<configuration/>'
          else:
            raise resourceException

      arg_6 = ElementTree.XML(arg_5)

      if arg_6.tag != 'configuration':
        raise RuntimeError("Expected top-level element to be 'configuration' "
                           "but got '%s'" % (arg_6.tag))

      # ------------------------------------------------------------------
      # Add in each property found
      arg_7 = arg_6.findall('./property')

      for arg_8 in arg_7:

        arg_9 = dict()

        # Parse this property element
        arg_10 = list(arg_8)
        for arg_11 in arg_10:
          arg_9[arg_11.tag] = arg_11.text

        # Get the name
        arg_13 = arg_9.get('name', None)

        # value is allowed to be empty string
        if 'value' in arg_9 and arg_9['value'] is None:
          arg_14 = ''
        else:
          arg_14 = arg_9.get('value', None)

          if arg_14 is None:
            if 'novalue' in arg_9:
              # Placeholder "novalue" properties are intended to be overridden
              # via dynamic configuration or another configuration layer.
              continue
            else:
              raise RuntimeError("Missing 'value' element within the property "
                                 "element: => %s " % (str(arg_9)))

        # The value is allowed to contain substitution tags of the form
        # ${env.VARNAME}, which should be substituted with the corresponding
        # environment variable values
        arg_15 = arg_14
        arg_14 = ''
        while True:
          # Find the beginning of substitution tag
          arg_16 = arg_15.find('${env.')
          if arg_16 == -1:
            # No more environment variable substitutions
            arg_14 += arg_15
            break

          # Append prefix to value accumulator
          arg_14 += arg_15[0:arg_16]

          # Find the end of current substitution tag
          arg_17 = arg_15.find('}', arg_16)
          if arg_17 == -1:
            raise RuntimeError(
              "Trailing environment variable tag delimiter '}'"
              " not found in %r" % (arg_15))

          # Extract environment variable name from tag
          arg_18 = arg_15[arg_16 + 6:arg_17]
          if arg_18 not in os.environ:
            raise RuntimeError("Attempting to use the value of the environment"
                               " variable %r, which is not defined" % (
                               arg_18))
          arg_19 = os.environ[arg_18]

          arg_14 += arg_19

          arg_15 = arg_15[arg_17 + 1:]

        # Check for errors
        if arg_13 is None:
          raise RuntimeError(
            "Missing 'name' element within following property "
            "element:\n => %s " % (str(arg_9)))

        arg_9['value'] = arg_14
        arg_3[arg_13] = arg_9

      return arg_3
    except Exception:
      _getLoggerBase().exception("Error while parsing configuration file: %s.",
                             arg_4)
      raise


def Func(arg_0, arg_1):
    """ 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 custom configuration properties=%r; caller=%r",
                      arg_1, traceback.format_stack())

    _CustomConfigurationFileWrapper.edit(arg_1)

    for arg_2, arg_3 in arg_1.iteritems():
      arg_0.set(arg_2, arg_3)


def Func(arg_0):
    """ Clear all custom configuration settings and delete the persistent
    custom configuration store.
    """
    _getLogger().info("Resetting all custom configuration properties; "
                      "caller=%r", traceback.format_stack())

    # Clear the in-memory settings cache, forcing reload upon subsequent "get"
    # request.
    super(Configuration, arg_0).clear()

    # Delete the persistent custom configuration store and reset in-memory
    # custom configuration info
    _CustomConfigurationFileWrapper.clear(persistent=True)


def Func(arg_0, arg_1=False):
    """ If persistent is True, delete the temporary file

    Parameters:
    ----------------------------------------------------------------
    persistent: if True, custom configuration file is deleted
    """
    if arg_1:
      try:
        os.unlink(arg_0.getPath())
      except OSError, e:
        if e.errno != errno.ENOENT:
          _getLogger().exception("Error %s while trying to remove dynamic " \
                                 "configuration file: %s", e.errno,
                                 arg_0.getPath())
          raise
    arg_0._path = None


def Func(arg_0):
    """ Returns a dict of all temporary values in custom configuration file

    """
    if not os.path.exists(arg_0.getPath()):
      return dict()

    arg_1 = Configuration._readConfigFile(os.path.basename(
      arg_0.getPath()), os.path.dirname(arg_0.getPath()))

    arg_2 = dict()
    for arg_3 in arg_1:
      if 'value' in arg_1[arg_3]:
        arg_2[arg_3] = arg_1[arg_3]['value']

    return arg_2


def Func(arg_0, arg_1):
    """ 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 name, value is value)
    """
    arg_2 = copy(arg_1)

    arg_3 = arg_0.getPath()

    try:
      with open(arg_3, 'r') as fp:
        arg_4 = fp.read()
    except IOError, arg_7:
      if arg_7.errno != errno.ENOENT:
        _getLogger().exception("Error %s reading custom configuration store "
                               "from %s, while Funcing properties %s.",
                               arg_7.errno, arg_3, arg_1)
        raise
      arg_4 = '<configuration/>'

    try:
      arg_5 = ElementTree.XML(arg_4)
      ElementTree.tostring(arg_5)
    except Exception, arg_7:
      # Raising error as RuntimeError with custom message since ElementTree
      # exceptions aren't clear.
      arg_6 = "File contents of custom configuration is corrupt.  File " \
            "location: %s; Contents: '%s'. Original Error (%s): %s." % \
            (arg_3, arg_4, type(arg_7), arg_7)
      _getLogger().exception(arg_6)
      raise RuntimeError(arg_6), None, sys.exc_info()[2]

    if arg_5.tag != 'configuration':
      arg_7 = "Expected top-level element to be 'configuration' but got '%s'" % \
          (arg_5.tag)
      _getLogger().error(arg_7)
      raise RuntimeError(arg_7)

    # Apply new properties to matching settings in the custom config store;
    # pop matching properties from our copy of the properties dict
    for arg_8 in arg_5.findall('./property'):
      arg_9 = dict((attr.tag, attr.text) for attr in arg_8)
      arg_10 = arg_9['name']
      if arg_10 in arg_2:
        arg_11 = arg_8.findall('./value')
        if len(arg_11) > 0:
          arg_11[0].text = str(arg_2.pop(arg_10))
          if not arg_2:
            break
        else:
          arg_7 = "Property %s missing value tag." % (arg_10,)
          _getLogger().error(arg_7)
          raise RuntimeError(arg_7)

    # Add unmatched remaining properties to custom config store
    for arg_13, arg_14 in arg_2.iteritems():
      arg_15 = ElementTree.Element('property')
      arg_16 = ElementTree.Element('name')
      arg_16.text = arg_13
      arg_15.append(arg_16)

      arg_17 = ElementTree.Element('value')
      arg_17.text = str(arg_14)
      arg_15.append(arg_17)

      arg_5.append(arg_15)

    try:
      makeDirectoryFromAbsolutePath(os.path.dirname(arg_3))
      with open(arg_3, 'w') as fp:
        fp.write(ElementTree.tostring(arg_5))
    except Exception, arg_7:
      _getLogger().exception("Error while saving custom configuration "
                             "properties %s in %s.", arg_1,
                             arg_3)
      raise


def Func(arg_0):
    """ Sets the path of the custom configuration file
    """
    arg_0._path = os.path.join(os.environ['NTA_DYNAMIC_CONF_DIR'],
                             arg_0.customFileName)


def Func(arg_0):
    """Get the particle state as a dict. This is enough information to
    instantiate this particle on another worker."""
    arg_1 = dict()
    for arg_2, arg_3 in arg_0.permuteVars.iteritems():
      arg_1[arg_2] = arg_3.Func()

    return dict(id=arg_0.particleId,
                genIdx=arg_0.genIdx,
                swarmId=arg_0.swarmId,
                arg_1=arg_1)


def Func(arg_0, arg_1, arg_2, arg_3):
    """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 evoloving a particle
    because the bestResult and position as stored in was the best AT THE TIME
    THAT PARTICLE STARTED TO RUN and does not include the best since that
    particle completed.
    """
    # Get the update best position and result?
    if arg_3:
      (arg_4, arg_5) = arg_0._resultsDB.getParticleBest(arg_1)
    else:
      arg_4 = arg_5 = None

    # Replace with the position and velocity of each variable from
    #  saved state
    arg_6 = arg_2['varStates']
    for arg_7 in arg_6.keys():
      arg_8 = copy.deepcopy(arg_6[arg_7])
      if arg_3:
        arg_8['bestResult'] = arg_4
      if arg_5 is not None:
        arg_8['bestPosition'] = arg_5[arg_7]
      arg_0.permuteVars[arg_7].setState(arg_8)


def Func(arg_0, arg_1, arg_2):
    """Copy specific variables from particleState into this particle.

    Parameters:
    --------------------------------------------------------------
    particleState:        dict produced by a particle's getState() method
    varNames:             which variables to copy
    """
    # Set this to false if you don't want the variable to move anymore
    #  after we set the state
    arg_3 = True

    for arg_4 in arg_1['varStates']:
      if arg_4 in arg_2:

        # If this particle doesn't include this field, don't copy it
        if arg_4 not in arg_0.permuteVars:
          continue

        # Set the best position to the copied position
        arg_5 = copy.deepcopy(arg_1['varStates'][arg_4])
        arg_5['_position'] = arg_5['position']
        arg_5['bestPosition'] = arg_5['position']

        if not arg_3:
          arg_5['velocity'] = 0

        # Set the state now
        arg_0.permuteVars[arg_4].setState(arg_5)

        if arg_3:
          # Let the particle move in both directions from the best position
          #  it found previously and set it's initial velocity to a known
          #  fraction of the total distance.
          arg_0.permuteVars[arg_4].resetVelocity(arg_0._rng)


def Func(arg_0):
    """Return the position of a particle given its state dict.

    Parameters:
    --------------------------------------------------------------
    retval:     dict() of particle position, keys are the variable names,
                  values are their positions
    """
    arg_1 = dict()
    for (arg_2, arg_3) in arg_0['varStates'].iteritems():
      arg_1[arg_2] = arg_3['position']

    return arg_1


def Func(arg_0):
    """Agitate this particle so that it is likely to go to a new position.
    Every time Func is called, the particle is jiggled an even greater
    amount.

    Parameters:
    --------------------------------------------------------------
    retval:               None
    """
    for (arg_1, arg_2) in arg_0.permuteVars.iteritems():
      arg_2.Func()

    arg_0.newPosition()