Python types.NoneType() Examples

The following are code examples for showing how to use types.NoneType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 7 votes vote down vote up
def __init__(self, function, name=None):
        """
        Construct a new C{FunctionFeatureDetector} from the given
        function.

        @param function: The function that this feature detector is based
            on.  When this feature detector is applied to a labeled
            text M{lt}, it will return M{C{func}(lt)}.
        @type function: C{LabeledText} -> (any)
        @param name: A name for the function used by this feature
            detector.  This name is used in the string representation
            of the feature detector.
        """
        assert _chktype(1, function, types.FunctionType,
                        types.BuiltinFunctionType, types.ClassType)
        assert _chktype(2, name, types.NoneType, types.StringType)
        self._name = name
        self._func = function 
Example 2
Project: Depth-Map-Prediction   Author: hjimce   File: thutil.py    GNU General Public License v3.0 6 votes vote down vote up
def breakpoint(output, vars=None, cond=lambda v: True, grad=True):
    tb = tuple(traceback.extract_stack()[:-1])
    py_vars = {}
    if type(vars) not in (tuple, list, dict, types.NoneType):
        raise ValueError('vars keyword arg must be None, dict, list or tuple')
    if not isinstance(vars, dict):
        frame_locals = inspect.stack()[1][0].f_locals
        if vars is not None:
            frame_locals = dict((name, val)
                                for (name, val) in frame_locals.iteritems()
                                if name in vars or val in vars)
        vars = frame_locals
    assert isinstance(vars, dict)
    th_vars = dict((name, val) for (name, val) in vars.iteritems()
                               if isinstance(val, _theano_types))
    py_vars = dict((name, val) for (name, val) in vars.iteritems()
                               if name not in th_vars)
    (th_var_names, th_var_vals) = zip(*th_vars.iteritems())
    return Breakpoint(th_var_names, cond, tb, py_vars, grad) \
                     (output, *th_var_vals) 
Example 3
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def reduce(self, production=None):
        """
        Use C{production} to combine the rightmost stack elements into
        a single C{Tree}.  If C{production} does not match the
        rightmost stack elements, then do nothing.

        @return: The production used to reduce the stack, if a
            reduction was performed.  If no reduction was performed,
            return C{None}.
        
        @rtype: C{CFGProduction} or C{None}
        """
        assert chktype(1, production, CFGProduction, types.NoneType)
        self._history.append( (self._stack[:], self._remaining_text[:]) )
        return_val = self._reduce(self._stack, self._remaining_text,
                                  production)

        if not return_val: self._history.pop()
        return return_val 
Example 4
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 6 votes vote down vote up
def __init__(self, freqdist, bins=None):
        """
        Use the Laplace estimate to create a probability distribution
        for the experiment used to generate C{freqdist}.

        @type freqdist: C{FreqDist}
        @param freqdist: The frequency distribution that the
            probability estimates should be based on.
        @type bins: C{int}
        @param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            C{bins} is not specified, it defaults to C{freqdist.B()}.
        """
        assert _chktype(1, freqdist, FreqDist)
        assert _chktype(2, bins, types.IntType, types.NoneType)
        LidstoneProbDist.__init__(self, freqdist, 1, bins) 
Example 5
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 6 votes vote down vote up
def __init__(self, function, name=None):
        """
        Construct a new C{FunctionFeatureDetector} from the given
        function.

        @param function: The function that this feature detector is based
            on.  When this feature detector is applied to a labeled
            text M{lt}, it will return M{C{func}(lt)}.
        @type function: C{LabeledText} -> (any)
        @param name: A name for the function used by this feature
            detector.  This name is used in the string representation
            of the feature detector.
        """
        assert _chktype(1, function, types.FunctionType,
                        types.BuiltinFunctionType, types.ClassType)
        assert _chktype(2, name, types.NoneType, types.StringType)
        self._name = name
        self._func = function 
Example 6
Project: MKLpy   Author: IvanoLauriola   File: matrices.py    GNU General Public License v3.0 6 votes vote down vote up
def ideal_kernel(y, z=None):
    """performs the ideal kernel between the labels vectors *Y* and *Z*.
    The ideal kernel kernel is defines as:
    .. math:: YZ^\top

    Parameters
    ----------
    Y : (n) array_like,
        the train labels vector.
    Z : (l) array_like,
        the test labels vector. If it is not defined, then the kernel is calculated
        between *Y* and *Y*.

    Returns
    -------
    K : (l,n) ndarray,
        the ideal kernel matrix.
    """
    z = y if type(z) == types.NoneType else z
    return np.dot(np.array([y]).T,np.array([z])) 
Example 7
Project: backend   Author: bitex-coin   File: utils.py    GNU General Public License v2.0 6 votes vote down vote up
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
  """
  Returns a bytestring version of 's', encoded as specified in 'encoding'.

  If strings_only is True, don't convert (some) non-string-like objects.
  """
  if strings_only and isinstance(s, (types.NoneType, int)):
    return s
  if not isinstance(s, basestring):
    try:
      return str(s)
    except UnicodeEncodeError:
      if isinstance(s, Exception):
        # An Exception subclass containing non-ASCII data that doesn't
        # know how to print itself properly. We shouldn't raise a
        # further exception.
        return ' '.join([smart_str(arg, encoding, strings_only,
                                   errors) for arg in s])
      return unicode(s).encode(encoding, errors)
  elif isinstance(s, unicode):
    return s.encode(encoding, errors)
  elif s and encoding != 'utf-8':
    return s.decode('utf-8', errors).encode(encoding, errors)
  else:
    return s 
