Exemple #1
0
 def private_key(algorithm, tokens, affordances):
     key_create_time = float('-inf')
     while True:
         if _time() - key_create_time > algorithm.private_key_lifespan:
             key = _b64encode(str(_random()))
             key_create_time = _time()
         yield key
Exemple #2
0
def nonce():
    """
    Returns a new nonce to be used with the Piazza API.
    """
    nonce_part1 = _int2base(int(_time() * 1000), 36)
    nonce_part2 = _int2base(round(_random() * 1679616), 36)
    return "{}{}".format(nonce_part1, nonce_part2)
Exemple #3
0
	def SASLHandler(self, conn, challenge):
		if challenge.getNamespace() != NS_SASL:
			return None
		if challenge.getName() == "failure":
			self.startsasl = "failure"
			try:
				reason = challenge.getChildren()[0]
			except Exception:
				reason = challenge
			self.DEBUG("Failed SASL authentification: %s" % reason, "error")
			raise NodeProcessed()
		elif challenge.getName() == "success":
			self.startsasl = "success"
			self.DEBUG("Successfully authenticated with remote server.", "ok")
			handlers = self._owner.Dispatcher.dumpHandlers()
			self._owner.Dispatcher.PlugOut()
			dispatcher.Dispatcher().PlugIn(self._owner)
			self._owner.Dispatcher.restoreHandlers(handlers)
			self._owner.User = self.username
			raise NodeProcessed()
		incoming_data = challenge.getData()
		chal = {}
		data = decodestring(incoming_data)
		self.DEBUG("Got challenge:" + data, "ok")
		for pair in re_findall('(\w+\s*=\s*(?:(?:"[^"]+")|(?:[^,]+)))', data):
			key, value = [x.strip() for x in pair.split("=", 1)]
			if value[:1] == '"' and value[-1:] == '"':
				value = value[1:-1]
			chal[key] = value
		if "qop" in chal and "auth" in [x.strip() for x in chal["qop"].split(",")]:
			resp = {}
			resp["username"] = self.username
			resp["realm"] = self._owner.Server
			resp["nonce"] = chal["nonce"]
			cnonce = ""
			for i in xrange(7):
				cnonce += hex(int(_random() * 65536 * 4096))[2:]
			resp["cnonce"] = cnonce
			resp["nc"] = ("00000001")
			resp["qop"] = "auth"
			resp["digest-uri"] = "xmpp/" + self._owner.Server
			A1 = C([H(C([resp["username"], resp["realm"], self.password])), resp["nonce"], resp["cnonce"]])
			A2 = C(["AUTHENTICATE", resp["digest-uri"]])
			response = HH(C([HH(A1), resp["nonce"], resp["nc"], resp["cnonce"], resp["qop"], HH(A2)]))
			resp["response"] = response
			resp["charset"] = "utf-8"
			sasl_data = ""
			for key in ("charset", "username", "realm", "nonce", "nc", "cnonce", "digest-uri", "response", "qop"):
				if key in ("nc", "qop", "response", "charset"):
					sasl_data += "%s=%s," % (key, resp[key])
				else:
					sasl_data += "%s=\"%s\"," % (key, resp[key])
			node = Node("response", attrs={"xmlns": NS_SASL}, payload=[encodestring(sasl_data[:-1]).replace("\r", "").replace("\n", "")])
			self._owner.send(node.__str__())
		elif "rspauth" in chal:
			self._owner.send(Node("response", attrs={"xmlns": NS_SASL}).__str__())
		else:
			self.startsasl = "failure"
			self.DEBUG("Failed SASL authentification: unknown challenge", "error")
		raise NodeProcessed()
Exemple #4
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.wander_angle = randint(0, 359)
     self.velocity = Vector(-1, 0).rotate(self.wander_angle).scale(
         self.speed * _random())
     self.state = state.wander
     self.target = None
Exemple #5
0
def build_rand_real_data(size, n):
    x = []
    for i in range(size):
        y = []
        for j in range(n):
            y.append(_random())
        x.append(y)
    return x
Exemple #6
0
	def SASLHandler(self,conn,challenge):
		""" Perform next SASL auth step. Used internally. """
		if challenge.getNamespace()<>NS_SASL: return
		if challenge.getName()=='failure':
			self.startsasl='failure'
			try: reason=challenge.getChildren()[0]
			except: reason=challenge
			self.DEBUG('Failed SASL authentification: %s'%reason,'error')
			raise NodeProcessed
		elif challenge.getName()=='success':
			self.startsasl='success'
			self.DEBUG('Successfully authenticated with remote server.','ok')
			handlers=self._owner.Dispatcher.dumpHandlers()
			self._owner.Dispatcher.PlugOut()
			dispatcher.Dispatcher().PlugIn(self._owner)
			self._owner.Dispatcher.restoreHandlers(handlers)
			self._owner.User=self.username
			raise NodeProcessed
