Exemplo n.º 1
0
 def initialize(self):
     targets = []
     observers = []
     no_targets = self.no_targets_arr[RI(0, 4)]
     no_observers = self.no_observers_arr[RI(0, 4)]
     sensor_range_targets = self.sensor_range[RI(0, 4)]
     sensor_range_observers = self.sensor_range[RI(0, 4)]
     for i in range(no_targets):
         targets.append(
             T(R() * 150,
               R() * 150, self.target_speed[RI(0, 5)],
               R() * 360, sensor_range_observers))
     for i in range(no_observers):
         observers.append(
             O(R() * 150,
               R() * 150, self.observer_speed, sensor_range_targets))
     return (no_targets, no_observers, targets, observers)
Exemplo n.º 2
0
def test_should_find_missing_number_for_random_performance_tests():
    base = list(range(1, 1000001))
    S(base)
    for _ in range(20):
        n = R(1, 1000000)
        a = base[:]
        a.remove(n)
        assert find_missing_number(a) == n
Exemplo n.º 3
0
 def initialize(self):
     no_observers_arr=[2,6,10,14,18]
     no_targets_arr=[3,9,15,21,27]
     target_speed=[0.2,0.5,0.8,1.0,1.2,1.5]
     observer_speed=1.0
     sensor_range=[5,10,15,20,25]
     observer_target_dict={}
     obstacle_len=[2,5,8,10,12,20]
     targets=[]
     a=[-1 ,1]
     observers=[]
     obstacles=[]
     no_targets=no_targets_arr[RI(0,4)]
     no_observers=no_observers_arr[RI(0,4)]
     no_obstacles=int(ceil(no_targets/3))
     for i in range(no_targets):
         targets.append(T(R()*150*a[RI(0,1)],R()*150*a[RI(0,1)],target_speed[RI(0,5)],R()*360,sensor_range[RI(0,4)]))
     for i in range(no_observers):
         observers.append(O(R()*150*a[RI(0,1)],R()*150*a[RI(0,1)],observer_speed,sensor_range[RI(0,4)]))
     for i in range(no_obstacles):
         obs_len=obstacle_len[RI(0,5)]
         angle=R()*360
         pos_x=R()*150*a[RI(0,1)]
         pos_y=R()*150*a[RI(0,1)]
         temp_obs=[]
         for j in range(obs_len):
             temp_obs.append(Ob(pos_x+j*sin(angle),pos_y+j*cos(angle),angle,i))
         obstacles.append((obs_len,temp_obs))
     return (no_targets,no_observers,no_obstacles,targets,observers,obstacles)
Exemplo n.º 4
0
def str_prod(s, lo, hi=None):
    # string producer, make chunks of size in the range lo, hi (or just <lo>)
    i = 0
    ls = len(s)
    while i < ls:
        if hi is None:
            size = lo
        else:
            size = R(lo, hi)
        yield s[i:i + size]
        i += size
Exemplo n.º 5
0
def genexpr(kw, endprob, probgrad):
    res = ''
    if R(0, 1):
        res += '!'

    if random.random() < endprob:
        res += random.choice(kw['content'])
        return res

    par = R(0, 1)
    if par:
        res += '('

    res += genexpr(kw, endprob * probgrad, probgrad)
    res += random.choice(['&', '|'])
    res += genexpr(kw, endprob * probgrad, probgrad)

    if par:
        res += ')'
    return res
Exemplo n.º 6
0
def foo11():
    l = []
    total = 0
    for i in range(100):
        l.append(R(0, 1000))
    for item in l:
        count = 0
        for Item in l:
            if abs(item - Item) <= 20:
                count += 1
        if count <= 1:
            total += 1
    return total
Exemplo n.º 7
0
def random_proname():
    """生成一个数据库里面未注册的项目名称"""
    while True:
        name = "fls"
        for i in range(5):
            r = R(0, 9)
            name += str(r)
        # 数据库查询该用户名是否存在
        sql = 'SELECT * FROM test.tb_projects WHERE name="{}"'.format(name)
        res = db.find_count(sql)
        # 如果不存在,则返回该用户名
        if res == 0:
            return name
