def choose(dur):
    if dur == 2:
        return weighted_choice([[2], [1, 1]], [3, 1])
    if dur == 4:
        return weighted_choice(options_4, weights_4)
    if dur == 8:
        return weighted_choice(options_8, weights_8)
Example #2
0
def choose(dur):
    if dur == 2:
        return weighted_choice([[2], [1, 1]], [4, 1])
    if dur == 4:
        return weighted_choice(options_4, weights_4)
    if dur == 8:
        return weighted_choice(options_8, weights_8)
Example #3
0
def choose():
    try:  # TODO HOLY SHIT REMOVE THIS. infinite loop danger. find actual bug.
        forms, weights = weighted_choice(GROUP_OPTIONS, GROUP_WEIGHTS)
        return weighted_choice(forms, weights)
    except:
        print 'warning!  song_forms.choose failed and retried.'
        return choose()
Example #4
0
    def random_cmd(self, commands=[]):
        if commands:
            cmds = [self.commands[name] for name in commands]
            cmd = utils.weighted_choice(cmds)
        else:
            cmd = utils.weighted_choice(self.commands)

        return command.RunnableCommand.random(cmd)
Example #5
0
    def random_cmd(self, commands=[]):
        if commands:
            cmds = [self.commands[name] for name in commands]
            cmd = utils.weighted_choice(cmds)
        else:
            cmd = utils.weighted_choice(self.commands)

        return command.RunnableCommand.random(cmd)
    def get_rolls(self):
        """Get 5 card random rarities

        You're guaranteed at least a rare. I'm not really sure how that's implemented,
        so if we get 5 commons we re-roll the last one"""
        rolls = [utils.weighted_choice(CHANCE) for i in range(5)]
        if all(roll == 'c' for roll in rolls):
            rolls[4] = utils.weighted_choice(CHANCE[1:])
        return rolls
Example #7
0
    def bass_next(self):
        bar_number = self.bass.duration() // 4
        bar_in_progression = bar_number % len(BLUES_PROGRESSION)

        beat_number = int(self.bass.duration() % 4)

        previous_pitch = self.bass.get_last_pitched().pitch

        pitch_options = []
        weights = []

        available_pitches = range(35, 52)
        for pitch_option in available_pitches:
            weight = 1.0

            if pitch_option % 12 not in SCALE:
                weight = .1

            if pitch_option % 12 in BLUES_PROGRESSION[bar_in_progression]:
                weight = 8.0

            # The further away the new pitch from the previous pitch, the lower the weight
            distance = abs(previous_pitch - pitch_option)

            if distance == 0:
                weight = 1.0
            else:
                if distance < 3:
                    weight = weight * 8
                elif distance < 6:
                    weight = weight * 4
                # elif distance < 9:
                #     weight = weight * 2
                elif distance > 12:
                    weight = .125

            pitch_options.append(pitch_option)
            weights.append(weight)

        pitch = weighted_choice(pitch_options, weights)

        if beat_number == 0:
            duration_options = [1, 2, 3, 4, 5, 6, 7, 8]
            duration_weights = [35, 24, 2, 6, 1, 1, 1, 2]
        elif beat_number == 1:
            duration_options = [1, 2, 3, 4, 5, 6, 7]
            duration_weights = [35, 12, 16, 1, 1, 1, 3]
        elif beat_number == 2:
            duration_options = [1, 2, 4, 6]
            duration_weights = [24, 24, 1, 2]
        elif beat_number == 3:
            duration_options = [1, 2, 5]
            duration_weights = [40, 2, 5]

        duration = weighted_choice(duration_options, duration_weights)

        self.bass.add_note(pitch=pitch, duration=duration)
Example #8
0
def generation():
    global pop, generation_index

    with Pool() as p:
        pop = p.map(evaluate_fitness, pop)

    # fitness of every individual controller in population
    fitnesses = [r.fitness for r in pop]
    # fitness of every individual at every generation for plotting
    pop_fit_history.append(sorted(np.array(fitnesses)))

    # plot trajectories of best and worst individual every nth gen
    if (generation_index % DRAW_EVERY_NTH_GENERATION) == 0:
        best_index = np.argmax(fitnesses)
        plot_state_history(savepath, pop[best_index], 'best')
        pop[best_index].plot_links('best')

        np.save(os.path.join(savepath, 'best_genome.npy'),
                pop[best_index].genome)

        worst_index = np.argmin(fitnesses)
        plot_state_history(savepath, pop[worst_index], 'worst')
        pop[worst_index].plot_links('worst')

    # normalize distribution of fitnesses to lie between 0 and 1
    f_normalized = np.array([x for x in fitnesses])
    f_normalized -= min(f_normalized)
    if max(f_normalized) > 0.0:
        f_normalized /= max(f_normalized)
    sum_f = max(0.01, sum(f_normalized))

    # probability of being selected as a parent of each individual in next generation
    ps = [f / sum_f for f in f_normalized]

    # "elitism" -- seed next generation with a copy of best individual from previous generation
    best_index = np.argmax(fitnesses)
    best_individual = pop[best_index]
    next_generation = [Controller(genome=best_individual.genome)]

    # populate rest of next generation by selecting parents weighted by fitness
    while len(next_generation) < POP_SIZE:
        a_i = weighted_choice(ps)
        b_i = weighted_choice(ps)
        ma = pop[a_i]
        pa = pop[b_i]
        baby = ma.procreate_with(pa)
        next_generation.append(baby)

    ## replace old generation with new
    pop = next_generation

    print(
        f'GENERATION # {generation_index}.\t(mean/min/max)' +
        f'({np.mean(fitnesses):.4f}/{np.min(fitnesses):.4f}/{np.max(fitnesses):.4f})'
    )
    generation_index += 1
Example #9
0
    def add_scalar_ornament(self, note, prev, harmonies):
        interval = prev['pitch'] - note['pitch']
        if interval > 0:
            direction = 'ascending'
        if interval < 0:
            direction = 'descending'
        if interval == 0:
            direction = random.choice(['ascending', 'descending'])

        # Choose the number of notes in the ornament
        if prev['duration'] >= 1:
            n = weighted_choice([1, 2, 3, 4, 5, 6], [2, 3, 4, 6, 5, 4])
        elif prev['duration'] >= 0.75:
            n = weighted_choice([1, 2, 3], [1, 2, 4])
        else:
            n = random.randint(1, 2)

        orn = scalar_ornaments.choose(n, direction)

        harm = []
        for chord in harmonies:
            for p in chord:
                if p not in harm:
                    harm.append(p)

        scale_options = diatonic_scales_for_harmony(harm)

        if random.random() < .16 or not scale_options:
            scale_options = other_scales_for_harmony(harm)

        if scale_options:
            scale_type = random.choice(scale_options)

            note_pitch = int(note['pitch'])

            note_pitch_class = note_pitch % 12

            diff = note_pitch - note_pitch_class
            scale = []
            for octave in [diff - 12, diff, diff + 12]:
                for pc in scale_type:
                    p = pc + octave
                    scale.append(p)

            i = scale.index(note_pitch)
            scale = scale[i - 2:i + 3]

            orn_type = []
            for i in orn:
                pitch = scale[i + 2]
                orn_type.append(pitch)

            return orn_type
Example #10
0
 def rewrite(tokens, into):
     for token in tokens:
         if token in self.rules:
             non_terminal, prob = weighted_choice(self.rules[token])
             into[1] *= prob
             rewrite(non_terminal, into)
         elif token in self.lexicon:
             terminal, prob = weighted_choice(self.lexicon[token])
             into[0].append(terminal)
             into[1] *= prob
         else:
             into[0].append(token)
     return into
Example #11
0
 def rewrite(tokens, into):
     for token in tokens:
         if token in self.rules:
             non_terminal, prob = weighted_choice(self.rules[token])
             into[1] *= prob
             rewrite(non_terminal, into)
         elif token in self.lexicon:
             terminal, prob = weighted_choice(self.lexicon[token])
             into[0].append(terminal)
             into[1] *= prob
         else:
             into[0].append(token)
     return into
Example #12
0
 def _emitHMM_with_past(self, token_type, past_states, past_emissions):
     """ emits a word based on previous states (=token) and previous emissions (=words)
     The states and emissions are weighted according to their defined probabilities
         self.prob_hmm_states and self.prob_hmm_emissions"""
     assert token_type in self.emissions
     states_items = [(x[0], x[1] * self.prob_hmm_states)
                     for x in self.emissions[token_type].items()]
     key_emissions = tuple(past_emissions)
     if key_emissions in self.emissions_past[token_type]:
         states_emissions = [(x[0], x[1] * self.prob_hmm_emissions) for x in self.emissions_past[
                             token_type][tuple(past_emissions)].items()]
         return utils.weighted_choice(states_items + states_emissions)
     return utils.weighted_choice(states_items)