########################################3333
		incoming_data=challenge.getData()
		chal={}
		data=decodestring(incoming_data)
		self.DEBUG('Got challenge:'+data,'ok')
		for pair in re_findall('(\w+\s*=\s*(?:(?:"[^"]+")|(?:[^,]+)))',data):
			key,value=[x.strip() for x in pair.split('=', 1)]
			if value[:1]=='"' and value[-1:]=='"': value=value[1:-1]
			chal[key]=value
		if chal.has_key('qop') and 'auth' in [x.strip() for x in chal['qop'].split(',')]:
			resp={}
			resp['username']=self.username
			resp['realm']=self._owner.Server
			resp['nonce']=chal['nonce']
			cnonce=''
			for i in range(7):
				cnonce+=hex(int(_random()*65536*4096))[2:]
			resp['cnonce']=cnonce
			resp['nc']=('00000001')
			resp['qop']='auth'
			resp['digest-uri']='xmpp/'+self._owner.Server
			A1=C([H(C([resp['username'],resp['realm'],self.password])),resp['nonce'],resp['cnonce']])
			A2=C(['AUTHENTICATE',resp['digest-uri']])
			response= HH(C([HH(A1),resp['nonce'],resp['nc'],resp['cnonce'],resp['qop'],HH(A2)]))
			resp['response']=response
			resp['charset']='utf-8'
			sasl_data=''
			for key in ['charset','username','realm','nonce','nc','cnonce','digest-uri','response','qop']:
				if key in ['nc','qop','response','charset']: sasl_data+="%s=%s,"%(key,resp[key])
				else: sasl_data+='%s="%s",'%(key,resp[key])
########################################3333
			node=Node('response',attrs={'xmlns':NS_SASL},payload=[encodestring(sasl_data[:-1]).replace('\r','').replace('\n','')])
			self._owner.send(node.__str__())
		elif chal.has_key('rspauth'): self._owner.send(Node('response',attrs={'xmlns':NS_SASL}).__str__())
		else:
			self.startsasl='failure'
			self.DEBUG('Failed SASL authentification: unknown challenge','error')
		raise NodeProcessed
Exemple #7
0
 def _generate_genotype_for_trial(self, target_index, mutagen_indices,
                                  dimensions):
     target = self.population[target_index]
     D = _randint(0, dimensions - 1)
     return [
         self._calculate_mutagen_value(mutagen_indices, genotype_index)
         if _random() < self.CR or genotype_index == D else
         target.genotype[genotype_index]
         for genotype_index in range(dimensions)
     ]
Exemple #8
0
    def producer(self, count=100, stop=None):
        from random import random as _random
        from time import sleep as _sleep

        counter = 0
        while counter < count:
            self.pipe.put(counter)
            _sleep(_random() * 0.00001)
            counter += 1
        self.pipe.done_sending()
Exemple #9
0
    def producer(self, count = 100, stop = None):
        from random import random as _random
        from time import sleep as _sleep

        counter = 0
        while counter < count:
            self.pipe.put(counter)
            _sleep(_random() * 0.00001)
            counter = counter + 1
        self.pipe.done_sending()
Exemple #10
0
 def wrapped(expiry=None):
     if expiry is None:
         # we want the next expiry
         return now() + timeout
     else:
         # we want to know if we should expire and its expiry time
         start = expiry - timeout
         delta = now() - start
         threshold = delta/timeout
         cache = last + timeout if _random() < threshold else False
         return cache