Example 8
Project: blatann   Author: ThomasGerstenberg   File: nrf_driver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ble_gap_encrypt(self, conn_handle, ediv, rand, ltk, lesc, auth):
        # TODO: Clean up
        # assert isinstance(sec_params, (BLEGapSecParams, NoneType)), 'Invalid argument type'
        # assert isinstance(sec_keyset, BLEGapSecKeyset), 'Invalid argument type'
        # print 'ediv %r' % master_id.ediv
        # print 'rand %r' % util.uint8_array_to_list(master_id.rand, 8)
        # print 'ltk  %r' % util.uint8_array_to_list(enc_info.ltk, enc_info.ltk_len)
        # print 'len  %r' % enc_info.ltk_len
        # print 'lesc %r' % enc_info.lesc
        # print 'auth %r' % enc_info.auth

        rand_arr = util.list_to_uint8_array(rand)
        ltk_arr = util.list_to_uint8_array(ltk)
        master_id = driver.ble_gap_master_id_t()
        master_id.ediv = ediv
        master_id.rand = rand_arr.cast()
        enc_info = driver.ble_gap_enc_info_t()
        enc_info.ltk_len = len(ltk)
        enc_info.ltk = ltk_arr.cast()
        enc_info.lesc = lesc
        enc_info.auth = auth
        return driver.sd_ble_gap_encrypt(self.rpc_adapter, conn_handle, master_id, enc_info) 
Example 9
Project: qgis-wps4server   Author: 3liz   File: soap_tests.py    GNU General Public License v3.0 6 votes vote down vote up
def testSOAPVersion(self):
        """Testing correct wps.parser.soapVersion"""
        self._setFromEnv()

        postpywps = pywps.Pywps(pywps.METHOD_POST)
        getCapabilitiesSOAP11RequestFile = open(os.path.join(
            pywpsPath, "tests", "requests", "wps_getcapabilities_request_SOAP11.xml"))
        postpywps.parseRequest(getCapabilitiesSOAP11RequestFile)
        self.assertEqual(int(postpywps.parser.soapVersion), int(11))

        getCapabilitiesSOAP11RequestFile = open(os.path.join(
            pywpsPath, "tests", "requests", "wps_getcapabilities_request_SOAP12.xml"))
        postpywps.parseRequest(getCapabilitiesSOAP11RequestFile)
        self.assertEqual(int(postpywps.parser.soapVersion), int(12))

        # Non soap
        getCapabilitiesRequestFile = open(os.path.join(
            pywpsPath, "tests", "requests", "wps_getcapabilities_request.xml"))
        postpywps.parseRequest(getCapabilitiesRequestFile)
        self.assertTrue(type(postpywps.parser.soapVersion) is types.NoneType) 
Example 10
Project: qgis-wps4server   Author: 3liz   File: Soap.py    GNU General Public License v3.0 6 votes vote down vote up
def doCleanBug5762(document):
    # Please check for explanation
    # http://bugs.python.org/issue5762
    # Problem cause by an empty XMLNS in the root element of the document
    # It's OK to have an empty attribute. Bug fixed in new python versions (2010-10-15 17:59)
    # Check for empty attributed in the root element and remove it:

    for node in doc_order_iter(document):
        attrMap = node.attributes
        try:
            for attrKey in attrMap.keys():
                attr = attrMap[attrKey]

            if (type(attr.value) == types.NoneType or len(attr.value) == 0):
                node.removeAttribute(attr.name)

        except:
            pass
    return document 
Example 11
Project: ttk   Author: tarsqi   File: xml_parser.py    Apache License 2.0 6 votes vote down vote up
def as_xml_tag(self):
        """Return a unicode string that represents the tag. Only useful for opening
        tags. Protects the attribute values from non-xml characters. Only lex tags need to
        be dealt this way, so use the simple self.get_content() for other tags, this also
        does the right thing for non-consuming tags like MAKEINSTANCE, which would not get
        the closing slash when using the code for lex tags below."""
        if not self.is_opening_tag(): return None
        if not self.tag == 'lex': return self.get_content()
        a_list = []
        if self.attrs:
            for (a,v) in self.attrs.items():
                if type(v) == IntType: v = str(v)
                if type(v) is NoneType: v = 'None'
                if type(v) == StringType: v = quoteattr(unicode(v, 'utf-8', 'replace'))
                a_list.append((a, v))
        if a_list:
            a_list = ' ' + ' '.join(["%s=%s" % (a,v) for (a,v) in a_list])
        else:
            a_list = ''
        xmltag = u"<%s%s>" % (self.tag, a_list)
        return xmltag 
Example 12
Project: flasky   Author: RoseOu   File: encoding.py    MIT License 5 votes vote down vote up
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    ) 
Example 13
Project: openhatch   Author: campbe13   File: trackref.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def format_live_refs(ignore=NoneType):
    if object_ref is object:
        return "The trackref module is disabled. Use TRACK_REFS setting to enable it."
    s = "Live References" + os.linesep + os.linesep
    now = time()
    for cls, wdict in live_refs.iteritems():
        if not wdict:
            continue
        if issubclass(cls, ignore):
            continue
        oldest = min(wdict.itervalues())
        s += "%-30s %6d   oldest: %ds ago" % (cls.__name__, len(wdict), \
            now-oldest) + os.linesep
    return s 