Exemplo n.º 8
0
 def initialize(self):
     no_observers_arr = [2, 6, 10, 14, 18]
     no_targets_arr = [3, 9, 15, 21, 27]
     self.x_limit = 150
     self.y_limit = 150
     target_speed = [0.2, 0.5, 0.8, 1.0, 1.2, 1.5]
     observer_speed = 1.0
     sensor_range = [5, 10, 15, 20, 25]
     self.total_steps = 1500
     self.update_steps = 10
     observer_target_dict = {}
     obstacle_len = [2, 5, 8, 10, 12, 20]
     self.template_probability_distribution = [
         0.001953125, 0.001953125, 0.00390625, 0.0078125, 0.015625, 0.03125,
         0.0625, 0.125, 0.25, 0.5
     ]
     targets = []
     a = [-1, 1]
     observers = []
     obstacles = []
     observer_strategy = []
     no_targets = no_targets_arr[RI(0, 4)]
     no_observers = no_observers_arr[RI(0, 4)]
     no_obstacles = int(ceil(no_targets / 3))
     for i in range(no_targets):
         targets.append(
             T(R() * 150 * a[RI(0, 1)],
               R() * 150 * a[RI(0, 1)], target_speed[RI(0, 5)],
               R() * 360, sensor_range[RI(0, 4)]))
     for i in range(no_observers):
         observers.append(
             O(R() * 150 * a[RI(0, 1)],
               R() * 150 * a[RI(0, 1)], observer_speed,
               sensor_range[RI(0, 4)]))
         observer_strategy.append(RI(1, 4))
     for i in range(no_obstacles):
         obs_len = obstacle_len[RI(0, 5)]
         angle = R() * 360
         pos_x = R() * 150 * a[RI(0, 1)]
         pos_y = R() * 150 * a[RI(0, 1)]
         temp_obs = []
         for j in range(obs_len):
             temp_obs.append(
                 Ob(pos_x + j * sin(angle), pos_y + j * cos(angle), angle,
                    i))
         obstacles.append((obs_len, temp_obs))
     return (no_targets, no_observers, no_obstacles, targets, observers,
             obstacles, observer_strategy)
Exemplo n.º 9
0
def generate_binary(text):
    name = rnd_string(15)

    with open(f"/tmp/{name}.c", "w") as f:
        code = ""

        l = R(3, 6)
        r = R(3, 6)

        for i in range(l):
            code += choice(prints).format(rnd_string(10), 10)

        code += choice(prints).format(text, len(text))

        for i in range(r):
            code += choice(prints).format(rnd_string(10), 10)

        f.write(template.format(code))

    p = Popen(["gcc", f"/tmp/{name}.c", "-o", f"/tmp/{name}"])
    p.wait()

    return f"/tmp/{name}"
Exemplo n.º 10
0
def random_intername():
    """生成一个数据库里面未注册的接口名"""
    while True:
        name = "inter"
        for i in range(5):
            r = R(0, 9)
            name += str(r)

        # 数据库查询该用户名是否存在
        # sql = "SELECT * From test.auth_user WHERE username ={}".format(name)
        sql = 'SELECT * FROM test.tb_interfaces WHERE name="{}"'.format(name)
        res = db.find_count(sql)
        # 如果不存在,则返回该用户名
        if res == 0:
            return name
Exemplo n.º 11
0
def m(s):
    a = lambda o, y, x: y.addch(o[0], o[1], x)
    q = lambda: (R(L - 2), R(C - 2))
    L, C = s.getmaxyx()
    curs_set(0)
    s.nodelay(1)
    s.border()
    s.refresh()
    r = newwin(L - 2, C - 2, 1, 1)
    n = deque()
    y, x = [L - 2, 0]
    d = N
    n.append(u)
    c = N
    p = q()
    a(p, r, N)
    a(u, s, 48)
    while 1:
        if c in z: d = c
        if d == N: y -= 1
        if d == S: y += 1
        if d == W: x -= 1
        if d == E: x += 1
        l = n.pop()
        if (y, x) in n: return
        if (y, x) == p:
            p = q()
            a(p, r, N)
            n.append(l)
            s.addstr(0, 0, str(len(n)))
        n.appendleft((y, x))
        a((y, x), r, S)
        a(l, r, 32)
        r.refresh()
        time.sleep(.2)
        c = s.getch()