Exemple #11
0
def evolution_strategy(m,
                       axis=0,
                       mu=10,
                       l=2,
                       epochs=50,
                       n=1,
                       tie=0.1,
                       method='swap',
                       history=False,
                       verbose=False):
    """ Use evolution strategy to search the best centrality ranking.

    Return the best ranking (and the best score of each generation if needed).

    Args:
        axis: candidates axis.
        mu: population size.
        l: mu * l = offspring size.
        epochs: number of iterations.
        n: number of swaps performed during a single mutation.
        tie: probability of performing a tie instead of a swap during mutation process.
        method: method used to compute centrality of the ranking.
        history: if True, return a tuple (ranking, history).
        verbose: if True, plot the learning curve.
    """
    r = np.arange(m.shape[axis])
    h = []
    population = [sorted(r, key=lambda k: _random())
                  for _ in range(mu)]  # mu random ranked ballots
    best_ranking = population[0]  # initialize best_ranking
    for epoch in tqdm(range(epochs)):
        offspring = [random_swap(x, n=n, tie=tie) for x in population * l
                     ]  # random swaps to generate new ranked ballots
        offspring.append(
            best_ranking
        )  # add the previous best to the offspring to avoid losing it if no children beat it
        scores = [
            centrality(m, child, axis=axis, method=method)
            for child in offspring
        ]  # compute fit function
        idx_best = np.argsort(scores)[len(scores) - mu:]
        population = list(
            np.array(offspring)[idx_best])  # select the mu best ballots
        argmax = idx_best[-1]
        best_ranking = offspring[argmax]
        h.append(scores[argmax])  # collect best score
    r = process_vote(m, best_ranking, axis=1 - axis)
    if verbose:
        show_learning_curve(h)
        print('Best centrality score: {}'.format(h[-1]))
    if history:
        return r, h  # return the best ranking and its score
    return r
Exemple #12
0
	def getLargestChildNew(self):
		"""Randomly Choose a child based on size"""
		sum = 0	
		for child in self.children:
			sum += child.length
		
		randNum = _random()
		previous = 0
		prob = 0
		for child in self.children:
			prob += child.length/float(sum)
			if randNum >= previous and prob > randNum :
				return child			
			previous = prob		
		return self.children[-1]
Exemple #13
0
def _try_to_say_something(bot, message):
    """Find a response and maybe say something."""
    try:
        room = _rooms[message.chat_id]

        previous_messages = room['dict'].keys()
        similar_messages = _get_close_matches(message.text, previous_messages)

        if len(similar_messages) > 0 and _random() < _talkativeness:
            choosen_message = _choice(similar_messages)
            response = room['dict'][choosen_message]
            bot.send_message(message.chat_id, response)
            _update_last_message(room, response, 'bot')

    except TypeError as te:
        if "'NoneType' object is not iterable" in str(te):
            # this happens when message.text==None
            return

        else:
            raise
Exemple #14
0
def makeRandomSet(weightedSet):
	"""Returns a new trainingSet by choosing examples based on weight probablitites""" 
	newtrainingSet = []
	
	#Make a list starting with zero and ending with MAX_INT
	#Where all of values inbetween are the probs of choosing this element
	probs = [0]
	for ex in weightedSet:		
		probs.append(ex.weight + probs[-1])
	
	probs.append(_MAX_INT)
		
	for i in range(len(weightedSet)): #Get N new smaples
		randNum = _random()
		for j in range(len(probs) - 1 ):	
			if randNum >= probs[j] and probs[j+1] > randNum : 
				newtrainingSet.append(boostExample(
					LabeledExample(weightedSet[j-1],label=weightedSet[j-1].label) ,weightedSet[j-1].weight) )
				break
		
	
	return newtrainingSet
    def select_model(self, **kwargs):
        '''
        Select a model to serve

        Returns
        --------
        model_name : str
            The model identifier that is going to be served
        '''
        r = _random()
        ratio_sum = 0

        # select last one by default
        return_index = len(self._models) - 1

        for (index, ratio) in enumerate(self.ratios):
            ratio_sum += ratio
            if r <= ratio_sum:
                return_index = index
                break

        self._serve_counts[return_index] += 1
        return self._models[return_index]
Exemple #16
0
    def select_model(self, **kwargs):
        '''
        Select a model to serve

        Returns
        -------
        model_name : str
            The model identifier that is going to be served
        '''
        r = _random()
        ratio_sum = 0

        # select last one by default
        return_index = len(self._models) - 1

        for (index, ratio) in enumerate(self.ratios):
            ratio_sum += ratio
            if r <= ratio_sum:
                return_index = index
                break

        self._serve_counts[return_index] += 1
        return self._models[return_index]
Exemple #17
0
    def select_model(self, **kwargs):
        '''
        Select a model to serve

        Returns
        -------
        model_name : str
            The model identifier that is going to be served
        '''
        r = _random()
        if r > self.epsilon:
            # exploitation
            max_value = max(self._values)

            # Randomly pick among those that have highest value
            indices = [i for i, x in enumerate(self._values) if x == max_value]
            r1 = _randrange(0, len(indices))
            return_index = indices[r1]
        else:
            # exploration
            return_index = _randrange(len(self._values))

        self._serve_counts[return_index] += 1
        return self._models[return_index]
    def select_model(self, **kwargs):
        '''
        Select a model to serve

        Returns
        --------
        model_name : str
            The model identifier that is going to be served
        '''
        r = _random()
        if r > self.epsilon:
            # exploitation
            max_value = max(self._values)

            # Randomly pick among those that have highest value
            indices = [i for i, x in enumerate(self._values) if x == max_value]
            r1 = _randrange(0, len(indices))
            return_index = indices[r1]
        else:
            # exploration
            return_index = _randrange(len(self._values))

        self._serve_counts[return_index] += 1
        return self._models[return_index]