Example 14
Project: deb-python-cassandra-driver   Author: openstack   File: encoder.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.mapping = {
            float: self.cql_encode_float,
            bytearray: self.cql_encode_bytes,
            str: self.cql_encode_str,
            int: self.cql_encode_object,
            UUID: self.cql_encode_object,
            datetime.datetime: self.cql_encode_datetime,
            datetime.date: self.cql_encode_date,
            datetime.time: self.cql_encode_time,
            Date: self.cql_encode_date_ext,
            Time: self.cql_encode_time,
            dict: self.cql_encode_map_collection,
            OrderedDict: self.cql_encode_map_collection,
            OrderedMap: self.cql_encode_map_collection,
            OrderedMapSerializedKey: self.cql_encode_map_collection,
            list: self.cql_encode_list_collection,
            tuple: self.cql_encode_list_collection,  # TODO: change to tuple in next major
            set: self.cql_encode_set_collection,
            sortedset: self.cql_encode_set_collection,
            frozenset: self.cql_encode_set_collection,
            types.GeneratorType: self.cql_encode_list_collection,
            ValueSequence: self.cql_encode_sequence
        }

        if six.PY2:
            self.mapping.update({
                unicode: self.cql_encode_unicode,
                buffer: self.cql_encode_bytes,
                long: self.cql_encode_object,
                types.NoneType: self.cql_encode_none,
            })
        else:
            self.mapping.update({
                memoryview: self.cql_encode_bytes,
                bytes: self.cql_encode_bytes,
                type(None): self.cql_encode_none,
            }) 
Example 15
Project: GeoPy   Author: aerler   File: lineplots.py    GNU General Public License v3.0 5 votes vote down vote up
def addSharedLegend(fig, plts=None, legs=None, fontsize=None, **kwargs):
  ''' add a common/shared legend to a multi-panel plot '''
  # complete input
  warn('Deprecated function: use Figure or Axes class methods.')
  if legs is None: legs = [plt.get_label() for plt in plts]
  elif not isinstance(legs, (list,tuple)): raise TypeError
  if not isinstance(plts, (list,tuple,NoneType)): raise TypeError
  # figure out fontsize and row numbers  
  fontsize = fontsize or fig.axes[0].get_yaxis().get_label().get_fontsize() # or fig._suptitle.get_fontsize()
  nlen = len(plts) if plts else len(legs)
  if fontsize > 11: ncols = 2 if nlen == 4 else 3
  else: ncols = 3 if nlen == 6 else 4              
  # make room for legend
  leghgt = np.ceil(nlen/ncols) * fontsize + 0.055
  ax = fig.add_axes([0, 0, 1,leghgt]) # new axes to hold legend, with some attributes
  ax.set_frame_on(False); ax.axes.get_yaxis().set_visible(False); ax.axes.get_xaxis().set_visible(False)
  fig = updateSubplots(fig, mode='shift', bottom=leghgt) # shift bottom upwards
  # define legend parameters
  legargs = dict(loc=10, ncol=ncols, borderaxespad=0., fontsize=fontsize, frameon=True,
                 labelspacing=0.1, handlelength=1.3, handletextpad=0.3, fancybox=True)
  legargs.update(kwargs)
  # create legend and return handle
  if plts: legend = ax.legend(plts, legs, **legargs)
  else: legend = ax.legend(legs, **legargs)
  return legend
  
  

# plots with error shading 
Example 16
Project: robot-navigation   Author: ronaldahmed   File: featurestructure.py    MIT License 5 votes vote down vote up
def __init__(self, identifier=None):
        """
        Construct a new feature structure variable.
        @type identifier: C{string}
        @param identifier: A unique identifier for this variable.
            Any two C{FeatureVariable} objects with the
            same identifier are treated as the same variable.
        """
        assert _chktype(1, identifier, str, NoneType)
        if identifier is None:
            self._identifier = FeatureVariable._next_numbered_id
            FeatureVariable._next_numbered_id += 1
        else:
            self._identifier = identifier 
Example 17
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 5 votes vote down vote up
def expand(self, production=None):
        """
        Expand the first element of the frontier.  In particular, if
        the first element of the frontier is a subtree whose node type
        is equal to C{production}'s left hand side, then add a child
        to that subtree for each element of C{production}'s right hand
        side.  If C{production} is not specified, then use the first
        untried expandable production.  If all expandable productions
        have been tried, do nothing.

        @return: The production used to expand the frontier, if an
           expansion was performed.  If no expansion was performed,
           return C{None}.
        @rtype: C{CFGProduction} or C{None}
        """
        LEAF = self.property('LEAF')
        
        assert chktype(1, production, CFGProduction, types.NoneType)
        # Make sure we *can* expand.
        if len(self._frontier) == 0:
            return None
        if not isinstance(self._tree[self._frontier[0]],
                          Tree):
            return None

        # If they didn't specify a production, check all untried ones.
        if production is None:
            productions = self.untried_expandable_productions()
        else: productions = [production]

        parses = []
        for prod in productions:
            # Record that we've tried this production now.
            self._tried_e.setdefault(self._freeze(self._tree), []).append(prod)

            # Try expanding.
            if self._expand(self._rtext, self._tree, self._frontier, prod):
                return prod

        # We didn't expand anything.
        return None 