Example #13
0
 def _emitHMM_with_past(self, token_type, past_states, past_emissions):
     """ emits a word based on previous states (=token) and previous emissions (=words)
     The states and emissions are weighted according to their defined probabilities
         self.prob_hmm_states and self.prob_hmm_emissions"""
     assert token_type in self.emissions
     states_items = [(x[0], x[1] * self.prob_hmm_states)
                     for x in self.emissions[token_type].items()]
     key_emissions = tuple(past_emissions)
     if key_emissions in self.emissions_past[token_type]:
         states_emissions = [(x[0], x[1] * self.prob_hmm_emissions)
                             for x in self.emissions_past[token_type][tuple(
                                 past_emissions)].items()]
         return utils.weighted_choice(states_items + states_emissions)
     return utils.weighted_choice(states_items)
Example #14
0
def main(*fnames):
    data = []
    for fname in fnames:
        with open(fname, 'r+') as fp:
            data.extend(json.load(fp))
            fp.close()

    i = 0
    stop = len(data)
    while True:
        freeze = random.random() * 0.5
        step = random.randint(1, 3)
        slc = min(i + step, stop - 1)

        tmp_ = data[i:slc]
        if tmp_:
            for x in tmp_:
                x.update(status=weighted_choice([('error',
                                                  .05), ('debug',
                                                         .65), ('info', .3)]))
            func = random.choice([prettify_json, prettify_pprint])
            shoot(func(tmp_))
            i += step
        else:
            i = 0
            # clear output each time the whole trace file is out
            os.system('clear')
            spinning_cursor(random.random())

        # occasionally output line breaks
        if weighted_choice([(True, 1), (False, 9)]):
            shoot('\n')

        # occasionally output table
        if weighted_choice([(True, 0.5), (False, 9.5)]):
            shoot('\n')
            shoot_table()
            freeze = random.uniform(0.2, 0.8)

        # occasionally output the whole random file from the current dir
        if weighted_choice([(True, 0.1), (False, 9.9)]):
            try:
                shoot_file()
            except IndexError:
                pass
            freeze = random.uniform(0.2, 0.8)

        time.sleep(freeze)
Example #15
0
def next_violin_dyad(previous, harmony, lowest_pitch, highest_pitch):
    harmony = [p % 12 for p in harmony]

    prev_lower = min(previous)
    prev_higher = max(previous)

    lower_ranked = rank_options(prev_lower, harmony, lowest_pitch, highest_pitch)
    higher_ranked = rank_options(prev_higher, harmony, lowest_pitch, highest_pitch)

    ranked = []
    for lower_rank, lower in enumerate(lower_ranked):
        for higher_rank, higher in enumerate(higher_ranked):
            interval = higher - lower
            if interval > 0 and interval < 8:
                rank = lower_rank + higher_rank
                ranked.append({
                    'rank': lower_rank + higher_rank,
                    'dyad': [lower, higher]
                })

    ranked.sort(key=lambda x: x['rank'])
    ranked = [r['dyad'] for r in ranked]

    weights = exp_weights(len(ranked))
    return weighted_choice(ranked, weights)
Example #16
0
    def clusters_pick_changing_instrument(self):
        # TODO: try prefering picking changing instruments when the other two instruments are playing a minor second

        weights = []
        for inst in self.clusters:
            sustain_time = inst.beats_since_last_rest() * (
                60.0 / self.music.starting_tempo_bpm)
            # weight = (inst.beats_since_last_rest() + 1) ** 2.0
            # weight = sustain_time ** 2
            sustain_weight = sustain_time

            # not_changing = [i for i in self.clusters if i is not inst]
            # revealed_harmony = self.clusters_get_revealed_harmony(not_changing)
            # revealed_harmony_weight =

            # weight = (sustain_weight * ) + (revealed_harmony_weight * )
            weight = sustain_weight
            weights.append(weight)

        changing = weighted_choice(self.clusters, weights)

        not_changing = [w for w in self.clusters if w is not changing]

        print
        print 'not_changing', not_changing
        print
        return changing, not_changing
Example #17
0
def main(post):
	#master process should randomize a mission choice and page choice.
	#should check against "pages done" list at some point

	choosenCraft = utils.weighted_choice(config.CRAFT_LIST)

	photos = getImagesList(choosenCraft['craft'], random.randint(1, choosenCraft['pages']))
	imgObj = selectRandImage(photos)
	text = None

	if 'not_found' not in imgObj['url'] or 'http' not in imgObj['url']:
		missionDataObj = getMissionData(imgObj['ring_obs_id'])
		text = writePostText(missionDataObj, choosenCraft['craft'])
	

	if post is False and text is not None:
		print imgObj['ring_obs_id']+" -> "+imgObj['url']
		print utils.striphtml(text['post'])
	elif text is not None:
		print imgObj['url']
		print utils.striphtml(text['post'])
		postToTumblr(imgObj['url'], text, choosenCraft['craft'])
	else:
		print 'Error while generating post for'+imgObj['ring_obs_id']+'.\nSkipping.'
	
		
	print '\n----------------------\n'
Example #18
0
    def _gen_asteroid(self):
        """Generates a new asteroid

        Returns:
            a new, randomly generated asteroid
        """
        # Get a random size, with probability depending on the game
        # rules
        size = weighted_choice(self.curr_level.size_weights)

        # Generate a position out of bounds, and a random direction
        # to move towards
        possible_x = range(-60, -10, 10) + range(WINDOW_WIDTH+20,
                                                 WINDOW_WIDTH+70, 10)
        possible_y = range(-60, -10, 10) + range(WINDOW_HEIGHT+20,
                                                 WINDOW_HEIGHT+70, 10)
        pos = Vector(rand.choice(possible_x), rand.choice(possible_y))
        direction = rand_direction(pos)

        # Generate random linear and rotational speeds
        lin_speed = rand.uniform(Asteroid.min_lin_speed,
                                 Asteroid.max_lin_speed)
        rot_speed = rand.uniform(0, Asteroid.max_rot_speed)

        return Asteroid(size, direction, lin_speed, rot_speed, pos=pos)
Example #19
0
def random_vibraphone_voicing(lowest, highest):
    # Voicing of the harmonic series
    prototype = [12, 19, 24, 28, 31, 34, 36, 38, 40, 42, 43, 44]
    offset = weighted_choice([0, 1, 2], [5, 4, 2])
    prototype = prototype[offset:]
    prototype = [p - prototype[0] for p in prototype]

    lowest = random.randint(lowest, lowest + 9)
    highest = random.randint(highest - 8, highest)

    options = [lowest + p for p in prototype if lowest + p < highest]

    len_options = len(options)

    if len_options < 5:
        return random_vibraphone_voicing(lowest, highest)

    if len_options >= 8:
        most = 8
    else:
        most = len_options
    n = random.randint(5, most)

    voicing = random.sample(options, n)
    voicing.sort()
    return voicing
Example #20
0
    def add_chromatic_interval(self, note, prev):
        interval = prev['pitch'] - note['pitch']
        if interval > 0:
            direction = 'ascending'
        if interval < 0:
            direction = 'descending'
        if interval == 0:
            direction = random.choice(['ascending', 'descending'])

        # Choose the number of notes in the ornament
        if prev['duration'] >= 1:
            max_notes = 4
            n = weighted_choice(range(1, max_notes + 1), [10, 9, 7, 5])
        elif prev['duration'] >= 0.75:
            max_notes = 3
            n = random.randint(1, max_notes)
        else:
            max_notes = 2
            n = random.randint(1, max_notes)

        orn = scored_ornaments.choose(n, direction)

        np = int(note['pitch'])
        orn_type = [np + p for p in orn]
        return orn_type
Example #21
0
    def client_write(self, data, conn_id, index=None):
        """Pick a client connector and write the data.
        Triggered by proxy_recv or proxy_finish.
        """

        if len(self.client_connectors) == 0:
            if self.retry_count < self.max_retry:
                logging.warning("no available socket")
                return reactor.callLater(1, lambda: self.client_write(data, conn_id, index))
            return
            # TODO: reload coordinator
        if conn_id not in self.client_write_queues_index:
            self.client_write_queues_index[conn_id] = 100000
            self.client_recved_queues_index[conn_id] = 100000
            self.client_write_buffer[conn_id] = dict()
        if self.swap_count <= 0 or not self.preferred_conn.authenticated:
            # TODO: better algorithm
            f = lambda c: 1.0 / (c.latency ** 2 + 1)
            self.preferred_conn = weighted_choice(self.client_connectors, f)
            self.preferred_conn.latency += 100
            self.swap_count = 8
        else:
            self.swap_count -= 1
        if index:
            self.preferred_conn.write(
                data, conn_id, index)
        else:
            self.preferred_conn.write(
                data, conn_id, str(self.client_write_queues_index[conn_id]))
            self.client_write_buffer[conn_id][
                self.client_write_queues_index[conn_id]] = data
            self.client_write_queues_index[conn_id] += 1
            if self.client_write_queues_index[conn_id] == 1000000:
                self.client_write_queues_index[conn_id] = 100000