Exemple #19
0
def random():
    """Return a random number on the interval [0, 1). 
    Identical to random() from the random module."""
    return _random()
Exemple #20
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.wander_angle = randint(0, 359)
     self.velocity = Vector(-1, 0).rotate(self.wander_angle).scale(self.speed * _random())
     self.state = state.wander
     self.target = None
Exemple #21
0
    def SASLHandler(self, conn, challenge):
        """
		Perform next SASL auth step. Used internally.
		"""
        if challenge.getNamespace() != NS_SASL:
            return None
        if challenge.getName() == "failure":
            self.startsasl = "failure"
            try:
                reason = challenge.getChildren()[0]
            except Exception:
                reason = challenge
            self.DEBUG("Failed SASL authentification: %s" % reason, "error")
            raise NodeProcessed()
        elif challenge.getName() == "success":
            self.startsasl = "success"
            self.DEBUG("Successfully authenticated with remote server.", "ok")
            handlers = self._owner.Dispatcher.dumpHandlers()
            self._owner.Dispatcher.PlugOut()
            dispatcher.Dispatcher().PlugIn(self._owner)
            self._owner.Dispatcher.restoreHandlers(handlers)
            self._owner.User = self.username
            raise NodeProcessed()
        incoming_data = challenge.getData()
        chal = {}
        data = decodestring(incoming_data)
        self.DEBUG("Got challenge:" + data, "ok")
        for pair in re_findall('(\w+\s*=\s*(?:(?:"[^"]+")|(?:[^,]+)))', data):
            key, value = [x.strip() for x in pair.split("=", 1)]
            if value[:1] == '"' and value[-1:] == '"':
                value = value[1:-1]
            chal[key] = value
        if "qop" in chal and "auth" in [
                x.strip() for x in chal["qop"].split(",")
        ]:
            resp = {}
            resp["username"] = self.username
            resp["realm"] = self._owner.Server
            resp["nonce"] = chal["nonce"]
            cnonce = ""
            for i in xrange(7):
                cnonce += hex(int(_random() * 65536 * 4096))[2:]
            resp["cnonce"] = cnonce
            resp["nc"] = ("00000001")
            resp["qop"] = "auth"
            resp["digest-uri"] = "xmpp/" + self._owner.Server
            A1 = C([
                H(C([resp["username"], resp["realm"], self.password])),
                resp["nonce"], resp["cnonce"]
            ])
            A2 = C(["AUTHENTICATE", resp["digest-uri"]])
            response = HH(
                C([
                    HH(A1), resp["nonce"], resp["nc"], resp["cnonce"],
                    resp["qop"],
                    HH(A2)
                ]))
            resp["response"] = response
            resp["charset"] = "utf-8"
            sasl_data = ""
            for key in ("charset", "username", "realm", "nonce", "nc",
                        "cnonce", "digest-uri", "response", "qop"):
                if key in ("nc", "qop", "response", "charset"):
                    sasl_data += "%s=%s," % (key, resp[key])
                else:
                    sasl_data += "%s=\"%s\"," % (key, resp[key])
            node = Node("response",
                        attrs={"xmlns": NS_SASL},
                        payload=[
                            encodestring(sasl_data[:-1]).replace("\r",
                                                                 "").replace(
                                                                     "\n", "")
                        ])
            self._owner.send(node.__str__())
        elif "rspauth" in chal:
            self._owner.send(
                Node("response", attrs={
                    "xmlns": NS_SASL
                }).__str__())
        else:
            self.startsasl = "failure"
            self.DEBUG("Failed SASL authentification: unknown challenge",
                       "error")
        raise NodeProcessed()
Exemple #22
0
def random(n=1): return _random() * n


# def random_range_i(fro,to): return randint(fro,to)
def randomfloat=random.uniform
Exemple #23
0
def random():
    return (_random() * 2 - 1, _random() * 2 - 1, _random() * 2 - 1)
Exemple #24
0
def random():
	return (_random()*2-1,_random()*2-1,_random()*2-1)