Example 18
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def __init__(self, freqdist, gamma, bins=None):
        """
        Use the Lidstone estimate to create a probability distribution
        for the experiment used to generate C{freqdist}.

        @type freqdist: C{FreqDist}
        @param freqdist: The frequency distribution that the
            probability estimates should be based on.
        @type gamma: C{float}
        @param gamma: A real number used to paramaterize the
            estimate.  The Lidstone estimate is equivalant to adding
            M{gamma} to the count for each bin, and taking the
            maximum likelihood estimate of the resulting frequency
            distribution.
        @type bins: C{int}
        @param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            C{bins} is not specified, it defaults to C{freqdist.B()}.
        """
        assert _chktype(1, freqdist, FreqDist)
        assert _chktype(2, gamma, types.FloatType, types.IntType)
        assert _chktype(3, bins, types.IntType, types.NoneType)
        if (bins == 0) or (bins is None and freqdist.N() == 0):
            name = self.__class__.__name__[:-8]
            raise ValueError('A %s probability distribution ' % name +
                             'must have at least one bin.')
        if (bins is not None) and (bins < freqdist.B()):
            name = self.__class__.__name__[:-8]
            raise ValueError('\nThe number of bins in a %s must be ' % name +
                             'greater than or equal to\nthe number of '+
                             'bins in the FreqDist used to create it.')
        
        self._freqdist = freqdist
        self._gamma = float(gamma)
        self._N = self._freqdist.N()

        if bins is None: bins = freqdist.B()
        self._bins = bins 
Example 19
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def __init__(self, base_fdist, heldout_fdist, bins=None):
        """
        Use the heldout estimate to create a probability distribution
        for the experiment used to generate C{base_fdist} and
        C{heldout_fdist}.

        @type base_fdist: C{FreqDist}
        @param base_fdist: The base frequency distribution.
        @type heldout_fdist: C{FreqDist}
        @param heldout_fdist: The heldout frequency distribution.
        @type bins: C{int}
        @param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            C{bins} is not specified, it defaults to C{freqdist.B()}.
        """
        assert _chktype(1, base_fdist, FreqDist)
        assert _chktype(2, heldout_fdist, FreqDist)
        assert _chktype(3, bins, types.IntType, types.NoneType)
        
        self._base_fdist = base_fdist
        self._heldout_fdist = heldout_fdist

        # The max number of times any sample occurs in base_fdist.
        self._max_r = base_fdist.count(base_fdist.max())

        # Calculate Tr, Nr, and N.
        Tr = self._calculate_Tr()
        Nr = [base_fdist.Nr(r, bins) for r in range(self._max_r+1)]
        N = heldout_fdist.N()

        # Use Tr, Nr, and N to compute the probability estimate for
        # each value of r.
        self._estimate = self._calculate_estimate(Tr, Nr, N) 
Example 20
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def __init__(self, freqdists, bins):
        """
        Use the cross-validation estimate to create a probability
        distribution for the experiment used to generate
        C{freqdists}.

        @type freqdists: C{list} of C{FreqDist}
        @param freqdists: A list of the frequency distributions
            generated by the experiment.
        @type bins: C{int}
        @param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            C{bins} is not specified, it defaults to C{freqdist.B()}.
        """
        assert _chktype(1, freqdists, [FreqDist], (FreqDist,))
        assert _chktype(2, bins, types.IntType, types.NoneType)
        self._freqdists = freqdists

        # Create a heldout probability distribution for each pair of
        # frequency distributions in freqdists.
        self._heldout_probdists = []
        for fdist1 in freqdists:
            for fdist2 in freqdists:
                if fdist1 is not fdist2:
                    probdist = HeldoutProbDist(fdist1, fdist2, bins)
                    self._heldout_probdists.append(probdist) 
Example 21
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def __init__(self, freqdist, bins=None):
        """
        Creates a distribution of Witten-Bell probability estimates.  This
        distribution allocates uniform probability mass to as yet unseen
        events by using the number of events that have only been seen once.
        The probability mass reserved for unseen events is equal to:

            - M{T / (N + T)}

        where M{T} is the number of observed event types and M{N} is the total
        number of observed events. This equates to the maximum likelihood
        estimate of a new type event occuring. The remaining probability mass
        is discounted such that all probability estimates sum to one,
        yielding:

            - M{p = T / Z (N + T)}, if count = 0
            - M{p = c / (N + T)}, otherwise

        The parameters M{T} and M{N} are taken from the C{freqdist} parameter
        (the C{B()} and C{N()} values). The normalising factor M{Z} is
        calculated using these values along with the C{bins} parameter.

        @param freqdist:    The frequency counts upon which to base the
                            estimation.
        @type  freqdist:    C{FreqDist}
        @param bins:        The number of possible event types. This must be
                            at least as large as the number of bins in the
                            C{freqdist}. If C{None}, then it's assumed to be
                            equal to that of the C{freqdist}
        @type  bins:        C{Int}
        """
        assert _chktype(1, freqdist, FreqDist)
        assert _chktype(2, bins, types.IntType, types.NoneType)
        assert bins == None or bins >= freqdist.B(),\
            'Bins parameter must not be less than freqdist.B()'
        if bins == None:
            bins = freqdist.B()
        self._freqdist = freqdist
        self._T = self._freqdist.B()
        self._Z = bins - self._freqdist.B()
        self._N = self._freqdist.N() 
Example 22
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, normalise=False, svd_dimensions=None):
        """
        @param normalise:       should vectors be normalised to length 1
        @type normalise:        boolean
        @param svd_dimensions:  number of dimensions to use in reducing vector
                                dimensionsionality with SVD
        @type svd_dimensions:   int 
        """
        assert chktype(1, normalise, bool)
        assert chktype(2, svd_dimensions, int, types.NoneType)
        self._Tt = None
        self._should_normalise = normalise
        self._svd_dimensions = svd_dimensions 