Exemplo n.º 12
0
 def random_email():
     """生成一个数据库里面未注册的邮箱地址"""
     while True:
         num = ""
         address = ""
         email = "@qq.com"
         for i in range(9):
             r = R(0, 9)
             num += str(r)
             address = num + email
         # 数据库查询该用户名是否存在
         sql = 'SELECT * from test.auth_user WHERE email ="{}"'.format(
             address)
         res = db.find_count(sql)
         # 如果不存在,则返回该用户名
         if res == 0:
             return address
Exemplo n.º 13
0
def initialize_param(no_targets,no_observers):
	targets=[]
	a=[-1 ,1]
	observers=[]
	obstacles=[]
	no_obstacles=int(ceil(no_targets/3))
	for i in range(no_targets):
		targets.append(T(R()*150*a[RI(0,1)],R()*150*a[RI(0,1)],target_speed[RI(0,5)],R()*360,sensor_range[RI(0,4)]))
	for i in range(no_observers):
		observers.append(O(R()*150*a[RI(0,1)],R()*150*a[RI(0,1)],observer_speed,sensor_range[RI(0,4)]))
	for i in range(no_obstacles):
		obs_len=obstacle_len[RI(0,5)]
		angle=R()*360
		pos_x=R()*150*a[RI(0,1)]
		pos_y=R()*150*a[RI(0,1)]
		temp_obs=[]
		for j in range(obs_len):
			temp_obs.append(Ob(pos_x+j*sin(angle),pos_y+j*cos(angle),angle,i))
		obstacles.append((obs_len,temp_obs))
	return (no_targets,no_observers,no_obstacles,targets,observers,obstacles)
Exemplo n.º 14
0
Arquivo: rand4.py Projeto: soyccan/ada
from random import randint as R

N = 7
print(N)

s = sorted([R(1,30) for _ in range(3)])
A = sorted([R(1,30) for _ in range(N)])

print(' '.join(map(str,s)))
print(' '.join(map(str,A)))
Exemplo n.º 15
0
 def create(self):
     print('create')
     for i in range(6):
         self.sh += container[R(len(container))]
     tempsh = self.check(sh=self.sh)
     return tempsh
Exemplo n.º 16
0
def foo10a():
    li = []
    for i in range(5):
        li.append((R(-100, 100), R(-100, 100), R(-100, 100)))
    return li
Exemplo n.º 17
0
def gentest(kw, numtest, endprob, probgrad):
    cmds = ['add', 'remove', 'longest', 'query']
    cmdw = [800, 200, 400, 1000]
    mails = []

    for i in range(numtest):
        cmd = random.choices(cmds, weights=cmdw, k=1)[0]
        if cmd == 'add':
            mailid = R(1, 10000)
            mails.append(mailid)
            print(cmd, 'test_data/mail' + str(mailid))
        elif cmd == 'remove':
            mailid = random.choice(mails)
            print(cmd, mailid)
        elif cmd == 'query':
            qs = ''
            if not R(0, 1):
                datefrom = [
                    R(2000, 2020),
                    R(1, 12),
                    R(1, 31),
                    R(0, 23),
                    R(0, 59)
                ]
                dateto = [
                    R(2000, 2020),
                    R(1, 12),
                    R(1, 31),
                    R(0, 23),
                    R(0, 59)
                ]
                if datefrom > dateto:
                    datefrom, dateto = dateto, datefrom
                qs += ' -d'
                if not R(0, 10):
                    qs += ''.join(map(str, datefrom))
                qs += '~'
                if not R(0, 10):
                    qs += ''.join(map(str, dateto))
            if R(0, 1):
                from_ = random.choice(kw['from'])
                assert len(from_) < 50
                qs += ' -f"{}"'.format(from_)
            if R(0, 1):
                to = random.choice(kw['to'])
                assert len(to) < 50
                qs += ' -t"{}"'.format(to)
            expr = genexpr(kw, endprob, probgrad)
            qs += ' ' + expr
            print('query' + qs)
        elif cmd == 'longest':
            print('longest')
        else:
            print(f'{cmd=}')
Exemplo n.º 18
0
def gen_problemsRnd(max):
    i = 0
    while i < max:
        problems.append([int(R(1, 10, 1)), int(R(1, 100, 1))])
        i += 1
    return problems
Exemplo n.º 19
0
from matplotlib import pyplot as p
from math import log as l