Example #22
0
def next_soloist_note(soloist_name, previous, harmony, movement_number, volume_section_number):
    out_of_tune_rate = OUT_OF_TUNE_RATE[volume_section_number]
    global FIRST_NOTE
    if FIRST_NOTE:
        out_of_tune_rate = 1.0
        FIRST_NOTE = False

    if soloist_name == 'Bb Clarinet':
        out_of_tune_rate = 0.0

    registers = REGISTERS[movement_number]
    register = registers[soloist_name]
    lowest = register['lowest']
    highest = register['highest']
    if previous == None:
        previous = random.randint(lowest, highest)

    if random.random() < out_of_tune_rate:
        options = [p for p in range(previous - 2, previous + 3) if p >= lowest and p <= highest]
        p = random.choice(options)
        interval = random.choice([1, 2])
        if interval == 2:
            pitch = [p - 1, p + 1]
        elif interval == 1:
            up_or_down = random.choice([1, -1])
            pitch = [p, p + up_or_down]
            pitch.sort()
    else:
        options = [p for p in range(previous - 7, previous + 8) if p % 12 in harmony and p >= lowest and p <= highest]
        ranked_by_distance = rank_by_distance(previous, options)
        weights = exp_weights(len(ranked_by_distance), exponent=1.5)
        pitch = weighted_choice(ranked_by_distance, weights)

    return pitch
Example #23
0
    def choose_root(self):
        return random.randint(0, 11)

        root_motion = weighted_choice([7, 5, 2, 10, 3, 8, 4, 9, 1, 11, 0, 6],
                                      range(24, 12, -1))
        root = (self.prev_root + root_motion) % 12
        self.prev_root = root
        return root
Example #24
0
 def build_text(self, length):
     for i in range(length):
         self.text.append(self.word)
         nextwords = []
         if not self.words.get(self.word):
             self.word = random.choice(list(self.words.keys()))
         else:
             self.word = utils.weighted_choice(self.words)
Example #25
0
    def get_random_instance(device, app):
        if not device.is_foreground(app):
            # if current app is in background, bring it to foreground
            component = app.get_package_name()
            if app.get_main_activity():
                component += "/%s" % app.get_main_activity()
            return IntentEvent(Intent(suffix=component))

        else:
            choices = {TouchEvent: 6, LongTouchEvent: 2, SwipeEvent: 2}
            event_type = utils.weighted_choice(choices)
            return event_type.get_random_instance(device, app)
Example #26
0
File: ants.py Project: yarox/alos
    def step(self, graph):
        current = self.solution[-1]
        neighbors = list(set(graph.neighbors(current)) - set(self.visited))

        if not neighbors:
            raise RuntimeError('agent trapped')

        weights = [graph[current][n]['weight'] for n in neighbors]
        next = neighbors[weighted_choice(weights)]

        self.solution.append(next)
        self.visited.append(current)
Example #27
0
def ornament_bridge(a, b, n=None, prev_duration=0.75, width=2):
    """Find notes that bridge the interval between a and b"""

    if n is None:
        # Choose the number of notes in the ornament
        if prev_duration >= 0.75:
            n = weighted_choice([1, 2, 3, 4, 5, 6], [3, 3, 4, 5, 4, 3])
        else:
            n = weighted_choice([1, 2, 3], [3, 4, 5])

    interval = b - a
    direction = 0
    if interval > 0:
        direction = 1
    if interval < 0:
        direction = -1

    if direction == 0:
        option_groups = [range(int(a - width), int(a + width + 1))] * n

    else:
        offset_interval = float(interval) / n
        option_groups = []
        for offset in list(frange(a, b, offset_interval)):
            middle = int(round(offset))
            opts = range(middle - width, middle + width + 1)
            option_groups.append(opts)

    # Prevent the last note in the ornament from being the target note.
    if b in option_groups[-1]:
        option_groups[-1].remove(b)

    ornaments = []
    for opts in option_groups:
        choice = choose(opts, ornaments)
        ornaments.append(choice)

    return ornaments
Example #28
0
    def clusters_next(self):
        changing, not_changing = self.clusters_pick_changing_instrument()
        new_pitch = self.clusters_pick_new_pitch(changing, not_changing)

        total_event_duration = 0.0
        if random.randint(2, 17) < changing.beats_since_last_rest():
            # If the last note in the phrase was a quarter note, make it longer
            if changing[-1].duration == 1:
                # Make it even longer if the revealed harmony is good
                revealed_harmony = self.clusters_get_revealed_harmony(
                    not_changing)
                nice_dyads = [0, 1, 2, 7, 12]
                if revealed_harmony in nice_dyads:
                    options_for_durations_to_add = [
                        1.0, 2.0, 2.0, 2.0, 3.0, 4.0
                    ]
                else:
                    options_for_durations_to_add = [1.0, 1.0, 1.0, 2.0]

                dur_to_add = random.choice(options_for_durations_to_add)
                for instrument in self.clusters:
                    instrument[-1].duration += dur_to_add

            self.stats['beats_since_last_rest'][
                changing.beats_since_last_rest()] += 1

            # Add a rest before the next note
            rest_duration_options = [1, 2]
            rest_duration_weights = [16, 1]
            if changing.beats_since_last_rest(rest_duration=4) > 40:
                if random.random() < .5:
                    rest_duration_options = [4, 5, 6, 7]
                    rest_duration_weights = [16, 12, 2, 1]

            rest_duration = weighted_choice(rest_duration_options,
                                            rest_duration_weights)

            total_event_duration += rest_duration
            changing.add_note(pitch='rest', duration=rest_duration)

        note_duration = random.choice([1, 1, 1, 1, 1, 2, 2, 3])
        total_event_duration += note_duration

        changing.add_note(pitch=new_pitch, duration=note_duration)

        for i in not_changing:
            i[-1].duration += total_event_duration

        harmony = pitches_to_chord_type([i[-1].pitch for i in self.clusters])
        self.stats['harmonies'][harmony] += 1
Example #29
0
def BATFGraph(m0 = 10, m = 1):
    # initialize graph with m0 vertices
    g = Graph(n = m0, directed=True)
    for v in xrange(m0):
        # PA step
        weights = g.vs.degree()
        u = weighted_choice(weights)
        g.add_edges((v,u))
        # TF step
        neighbors_u = g.neighbors(u)
        if neighbors_u:
            w = random.choice(neighbors_u)
            g.add_edges((v,w))
    return g
def choose_next_harmony(history, chord_type):
    last = history[-1]
    intervals = pitches_to_intervals(chord_type)
    chords = build_chord_type_on_all_roots(intervals)

    scored = []
    for chord in chords:
        transition_score = score_transition(last, chord)
        scored.append({"chord": chord, "transition_score": transition_score})

    scored.sort(key=lambda x: x["transition_score"], reverse=True)

    options = scored[:6]
    weights = [10, 5, 3, 2, 1]
    choice = weighted_choice(options, weights)
    return choice["chord"]
Example #31
0
 def random_successor(self, node):
     clause_vector = node.state
     possible_literals, flip_weights, constraints, pset, nset = node.extra
     index = weighted_choice(flip_weights)
     new_j = choice([
         j for j in range(len(possible_literals[index]))
         if j != clause_vector[index]
     ])
     new_clause_vector = tuple(new_j if i == index else j
                               for i, j in enumerate(clause_vector))
     score = clause_vector_score(new_clause_vector, possible_literals,
                                 constraints, pset, nset)
     return Node(new_clause_vector,
                 None,
                 None,
                 -1 * score,
                 extra=node.extra)
Example #32
0
def replaceChars(token, subData):
    subProb = subData["count"]
    subMatrix = subData["subs"]
    appliable = {k: subProb[k] for k in subProb.keys() if k in token}
    subCandidates = list(appliable.keys())
    shuffle(subCandidates)
    tokenBitMask = [0 for char in token]
    for sub in subCandidates:
        subProb = appliable[sub]
        subWith = weighted_choice(subMatrix[sub])
        for start in find_all(token, sub):
            if sum(tokenBitMask[start:start + len(sub)]
                   ) == 0 and probability_boolean(subProb):
                token = token[:start] + subWith + token[start + len(sub):]
                tokenBitMask = tokenBitMask[:start] + \
                    [1 for c in subWith] + tokenBitMask[start+len(sub):]
    return token
