Example #1
0
 def getValue(self, fraction, interval, value=None, **kw):
     if value is not None:
         if fraction <= 0.0 or fraction >= 1.0:
             return value
         else:
             from random import random as r
             return [value[0] + r(), value[1] + r(), value[2] + r()]
 def getValue(self, fraction, interval, value=None, **kw):
     if value is not None:
         if fraction <= 0.0 or fraction >= 1.0:
             return value
         else:
             from random import random as r
             return [value[0]+r(), value[1]+r(), value[2]+r()]
Example #3
0
def addSounds(name, amount, soundPath):
    base = AS.from_wav(name)
    sounds = list(listdir(soundPath))

    length = len(base) / 1000
    amount = max(1, int(amount * length / 60))
    intv = length / amount
    t, i = 0, 0
    while i < amount:
        t = u(t, t + 2 * intv) % length
        sfx = randomSound(sounds, soundPath)
        pos = int(t * 1000)
        if r(7) == 2:
            repeats = r(4) + 1
            for o in range(repeats):
                base = base.overlay(sfx, position=pos + o * 1250)
                t += 1
        else:
            base = base.overlay(sfx, position=pos)
        i += 1

    exportName = f"{getDir(name)}/SFX{getName(name)}"

    base.export(exportName, format="wav")
    remove(name)
    rename(exportName, name)
Example #4
0
def GenerarListas():
    '''Genera las dos listas pedidas'''
    m = r(1, 10)
    n = r(1, 10)
    lista1 = [r(1, 50) for i in range(m)]
    lista2 = [r(1, 50) for z in range(n)]
    return lista1, lista2
Example #5
0
    def populateAdvantage(self, num):
        self.population += num
        for i in range(0, num):
            x = r(0, len(self.list) - 1)
            y = r(0, len(self.list) - 1)

            self.list[max(x, y)] += 1
Example #6
0
 def _search_medium(self,list_positions,admin,word_list):
     """
     Funcion similar a _search_easy el unico cambio es que la IA primero busca si existen posiciones 
     posibles sin descuentos de puntaje y de no haber ingresa la palabra en una posicion con descuentos de puntaje
     """
     if word_list == []:
         return None,None
     word_act = word_list[-1]
     ls_aux =[]
     for i in list_positions:
         if len(i) >= len(word_act):
             for j in range(len(i)-len(word_act)):
                 ok = True
                 for k in i[j:j+len(word_act)]:
                     if k in admin.get_bad_positions():
                         ok = False
                 if ok:
                     ls_aux.append(i)
     if ls_aux == []:
         for i in list_positions:
             if len(i) >= len(word_act):
                 ls_aux.append(i)
     if ls_aux != []:
         ls_def = ls_aux[r(0,len(ls_aux)-1)]
         st_pos = r(0,(len(ls_def)-1)-(len(word_act)-1))
         return ls_def[st_pos:st_pos+len(word_act)],word_act
     else:
         serach_medium(list_positions,admin,word_list[1:])
 def gen(self):
     x1, y1 = r()*self.diag.x-self.diag.x/2, r()*self.diag.y-self.diag.y/2
     while not self.s.sat(x1,y1):
         x1, y1 = r()*self.diag.x-self.diag.x/2, r()*self.diag.y-self.diag.y/2
     theta = r()*2*pi
     x2, y2 = self.mod(x1+cos(theta)), self.mod(y1+sin(theta))
     return x1, y1, x2, y2
Example #8
0
 def test_unit_vector(self):
     for _ in range(100):
         a, b, c = r(-10, 10), r(-10, 10), r(-10, 10)
         vec = Vec3(a, b, c)
         square_root = vec.length
         res = Vec3(a / square_root, b / square_root, c / square_root)
         self.assertEqual(res, vec.unit_vector())
Example #9
0
 def add_rects(self, label, wid, count, *largs):
     label.text = str(int(label.text) + count)
     with wid.canvas:
         for x in range(count):
             Color(r(), 1, 1, mode='hsv')
             Rectangle(pos=(r() * wid.width + wid.x,
                            r() * wid.height + wid.y), size=(10, 10))