Example 23
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, num_clusters=1, normalise=True, svd_dimensions=None):
        assert chktype(1, num_clusters, int)
        assert chktype(2, normalise, bool)
        assert chktype(3, svd_dimensions, int, types.NoneType)
        VectorSpaceClusterer.__init__(self, normalise, svd_dimensions)
        self._num_clusters = num_clusters
        self._dendogram = None
        self._groups_values = None 
Example 24
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, initial_means, priors=None, covariance_matrices=None,
                       conv_threshold=1e-6, bias=0.1, normalise=False,
                       svd_dimensions=None):
        """
        Creates an EM clusterer with the given starting parameters,
        convergence threshold and vector mangling parameters.

        @param  initial_means: the means of the gaussian cluster centers
        @type   initial_means: [seq of] Numeric array or seq of SparseArray
        @param  priors: the prior probability for each cluster
        @type   priors: Numeric array or seq of float
        @param  covariance_matrices: the covariance matrix for each cluster
        @type   covariance_matrices: [seq of] Numeric array 
        @param  conv_threshold: maximum change in likelihood before deemed
                    convergent
        @type   conv_threshold: int or float
        @param  bias: variance bias used to ensure non-singular covariance
                      matrices
        @type   bias: float
        @param  normalise:  should vectors be normalised to length 1
        @type   normalise:  boolean
        @param  svd_dimensions: number of dimensions to use in reducing vector
                               dimensionsionality with SVD
        @type   svd_dimensions: int 
        """
        #assert chktype(1, initial_means, [])
        #assert chktype(2, priors, [], types.NoneType)
        #assert chktype(3, covariance_matrices, [], types.NoneType)
        assert chktype(4, conv_threshold, float, int)
        assert chktype(6, normalise, bool)
        assert chktype(7, svd_dimensions, int, types.NoneType)
        VectorSpaceClusterer.__init__(self, normalise, svd_dimensions)
        self._means = Numeric.array(initial_means, Numeric.Float64)
        self._num_clusters = len(initial_means)
        self._conv_threshold = conv_threshold
        self._covariance_matrices = covariance_matrices
        self._priors = priors
        self._bias = bias 
Example 25
Project: recipes-py   Author: luci   File: api.py    Apache License 2.0 5 votes vote down vote up
def get_text(self, url, step_name=None, headers=None, transient_retry=True,
               timeout=None, default_test_data=None):
    """GET data at given URL and writes it to file.

    Args:
      * url: URL to request.
      * step_name: optional step name, 'fetch <url>' by default.
      * headers: a {header_name: value} dictionary for HTTP headers.
      * transient_retry (bool or int): Determines how transient HTTP errorts
          (>500) will be retried. If True (default), errors will be retried up
          to 10 times. If False, no transient retries will occur. If an integer
          is supplied, this is the number of transient retries to perform. All
          retries have exponential backoff applied.
      * timeout: Timeout (see step.__call__).
      * default_test_data (str): If provided, use this as the text output when
          testing if no overriding data is available.

    **Returns (UrlApi.Response)** - Response with the content as its output
    value.

    **Raises:**
      * HTTPError, InfraHTTPError: if the request failed.
      * ValueError: If the request was invalid.
    """
    assert isinstance(default_test_data, (types.NoneType, str))
    return self._get_step(url, None, step_name, headers, transient_retry,
                          None, False, timeout, default_test_data) 
Example 26
Project: msdas   Author: cokelaer   File: annotations.py    GNU General Public License v3.0 5 votes vote down vote up
def _append_uniprot_entry_names_to_df(self):

        if isinstance(self.annotations, types.NoneType) == True:
            self.error("must call set_annotations first")
            return
        # let us add the Entry_name column as well
        entry_names = [self.annotations.ix[e]['Entry name'] if e in self.annotations.index else "" for e in self.df.Entry]
        self.df['Entry_name'] = entry_names 
Example 27
Project: msdas   Author: cokelaer   File: annotations.py    GNU General Public License v3.0 5 votes vote down vote up
def check_entries_versus_sequence(self):
        """Check that peptide sequence are contained in uniprot sequence

        This is a very good sanity check on the validity of the uniprot entry names
        found by :meth:`get_uniprot_entries` method

        If a peptide sequence is not found, it means that the protein name is
        not correct.

        See AnnotationsYeast class where the :meth:`AnnotationsYeast.update_mapping` is used to
        update the incorrect mapping.

        .. seealso:: :meth:`find_sequence_blast`

        """

        self.logging.info("Comparing peptide sequence in the attribute df with sequences in the annotations")
        self.logging.info("row index, protein name, uniprot entry")
        if isinstance(self.annotations, types.NoneType):
            raise Exception("annotations not set. call set_annotations")
        found = False
        for i in self.df.index:
            entry = self.df.ix[i].Entry
            if entry not in self.annotations.index:
                print("{} not found in the annotations index".format(entry))
                continue
            if self.df.ix[i].Sequence not in self.annotations.ix[entry].Sequence:
                if found == False:
                    print("Found unknown entries\nindex, protein name, uniprot entry ")
                    found = True
                print(i, self.df.ix[i].Protein, self.df.ix[i].Entry) 