Example #33
0
def random_word(n, ngram, prev_ngram, prefix=None):
    """Generate random word of length n with given prefix

    ngram -- ngram frequency array of depth k,
    prev_ngram -- array of depth k-1"""

    def init():
        if prefix:
            return prefix
        return weighted_choice(as_dict(prev_ngram).items())


    def depth():
        c = 0
        obj = prev_ngram
        while type(obj) == list:
            c, obj = c + 1, obj[0]
        return c


    FORBIDDEN_ENDINGS = u"ъыь"


    word = init()
    k = depth()
    iters_left = 100
    while len(word) != n:
        iters_left -= 1
        if iters_left == 0:
            # if the word with given prefix cannot be generated
            # we generate fully random word
            word = random_word(n, ngram, prev_ngram)
            break
        idx = weighted_choice(
                enumerate(access_ngram(ngram, word[-k:]))
            )
        if idx is None or (
                len(word) == n-1 and RUSSIAN_ALPHABET[idx] in FORBIDDEN_ENDINGS):
            if len(word) <= k + 1:
                word = init()
            else:
                word = word[:-2]
        else:
            word += RUSSIAN_ALPHABET[idx]
    return word
    def make_rhythm(self, n_bars):
        rhythm = []
        subdivisions = self._choose_subdivisions(n_bars)
        for n in subdivisions:
            choice = weighted_choice(self.OPTIONS[n], self.WEIGHTS[n])
            rhythm.extend(choice)

        # Make sure this rhythm is the right length
        # total = 0
        # for duration in rhythm:
        #     if isinstance(duration, tuple):
        #         duration = sum(duration)
        #     total += duration
        # if total != (n_bars * 16):
        #     print 'Whoa! Wrong length.', n_bars, total, subdivisions, rhythm
        #     raise Exception()

        return rhythm
Example #35
0
    def __generate_session(self):
        possible_initial_screen = [
            screen for screen in self.__screens
            if screen.get('can_be_initial', False)
        ]
        random_start_screen = choice(possible_initial_screen)
        user_journey_length = randint(2, 12)
        journey = [random_start_screen]
        actions = [*self.__generate_actions_on_screen(journey[0])]
        for i in range(1, user_journey_length):
            prev_screen = journey[i - 2] if i >= 2 else None
            curr_screen = journey[i - 1]
            last_action = {}
            if 1 <= i < len(actions):
                last_action = actions[i - 1]

            action_navigation_screen_id = last_action.get('navigates_to', None)
            if action_navigation_screen_id is not None:
                screen_to_navigate_on_action = self.get_screen_by_id(
                    action_navigation_screen_id)
                if screen_to_navigate_on_action:
                    journey.append()
                continue

            next_possible_screen_weighted_ids = curr_screen.get(
                'can_go_to', []).copy()
            if prev_screen:
                next_possible_screen_weighted_ids.append(
                    [prev_screen['id'], 20])

            if len(next_possible_screen_weighted_ids) == 0:
                if prev_screen:
                    journey.append(prev_screen)
                else:
                    break
            else:
                next_screen_id = utils.weighted_choice(
                    next_possible_screen_weighted_ids)
                journey.append(self.get_screen_by_id(next_screen_id))

        for screen in journey:
            screen['actions'] = self.__generate_actions_on_screen(screen)

        return journey
Example #36
0
def view_status_code(codes):
    """Return status code or random status code if more than one are given"""

    if ',' not in codes:
        code = int(codes)
        return status_code(code)

    choices = []
    for choice in codes.split(','):
        print choice
        if ':' not in choice:
            code = choice
            weight = 1
        else:
            code, weight = choice.split(':')
        choices.append((int(code), float(weight)))

    code = weighted_choice(choices)
    print code
    return status_code(code)
Example #37
0
    def choose_root(self):
        return random.randint(0, 11)

        root_motion = weighted_choice([
            7,
            5,
            2,
            10,
            3,
            8,
            4,
            9,
            1,
            11,
            0,
            6
        ], range(24, 12, -1))
        root = (self.prev_root + root_motion) % 12
        self.prev_root = root
        return root
Example #38
0
def next_bass_note(previous, harmony, lowest_pitch, highest_pitch):
    harmony = [p % 12 for p in harmony]
    options = [p for p in range(previous - 7, previous + 8) if p % 12 in harmony and p >= lowest_pitch and p <= highest_pitch]
    ranked_by_distance = rank_by_distance(previous, options)
    ranked_by_best_root = rank_by_best_root(harmony, options)

    ranks = defaultdict(list)
    len_options = len(options)
    for p in options:
        distance_rank = len_options - ranked_by_distance.index(p)
        root_rank = len_options - ranked_by_best_root.index(p)
        rank = distance_rank + root_rank
        ranks[rank].append(p)
    ranked = []
    for k in sorted(ranks.keys(), reverse=True):
        random.shuffle(ranks[k])
        ranked.extend(ranks[k])

    weights = exp_weights(len(ranked))
    return weighted_choice(ranked, weights)
Example #39
0
 def gettheme(self, biomeid):
     # Choose DICT based on biome
     if (biomeid == 2 or     # Desert
         biomeid == 17):     # DesertHills
         theme_weights = [('egyptian', 50),
                          ('greek', 10),
                          ('roman', 10)]
     elif (biomeid == 5 or   # Taiga
           biomeid == 10 or  # FrozenOcean
           biomeid == 12 or  # Ice Plains
           biomeid == 13 or  # Ice Mountains
           biomeid == 19):   # TaigaHills
         theme_weights = [('norse', 50),
                          ('elven', 10),
                          ('saxon', 10)]
     elif (biomeid == 6 or   # Swampland
           biomeid == 3 or   # ExtremeHills
           biomeid == 20 or  # ExteremeHillsEdge
           biomeid == 1):    # Plains
         theme_weights = [('saxon', 20),
                          ('roman', 10),
                          ('greek', 10)]
     elif (biomeid == 4 or   # Forest
           biomeid == 18):   # ForestHills
         theme_weights = [('elven', 50),
                          ('roman', 10),
                          ('norse', 10)]
     elif (biomeid == 21 or  # Jungle
           biomeid == 22):   # Jungle Hills
         theme_weights = [('mayan', 60),
                          ('elven', 10)]
     elif (biomeid == 14 or  # MushroomIsland
           biomeid == 15):   # MushroomIslandShore
         theme_weights = [('welsh', 1)]
     else:                   # The rest. Including rivers, oceans etc
         theme_weights = [('saxon', 10),
                          ('roman', 10),
                          ('greek', 10),
                          ('norse', 10),
                          ('elven', 10)]
     return weighted_choice(theme_weights)
Example #40
0
 def make_bars(self):
     bar_index = 0
     for movement_number in Conf.movements:
         for drone in [True, None]:
             if drone:
                 drone = self.drones[movement_number]
             for volume in ["q1", "l1", "q2", "l2"]:
                 n_bars = weighted_choice(Conf.n_bars_options[movement_number], Conf.n_bars_weights[movement_number])
                 for bar_n in range(n_bars):
                     bar = dict(
                         movement_number=movement_number,
                         movement_name=Conf.movement_names[movement_number],
                         drone=drone,
                         volume=volume,
                         bar_index=bar_index,
                         soloist=Conf.soloist[movement_number],
                         accompanists=Conf.accompanists[movement_number] if volume.startswith("l") else (),
                         dynamics=Conf.dynamics[movement_number][volume[0]],
                     )
                     bar["dynamics"]["drone"] = Conf.dynamics[movement_number]["drone"]
                     self.bars.append(bar)
                     bar_index += 1
Example #41
0
    def client_write(self, data, conn_id, assigned_index=None):
        """Pick a client connector and write the data.
        Triggered by proxy_recv or proxy_finish.
        """

        conns_avail = filter(
            lambda _: _ not in (None, 1), self.client_connectors_pool)
        if not len(conns_avail):
            if self.retry_count < self.max_retry and self.req_num == 1:
                logging.warning("no available socket")
                return reactor.callLater(1, lambda: self.client_write(data, conn_id, assigned_index))
            else:
                self.dispose()
            return
            # TODO: reload coordinator
        if conn_id not in self.proxy_recv_index_dict:
            self.proxy_recv_index_dict[conn_id] = 100000
        if self.swap_count <= 0 or not self.preferred_conn.authenticated:
            # TODO: better algorithm
            f = lambda c: 1.0 / (c.latency ** 2 + 1)
            self.preferred_conn = weighted_choice(conns_avail, f)
            self.preferred_conn.latency += 100
            self.swap_count = 8
        else:
            self.swap_count -= 1
        if assigned_index:
            self.preferred_conn.write(data, conn_id, assigned_index)
        else:
            index = self.proxy_recv_index_dict[conn_id]
            self.preferred_conn.write(data, conn_id, str(index))
            i = self.client_connectors_pool.index(self.preferred_conn)
            if conn_id not in self.client_buf_pool[i]:
                self.client_buf_pool[i][conn_id] = deque()
            self.client_buf_pool[i][conn_id].append((index, data))
            self.proxy_recv_index_dict[conn_id] += 1
            if self.proxy_recv_index_dict[conn_id] == 1000000:
                # TODO: raise exception / cut connection
                self.proxy_recv_index_dict[conn_id] = 100000