Exemple #25
0
def randMom(m):
    """Return a random number distributed uniformly on the interval (-m, m)."""
    return m * (2 * _random() - 1)
Exemple #26
0
def random(request):
    return JsonResponse({'random': _random()})
Exemple #27
0
    def SASLHandler(self, conn, challenge):
        """ Perform next SASL auth step. Used internally. """
        if challenge.getNamespace() <> NS_SASL: return
        if challenge.getName() == 'failure':
            self.startsasl = 'failure'
            try:
                reason = challenge.getChildren()[0]
            except:
                reason = challenge
            self.DEBUG('Failed SASL authentification: %s' % reason, 'error')
            raise NodeProcessed
        elif challenge.getName() == 'success':
            self.startsasl = 'success'
            self.DEBUG('Successfully authenticated with remote server.', 'ok')
            handlers = self._owner.Dispatcher.dumpHandlers()
            self._owner.Dispatcher.PlugOut()
            dispatcher.Dispatcher().PlugIn(self._owner)
            self._owner.Dispatcher.restoreHandlers(handlers)
            self._owner.User = self.username
            raise NodeProcessed
########################################3333
        incoming_data = challenge.getData()
        chal = {}
        data = decodestring(incoming_data)
        self.DEBUG('Got challenge:' + data, 'ok')
        for pair in re_findall('(\w+\s*=\s*(?:(?:"[^"]+")|(?:[^,]+)))', data):
            key, value = [x.strip() for x in pair.split('=', 1)]
            if value[:1] == '"' and value[-1:] == '"': value = value[1:-1]
            chal[key] = value
        if chal.has_key('qop') and 'auth' in [
                x.strip() for x in chal['qop'].split(',')
        ]:
            resp = {}
            resp['username'] = self.username
            resp['realm'] = self._owner.Server
            resp['nonce'] = chal['nonce']
            cnonce = ''
            for i in range(7):
                cnonce += hex(int(_random() * 65536 * 4096))[2:]
            resp['cnonce'] = cnonce
            resp['nc'] = ('00000001')
            resp['qop'] = 'auth'
            resp['digest-uri'] = 'xmpp/' + self._owner.Server
            A1 = C([
                H(C([resp['username'], resp['realm'], self.password])),
                resp['nonce'], resp['cnonce']
            ])
            A2 = C(['AUTHENTICATE', resp['digest-uri']])
            response = HH(
                C([
                    HH(A1), resp['nonce'], resp['nc'], resp['cnonce'],
                    resp['qop'],
                    HH(A2)
                ]))
            resp['response'] = response
            resp['charset'] = 'utf-8'
            sasl_data = ''
            for key in [
                    'charset', 'username', 'realm', 'nonce', 'nc', 'cnonce',
                    'digest-uri', 'response', 'qop'
            ]:
                if key in ['nc', 'qop', 'response', 'charset']:
                    sasl_data += "%s=%s," % (key, resp[key])
                else:
                    sasl_data += '%s="%s",' % (key, resp[key])


########################################3333
            node = Node('response',
                        attrs={'xmlns': NS_SASL},
                        payload=[
                            encodestring(sasl_data[:-1]).replace('\r',
                                                                 '').replace(
                                                                     '\n', '')
                        ])
            self._owner.send(node.__str__())
        elif chal.has_key('rspauth'):
            self._owner.send(
                Node('response', attrs={
                    'xmlns': NS_SASL
                }).__str__())
        else:
            self.startsasl = 'failure'
            self.DEBUG('Failed SASL authentification: unknown challenge',
                       'error')
        raise NodeProcessed
Exemple #28
0
def build_rand_nparray(size):
    x = []
    for i in range(size):
        x.append(_random())
    return _np_array(x)
Exemple #29
0
def rand(n=1): return _random() * n


def random(n=1): return _random() * n
Exemple #30
0
def random(request):
    """the function of random"""
    return JsonResponse({'random': _random()})
Exemple #31
0
def uniform(a=0, b=1):
    return _random() * (b - a) + a
Exemple #32
0
def rand(n=1): return _random() * n


def random(n=1): return _random() * n
Exemple #33
0
def random(n=1): return _random() * n


def random_array(l): return np.random.rand(l)  # (0,1) x,y don't work ->
Exemple #34
0
def random(n=1): return _random() * n


def random_array(l): return np.random.rand(l)  # (0,1) x,y don't work ->
Exemple #35
0
def random(n):
	return _random() % (n + 1)
Exemple #36
0
 def func(_):
     return _random(min_seconds, max_seconds)