Example 28
Project: nmap-tor-scanner   Author: BlackBox-CSP   File: nmap.py    MIT License 5 votes vote down vote up
def scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', callback=None):
        """
        Scan given hosts in a separate process and return host by host result using callback function

        PortScannerError exception from standard nmap is catched and you won't know about it

        hosts = string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
        ports = string for ports as nmap use it '22,53,110,143-4564'
        arguments = string of arguments for nmap '-sU -sX -sC'
        callback = callback function which takes (host, scan_data) as arguments
        """

        assert type(hosts) in types.StringTypes, 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts))
        assert type(ports) in types.StringTypes+(types.NoneType,), 'Wrong type for [ports], should be a string [was {0}]'.format(type(ports))
        assert type(arguments) in types.StringTypes, 'Wrong type for [arguments], should be a string [was {0}]'.format(type(arguments))
        assert type(callback) in (types.FunctionType, types.NoneType), 'Wrong type for [callback], should be a function or None [was {0}]'.format(type(callback))

        def scan_progressive(self, hosts, ports, arguments, callback):
            for host in self._nm.listscan(hosts):
                try:
                    scan_data = self._nm.scan(host, ports, arguments)
                except PortScannerError:
                    pass
                if callback is not None and callable(callback):
                    callback(host, scan_data)
            return

        self._process = Process(
            target=scan_progressive,
            args=(self, hosts, ports, arguments, callback)
            )
        self._process.daemon = True
        self._process.start()
        return 
Example 29
Project: nmap-tor-scanner   Author: BlackBox-CSP   File: nmap.py    MIT License 5 votes vote down vote up
def wait(self, timeout=None):
        """
        Wait for the current scan process to finish, or timeout
        """

        assert type(timeout) in (types.IntType, types.NoneType), 'Wrong type for [timeout], should be an int or None [was {0}]'.format(type(timeout))

        self._process.join(timeout)
        return 
Example 30
Project: MKLpy   Author: IvanoLauriola   File: arrange.py    GNU General Public License v3.0 5 votes vote down vote up
def multiplication (K_list, weights = None):
    """perform the weighted multiplication of each kernel in K_list.

    Parametes
    ---------
    K_list : (l,n,m) ndarray or kernel_list,
             where *l* is the number of kernels in list and *(n,m)* is the shape of kernels.
    weights : (l) array_like,
              if it is not defined, then is performed the simple multiplication.

    Returns
    -------
    K : (n,m) ndarray,
        the multiplication of *l* kernels in list.

    Examples
    --------
    >>> Klist   = np.array([HPK_kernel(X,degree=i) for i in range(1,11)])
    >>> weights = range(1,11)
    >>> Ksum    = multiplication(Klist)
    >>> Kwsum   = multiplication(Klist,weights)
    """
    K = np.ones(K_list[0].shape, dtype = np.float64)
    l = len(K_list)
    weights = np.ones(l, dtype = np.double) if type(weights) == types.NoneType else weights
    for w,ker in zip(weights, K_list):
        K = K * w * ker
    return K 
Example 31
Project: MKLpy   Author: IvanoLauriola   File: boolean.py    GNU General Public License v3.0 5 votes vote down vote up
def tanimoto_kernel(X,T=None):#?
    T = X if type(T) == types.NoneType else T
    L = np.dot(X,T.T)
    xx = np.linalg.norm(X,axis=1)
    tt = np.linalg.norm(T,axis=1) 
Example 32
Project: MKLpy   Author: IvanoLauriola   File: validation.py    GNU General Public License v3.0 5 votes vote down vote up
def check_X_T(X,T):
    #T = X if type(T) == types.NoneType else T
    T = T if T is not None else X
    return X,T 
Example 33
Project: MKLpy   Author: IvanoLauriola   File: validation.py    GNU General Public License v3.0 5 votes vote down vote up
def process_list(X,gen=None, T=None):
    '''if X is a samples matrix, then generate a kernels list according to gen object'''
    x0 = np.array(X[0]) # X può essere pure una lista
    if len(x0.shape) == 2 :
        KL = check_KL(X)  #KL can be a List and not ndarray
    else :
        T = X if type(T) == types.NoneType else T
        gen = gen if gen else HPK_generator(n=10)
        KL = gen.make_a_list(X,T)   # TOTO: use a generator to make a list
    return KL 
Example 34
Project: bbq   Author: ocadotechnology   File: big_query_table_metadata.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, big_query_table):
        assert isinstance(big_query_table, (dict, NoneType))
        self.table_metadata = big_query_table 
Example 35
Project: snape   Author: mbernico   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_random_state(random_state):
    # if it's a seed, return a new seeded RandomState
    if isinstance(random_state, (int, np.int, long, np.long, NoneType)):
        return RandomState(random_state)
    # if it's a RandomState, it's been initialized
    elif isinstance(random_state, RandomState):
        return random_state
    else:
        raise TypeError('cannot seed new RandomState with type=%s'
                        % type(random_state)) 
Example 36
Project: centreon-discovery   Author: Centreon-Community   File: nmap.py    GNU General Public License v2.0 5 votes vote down vote up
def scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', callback=None):
        """
        Scan given hosts in a separate process and return host by host result using callback function

        PortScannerError exception from standard nmap is catched and you won't know about it

        hosts = string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
        ports = string for ports as nmap use it '22,53,110,143-4564'
        arguments = string of arguments for nmap '-sU -sX -sC'
        callback = callback function which takes (host, scan_data) as arguments
        """

        assert type(hosts) in types.StringTypes, 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts))
        assert type(ports) in types.StringTypes+(types.NoneType,), 'Wrong type for [ports], should be a string [was {0}]'.format(type(ports))
        assert type(arguments) in types.StringTypes, 'Wrong type for [arguments], should be a string [was {0}]'.format(type(arguments))
        assert type(callback) in (types.FunctionType, types.NoneType), 'Wrong type for [callback], should be a function or None [was {0}]'.format(type(callback))
        
        def scan_progressive(self, hosts, ports, arguments, callback):
            for host in self._nm.listscan(hosts):
                try:
                    scan_data = self._nm.scan(host, ports, arguments)
                except PortScannerError:
                    pass
                if callback is not None and callable(callback):
                    callback(host, scan_data)
            return

        self._process = Process(
            target=scan_progressive,
            args=(self, hosts, ports, arguments, callback)
            )
        self._process.daemon = True
        self._process.start()
        return 