def choose_primary():
    options = [
        (0, 4, 7),
        (0, 3, 7),
        (0, 4, 7, 10),
        (0, 3, 7, 10),
        (0, 7),
        (0, 4, 7, 11),
        (0, 5, 7),
        (0, 5),
        (0, 4),
    ]
    weights = [
        47,
        19,
        15,
        7,
        6,
        2,
        2,
        1,
        1,
    ]
    return weighted_choice(options, weights)
Example #43
0
    def sample_table(self, t_n, d_n, u_n):
        """Samples table b_n and topic z_n together for the event n.


        Parameters
        ----------
        t_n : float
            The time of the event.

        d_n : list
            The document for the event.

        u_n : int
            The user id.


        Returns
        -------
        table : int

        dish : int
        """
        if self.total_tables_per_user[u_n] == 0:
            # This is going to be the user's first table
            self.dish_on_table_per_user[u_n] = {}
            self.user_table_cache[u_n] = {}
            self.time_previous_user_event[u_n] = 0

        tables = range(self.total_tables_per_user[u_n])
        num_dishes = len(self.dish_counters)
        intensities = []
        dn_word_counts = Counter(d_n)
        count_dn = len(d_n)
        # Precompute the doc_log_likelihood for each of the dishes
        dish_log_likelihood = []
        for dish in self.dish_counters:
            dll = self.document_log_likelihood(dn_word_counts, count_dn,
                                               dish)
            dish_log_likelihood.append(dll)

        table_intensity_threshold = 1e-8  # below this, the table is inactive

        # Provide one option for each of the already open tables
        mu = self.mu_per_user[u_n]
        total_table_int = mu
        dish_log_likelihood_array = []
        for table in tables:
            if table in self.active_tables_per_user[u_n]:
                dish = self.dish_on_table_per_user[u_n][table]
                alpha = self.time_kernels[dish]
                t_last, sum_kernels = self.user_table_cache[u_n][table]
                update_value = self.kernel(t_n, t_last)
                table_intensity = alpha * sum_kernels * update_value
                table_intensity += alpha * update_value
                total_table_int += table_intensity
                if table_intensity < table_intensity_threshold:
                    self.active_tables_per_user[u_n].remove(table)
                dish_log_likelihood_array.append(dish_log_likelihood[dish])
                intensities.append(table_intensity)
            else:
                dish_log_likelihood_array.append(0)
                intensities.append(0)
        log_intensities = [ln(inten_i / total_table_int) + dish_log_likelihood_array[i]
                           if inten_i > 0 else -float('inf')
                           for i, inten_i in enumerate(intensities)]

        # Provide one option for new table with already existing dish
        for dish in self.dish_counters:
            dish_intensity = (mu / total_table_int) *\
                self.dish_counters[dish] / (self.total_tables + self.beta)
            dish_intensity = ln(dish_intensity)
            dish_intensity += dish_log_likelihood[dish]
            log_intensities.append(dish_intensity)

        # Provide a last option for new table with new dish
        new_dish_intensity = mu * self.beta /\
            (total_table_int * (self.total_tables + self.beta))
        new_dish_intensity = ln(new_dish_intensity)
        new_dish_log_likelihood = self.document_log_likelihood(dn_word_counts,
                                                               count_dn,
                                                               num_dishes)
        new_dish_intensity += new_dish_log_likelihood
        log_intensities.append(new_dish_intensity)

        normalizing_log_intensity = logsumexp(log_intensities)
        intensities = [exp(log_intensity - normalizing_log_intensity)
                       for log_intensity in log_intensities]
        self._Qn = normalizing_log_intensity
        k = weighted_choice(intensities, self.prng)
        opened_table = False
        if k in tables:
            # Assign to one of the already existing tables
            table = k
            dish = self.dish_on_table_per_user[u_n][table]
            # update cache for that table
            t_last, sum_kernels = self.user_table_cache[u_n][table]
            update_value = self.kernel(t_n, t_last)
            sum_kernels += 1
            sum_kernels *= update_value
            self.user_table_cache[u_n][table] = (t_n, sum_kernels)
        else:
            k = k - len(tables)
            table = len(tables)
            self.total_tables += 1
            self.total_tables_per_user[u_n] += 1
            dish = k
            # Since this is a new table, initialize the cache accordingly
            self.user_table_cache[u_n][table] = (t_n, 0)
            self.dish_on_table_per_user[u_n][table] = dish
            opened_table = True
            if dish not in self.time_kernel_prior:
                self.time_kernel_prior[dish] = self.alpha_0
                dll = self.document_log_likelihood(dn_word_counts, count_dn,
                                                   dish)
                dish_log_likelihood.append(dll)

        self.table_history_with_user.append((u_n, table))
        self.time_previous_user_event[u_n] = t_n
        return table, dish, opened_table, dish_log_likelihood[dish]
def main():
  # Get all resources from specified website
  page = requests.get(home_page)
  # tree = html.fromstring(page.text)
  source = page.text
  resources = []
  a = source.split('href="')

  for href in a:
    if ('.html' in href) or ('.jsp' in href):
      resources.append(href.split('"')[0])
  resources = resources[1:]

  user_agents_dir = "user_agents/"
  useragents_list = glob.glob(user_agents_dir + '*.txt')
  all_user_agents = []

  for file in useragents_list:
    all_user_agents.append(open(file, 'r').readlines())

  f = open('out.log', 'w')
  s = open('suspicious.log', 'w')
  
  while True:
    try:
      ip = str(randint(10,255)) + '.' + str(randint(0,255)) + '.' + str(randint(0,255)) + '.' + str(randint(0,255))
      date = str(u.random_date(initial_date, final_date))
      date = date.replace(" ", ":").replace("-", "/").split(' ')[0]
      resource = str(choice(resources))
      request = "GET " + resource
      response = str(u.weighted_choice([	
				(http_responses[0], 90), 
				(http_responses[1], 10), 
				(http_responses[2], 40), 
				(http_responses[3], 30), 
				(http_responses[4], 50)
			     ]))

      response_bytes = str(randint(2000,5000))
      referer = str(u.weighted_choice([
			(referers[0], 20),
                        (referers[1], 40),
                        (referers[2], 50),
                        (referers[3], 30),
                        (referers[4], 30),
                        (referers[5], 20),
                        (referers[6], 50),
                        (referers[7], 40),
                        (referers[8], 40),
                        (referers[9], 15),
                        (referers[10],15),
			]))
      user_agent = str(choice(choice(all_user_agents))).split("\n")[0]

      if process_ip(ip):
        # write in suspicious file
        s.write(ip + ' -' + ' - '  +'[' + date + ']' + ' ' + '"' + request + '"' + ' ' + response + ' ' + response_bytes + ' ' + '"' + referer + '"' + ' ' + '"' + user_agent + '"' + '\n')
      else:
        f.write(ip + ' -' + ' - '  +'[' + date + ']' + ' ' + '"' + request + '"' + ' ' + response + ' ' + response_bytes + ' ' + '"' + referer + '"' + ' ' + '"' + user_agent + '"' + '\n')

    except KeyboardInterrupt:
      print 'KeyboradInterrupt exception raised: Generating out_log...'
      f.write(ip + ' -' + ' - '  +'[' + date + ']' + ' ' + '"' + request + '"' + ' ' + response + ' ' + response_bytes + ' ' + '"' + referer + '"' + ' ' + '"' + user_agent + '"' + '\n')
      sys.exit()