Example #10
0
    def on_loop(self):

        for i in range(2, self.player.length):
            if self.game.isCollision(self.player.x[0], self.player.y[0],
                                     self.player.x[i], self.player.y[i], 15):
                #print('You lose! Score: ' + str(self.player.length - 1))
                self.restart()
                break
                exit(0)

        #for i in range(0, self.player.length):
        if self.game.isCollision(self.apple.pos_x, self.apple.pos_y,
                                 self.player.x[0], self.player.y[0], 25):
            self.apple.pos_x = r(15, self.screen_width - 25)
            self.apple.pos_y = r(15, self.screen_height - 25)
            self.player.length += 1

        if self.player.x[0] + 20 >= self.screen_width or self.player.x[
                0] + 0 <= 0:
            #print('YOU DIED. Score: ' + str(self.player.length - 1))
            self.restart()

            exit()

        if self.player.y[0] + 20 >= self.screen_height or self.player.y[
                0] + 0 <= 0:
            #print('YOU DIED. Score: ' + str(self.player.length - 1))
            self.restart()

            exit()
def get_conven_pass():
    part1, part2 = '', ''

    for i in range(length - 4):
        a = r(0, 3)
        b = c(data[a])
        part1 += b

    for i in range(0, 4):  # part two of string to ensure
        b = c(data[i])  # each category has at least
        part2 += b  # one element in the password

    temp = list(part1)

    while (part2 != ''):
        t = part2[0]  # each character of part2 being
        part2 = part2[1:]  # added into random positions
        temp.insert(r(0, len(temp)), t)  # of part1

    final = ''

    for i in temp:
        final += str(i)

    return (final)
Example #12
0
    def test_badCase2(self):
        #initialisation
        b = r(0,5)*[0]
        b0 = len(b)*[0]
        for i in range(len(b)):
            b[i] = r(0,100)
            b0[i] = b[i]
        a = r(6,10)*[0]
        a0 = len(a)*[0]
        for i in range(len(a)):
            a[i] = r(0,100)
            a0[i] = a[i]
        #execution + gestion fichier-out
        orig = sys.stdout
        with open('redirect_student.txt', 'w') as f:
            sys.stdout = f
            q.inverse(a, b)
        sys.stdout = orig
        #verification
        n = 0
        with open('redirect_student.txt', 'r') as f:
            for line in f:
                n += 1
        if n>1:
            self.fail(_("Votre code affiche plus que 1 ligne d'erreur quand la longueur de b est inférieur à celle de a."))

        if n==0:
            self.fail(_("Votre code n´affiche pas de ligne d'erreur quand la longueur de b est inférieur à celle de a."))
Example #13
0
def GenerarLista():
    '''Crea una lista de 10 a 50 elementos con valores entre 0 y 100'''
    num = r(10, 50)
    while num % 2 != 0:
        num = r(10, 50)
    lista = [r(0, 100) for i in range(num)]
    return lista
Example #14
0
 def _create_star(self):
     star = Star(self)
     x_loc = r(0, self.settings.screen_width)
     y_loc = r(0, self.settings.screen_height)
     star.rect.x = x_loc
     star.rect.y = y_loc
     self.stars.add(star)
def pedra1():
    s(0.5)

    if r(1, 3) == 1:
        output = Label(Tela, width=18, text='Empatou!!\n Também escolhi Pedra')
        output['bg'] = 'red'

        output.place(x=140, y=80)
    elif r(1, 3) == 2:
        output = Label(Tela, width=18, text='Ganhei!!\n Eu escolhi Papel')
        output['bg'] = 'red'

        output.place(x=140, y=80)

        global pc

        pc += 1
        pc_ = Label(Tela, text='Você: {}'.format(pc))
        pc_['bg'] = 'red'
        pc_.place(x=150, y=200)

    else:
        output = Label(Tela, width=18, text='Perdi!!\n Eu escolhi Tesoura')
        output['bg'] = 'red'

        output.place(x=140, y=80)

        global voce

        voce += 1
        voce_ = Label(Tela, text='Você: {}'.format(voce))
        voce_['bg'] = 'red'
        voce_.place(x=15, y=200)
Example #16
0
 def _execute_a_render_mission(self, mission):
     """handle Model mission and do the render"""
     if mission['add_rect']:
         with self.canvas:
             Color(r(), 1, 1, mode='hsv')
             Rectangle(pos=(r() * self.width,
                 r() * self.height), size=(20, 20))