#Defining all variables
population = 1
step = 12
time = 0
birth_rate = 0.15
death_rate = 0.005
predator_rate = 0.05
exes = []
wise = []

for i in range(12):
	for j in range(population):
		k = int(t(1,10,7))
		for l in range(k):
			if R() <= birth_rate:
				population += 1
	population=int(round(population*(1-(death_rate+predator_rate))))
	print(population)
	exes.append(i*step)
	wise.append(population)

p.figure()
p.plot(exes,wise)
p.xlabel('Hours')
p.ylabel('Population')
p.title('Trebble Population Growth')
p.legend(['Trebble population'],loc='upper right')
p.show()
Exemplo n.º 20
0
def game():

    # set f to True
    f = True
    # the true grid
    minegrid = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]

    # the grid you see at first
    graygrid = [[None, None, None, None, None, None, None, None],
                [None, None, None, None, None, None, None, None],
                [None, None, None, None, None, None, None, None],
                [None, None, None, None, None, None, None, None],
                [None, None, None, None, None, None, None, None],
                [None, None, None, None, None, None, None, None],
                [None, None, None, None, None, None, None, None],
                [None, None, None, None, None, None, None, None]]

    # give mines
    mines = 10
    mine_locations = set()

    # add mines to empty mine field
    while len(mine_locations) < mines:
        row = R(0, 7)
        col = R(0, 7)
        mine_locations.add((row, col))
        minegrid[row][col] = '*'

    for row in range(len(graygrid)):
        for col in range(len(graygrid[row])):
            if minegrid[row][col] == "*":
                continue
            count = 0
            for i in range(-1, 2):
                for j in range(-1, 2):
                    if in_bounds(row + i, col + j, minegrid) and check_if_mine(
                            row + i, col + j, minegrid):
                        count += 1
            minegrid[row][col] = count

    # loop
    while f is True:

        # show grid
        print('\n' * 30)
        print(show_grid(graygrid))

        while True:
            # show instructions
            guess = input(
                """Give X and Y coordinates (x, y). Type 'R' to restart, 'Q' to
quit: """).strip().lower()

            # options
            if guess == "r":
                game()
            elif guess == "q":
                sys.exit()
            elif is_valid(guess):

                # split input into a list
                guess = guess.split(',')

                # set x and y to be what user has input
                x = (int(guess[0]) - 1)
                y = (int(guess[1]) - 1)
                break

        # check for a mine
        graygrid[y][x] = minegrid[y][x]
        f = is_mine((minegrid[y][x]), minegrid, graygrid)
from random import randint as r
from random import random as R

#LHS
# Dict = {}
# for i in range(10):
# 	Dict[i] = 0
# for i in range(10000):
# 	Dict[r(0,9)] += 1
# for key in Dict:
# 	print('num', key,':', Dict[key])

#RHS
d = {}
for i in range(10):
    d[i] = []
for i in range(21):
    n = R() * 10
    d[int(n)].append(round(n, 2))
for key in d:
    print(key, ':', d[key])
Exemplo n.º 22
0
from random import randint as R

N = 80
print(N)
for i in range(N):
    for j in range(N):
        x = R(0, 100)
        if x > 8:
            y = 1
        else:
            y = 0
        print(y, end='')
    print()
Exemplo n.º 23
0
 def gen_fake_if():
     if C([True, False]):
         return self._random_str(5), '!='
     else:
         return R(1, 100), '-'