def next_accompaniment_notes(name_a, name_b, previous_a, previous_b, harmony, unused_harmony, movement_number):
    registers = REGISTERS[movement_number]

    a_register = registers[name_a]
    b_register = registers[name_b]

    previous_a = get_previous(previous_a)
    previous_b = get_previous(previous_b)

    if previous_a == None:
        previous_a = random.randint(a_register['lowest'], a_register['highest'])

    if previous_b == None:
        previous_b = random.randint(b_register['lowest'], b_register['highest'])

    a_options = build_options(previous_a, harmony, unused_harmony, a_register['lowest'], registers[name_a]['highest'])
    b_options = build_options(previous_b, harmony, unused_harmony, b_register['lowest'], registers[name_b]['highest'])

    a_weights = exp_weights(len(a_options))
    b_weights = exp_weights(len(b_options))

    max_weight = a_weights[0] + b_weights[0]

    weighted_interval_options = []
    for a, a_weight in zip(a_options, a_weights):
        for b, b_weight in zip(b_options, b_weights):
            interval_class = get_interval_class(a, b)
            if interval_class == 1:
                continue
            if interval_class in [5, 4, 3]:
                weight = max_weight
            elif interval_class in [2, 0]:
                weight = max_weight / 2
            elif interval_class == 6:
                weight = 0

            if a == b:
                weight = 0

            weight = weight + a_weight + b_weight

            weighted_interval_options.append(((a, b), weight))

    choice_a, choice_b = weighted_choice(*zip(*weighted_interval_options))

    # Add double stops
    if name_a == 'Violin' and name_b == 'Cello':
        new_choice_a = None
        new_a_options = []
        for p in a_options:
            interval_class = get_interval_class(choice_a, p)
            in_other = p % 12 == choice_b % 12
            if interval_class in [3, 4, 5] or in_other and p != choice_a:
                new_a_options.append(p)
        a_options = new_a_options
        if a_options:
            violin_second_note = random.choice(a_options)
            new_choice_a = [choice_a, violin_second_note]

        new_choice_b = None
        new_b_options = []
        for p in b_options:
            interval_class = get_interval_class(choice_b, p)
            in_other = p % 12 == choice_a % 12
            if interval_class in [3, 4, 5] or in_other and p != choice_b:
                new_b_options.append(p)
        b_options = new_b_options
        if b_options:
            cello_second_note = random.choice(b_options)
            new_choice_b = [choice_b, cello_second_note]

        if new_choice_a:
            choice_a = new_choice_a

        if new_choice_b:
            choice_b = new_choice_b

    return choice_a, choice_b
Example #46
0
def get_target_offset(numerator):
    beat_types = {}
    beat_types[2] = [
        [0],
        [1],
        list(frange(0.5, 1, 1)),
        list(frange(0.25, 1, 0.5)),
    ]
    beat_types[4] = [
        [0],
        [2],
        [1, 3],
        list(frange(0.5, 3, 1)),
        list(frange(0.25, 3, 0.5)),
    ]
    beat_types[8] = [
        [0],
        [4],
        [2, 6],
        [1, 3, 5, 7],
        list(frange(0.5, 7, 1)),
        list(frange(0.25, 7, 0.5)),
    ]

    beat_type_weights = {}
    beat_type_weights[2] = scale_list([6, 5, 3, 1])
    beat_type_weights[4] = scale_list([7, 6, 5, 3, 1])
    beat_type_weights[8] = scale_list([8, 7, 6, 5, 3, 1])

    level = weighted_choice(beat_types[numerator], beat_type_weights[numerator])



    split_point = int(num_options * .75)
    a = level[:split_point]
    b = level[split_point:]


    numerator

    num_options = len(level)
    if num_options == 1:
        return level[0]
    elif num_options == 2:
        return random.choice(level)
    else:
        split_point = int(num_options * .75)
        a = level[:split_point]
        b = level[split_point:]
        if random.random() < 0.9:
            return random.choice(a)
        else:
            return random.choice(b)






    beats = []
    weights = []
    for beat_type, w in zip(beat_types, beat_type_weights):
        weight = w / len(beat_type)
        for beat in beat_type:
            weights.append(weight)
            beats.append(beat)
    return beats, weights
Example #47
0
def choose_meter_position():
    beats, weights = METER_WEIGHTS
    return weighted_choice(beats, weights)
Example #48
0
 def choose(self):
     weights, options = zip(*self.weighted_options)
     choice = weighted_choice(options, weights)
     if isinstance(choice, S):
         return choice.choose()
     return choice
 def choose(self):
     choice = weighted_choice(self.options, self.weights)
     if choice.type == 'terminal':
         return choice.value
     else:
         return choice.choose()
Example #50
0
# -*- coding: utf-8 -*-

import os
import time
import random
from utils import shoot, random, spinning_cursor, rand_string, weighted_choice

i = 0
curr = 0
while True:
    disp = int((curr + random.uniform(1, 35)) / 2.)  # smooth it out
    curr = disp

    attrs = None if disp > 25 else ['dark']

    shoot('{0: <35}'.format("|" * disp), 'white', attrs=attrs)
    time.sleep(random.random() * 0.1)
    i += 1

    # occasionally clear the screen and output rand string
    if i >= 100:
        if weighted_choice([(True, 1), (False, 9)]):
            os.system('clear')
            shoot("\n%s\n" % rand_string(random.randint(200, 800)),
                  color='red')
            spinning_cursor(random.random() * 0.5)
        i = 0
def main(argv):

  http_responses = [200, 400, 403, 404, 500]

  referers = 	['http://www.rankia.com/', 
		'http://www.elblogsalmon.com/', 
		'http://www.finanzas.com/',
		'http://www.bankimia.com/',
		'http://www.elconfidencial.com/mercados/',
		'http://www.invertia.com/',
		'http://cincodias.com/',
		'http://www.expansion.com/',
		'http://www.eleconomista.es/',
		'https://www.facebook.com/',
		'https://www.twitter.com/',
		'https://www.linkedin.com/'
		]

  # initial_date = datetime.strptime('09/24/2015 12:00 AM', '%m/%d/%Y %I:%M %p')
  # final_date = datetime.strptime('9/24/2015 11:59 PM', '%m/%d/%Y %I:%M %p')

  # Get all resources from specified website
  page = requests.get('https://www.bbva.es/particulares/index.jsp')
  # tree = html.fromstring(page.text)
  source = page.text
  resources = []
  a = source.split('href="')
  for href in a:
    if ('.html' in href) or ('.jsp' in href):
      resources.append(href.split('"')[0])
  resources = resources[1:]

  user_agents_dir = "user_agents/"
  useragents_list = glob.glob(user_agents_dir + '*.txt')
  all_user_agents = []
  for file in useragents_list:
    all_user_agents.append(open(file, 'r').readlines())

  # f = open('out_log.log', 'w')

  current_time = strftime("%Y-%m-%d_%H:%M:%S", gmtime())
  f = open(current_time + '.log', 'w')
  rows = 0

  d1 = datetime.strptime(str(argv[0]) + ' 12:00 AM', '%m/%d/%Y %I:%M %p')
  d2 = datetime.strptime(str(argv[0]) + ' 11:59 PM', '%m/%d/%Y %I:%M %p')

  while True:
    try:
      ip = str(randint(10,255)) + '.' + str(randint(0,255)) + '.' + str(randint(0,255)) + '.' + str(randint(0,255))
      # date = str(u.random_date(initial_date, final_date))
      date = str(u.random_date(d1, d2))
      date = date.replace(" ", ":").replace("-", "/").split(' ')[0]
      resource = str(choice(resources))
      request = "GET " + resource
      # response = str(random.choice(http_responses)) # [200, 400, 403, 404, 500]
      response = str(u.weighted_choice([	
				(http_responses[0], 90), 
				(http_responses[1], 10), 
				(http_responses[2], 40), 
				(http_responses[3], 30), 
				(http_responses[4], 50)
			     ]))

      response_bytes = str(randint(2000,5000))
      # referer = str(choice(referers))
      referer = str(u.weighted_choice([
			(referers[0], 20),
                        (referers[1], 40),
                        (referers[2], 50),
                        (referers[3], 30),
                        (referers[4], 30),
                        (referers[5], 20),
                        (referers[6], 50),
                        (referers[7], 40),
                        (referers[8], 40),
                        (referers[9], 15),
                        (referers[10],15),
                        (referers[11],15),
			]))
      user_agent = str(choice(choice(all_user_agents))).split("\n")[0]

      # print ip, date, request, response, response_bytes, referer, user_agent
      if (rows % 10 == 0): # row count mod 10 is 0
        f.write(ip + ' -' + ' - '  +'[' + date + ']' + ' ' + '"' + request + '"' + ' ' + response + ' ' + response_bytes + ' ' + '"' + referer + '"' + ' ' + '"' + user_agent + '"' + '\n')
        rows += 1
        current_time = strftime("%Y-%m-%d_%H:%M:%S", gmtime())
        f = open(current_time + '.log', 'w')
      else: 
        f.write(ip + ' -' + ' - '  +'[' + date + ']' + ' ' + '"' + request + '"' + ' ' + response + ' ' + response_bytes + ' ' + '"' + referer + '"' + ' ' + '"' + user_agent + '"' + '\n')
        rows += 1

    except KeyboardInterrupt:
      print 'KeyboradInterrupt exception raised: Generating out_log...'
      f.write(ip + ' -' + ' - '  +'[' + date + ']' + ' ' + '"' + request + '"' + ' ' + response + ' ' + response_bytes + ' ' + '"' + referer + '"' + ' ' + '"' + user_agent + '"' + '\n')
      sys.exit()