Example 37
Project: centreon-discovery   Author: Centreon-Community   File: nmap.py    GNU General Public License v2.0 5 votes vote down vote up
def wait(self, timeout=None):
        """
        Wait for the current scan process to finish, or timeout
        """

        assert type(timeout) in (types.IntType, types.NoneType), 'Wrong type for [timeout], should be an int or None [was {0}]'.format(type(timeout))

        self._process.join(timeout)
        return 
Example 38
Project: rpython-lang-scheme   Author: tomoh1r   File: lltype.py    MIT License 5 votes vote down vote up
def typeOf(val):
    try:
        return val._TYPE
    except AttributeError:
        tp = type(val)
        if tp is _uninitialized:
            raise UninitializedMemoryAccess("typeOf uninitialized value")
        if tp is NoneType:
            return Void   # maybe
        if tp is int:
            return Signed
        if tp is long:
            if -maxint-1 <= val <= maxint:
                return Signed
            else:
                return SignedLongLong
        if tp is bool:
            return Bool
        if issubclass(tp, base_int):
            return build_number(None, tp)
        if tp is float:
            return Float
        if tp is r_longfloat:
            return LongFloat
        if tp is str:
            assert len(val) == 1
            return Char
        if tp is unicode:
            assert len(val) == 1
            return UniChar
        if issubclass(tp, Symbolic):
            return val.lltype()
        # if you get a TypeError: typeOf('_interior_ptr' object)
        # here, it is very likely that you are accessing an interior pointer
        # in an illegal way!
        raise TypeError("typeOf(%r object)" % (tp.__name__,)) 
Example 39
Project: rpython-lang-scheme   Author: tomoh1r   File: signature.py    MIT License 5 votes vote down vote up
def _compute_annotation(t, bookkeeper=None):
    from rpython.rtyper.lltypesystem import lltype
    from rpython.rtyper.llannotation import lltype_to_annotation
    if isinstance(t, SomeObject):
        return t
    elif isinstance(t, lltype.LowLevelType):
        return lltype_to_annotation(t)
    elif isinstance(t, list):
        assert len(t) == 1, "We do not support type joining in list"
        listdef = ListDef(bookkeeper, annotation(t[0]), mutated=True, resized=True)
        return SomeList(listdef)
    elif isinstance(t, tuple):
        return SomeTuple(tuple([annotation(i) for i in t]))
    elif isinstance(t, dict):
        assert len(t) == 1, "We do not support type joining in dict"
        result = SomeDict(DictDef(bookkeeper, annotation(t.keys()[0]),
                                annotation(t.values()[0])))
        return result
    elif type(t) is types.NoneType:
        return s_None
    elif extregistry.is_registered(t):
        entry = extregistry.lookup(t)
        entry.bookkeeper = bookkeeper
        return entry.compute_result_annotation()
    else:
        return annotationoftype(t, bookkeeper) 
Example 40
Project: rpython-lang-scheme   Author: tomoh1r   File: signature.py    MIT License 5 votes vote down vote up
def annotationoftype(t, bookkeeper=False):
    from rpython.rtyper import extregistry

    """The most precise SomeValue instance that contains all
    objects of type t."""
    assert isinstance(t, (type, types.ClassType))
    if t is bool:
        return SomeBool()
    elif t is int:
        return SomeInteger()
    elif t is float:
        return SomeFloat()
    elif issubclass(t, str): # py.lib uses annotated str subclasses
        return SomeString()
    elif t is unicode:
        return SomeUnicodeString()
    elif t is types.NoneType:
        return s_None
    elif bookkeeper and extregistry.is_registered_type(t):
        entry = extregistry.lookup_type(t)
        return entry.compute_annotation_bk(bookkeeper)
    elif t is type:
        return SomeType()
    elif bookkeeper and not hasattr(t, '_freeze_'):
        classdef = bookkeeper.getuniqueclassdef(t)
        return SomeInstance(classdef)
    else:
        raise AssertionError("annotationoftype(%r)" % (t,)) 