Exemplo n.º 24
0
def index():
    from os import stat
    from os.path import join
    try:
        if stat(
                join("applications", request.application, "databases",
                     "geoip.db"))[6] == 0L:
            raise ValueError
    except:
        redirect(URL(r=request, f="installation"))
    if len(request.args):
        ip = request.args[0]
        if ip == "random":
            from random import randint as R
            ip = ".".join(
                map(str, (R(0, 255), R(0, 255), R(0, 255), R(0, 255))))
        try:
            data = geoip(ip)
            if data:
                session.data = session.data = B(
                    IMG(_src=URL(r=request,
                                 c="static",
                                 f="flags/" + data[1].lower() + ".png"),
                        _alt="geoip flag",
                        _style="margin-bottom: -4px"),
                    B(data[0] + " (" + data[1] + ")"))
            else:
                session.data = B("Unknown")
        except:
            redirect(URL(r=request, f="index"))
        session.ip = ip
    form = FORM(
        B("Address: "),
        INPUT(
            _type="text",
            _name="ip",
            _value=session.ip,
            _size="15",
            _maxlength="15",
            requires=IS_MATCH(
                "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
            )), INPUT(_type="submit", _value="Locate"), " ",
        A("random", _href=URL(r=request, c="default", f="index/random")), BR(),
        BR(), session.data)
    if form.accepts(request, keepvalues=True):
        session.ip = request.vars.ip
        data = geoip(session.ip)
        if data:
            session.data = session.data = B(
                IMG(_src=URL(r=request,
                             c="static",
                             f="flags/" + data[1].lower() + ".png"),
                    _alt="geoip flag",
                    _style="margin-bottom: -4px"),
                B(data[0] + " (" + data[1] + ")"))
        else:
            session.data = B("Unknown")
        redirect(URL(r=request, f="index"))
    elif form.errors:
        form.errors.clear()
        response.flash = "Invalid IPv4 address"
    return dict(form=form)
Exemplo n.º 25
0
def init():
    for i in range(10):
        M.append(["."] * 10)
        V.append([50] * 10)
    M[0][0] = "P"
    M[R(2, 9)][R(2, 9)] = "F"
Exemplo n.º 26
0
Arquivo: rand2.py Projeto: soyccan/ada
from random import randint as R

N = 100000
M = 260
K = 50
print(N, M, K)
for _ in range(N):
    print(R(0, M - 1), end=' ')
Exemplo n.º 27
0
from random import randint as R

N = 500
K = 87
print(N, K)
for _ in range(N):
    print(R(0, 100), R(0, 100))
Exemplo n.º 28
0
    n = 5  # liczba punktów kontrolnych (stopieñ krzywej+1)

    rozdzielczosc = 600  # rozdzielczo¶æ obrazów
    k = 200  # liczba segmentów ³amanej przybli¿aj±cej krzyw±
    l = 50  # liczba obrazów generowanych przy jednym
    # uruchomieniu programu

    image = Image.new("RGB", (rozdzielczosc, rozdzielczosc))
    draw = ImageDraw.Draw(image)
    from random import randint as R

    for i in xrange(l):
        print "Tworzenie krzywej %d z %d" % (i + 1, l)
        # 1. Wylosowanie n punktów kontrolnych
        #    (oczywi¶cie mo¿na je wpisaæ rêcznie, do czego zachêcamy)
        punkty_kontrolne = [(R(0, rozdzielczosc), R(0, rozdzielczosc))
                            for _ in xrange(n)]

        # 2. Wyznaczenie ³amanej p przyli¿aj±c± krzyw± Beziera
        p = Bezier2D(punkty_kontrolne, k)

        # 3. Rysowanie krzywej:
        # 3a. wyczyszczenie obrazu (kolorem bia³ym)
        draw.rectangle([0, 0, rozdzielczosc, rozdzielczosc], fill="#fff")

        # 3b. rysowanie ³amanej kontrolnej (w kolorze jasnoszarym)
        draw.line(punkty_kontrolne, fill="#ccc")

        # 3c. zaznaczenie niebieskimi kó³kami punktów kontrolnych
        r = 2  # promieñ
        for (x, y) in punkty_kontrolne:
Exemplo n.º 29
0
 def it_1():
     for _ in range(100):
         n = R(1, 20)
         a = [[R(1, 1000) for _ in range(n)] for _ in range(n)]
         b = [x[:] for x in a]
         test.assert_equals(snail(a), solution(b))
Exemplo n.º 30
0
    tampil('?m[!] Gagal membuka ?c' + D[1])
    exit()

if D[2] not in ('1', '2', '3'):
    baliho()
    tampil('?m[!] Mode ?c%s?m tidak ada' % D[2])
    exit()
try:
    c = compile(s, '<script>', 'exec')
except:
    baliho()
    tampil('?mFile tidak support')
    exit()

d = marshal.dumps(c)
r = lambda : R(0, 255)
k = []
for i in range(255):
    k.append(r())

def enc(d, k):
    e = ''
    i, j = (0, 0)
    while 1:
        if i >= len(d):
            break
        if j >= len(k):
            j = 0
        e += chr(ord(d[i]) ^ k[j])
        i += 1
        j += 1