Example #52
0
    def render(self):
        # Figure out what sort of thing will be fired
        name = weighted_choice(cfg.master_projectile_traps)
        data_tag = cfg.lookup_projectile_traps[name][2]
        name = cfg.lookup_projectile_traps[name][0]

        # Start position
        pos = self.position.down(5) + self.dl - self.dw

        # Materials lookup
        # Default is looking East
        mat = {
            'RW': [materials.RedstoneWire, 0],
            '*>': [materials.RedstoneRepeaterOff, 2],
            '<*': [materials.RedstoneRepeaterOff, 0],
            'C1': [materials.CommandBlock, 0],
            'C2': [materials.CommandBlock, 0],
            '[]': [materials.StoneBrick, 3],
            '~P': [materials.StonePressurePlate, 0],
            '~T': [materials.TNT, 0],
        }

        # Commands
        cmds = {
            'C1': '/summon {0} ~ ~3 ~1.8 {{Motion:{1},direction:{1},{2}}}'.format(
                name,
                '[0.0,0.2,1.0]',
                data_tag),
            'C2': '/summon {0} ~ ~3 ~-1.8 {{Motion:{1},direction:{1},{2}}}'.format(
                name,
                '[0.0,0.2,-1.0]',
                data_tag)}

        # If looking South, rotate some materials, and adjust the command
        # blocks.
        if self.direction == dirs.S:
            mat['*>'][1] = 1
            mat['<*'][1] = 3
            cmds = {
                'C1': '/summon {0} ~1.8 ~3 ~ {{Motion:{1},direction:{1},{2}}}'.format(
                    name,
                    '[1.0,0.2,0.0]',
                    data_tag),
                'C2': '/summon {0} ~-1.8 ~3 ~ {{Motion:{1},direction:{1},{2}}}'.format(
                    name,
                    '[-1.0,0.2,0.0]',
                    data_tag)}

        # Trap template.
        # tmpl[level][dl][dw]
        tmpl = [[
            ['C1', '<*', 'RW', '*>', 'C2'],
        ], [
            ['XX', 'XX', 'XX', 'XX', 'XX'],
        ], [
            ['XX', 'XX', '~P', 'XX', 'XX'],
        ], [
            ['XX', '[]', 'XX', '[]', 'XX'],
        ]]

        # Make boom!
        if self._explosions:
            tmpl[0][0][2] = '~T'
            tmpl[0][0][0] = '[]'
            tmpl[0][0][4] = '[]'

        # Repetitions for each template row and column.
        reps = {
            'w': [1, 1, self.size - 2, 1, 1],
            'l': [self.length - 2],
        }

        self.apply_template(tmpl, cmds, mat, reps, pos)

        # Vary the timing on the repeaters
        for p in iterate_cube(
            self.position.down(5),
            self.position.down(5) + self.dw * (self.size - 1) + self.dl * (self.length - 1)
        ):
            if (
                p in self.parent.blocks and
                self.parent.blocks[p].material == materials.RedstoneRepeaterOff
            ):
                self.parent.blocks[p].data += random.choice((4, 8, 12))
Example #53
0
    f.close()

i = 0
while True:
    freeze = random.random() * 0.3
    try:
        shoot(lines[i])
        i += 1
    except IndexError:
        i = 0
        # clear output each time the whole trace file is out
        os.system('clear')
        spinning_cursor(random.random())

    # occasionally output line breaks
    if weighted_choice([(True, 1), (False, 9)]):
        shoot('\n')

    # occasionally output table
    if weighted_choice([(True, 0.5), (False, 9.5)]):
        shoot('\n')
        shoot_table()
        freeze = random.uniform(0.2, 0.8)

    # occasionally output the whole random file from the current dir
    if weighted_choice([(True, 0.1), (False, 9.9)]):
        try:
            shoot_file()
        except IndexError:
            pass
        freeze = random.uniform(0.2, 0.8)
Example #54
0
    def sample_user_events(self,
                           min_num_events=100,
                           max_num_events=None,
                           t_max=None):
        """Samples events for a user.


        Parameters
        ----------
        min_num_events : int, default is 100
            The minimum number of events to sample.

        max_num_events : int, default is None
            If not None, this is the maximum number of events to sample.

        t_max : float, default is None
            The time limit until which to sample events.


        Returns
        -------
        events : list
            A list of the form [(t_i, doc_i, user_i, meta_i), ...] sorted by
            increasing time that has all the events of the sampled users.
            Above, doc_i is the document and meta_i is any sort of metadata
            that we want for doc_i, e.g. question_id. The generator will return
            an empty list for meta_i.
        """
        user = len(self.mu_per_user)
        mu_u = self.sample_mu()
        self.mu_per_user[user] = mu_u

        # Populate the list with the first event for each pattern
        next_time_per_pattern = [
            self.sample_next_time(pattern, user)
            for pattern in range(self.num_patterns)
        ]
        next_time_per_pattern = asfortranarray(next_time_per_pattern)

        iteration = 0
        over_tmax = False
        while iteration < min_num_events or not over_tmax:
            if max_num_events is not None and iteration > max_num_events:
                break
            z_n = next_time_per_pattern.argmin()
            t_n = next_time_per_pattern[z_n]
            if t_max is not None and t_n > t_max:
                over_tmax = True
                break
            num_tables_user = self.total_tables_per_user[user] \
                if user in self.total_tables_per_user else 0
            tables = range(num_tables_user)
            tables = [
                table for table in tables
                if self.dish_on_table_per_user[user][table] == z_n
            ]
            intensities = []

            alpha = self.time_kernels[z_n]
            for table in tables:
                t_last, sum_kernels = self.user_table_cache[user][table]
                update_value = self.kernel(t_n, t_last)
                table_intensity = alpha * sum_kernels * update_value
                table_intensity += alpha * update_value
                intensities.append(table_intensity)
            intensities.append(mu_u * self.pattern_popularity[z_n])
            log_intensities = [
                ln(inten_i) if inten_i > 0 else -float('inf')
                for inten_i in intensities
            ]

            normalizing_log_intensity = logsumexp(log_intensities)
            intensities = [
                exp(log_intensity - normalizing_log_intensity)
                for log_intensity in log_intensities
            ]
            k = weighted_choice(intensities, self.prng)

            if k < len(tables):
                # Assign to already existing table
                table = tables[k]
                # update cache for that table
                t_last, sum_kernels = self.user_table_cache[user][table]
                update_value = self.kernel(t_n, t_last)
                sum_kernels += 1
                sum_kernels *= update_value
                self.user_table_cache[user][table] = (t_n, sum_kernels)
            else:
                table = num_tables_user
                self.total_tables += 1
                self.total_tables_per_user[user] += 1
                # Since this is a new table, initialize the cache accordingly
                self.user_table_cache[user][table] = (t_n, 0)
                self.dish_on_table_per_user[user][table] = z_n

            if z_n not in self.first_observed_time or\
                    t_n < self.first_observed_time[z_n]:
                self.first_observed_time[z_n] = t_n
            self.dish_counters[z_n] += 1

            doc_n = self.sample_document(z_n)
            self._update_word_counters(doc_n.split(), z_n)
            self.document_history_per_user[user]\
                .append(doc_n)
            self.table_history_per_user[user].append(table)
            self.time_history_per_user[user].append(t_n)
            self.last_event_user_pattern[user][z_n] = t_n

            # Resample time for that pattern
            next_time_per_pattern[z_n] = self.sample_next_time(z_n, user)
            z_n = next_time_per_pattern.argmin()
            t_n = next_time_per_pattern[z_n]
            iteration += 1

        events = [(self.time_history_per_user[user][i],
                   self.document_history_per_user[user][i], user, [])
                  for i in range(len(self.time_history_per_user[user]))]

        # Update the full history of events with the ones generated for the
        # current user and re-order everything so that the events are
        # ordered by their timestamp
        self.events += events
        self.events = sorted(self.events, key=lambda x: x[0])
        self.num_users += 1
        return events