Example 41
Project: ironpython2   Author: IronLanguages   File: test_descr.py    Apache License 2.0 5 votes vote down vote up
def test_unsubclassable_types(self):
        with self.assertRaises(TypeError):
            class X(types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(object, types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(types.NoneType, object):
                pass
        class O(object):
            pass
        with self.assertRaises(TypeError):
            class X(O, types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(types.NoneType, O):
                pass

        class X(object):
            pass
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType,
        with self.assertRaises(TypeError):
            X.__bases__ = object, types.NoneType
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType, object
        with self.assertRaises(TypeError):
            X.__bases__ = O, types.NoneType
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType, O 
Example 42
Project: py2cpp   Author: mugwort-rc   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def create(field, node, parent=None):
        item = ASTAttrTreeItem(field, node, parent)
        if isinstance(node, list):
            for child in node:
                item.children.append(ASTTreeItem.create(child, parent=item))
        elif not isinstance(node, (str, int, float, types.NoneType)):
            item.children.append(ASTTreeItem.create(node, parent=item))
        return item 
Example 43
Project: MusicML   Author: tonyhong272   File: fetchTracks.py    MIT License 5 votes vote down vote up
def save_sqlite(track_info):
    [track, trackInfoEchoNest, trackInfoLastFM] = track_info
    convert_type_dict = {float:'REAL', unicode:'TEXT', int:'INTEGER', str:'TEXT'}
    
    EN_key_list = trackInfoEchoNest.keys()
    LF_key_list = trackInfoLastFM.keys()
    
    table_columns = []
    column_names = []
    question_mark_sign = []
    for key in EN_key_list:
        if type(trackInfoEchoNest[key]) != types.NoneType:
            column_names.append('EN_' + key)
            table_columns1 = ' '.join(['EN_' + key, convert_type_dict[type(trackInfoEchoNest[key])]])
            table_columns.append(table_columns1)
            question_mark_sign.append('?')
        else:
            trackInfoEchoNest.pop(key)
    
    for key in LF_key_list:
        if type(trackInfoLastFM[key]) != types.NoneType:
            column_names.append('LF_' + key)
            table_columns1 = ' '.join(['LF_' + key, convert_type_dict[type(trackInfoLastFM[key])]])
            table_columns.append(table_columns1)
            question_mark_sign.append('?')
        else:
            trackInfoLastFM.pop(key)

    con = lite.connect('musicdata.db')
    with con:
        cur = con.cursor()
        #cur.execute("DROP TABLE IF EXISTS BoardEntries")
        cur.execute("SELECT ROWID FROM TrackEntries WHERE EN_title = ? and EN_artist_name = ?", (trackInfoEchoNest['title'],trackInfoEchoNest['artist_name']))
        existingEntry=cur.fetchone()
        if existingEntry is None:
            print('saving into database %s, %s'%(trackInfoEchoNest['title'], trackInfoEchoNest['artist_name']))
            single_entry = tuple([str(time.strftime("%Y-%m-%d %H:%M:%S")), track['title'], track['artist']] + trackInfoEchoNest.values() + trackInfoLastFM.values())
            cur.execute('INSERT OR IGNORE INTO TrackEntries(ID, EntryDate, SearchTitle, SearchArtist, ' + ', '.join(column_names) + ') VALUES (NULL, ?,?,?, ' + ', '.join(question_mark_sign)+')', single_entry)
        else:
            print('found in database %s, %s'%(trackInfoEchoNest['title'], trackInfoEchoNest['artist_name']))
    con.close() 
Example 44
Project: chihu   Author: yelongyu   File: encoding.py    GNU General Public License v3.0 5 votes vote down vote up
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    ) 
Example 45
Project: gcp-census   Author: ocadotechnology   File: bigquery_table_metadata.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, table):
        assert isinstance(table, (dict, NoneType))
        self.table = table 
Example 46
Project: blatann   Author: ThomasGerstenberg   File: nrf_driver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ble_gap_conn_param_update(self, conn_handle, conn_params):
        assert isinstance(conn_params, (BLEGapConnParams, NoneType)), 'Invalid argument type'
        if conn_params:
            conn_params = conn_params.to_c()
        return driver.sd_ble_gap_conn_param_update(self.rpc_adapter, conn_handle, conn_params) 
Example 47
Project: blatann   Author: ThomasGerstenberg   File: nrf_driver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ble_gap_authenticate(self, conn_handle, sec_params):
        assert isinstance(sec_params, (BLEGapSecParams, NoneType)), 'Invalid argument type'
        return driver.sd_ble_gap_authenticate(self.rpc_adapter,
                                              conn_handle,
                                              sec_params.to_c() if sec_params else None) 
Example 48
Project: blatann   Author: ThomasGerstenberg   File: nrf_driver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ble_gap_sec_params_reply(self, conn_handle, sec_status, sec_params, sec_keyset):
        assert isinstance(sec_status, BLEGapSecStatus), 'Invalid argument type'
        assert isinstance(sec_params, (BLEGapSecParams, NoneType)), 'Invalid argument type'
        assert isinstance(sec_keyset, BLEGapSecKeyset), 'Invalid argument type'

        return driver.sd_ble_gap_sec_params_reply(self.rpc_adapter,
                                                  conn_handle,
                                                  sec_status.value,
                                                  sec_params.to_c() if sec_params else None,
                                                  sec_keyset.to_c()) 
Example 49
Project: blatann   Author: ThomasGerstenberg   File: nrf_driver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ble_gap_sec_info_reply(self, conn_handle, enc_info=None, irk=None, sign_info=None):
        assert isinstance(enc_info, (BLEGapEncryptInfo, NoneType)), "Invalid argument type"
        assert isinstance(irk, (BLEGapIdKey, NoneType)), "Invalid argument type"
        assert isinstance(sign_info, (BLEGapSignKey, NoneType)), "Invalid argument type"
        if enc_info is not None:
            enc_info = enc_info.to_c()
        if irk is not None:
            irk = irk.to_c().id_info
        if sign_info is not None:
            sign_info = sign_info.to_c()

        return driver.sd_ble_gap_sec_info_reply(self.rpc_adapter, conn_handle, enc_info, irk, sign_info) 
Example 50
Project: blatann   Author: ThomasGerstenberg   File: generic.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, vs_uuid_base=None, uuid_type=None):
        assert isinstance(vs_uuid_base, (list, NoneType)), 'Invalid argument type'
        assert isinstance(uuid_type, (int, long, NoneType)), 'Invalid argument type'
        if vs_uuid_base is None:
            self.base = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
                         0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB]
            self.def_base = True
        else:
            self.base = vs_uuid_base
            self.def_base = False

        if uuid_type is None and self.def_base:
            self.type = driver.BLE_UUID_TYPE_BLE
        else:
            self.type = uuid_type if uuid_type is not None else 0