Example #17
0
 def random_direction(self):
     if r(0, 10) > 7:
         return [north, south, east, west][r(
             0, 3
         )]  #This runs is where the random NPC's decide to move or not,
     else:  #they do an if statment with a random number generator, it has
         return None  #a 3/10 chance to move the character and then tries to go a
Example #18
0
 def test_squared_length(self):
     for _ in range(100):
         a, b, c = r(-10, 10), r(-10, 10), r(-10, 10)
         tmp = a * a + b * b + c * c
         vec = Vec3(a, b, c)
         res = vec.squared_length()
         self.assertEqual(res, tmp)
Example #19
0
def draw_rv():
    segments = []
    for i in range(10):
        segments.append(sg.Segment2(sg.Point2(r(), r()),
                                    sg.Point2(r(), r())))

    intersections = []
    for s1, s2 in itertools.permutations(segments, 2):
        isect = sg.intersection(s1, s2)
        if isect:
            intersections.append(isect)

    for s in segments:
        draw(s)
    for i in intersections:
        draw(i)

    HEIGHT = 10
    THETA_H = 45
    THETA_V = 60
    
    pt_h_r = sg.Point2(HEIGHT * math.tan(THETA_H * math.pi / 180), 0)
    pt_v_r = sg.Point2(HEIGHT * math.tan(THETA_V * math.pi / 180), 0)
    print(dir(sg.Transformation2))
    pt_v_r = pt_v_r.transform(sg.Transformation2.Rotation(3, math.pi/2))
    pt_r = sg.Segment2(pt_h_r, pt_v_r)
    draw(pt_h_r)
    draw(pt_v_r)
    draw(pt_r)
    plt.show()
 def init(self):
     self.m = 1000000
     self.arr = [None] * self.m
     self.p = 1000003
     self.n = 0
     self.a = r(1, self.p - 1)
     self.b = r(0, self.p - 1)
Example #21
0
def ab():
    c()
    a = ['rock', 'paper', 'scissors']
    pc = a[r(0, 2)]
    user = False
    while user == False:
        user = input("rock,paper,scissors?")
        if user == pc:
            print("adthe match id..ith tie aayi poi ;(")
            exit()
        elif user == "rock":
            if pc == "paper":
                print("You lose!", pc, "ninte", user, "pothinj!")
                exit()
            else:
                print("You win!", user, pc, "pothinj")
        elif user == "paper":
            if pc == "scissors":
                print("You lose!", pc, "ninte", user, "murich")
                exit()
            else:
                print("You win!", user, pc, "moodi")
        elif user == "scissors":
            if pc == "rock":
                print("You lose...", pc, user, "potich")
                exit()
            else:
                print("You win!", user, pc, "murich")
        else:
            print("pottaah!..spelling correct aak")
        user = False
        pc = a[r(0, 2)]
def test(x,y,reps,dyct):
    #bad count
    bad = 0
    for rep in range(reps):
        #first pair of points
        x1 = r()*x
        y1 = r()*y
        #choose a random angle/direction to move
        theta = r()*2*pi
        #second point one unit away
        x2 = (x1+cos(theta))%x-x/2
        y2 = (y1+sin(theta))%y-y/2
        #fix to be centered at 0
        x1-=x/2
        y1-=y/2
        #check which region contains the first point
        for s in dyct:
            if s.sat(x1,y1):
                c1 = dyct[s]
                break
        #check which region contains the second point
        for s in dyct:
            if s.sat(x2,y2):
                c2 = dyct[s]
                break
        #if the colors are the same, increase the count
        #print(c1,c2)
        if c1 == c2:
            bad +=1
    return float(bad)/reps, bad
Example #23
0
 async def haircmd(self, message):
     """Волос!"""
     reply = await message.get_reply_message()
     if not reply:
         return await message.edit("Нет реплая на картинку/стикер.")
     if reply.photo or reply.file.ext == ".webp":
         im = Image.open(
             io.BytesIO(await message.client.download_file(reply, bytes)))
         draw = ImageDraw.Draw(im)
         w, h = im.size
         x = r(w)
         y = r(h)
         b = r(300)
         c = r(550)
         a = r(350)
         draw.arc((x, y, x + b, y + c), a, 180 + a, fill="black", width=1)
         out = io.BytesIO()
         if reply.file.ext == ".webp":
             out.name = "witHair.webp"
         else:
             out.name = "witHair.png"
         im.save(out)
         out.seek(0)
         await message.client.send_file(
             message.to_id, out, reply_to=reply.id if reply else None)
         await message.delete()
     else:
         return await message.edit("Это не картинка/стикер.")
 def el_boton_01_clicked(self):
     print("ME HICIERON CLIC BTN01")
     color = (r(0, 255), r(0, 255), r(0, 255))
     print(color)
     color_hex = "#%02x%02x%02x" % color
     print(color_hex)
     self.setStyleSheet("background-color:" + color_hex + ";")