Example #55
0
def enchant(item, level, debug=False):
    # Based on the info available in the wiki as of 1.3.1:
    # http://www.minecraftwiki.net/wiki/Enchantment_Mechanics
    #
    # NBT for an item in a chest looks like this:
    #
    # Iron Sword (267) with Smite V, Knockback II, and Fire Aspect II
    #
    # TAG_List( "Items" ):
    #     TAG_Compound():
    #         TAG_Short( "id" ): 267
    #         TAG_Short( "Damage" ): 0
    #         TAG_Byte( "Count" ): 1
    #         TAG_Compound( "tag" ):
    #             TAG_List( "ench" ):
    #                 TAG_Compound():
    #                     TAG_Short( "id" ): 17
    #                     TAG_Short( "lvl" ): 5
    #
    #                 TAG_Compound():
    #                     TAG_Short( "id" ): 19
    #                     TAG_Short( "lvl" ): 2
    #
    #                 TAG_Compound():
    #                     TAG_Short( "id" ): 20
    #                     TAG_Short( "lvl" ): 2

    # Determine what type of item we are dealing with
    type = 'none'
    if 'sword' in item:
        type = 'sword'
    elif 'bow' in item and 'bowl' not in item:
        type = 'bow'
    elif ('pickaxe' in item or 'shovel' in item or 'shears' in item
          or 'hoe' in item or 'fishing rod' in item
          or 'carrot on a stick' in item or 'flint and steel' in item
          or 'axe' in item):
        type = 'tool'
    elif ('helmet' in item or 'chestplate' in item or 'leggings' in item
          or 'boots' in item):
        type = 'armor'
    elif (item == 'enchanted book'):
        type = 'book'
    elif ('shield' in item):
        type = 'shield'
    elif (item == 'elytra'):
        type = 'elytra'

    enchantability = 1.0
    material = ''
    # Determine material enchantability
    if 'wooden' in item:
        material = 'wood'
        enchantability = 15.0
    elif 'leather' in item:
        material = 'leather'
        enchantability = 15.0
    elif 'stone' in item:
        material = 'stone'
        enchantability = 5.0
    elif 'iron' in item:
        material = 'iron'
        enchantability = 14.0
        if type == 'armor':
            enchantability = 9.0
    elif 'chainmail' in item:
        material = 'chainmail'
        enchantability = 12.0
    elif 'diamond' in item:
        material = 'diamond'
        enchantability = 10.0
        if type == 'armor':
            enchantability = 10.0
    elif 'gold' in item:
        material = 'gold'
        enchantability = 22.0
        if type == 'armor':
            enchantability = 25.0

    # Modify the enchantment level
    # Step 1 = level plus random 0 - enchantability plus one
    mlevel = level + random.triangular(0, enchantability) + 1
    # Step 2 = vary by +- 25%
    mlevel = int(mlevel * random.triangular(0.75, 1.25) + .5)

    # Further determine the type
    if 'helmet' in item:
        type = 'helmet'
    elif 'chestplate' in item:
        type = 'chestplate'
    elif 'leggings' in item:
        type = 'leggings'
    elif 'boots' in item:
        type = 'boots'
    elif 'shears' in item:
        type = 'shears'
    elif 'hoe' in item:
        type = 'hoe'
    elif 'fishing rod' in item:
        type = 'fishing rod'
    elif 'carrot on a stick' in item:
        type = 'carrot on a stick'
    elif 'flint and steel' in item:
        type = 'flint and steel'
    elif 'axe' in item and 'pickaxe' not in item:
        type = 'axe'

    # Gather a list of possible enchantments and levels
    enchantments = {}
    prob = []

    def check_enchantment(ench, mlevel):
        for x in xrange(4, -1, -1):
            if (mlevel >= _ench_level[ench][x][0]
                    and mlevel <= _ench_level[ench][x][1]):
                enchantments[ench] = x + 1
                prob.append((ench, _ench_prob[ench]))
                return
        return

    if (cfg.enchant_system == 'table'):
        item_filter = _ench_items_table
    elif (cfg.enchant_system == 'extended'):
        item_filter = _ench_items_extended
    elif (cfg.enchant_system == 'zistonian'):
        item_filter = _ench_items_zistonian
    elif (cfg.enchant_system == 'anything'):
        item_filter = _ench_items_anything
    else:  # "table+book" and catch anything else
        item_filter = _ench_items_table_book

    # Loop through every enchantment and do check_enchantment if there
    # is a match for the item type
    for (enchant, name) in _ench_name.items():
        if (item_filter[enchant][0] == 'any' or type in item_filter[enchant]):
            check_enchantment(enchant, mlevel)

    # Item did not result in any enchantments
    if len(enchantments) == 0:
        return

    if debug is True:
        print 'Enchanting', item
        print 'Enchantability of', material, '=', enchantability
        print 'Modified level:', '(', level, ') ~=', mlevel
        print 'Possible enchantments for', type, '@', 'level', mlevel
        for k, v in enchantments.items():
            print '\t', _ench_name[k], _level_name[v], '@', _ench_prob[k]

    # Pick some enchantments
    final = {}
    while True:
        # Pick one.
        ench = utils.weighted_choice(prob)
        # Add it.
        final[ench] = enchantments[ench]
        # Remove it so we don't pick again.
        prob.remove((ench, _ench_prob[ench]))
        # Some enchantments conflict with each other. If we picked one, remove
        # its counterparts.
        if ench in [
                PROTECTION, FIRE_PROTECTION, BLAST_PROTECTION,
                PROJECTILE_PROTECTION
        ]:
            for x in [
                    PROTECTION, FIRE_PROTECTION, BLAST_PROTECTION,
                    PROJECTILE_PROTECTION
            ]:
                if (x, _ench_prob[x]) in prob:
                    prob.remove((x, _ench_prob[x]))

        if ench in [SHARPNESS, SMITE, BANE_OF_ARTHROPODS]:
            for x in [SHARPNESS, SMITE, BANE_OF_ARTHROPODS]:
                if (x, _ench_prob[x]) in prob:
                    prob.remove((x, _ench_prob[x]))

        # Frost Walking conflicts with Depth strider
        if ench in [FROST_WALKER, DEPTH_STRIDER]:
            for x in [FROST_WALKER, DEPTH_STRIDER]:
                if (x, _ench_prob[x]) in prob:
                    prob.remove((x, _ench_prob[x]))
        # Abort if we ran out of enchantments
        if len(prob) == 0:
            break
        # Check for additional enchantments
        mlevel /= 2
        if random.randint(1, 50) > mlevel + 1:
            break

    if debug is True:
        print 'Final enchantments'
        for k, v in final.items():
            print '\t', _ench_name[k], _level_name[v]

    for k, v in final.items():
        yield dict({'id': k, 'lvl': v})
Example #56
0
 def gettheme(self, biomeid):
     # Choose DICT based on biome
     if (biomeid in (
             2,  # Desert
             130,  # Desert M
             17,  # DesertHills
             35,  # Savanna
             163,  # Savanna M
             36,  # Savanna Plateau
             164,  # Savanna Plateau M
             37,  # Mesa
             165,  # Mesa (Bryce)
             38,  # Mesa Plateau F
             166,  # Mesa Plateau F M
             39,  # Mesa Plateau
             167,  # Mesa Plateau M
     )):
         theme_weights = [('egyptian', 50), ('greek', 10), ('roman', 10)]
     elif (biomeid in (
             5,  # Taiga
             133,  # Taiga M
             10,  # FrozenOcean
             12,  # Ice Plains
             140,  # Ice Plains Spikes
             13,  # Ice Mountains
             19,  # TaigaHills
             26,  # Cold Beach
             30,  # Cold Taiga
             158,  # Cold Taiga M
             31,  # Cold Taiga Hills
             32,  # Mega Taiga
             160,  # Mega Spruce Taiga
             33,  # Mega Taiga Hills
             161,  # Mega Spruce Taiga
     )):
         theme_weights = [('norse', 50), ('elven', 10), ('saxon', 10)]
     elif (biomeid in (
             1,  # Plains
             129,  # Sunflower Plains
             3,  # Extreme Hills
             131,  # Extreme Hills M
             6,  # Swampland
             134,  # Swampland M
             20,  # Extreme Hills Edge
             26,  # Stone Beach
             34,  # Extreme Hills+
             162,  # Extreme Hills+ M
     )):
         theme_weights = [('saxon', 20), ('roman', 10), ('greek', 10)]
     elif (biomeid in (
             4,  # Forest
             132,  # Flower Forest
             18,  # ForestHills
             27,  # Birch Forest
             155,  # Birch Forest M
             28,  # Birch Forest Hills
             156,  # Birch Forest Hills M
             29,  # Roofed Forest
             157,  # Roofed Forest M
     )):
         theme_weights = [('elven', 50), ('roman', 10), ('norse', 10)]
     elif (biomeid in (
             21,  # Jungle
             149,  # Jungle M
             22,  # JungleHills
             23,  # JungleEdge
             151,  # JungleEdge M
     )):
         theme_weights = [('mayan', 60), ('elven', 10)]
     elif (biomeid in (
             14,  # MushroomIsland
             15,  # MushroomIslandShore
     )):
         theme_weights = [('welsh', 1)]
     else:  # The rest. Including rivers, oceans etc
         theme_weights = [('saxon', 10), ('roman', 10), ('greek', 10),
                          ('norse', 10), ('elven', 10)]
     return weighted_choice(theme_weights)
Example #57
0
 def choose(self):
     choice = weighted_choice(self.options, self.weights)
     if choice.type == 'terminal':
         return choice.value
     else:
         return choice.choose()