Example #25
0
def bLogin():
    nMayor = 10
    nombre = nEntrada.get()
    apellido = aEntrada.get()
    bronce = r(1, 5)
    plata = r(1, 5)
    oro = r(1, 5)
    nombres.append(nombre)
    apellidos.append(apellido)
    if var.get() == "Perú":
        peru[0] += bronce
        peru[1] += plata
        peru[2] += oro
    elif var.get() == "Brasil":
        brasil[0] += bronce
        brasil[1] += plata
        brasil[2] += oro
    elif var.get() == "Chile":
        chile[0] += bronce
        chile[1] += plata
        chile[2] += oro
    elif var.get() == "Argentina":
        argentina[0] += bronce
        argentina[1] += plata
        argentina[2] += oro
    elif var.get() == "Uruguay":
        uruguay[0] += bronce
        uruguay[1] += plata
        uruguay[2] += oro
    #Esto solo es para ver si los datos están siendo ingresados, no quedarán en la presentación final
    """print(peru)
Example #26
0
 def add_rects(self, label, wid, count, *largs):
     label.text = str(int(label.text) + count)
     with wid.canvas:
         for x in xrange(count):
             Color(r(), 1, 1, mode='hsv')
             Rectangle(pos=(r() * wid.width + wid.x,
                            r() * wid.height + wid.y), size=(20, 20))
Example #27
0
 def dataset():
     v = []
     for _ in range(size):
         x = [round(r() - r(), 2) for __ in range(length)]
         y = round(sum([i**2 for i in x]) + (r() - r()) * noise, 2)
         v += [{'x': x, 'y': [y]}]
     return DataSet(v)
Example #28
0
def add_noise(chromosome, sigma):
    """
    This is a function that will add some noise to the chromosome.
    """
    new_x = chromosome[0] + (r() - 0.5) * sigma
    new_y = chromosome[1] + (r() - 0.5) * sigma
    return new_x, new_y
Example #29
0
 def add_rects(self, wid, count, *largs):
     with wid.canvas:
         for x in range(count):
             Color(r(), 1, 1, mode='hsv')
             Rectangle(pos=(r() * wid.width + wid.x,
                            r() * wid.height + wid.y),
                       size=(20, 20))
Example #30
0
    def loop(self):
        # Input Suggestion

        from random import randint as r
        import os
        while True:
            os.system('clear')

            # Display status
            # print(80 * '/')
            # print(self.solution)
            # for player in self.hidden_players:
            #     self.player_displayer.display_player(player)

            players = [self.players[i] for i in range(
                len(self.players)) if i != self.suggesting_player_index]
            for player in players:
                self.player_displayer.display_player(player)

            suggestion = {
                CardType.SUSPECT: SUSPECTS[r(0, 5)],
                CardType.WEAPON: WEAPONS[r(0, 5)],
                CardType.ROOM: ROOMS[r(0, 8)],
            }
            print('Turn', self.turn_number)

            turn_start_summary = ' '.join([
                'Player',
                str(self.suggesting_player_index + 1),
                'Suggestion:',
                str(suggestion)
            ])
            print(turn_start_summary)

            acting_players = self.get_acting_players(
                self.players[
                    self.suggesting_player_index
                ]
            )
            for player in acting_players:
                ps = None
                while ps not in ['p', 's', 'x']:
                    print(player.name)
                    ps = input('p/s: ')

                if ps == 's':
                    self.analyzer.player_stopped(player, suggestion)
                    break

                if ps == 'p':
                    self.analyzer.player_passed(player, suggestion)

                if ps == 'x':
                    sys.exit()

            self.turn_number += 1
            self.suggesting_player_index += 1
            if self.suggesting_player_index >= len(self.players):
                self.suggesting_player_index = 0
Example #31
0
def run(parent):
	try:
		play(‘happy_otter.mp3’)
  		move_and_wait(RARM=r(0, 10))	
  		move_and wait(RARM=r(90, 100))
  		move_to(RARM=r(0, 10))
	finally:
		parent.exit()
Example #32
0
 def __init__(self, i):
     self.i = i
     self.x = r(50, screen_x - 50)
     self.y = r(50, screen_y - 50)
     self.h = 0
     self.f = 0
     self.g = 0
     self.neighbors = []
    def get_random_move(self):
        from random import randint as r

        print('making random move')
        moveX = r(0,2)
        moveY = r(0,2)
        args = moveX, moveY
        return args
Example #34
0
def main():
    from random import random as r
    segments = [
        Segment.from_floats(i + r(), j + r(), i + r(), j + r())
        for i in range(3) for j in range(3) for _ in range(100)
    ]
    plt.plot(*(pair for a, b in segments for pair in [(a.x, b.x), (a.y, b.y)]))
    plt.savefig('half-dense-half-sparse-example.png')
Example #35
0
 def add_planet(self,root,x,y,ray,rho=r()*100000.,mass=r(),*largs):
     wid=physObject()
     wid.mass=1.
     wid.pos=[r()*root.width,r()*root.height]
     wid.rho=1000.
     s=math.sqrt(wid.mass/(wid.rho*math.pi))
     wid.size_hint=(s,s)
     root.add_widget(wid)
Example #36
0
File: vec.py Project: zagfai/CTCer
def confuse(T):
    print 'confusing data...',
    from random import random as r
    size = len(T)
    for i in range(int(size**1.5)):
        x,y = int(size*r()), int(size*r())
        T[x], T[y] = T[y], T[x]
    print 'finish.'
    return T
Example #37
0
def run(parent):
	try:
		play(‘happy_otter.mp3’)
		move_and_wait(LARM=r(0, 10)); 
		move_and_wait(LARM=r(50, 60))
		move_to(LARM=r(0,10))

	finally:
		parent.exit()
Example #38
0
def gen_scramble(l):
	scramble = ""
	m=b=9
	for u in range(l):
		c=b;b=m
		while c+b-4 and m==c or m==b:
			m=r(0,5)
		scramble += "URFBLD"[m]+" '2"[r(0,2)]+" "
	return scramble.replace("  "," ")[:-1]
Example #39
0
def sendFakeBrainwaves():
    brainwaves = ",".join(
    [str(x) for x in \
        [0] +\
        [r(0,100) for x in range(2)] +\
        [r(0,100000) for x in range(8)]
    ])+"\n"
    print brainwaves
    clientsocket.send(brainwaves)
Example #40
0
def draw():
    save("pic.jpeg")
    background(255)
    
    noStroke()
    fill(r(255), r(255), r(255))
    #[draw_square(i,j,r(2)) for i in range(n + 1) for j in range(n + 1)] 
    [draw_sim_square(i,j,r(2)) for i in range((n + 1)/2) for j in range((n + 1)/2)] 
    delay(1000)
 def add_rects(self, *largs):
     print 'adding_rects', '=' * 80
     wid = self.wid
     count = 1000
     print 'adding', count, 'rects'
     with wid.canvas:
         for x in xrange(count):
             Color(r(), 1, 1, mode='hsv')
             Rectangle(pos=(r() * 100. - 50.,
                            r() * 100. - 50.), size=(100 * r(), 200 * r()))
Example #42
0
def test_ray_passes_through_focus():
    location = [0]*100
    for t in arange(100):
        ray = Ray([r()*5e-2,r()*5e-2,0], [0,0,1], op_wavelength)
        aol.propagate_to_distance_past_aol([ray], 0, focal_length)
        location[t] = ray.position
    
    focus_theory = focus_position + concatenate( (aol_simple.base_ray_positions[3], [aod_spacing.sum()]) ) 
    assert allclose(mean(location, axis=0), focus_theory, rtol=0, atol=1e-3) \
            and all(std(location, axis=0) < 5e-5)
 def __init__(self):
   # initialize node-activations
   self.ai = [1.0]*ni
   self.ah = [1.0]*nh
   self.ao = [1.0]*no
   self.Aah, self.Ach, self.Aao, self.Aco = [0]*nh, [0]*nh, [0]*no, [0]*no
   self.wi = [ [r() for j in range(nh)] for i in range(ni) ]
   self.wo = [ [r() for k in range(no)] for j in range(nh) ]
   self.ci = [[0.0]*nh]*ni
   self.co = [[0.0]*no]*nh
Example #44
0
def run(parent):
	try:
		move_to(PUR=100))
		move_and_wait(NECK=r(0,10))
		move_and_wait(NECK=r(50,60))
		move_and_wait(NECK=r(0,10))
		move_and_wait(NECK=r(50,60))
		move_to(NECK=50)
	finally:
		parent.exit()
Example #45
0
def test_ray_scans_correctly():
    t_step = 1e-6
    num_rays = 100
    location = [0]*num_rays
    for t in arange(num_rays):
        ray = Ray([r()*5e-2,r()*5e-2,0], [0,0,1], op_wavelength)
        aol.propagate_to_distance_past_aol([ray], t*t_step, focal_length)
        location[t] = ray.position
    
    focus_theory = focus_position + concatenate( (aol_simple.base_ray_positions[3], [aod_spacing.sum()]) ) + outer(arange(num_rays)*t_step, focus_velocity)
    assert allclose(location, focus_theory, rtol=0, atol=2e-3)
Example #46
0
    def handle(self, *args, **options):
	scramble = ""
	m=b=9
	for u in range(20):
		c=b;b=m
		while c+b-4 and m==c or m==b:
			m=r(0,5)
		scramble += "URFBLD"[m]+" '2"[r(0,2)]+" "
	scramble = scramble.replace("  "," ")[:-1]
	s = Scramble(scramble=scramble, pub_date=timezone.now())
	s.save()
Example #47
0
    def calib(self):
        now = datetime.datetime.now()
        date = now.strftime("%Y%m%d")
        TIME = now.strftime('%H%M%S')      

        self.datavault.cd(['', date, 'Calibrations',str(self.channelToCalib) + TIME], True)
        self.datavault.new(str(self.channelToCalib) + TIME,[('digital', '')], [('Analog', 'Volts', 'Volts')])
        self.datavault.add_parameter('plotLive',True)
	
        
        #stepsize = 0b101010101

        #stepsize = 1000
        stepsize = 500
        self.numSteps = (55000-11500)/stepsize        
        self.digVoltages = [ 11500 + r(0, stepsize) + i*stepsize for i in  range(self.numSteps)]
        self.compareVolts = [ 11500 + r(0, stepsize) + i*stepsize for i in  range(self.numSteps)]
            

        #self.digVoltages = range(0, 2**16, stepsize) # digital voltages we're going to iterate over
        self.anaVoltages = [] # corresponding analog voltages in volts
        self.dacserver.set_individual_digital_voltages([(str(self.channelToCalib).zfill(2), self.digVoltages[0])])
        time.sleep(.3)
        for dv in self.digVoltages: # iterate over digital voltages

            self.dacserver.set_individual_digital_voltages([(str(self.channelToCalib).zfill(2), dv)]) 

            time.sleep(.3)
            
            av = self.dmmserver.get_dc_volts()
            #av = 0

            self.anaVoltages.append(av)
            self.datavault.add(dv, av)
            print dv, "; ", av
        
#        plt.figure(1)
#        plt.plot(self.digVoltages, self.anaVoltages, 'ro')
#        plt.show()

        fit = np.polyfit(self.anaVoltages, self.digVoltages, 3) # fit to a second order polynomial
        if self.checksave.isChecked():
            # self.registry.cd(['', 'Calibrations'], True)
            #self.registry.mkdir(str(self.channelToCalib))
            #self.registry.cd(['', 'Calibrations', str(self.channelToCalib)], True)
            print ['', 'Servers', 'CCTDAC Server', 'Calibrations', str(self.channelToCalib)]
            self.registry.cd(['', 'Servers', 'CCTDAC Server', 'Calibrations', str(self.channelToCalib)], True)
            self.registry.set('c0', fit[3])
            self.registry.set('c1', fit[2])
            self.registry.set('c2', fit[1])
            self.registry.set('c3', fit[0])
    
        return fit
Example #48
0
def glitch(s, glitchness = 10):
    # for each character, we insert a random amount of diacritic characters
    result = ''
    for c in s:
        if c in let:
            pick_amount = r(0,glitchness)
            picks = [r(0,len(codes)-1) for a in range(pick_amount)]
            for i in picks:
                result+=chr(codes[i])
            result+=c
        else:
            result+=c
    return result
Example #49
0
File: oa.py Project: jokoon/eio
def loto(players, ticket, f=lambda: r()*r()):
	cash = players * ticket
	picks = [f() for a in range(players)]
	distrcoeffs = map(lambda i:i/sum(picks), picks)
	earnings = map(lambda i: i*cash, distrcoeffs)
	diffs = map(lambda i: i*cash-ticket, distrcoeffs)

	print players, "players with $"+str(ticket), "tickets", "total cash is", cash, "check sum", sum(earnings)
	print reduce (lambda i,j:1+i if j>0 else i, diffs,0), "winners"
	print "earnings";flo(earnings,pref='\t$')
	print "diffs";flo(diffs,pref='\t$')
	print stat(earnings)
	flo (map(lambda i: i*100/ticket,diffs),"%")
Example #50
0
def test(type, h, l, repeats):
    for _ in range(repeats):
        i = r(h, l)
        s = type.hexprints(i)
        v = type.hex2dec(s)
        assert i == v
        # if i != v:
        #     print(str(type) + " i: " + str(i) + " s: " + str(s) + " v: " + str(v))

    a = Array(type, 50)
    for n in range(50):
        i = [r(h, l) for j in range(n)]
        s = a.hexprints(i)
        v = a.hex2dec(s)
        assert i[:n] == v[:n]
    def calib(self):
        now = datetime.datetime.now()
        date = now.strftime("%Y%m%d")
        TIME = now.strftime("%H%M%S")

        self.datavault.cd(["", date, "Calibrations", str(self.channelToCalib) + TIME], True)
        self.datavault.new(str(self.channelToCalib) + TIME, [("digital", "")], [("Analog", "Volts", "Volts")])
        self.datavault.add_parameter("plotLive", True)

        # stepsize = 0b101010101

        stepsize = 1000
        self.numSteps = (61000 - 5000) / stepsize
        self.digVoltages = [5000 + r(0, stepsize) + i * stepsize for i in range(self.numSteps)]
        self.compareVolts = [5000 + r(0, stepsize) + i * stepsize for i in range(self.numSteps)]

        # self.digVoltages = range(0, 2**16, stepsize) # digital voltages we're going to iterate over
        self.anaVoltages = []  # corresponding analog voltages in volts
        self.dacserver.set_individual_digital_voltages([(int(self.channelToCalib), self.digVoltages[0])], 1)
        time.sleep(0.3)
        for dv in self.digVoltages:  # iterate over digital voltages

            self.dacserver.set_individual_digital_voltages([(int(self.channelToCalib), dv)], 1)

            time.sleep(0.3)

            av = self.dmmserver.get_dc_volts()
            # av = 0

            self.anaVoltages.append(av)
            self.datavault.add(dv, av)
            print dv, "; ", av

        #        plt.figure(1)
        #        plt.plot(self.digVoltages, self.anaVoltages, 'ro')
        #        plt.show()

        fit = np.polyfit(self.anaVoltages, self.digVoltages, 3)  # fit to a second order polynomial
        if self.checksave.isChecked():
            self.registry.cd(["", "cctdac_pulser", "Calibrations"])
            # self.registry.mkdir(str(self.channelToCalib))
            self.registry.cd(["", "cctdac_pulser", "Calibrations", str(self.channelToCalib)])
            self.registry.set("c0", fit[3])
            self.registry.set("c1", fit[2])
            self.registry.set("c2", fit[1])
            self.registry.set("c3", fit[0])

        return fit
Example #52
0
def pickOne(list):
    '''
    Picks one.
    First: a[0], last: a[-1], random: r(0, len(a) - 1)
    '''
    from random import randint as r
    return list[r(0, len(list) - 1)]
Example #53
0
def generateToken(time=10000):
	livetime = numTObase(time,6)
	from random import randrange as r
	import string
	a = string.ascii_lowercase
	offset = r(2)
	final = ''
	for i in str(TimestampMillisec64()):
		final+=a[int(i)+(10*offset)]
		if r(10)>6 and livetime!='':
			final+=a[int(livetime[0])+20]
			livetime=livetime[1:]
	while livetime!='':
		final+=a[int(livetime[0])+20]
		livetime=livetime[1:]
	return final
Example #54
0
 def load_sounds(self, mypath=None):
     """Add one or more sounds to the current scene"""
     if not mypath:
         mypath = askopenfilenames(filetypes=[(_("WAV audio files"), ".wav"), (_(
             "All files"), ".*")], initialdir=self.sound_dir)
         if not len(mypath):
             return
     n = 0
     for p in self.par:
         if p.n >= n:
             n = p.n + 1
     for f in mypath:
         if len(mypath) > 1:
             xpos = r() / 2. + .25
         else:
             xpos = .5
         try:
             self.par.append(Source(n, xpos, .5, f, self, active=True))
         except:
             tkMessageBox.showerror(
                 _("Add sounds"),
                 _(
                     "There was a problem with the sound file %s\nFormats other than WAV probably will not work.") % f
             )
         self.w.tag_raise("C%u" % n)
         self.w.tag_raise("T%u" % n)
         self.par[-1].play_or_stop()
         n += 1
     self.update_title()
     self.sound_dir = os.path.dirname(mypath[0])
     self.dirty()
Example #55
0
 def __init__(s, n, x, y, fn, m, active=False, animated=False, mod_amp=False, offset=None, looping=True):
     cx, cy = x * m.pix[0], y * m.pix[1]
     s.n = n
     s.fn = fn
     s.m = m
     s.active = active
     s.solo = False
     s.selected = False
     s.animated = animated
     s.vx, s.vy = 0, 0
     s.speed = 5
     s.mod_amp = mod_amp
     if (offset is None) or (offset == 0.):
         s.offset = r() * 30.
     else:
         s.offset = offset
     s.source = m.contextlistener.get_source()
     s.source.buffer = openal.Buffer(fn)
     s.circ = m.w.create_oval(
         cx - m.cr, cy - m.cr, cx + m.cr, cy + m.cr, fill="white", tags="C%u" % n)
     s.text = m.w.create_text(cx, cy, text="%u" % n, tags="T%u" % n)
     m.w.tag_bind("C%u" % n, "<Button-2>", s.clicked)
     m.w.tag_bind("T%u" % n, "<Button-2>", s.clicked)
     m.w.tag_bind("C%u" % n, "<Button-1>", s.sel)
     m.w.tag_bind("T%u" % n, "<Button-1>", s.sel)
     m.w.tag_bind("C%u" % n, "<B1-Motion>", s.moved)
     m.w.tag_bind("T%u" % n, "<B1-Motion>", s.moved)
     m.w.tag_bind("C%u" % n, "<Button-3>", s.makesolo)
     m.w.tag_bind("T%u" % n, "<Button-3>", s.makesolo)
     s.update_color()
     s.x, s.y = cx, cy
     s.source.looping = looping
     s.update_parameters()
 def getValue(self, fraction, interval, value=None, **kw):
     if value is not None:
         if fraction <= 0.0 or fraction >= 1.0:
             return value
         else:
             from random import random as r
             return  map(lambda x: x+r(), value)
def die():
    from random import randint as r
    x = []
    for i in range(50):
        die = r(1,6)
        x.append(die)
    print (x)
    return x
Example #58
0
def random_trinomials():
    """
    Returns a system of two trinomials equations for testing.
    A trinomial consists of three monomials in two variables.
    Exponents are uniform between 0 and 5 and coefficients are
    on the complex unit circle.
    """
    from random import randint as r
    exponents = [(r(0, 5), r(0, 5)) for i in range(0, 6)]
    monomials = map(lambda e: 'x^%d*y^%d' % e, exponents)
    from random import uniform as u
    from math import cos, sin, pi
    angles = [u(0, 2*pi) for i in range(0, 6)]
    cff = map(lambda a: '(' + str(cos(a)) + '%+.14f' % sin(a) + '*i)', angles)
    one = '+'.join(cff[i] + '*' + monomials[i] for i in range(0, 3)) + ';'
    two = '+'.join(cff[i] + '*' + monomials[i] for i in range(3, 6)) + ';'
    return [one, two]
Example #59
0
def draw_arc(angle_start, angle_stop, radial_size, my_color):
    print "draw arc with radial size " + str(radial_size)
    if r(2):
        #fill(*my_color)
        fill(0,0,0)
    else:
        fill(255,255,255)
        
    arc(radius,  radius, 2 * radial_size, 2 * radial_size, angle_start, angle_stop);