from logic import *

AKnight = Symbol("A is a Knight")
AKnave = Symbol("A is a Knave")

BKnight = Symbol("B is a Knight")
BKnave = Symbol("B is a Knave")

CKnight = Symbol("C is a Knight")
CKnave = Symbol("C is a Knave")

# Puzzle 0
# A says "I am both a knight and a knave."
knowledge0 = And(

    # Basic Code For Character That they can be either Knight And Knave
    Or(AKnave, AKnight),

    # They can't be Both at the Same time
    Not(And(AKnave, AKnight)),

    Biconditional(AKnight, And(AKnave, AKnight))
)

# Puzzle 1
# A says "We are both knaves."
# B says nothing.
knowledge1 = And(

    # Basic Code For Character That they can be either Knight And Knave
    Or(AKnave, AKnight),
    Or(BKnave, BKnight),

    # They can't be Both at the Same time
    Not(And(AKnave, AKnight)),
    Not(And(BKnave, BKnight)),

    # Statement Mentioned Above as one is knight and other is knave and we are assured that one is knight
    # This is because the other one didn't say anything
    # It leaves other as knave
    Biconditional(AKnight, And(AKnave, BKnave))
)

# Puzzle 2
# A says "We are the same kind."
# B says "We are of different kinds."
knowledge2 = And(

    # A and B are either knights or knaves
    Or(AKnave, AKnight),
    Or(BKnave, BKnight),
    Not(And(AKnave, AKnight)),
    Not(And(BKnave, BKnight)),

    # A says "We are the same kind."
    # B says "We are of different kinds."
    Biconditional(AKnight, Or(And(AKnave, BKnave), And(AKnight, BKnight))),
    Biconditional(BKnight, Or(And(AKnave, BKnight), And(AKnight, BKnave))),
)

# Puzzle 3
# A says either "I am a knight." or "I am a knave.", but you don't know which.
# B says "A said 'I am a knave'."
# B says "C is a knave."
# C says "A is a knight."
knowledge3 = And(

    # Basic Code For Character That they can be either Knight And Knave
    Or(AKnave, AKnight),
    Or(BKnave, BKnight),
    Or(CKnave, CKnight),

    # They can't be Both at the Same time
    Not(And(AKnave, AKnight)),
    Not(And(BKnave, BKnight)),
    Not(And(CKnave, CKnight)),

    # A can be either knight or knave
    # B Depends on A's statement and says C is a knave
    # C says A is knight
    Biconditional(Or(AKnight, AKnave), Or(AKnight, AKnave)),
    Biconditional(BKnight, Biconditional(AKnight, AKnave)),
    Biconditional(BKnight, CKnave),
    Biconditional(CKnight, AKnight)
)

def main():
    symbols = [AKnight, AKnave, BKnight, BKnave, CKnight, CKnave]
    puzzles = [
        ("Puzzle 0", knowledge0),
        ("Puzzle 1", knowledge1),
        ("Puzzle 2", knowledge2),
        ("Puzzle 3", knowledge3)
    ]
    for puzzle, knowledge in puzzles:
        print(puzzle)
        if len(knowledge.conjuncts) == 0:
            print("    Not yet implemented.")
        else:
            for symbol in symbols:
                if model_check(knowledge, symbol):
                    print(f"    {symbol}")

if __name__ == "__main__":
    main()


from keras.models import Sequential
from keras.layers import Dense, BatchNormalization, Dropout
import numpy
import json
import tensorflowjs as tfjs

dataset = numpy.loadtxt("../data/csv/data.csv", delimiter=",", skiprows=1, usecols=(0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,21,22,23,24))
numpy.random.shuffle(dataset)
total_rows, total_cols = dataset.shape
train_count = int(total_rows * 0.9)
input_col_count = total_cols - 2
non_averageable_col_count = 13
training_dataset = dataset[:train_count,:]
testing_dataset = dataset[train_count:,:]
averageable_data = training_dataset[:,non_averageable_col_count:input_col_count]
mean = averageable_data.mean(axis=0)
std = averageable_data.std(axis=0)
clean_training_dataset = numpy.concatenate((training_dataset[:,:non_averageable_col_count], (training_dataset[:,non_averageable_col_count:input_col_count] - mean) / std, training_dataset[:,input_col_count:]), axis=1)
clean_testing_dataset = numpy.concatenate((testing_dataset[:,:non_averageable_col_count], (testing_dataset[:,non_averageable_col_count:input_col_count] - mean) / std, testing_dataset[:,input_col_count:]), axis=1)

numpy.savetxt("training_cleaned.csv", clean_training_dataset, delimiter=",")

with open('meanstd.json', 'w') as outfile:
    json.dump({"mean": mean.tolist(), "std": std.tolist()}, outfile)

X = clean_training_dataset[:,0:input_col_count]
Xtest = clean_testing_dataset[:,0:input_col_count]
AY = clean_training_dataset[:,input_col_count:input_col_count+1]
AYtest = clean_testing_dataset[:,input_col_count:input_col_count+1]
PY = clean_training_dataset[:,input_col_count+1]
PYtest = clean_testing_dataset[:,input_col_count+1]

a_model = Sequential()
a_model.add(Dense(12, input_dim=input_col_count, activation='relu'))
a_model.add(BatchNormalization())
a_model.add(Dropout(0.1))
a_model.add(Dense(8, activation='relu'))
a_model.add(BatchNormalization())
a_model.add(Dropout(0.1))
a_model.add(Dense(4, activation='tanh'))
a_model.add(BatchNormalization())
a_model.add(Dropout(0.1))
a_model.add(Dense(1, activation='sigmoid'))

a_model.compile(loss='logcosh', optimizer='adam', metrics=['logcosh'])

a_model.fit(X, AY, epochs=500)

a_scores = a_model.evaluate(Xtest, AYtest)

p_model = Sequential()
p_model.add(Dense(12, input_dim=input_col_count, activation='relu'))
p_model.add(BatchNormalization())
p_model.add(Dropout(0.1))
p_model.add(Dense(8, activation='relu'))
p_model.add(BatchNormalization())
p_model.add(Dropout(0.1))
p_model.add(Dense(4, activation='tanh'))
p_model.add(BatchNormalization())
p_model.add(Dropout(0.1))
p_model.add(Dense(1, activation='sigmoid'))

p_model.compile(loss='logcosh', optimizer='adam', metrics=['logcosh'])

p_model.fit(X, PY, epochs=500)

p_scores = p_model.evaluate(Xtest, PYtest)

print("Aetherealness \n%s: %.2f%%" % (a_model.metrics_names[1], a_scores[1]*100))
print("Primordialness \n%s: %.2f%%" % (p_model.metrics_names[1], p_scores[1]*100))

tfjs.converters.save_keras_model(a_model, './aetherealness')
tfjs.converters.save_keras_model(p_model, './primordialness')


import requests
from datetime import datetime as dt, timedelta
import numpy as np

def get_data(is_west: bool = True):
    if is_west:
        URL = "https://norlys.dk/api/flexel/getall?days=1&sector=DK1&isBusiness=false"
    else:
        URL = "https://norlys.dk/api/flexel/getall?days=1&sector=DK2&isBusiness=false"

    r = requests.get(url=URL)
    data = r.json()

    return data

def parse_data(arg_data):
    # convert time
    today_date = dt.strptime(arg_data["PriceDate"], '%Y-%m-%dT%H:%M:%SZ')
    print(f"Prices for: {today_date.date()}")

    prices = [i["value"] for i in arg_data["DisplayPrices"]]
    prices = np.array(prices)

    min_index = int(np.argmin(prices))
    min_time = dt.time(today_date + timedelta(hours=min_index))

    max_index = int(np.argmax(prices))
    max_time = dt.time(today_date + timedelta(hours=max_index))

    print(f"MOST EXPENSIVE: {prices[max_index]} at {max_time}")
    print(f"CHEAPEST: {prices[min_index]} at {min_time}")
    print(" ")

def get_today_prices():
    parse_data(get_data()[1])

def get_tomorrow_prices():
    parse_data(get_data()[0])

if __name__ == "__main__":
    get_today_prices()
    get_tomorrow_prices()


# Problem: https://open.kattis.com/problems/gerrymandering

# External imports
import math

# Get first line of input
params = input("").split(" ")

# Init var
n_precinct = int(params[0])
n_district = int(params[1])
votes_a = [0] * n_district
votes_b = [0] * n_district
wasted_a = 0
wasted_b = 0
total_votes = 0

# Get additional lines of input and sort incoming information by
# candidate vote (list) and district (index)
for i in range(n_precinct):
    res = input("").split(" ")
    votes_a[int(res[0]) - 1] += int(res[1])
    votes_b[int(res[0]) - 1] += int(res[2])

# Calculate results for each district
for i in range(n_district):
    # Init district vars
    dist_votes_a = votes_a[i]
    dist_votes_b = votes_b[i]
    dist_total = dist_votes_a + dist_votes_b
    dist_req = math.floor(dist_total / 2) + 1

    # Determine district winner and use that to calculate wasted votes.
    # Print collected information on one line, space separated
    if dist_votes_a > dist_votes_b:
        dist_wasted_a = dist_votes_a - dist_req
        dist_wasted_b = dist_votes_b
        print("A", dist_wasted_a, dist_wasted_b)
    else:
        dist_wasted_a = dist_votes_a
        dist_wasted_b = dist_votes_b - dist_req
        print("B", dist_wasted_a, dist_wasted_b)

    # Add district information to election totals
    wasted_a += dist_wasted_a
    wasted_b += dist_wasted_b
    total_votes += dist_total

# Calculate and print efficiency gap, using election totals
print(abs(wasted_a - wasted_b) / total_votes)


from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
     Number, Operator, Punctuation

class SSMSStyle(Style):
    """
    A Pygments style inspired by Microsoft SSMS.
    """

    background_color = "#ffffff"
    default_style = ""

    styles = {
        Comment:                   "#008000",
        Keyword:                   "#0000ff",
        Operator:                  "#808080",
        Name:                      "#000000",
        Name.Function:             "#ff00ff",
        Name.Builtin:              "#01ff00",
        Name.Class:                "#0000ff",
        String:                    "#ff0000",
        Error:                     "border:#ff0000",
        Number:                    "#000000",
        Punctuation:               "#808080"
    }


class Person:
    count=0
    def __init__ (self, name, DOB, address):
        self.name=name
        self.DOB=DOB
        self.address=address
        Person.incPersonCount()
    @staticmethod
    def incPersonCount():
        Person.count+=1
    @staticmethod
    def getPersonCount():
        return Person.count
p1=Person('Rituraj','21,10,2001','Darbhanga')
p2=Person('Jhanvi','14,1,2001','Patna')
print(Person.getPersonCount())


# write a program which ask for person age and name
# when both value entered the check if person can go for 18-30 holiday
# if yes then print enjoy your holiday
# otherwise print a polite message

name = input('please enter your name ')
age = int(input('please enter your age'))

if not(name) and not(age):
    print('please enter your name and age')
else:
    if(age >= 18) and (age <= 30):
        print('enjoy your holiday')
    else:
        print('you are not old enough')

Program Flow Control in Python/challenge.py


# create a empty list for returning final value and for subset
# send initial index 0 as parameters
# if the index is equal to length of s then return the subset copy
# else loop the input from i
# if the current str is palindrome then append the palindrome part to subset and backtrack by increasing index
# then pop the value
# to find the palindrome part
# we need to make sure that the first and last value if equal until left and right is same
class Solution:
    def partition(self, s: str) -> list[list[str]]:
        res, part = [], []

        def dfs(i):
            if i >= len(s):
                res.append(part.copy())
                return
            for j in range(i, len(s)):
                if self.isPali(s, i, j):
                    part.append(s[i: j + 1])
                    dfs(j + 1)
                    part.pop()

        dfs(0)
        return res

    def isPali(self, s, l, r):
        while l < r:
            if s[l] != s[r]:
                return False
            l, r = l + 1, r - 1
        return True

s = "aab"
print(Solution().partition(s))


import sys
from collections import deque
sys.stdin = open('백준21756. 지우개.txt', 'r')

N = int(input())
queue = deque([i for i in range(1, N+1)])
while len(queue) > 1:
    for i in range(len(queue)):
        if not i%2:
            queue.popleft()
        else:
            queue.append(queue.popleft())
print(queue[0])


from scipy import stats

import argparse
import os
import time

from engine import Engine, Event
import evaluation

### Events specific to this simulation
###
### Each saves a reference to the simulation using it, so that we can access and
### update that simulation's methods and state variables
class Arrival(Event):
    ### Represents the arrival of a new customer
    def __init__(self, timestamp, sim):
        self.timestamp = timestamp
        self.sim = sim

    def callback(self):
        if not self.sim.is_closing(): # schedule the next arrival
            next_arrival_delay = self.sim.get_rand_time_before_next_arrival()
            next_arrival_time = self.sim.t + next_arrival_delay
            self.sim.engine.schedule(Arrival(next_arrival_time, self.sim))

        if (self.sim.num_waiting > 0) or (self.sim.num_idle == 0): # customer joins the line
            self.sim.num_waiting += 1
            self.sim.arrival_times.append(self.sim.t)
        else: # customer is immediately served
            self.sim.waiting_times.append([self.sim.t, 0]) # no waiting for this customer
            self.sim.num_idle -= 1 # a teller becomes busy
            self.sim.num_busy += 1
            transaction_time = self.sim.get_rand_customer_transaction_time() # schedule the end of the transaction
            finished_time = self.sim.t + transaction_time
            self.sim.engine.schedule(FinishedService(finished_time, self.sim))

class FinishedService(Event):
    ### Represents the completion of a customer's interaction with a teller
    def __init__(self, timestamp, sim):
        self.timestamp = timestamp
        self.sim = sim

    def callback(self):
        self.sim.num_busy -= 1 # a teller becomes free
        self.sim.num_idle += 1

        if (self.sim.will_i_take_a_lunch_break()):
            # if debug: print("teller {} is taking a lunch break, starting at time {} and lasting for {} hours".format(
                # self.sim.num_lunch_breaks_taken, self.sim.t, self.sim.lunch_break_length))
            self.sim.lunch_break_times.append(self.sim.t)
            self.sim.num_lunch_breaks_taken += 1
            self.sim.num_idle -= 1 # the teller who just finished takes a lunch break
            self.sim.num_lunch += 1
            finished_time = self.sim.t + self.sim.lunch_break_length
            self.sim.engine.schedule(FinishedLunchBreak(finished_time, self.sim))
        else:
            self.sim.engine.schedule(TellerBecomesIdle(self.sim.t, self.sim))

class FinishedLunchBreak(Event):
    ### Represents the completion of a teller's lunchbreak
    def __init__(self, timestamp, sim):
        self.timestamp = timestamp
        self.sim = sim

    def callback(self):
        self.sim.num_lunch -= 1 # teller comes back from lunch
        self.sim.num_idle += 1
        self.sim.engine.schedule(TellerBecomesIdle(self.sim.t, self.sim))

class TellerBecomesIdle(Event):
    ### Represents a teller who has just become idle, who will then call the next customer in line if there are any
    def __init__(self, timestamp, sim):
        self.timestamp = timestamp
        self.sim = sim

    def callback(self):
        if (self.sim.num_waiting > 0): # serve the customer who is first in line
            arrival_time = self.sim.arrival_times.pop(0)
            waiting_time = self.sim.t - arrival_time # determine how long this customer has been waiting for
            self.sim.waiting_times.append([arrival_time, waiting_time])
            self.sim.num_waiting -= 1

            self.sim.num_idle -= 1 # the teller becomes busy
            self.sim.num_busy += 1
            transaction_time = self.sim.get_rand_customer_transaction_time() # schedule the end of the transaction
            finished_time = self.sim.t + transaction_time
            self.sim.engine.schedule(FinishedService(finished_time, self.sim))

class BankSimulation():
    def __init__(self, lunch_break_length, num_tellers):
        self.engine = Engine()

        ### parameters
        self.lunch_break_length = lunch_break_length
        self.num_tellers = num_tellers

        ### state variables
        self.t = 0 # current time
        self.num_waiting = 0 # number of customers in line
        self.num_idle = self.num_tellers # all tellers start the day as idle
        self.num_busy = 0 # number of busy tellers
        self.num_lunch = 0 # number of tellers on lunch break
        self.num_lunch_breaks_taken = 0
        self.arrival_times = [] # used to calculate waiting time for each customer

        ### returned at the end of the simulation
        self.waiting_times = []
        self.num_waiting_list = []
        self.lunch_break_times = []

    ### Utility functions

    def get_truncated_normal(self, mean, std_dev, low, high):
        a, b = (low - mean) / std_dev, (high - mean) / std_dev
        return stats.truncnorm(a, b, loc=mean, scale=std_dev)

    def in_rush_period(self):
        return (2 < self.t < 4) or (8 < self.t < 10)

    def in_lunchtime(self):
        return (2 < self.t < 4)

    def is_closing(self):
        ### after 12 hours of operation, the bank stops accepting new customers in line
        return (self.t >= 12)

    ### Probability distributions (defined in their own functions to make testing easier)

    def get_time_before_next_arrival_distribution(self):
        if (self.in_rush_period()):
            return self.get_truncated_normal(0.04, 0.04, 0, 0.08)
        else:
            return self.get_truncated_normal(0.08, 0.04, 0, 0.16)

    def get_transaction_time_distribution(self):
        return self.get_truncated_normal(0.15, 0.04, 0, 0.3)

    def get_lunch_break_distribution(self):
        return self.get_truncated_normal(3, 1, 2, 4)

    ### Functions that use the distributions above to return an immediately useful value

    def get_rand_time_before_next_arrival(self):
        return self.get_time_before_next_arrival_distribution().rvs()

    def get_rand_customer_transaction_time(self):
        return self.get_transaction_time_distribution().rvs()

    def will_i_take_a_lunch_break(self):
        return (self.num_lunch_breaks_taken < self.num_tellers) and \
            (self.t > self.get_lunch_break_distribution().rvs())

    def run_simulation(self):
        self.engine.schedule(Arrival(0, self))
        event = self.engine.remove()
        while (event != None):
            assert self.t <= event.timestamp
            # if debug: print("t is {:4.2f}\tevent timestamp is {:4.2f}\tevent type is {:22}\tnum_waiting: {}".format(
                # self.t, event.timestamp, event.__class__.__name__, self.num_waiting))
            self.t = event.timestamp
            self.num_waiting_list.append([self.t, self.num_waiting])
            event.callback()
            event = self.engine.remove()
        print("finished simulation")
        return {
            "waiting_times" : self.waiting_times,
            "num_waiting_list" : self.num_waiting_list,
            "lunch_break_times" : self.lunch_break_times,
        }

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("lunch_break_length", type=float, help="length of each teller's lunch break (in hours)")
    parser.add_argument("num_tellers", type=int, help="number of tellers at the bank")
    parser.add_argument("--verbose", action="store_true", help="provide additional simulation output")

    args = parser.parse_args()
    debug = args.verbose

    print("running simulation with lunch break length {} and num_tellers {}".format(
        args.lunch_break_length, args.num_tellers))

    start_time = time.time()
    sim = BankSimulation(args.lunch_break_length, args.num_tellers)
    results = sim.run_simulation()
    end_time = time.time()

    print("took {:.2f} seconds to run".format(end_time - start_time))

    for data, data_name, display_name in (
        (results["waiting_times"], "waitingTimes", "customer waiting times"),
        (results["num_waiting_list"], "numCustomersInLine", "number of customers in line")):

        stats = evaluation.get_statistics([w for t,w in data])

        file_name = "lunchBreak={}_numTellers={}_{}.txt".format(args.lunch_break_length, args.num_tellers, data_name)
        file_path = os.path.join("sim_output", "statistics", file_name)
        print("saving statistics for {} to {}".format(display_name, file_path))
        if args.verbose:
            print("statistics for {} are:".format(display_name))
            for line in stats.split("\n"):
                print("\t" + line)
        with open(file_path, "w") as f:
            f.write(stats)

    for data, title, file_name, xlabel, ylabel, time in (
        (results["waiting_times"], "waiting times", "waitingTimes", "arrival time", "waiting time", True),
        (results["num_waiting_list"], "number of customers in line", "numCustomersInLine", "time",
            "number of customers in line", True)):

        plot_name = "lunchBreak={}_numTellers={}_{}.png".format(args.lunch_break_length, args.num_tellers, file_name)
        plot_path = os.path.join("sim_output", "plots", plot_name)
        print("saving plot for {} to {}".format(title, plot_path))
        evaluation.save_plot(data, title, xlabel, ylabel, plot_path, results["lunch_break_times"], args.lunch_break_length)


# Raspberry Pi to a Rotary Phone

from gpiozero import Button
import time
from signal import pause

phone_dial_working = Button(14) # white wire to dial
phone_dial_rotor = Button(15) # blue wire to dial
phone_hook = Button(18) # brown wire to hook

def phone_hook_down():
    print("phone back in cradle")

def phone_hook_lifted():
    print("phone lifted from cradle")

def phone_dial_active():
    if phone_hook.value == 1:
        #print("dial has been turned")
        rotor_value = 0
        rotor_cumulative = 0
        while phone_dial_working.value == 1:
            # the rotor is moving
            if rotor_value != phone_dial_rotor.value:
                rotor_value = phone_dial_rotor.value
                print(rotor_value, time.time())
                rotor_cumulative = rotor_cumulative + rotor_value
        if (rotor_cumulative == 11):
            rotor_cumulative = 1
        print("You dialed:",rotor_cumulative - 1)

phone_hook.when_pressed = phone_hook_lifted
phone_hook.when_released = phone_hook_down
phone_dial_working.when_pressed = phone_dial_active

pause()

Raspberry Pi Weekly/2020 - q2/rpi_phone.py


import os
from collections import defaultdict
from ycmd.completers.general_completer import GeneralCompleter
from ycmd import identifier_utils
from ycmd.utils import ImportCore, LOGGER, SplitLines
from ycmd import responses
ycm_core = ImportCore()

SYNTAX_FILENAME = 'YCM_PLACEHOLDER_FOR_SYNTAX'

class IdentifierCompleter( GeneralCompleter ):
  def __init__( self, user_options ):
    super().__init__( user_options )
    self._completer = ycm_core.IdentifierCompleter()
    self._tags_file_last_mtime = defaultdict( int )
    self._max_candidates = user_options[ 'max_num_identifier_candidates' ]

  def ShouldUseNow( self, request_data ):
    return self.QueryLengthAboveMinThreshold( request_data )

  def ComputeCandidates( self, request_data ):
    if not self.ShouldUseNow( request_data ):
      return []

    completions = self._completer.CandidatesForQueryAndType(
      _SanitizeQuery( request_data[ 'query' ] ),
      request_data[ 'first_filetype' ],
      self._max_candidates )

    completions = _RemoveSmallCandidates(
      completions, self.user_options[ 'min_num_identifier_candidate_chars' ] )

    def ConvertCompletionData( x ):
      return responses.BuildCompletionData(
              insertion_text = x,
              extra_menu_info='[ID]' )

    return [ ConvertCompletionData( x ) for x in completions ]

  def _AddIdentifier( self, identifier, request_data ):
    filetype = request_data[ 'first_filetype' ]
    filepath = request_data[ 'filepath' ]

    if not filetype or not filepath or not identifier:
      return

    LOGGER.info( 'Adding ONE buffer identifier for file: %s', filepath )
    self._completer.AddSingleIdentifierToDatabase( identifier,
                                                  filetype,
                                                  filepath )

  def _AddPreviousIdentifier( self, request_data ):
    self._AddIdentifier(
      _PreviousIdentifier(
        self.user_options[ 'min_num_of_chars_for_completion' ],
        self.user_options[ 'collect_identifiers_from_comments_and_strings' ],
        request_data ),
      request_data )

  def _AddIdentifierUnderCursor( self, request_data ):
    self._AddIdentifier(
      _GetCursorIdentifier(
        self.user_options[ 'collect_identifiers_from_comments_and_strings' ],
        request_data ),
      request_data )

  def _AddBufferIdentifiers( self, request_data ):
    filetype = request_data[ 'first_filetype' ]
    filepath = request_data[ 'filepath' ]

    if not filetype or not filepath:
      return

    collect_from_comments_and_strings = bool( self.user_options[
      'collect_identifiers_from_comments_and_strings' ] )
    text = request_data[ 'file_data' ][ filepath ][ 'contents' ]
    LOGGER.info( 'Adding buffer identifiers for file: %s', filepath )
    self._completer.ClearForFileAndAddIdentifiersToDatabase(
        _IdentifiersFromBuffer( text,
                                filetype,
                                collect_from_comments_and_strings ),
        filetype,
        filepath )

  def _FilterUnchangedTagFiles( self, tag_files ):
    for tag_file in tag_files:
      try:
        current_mtime = os.path.getmtime( tag_file )
      except Exception:
        LOGGER.exception( 'Error while getting %s last modification time',
                          tag_file )
        continue
      last_mtime = self._tags_file_last_mtime[ tag_file ]

      # We don't want to repeatedly process the same file over and over; we only
      # process if it's changed since the last time we looked at it
      if current_mtime <= last_mtime:
        continue

      self._tags_file_last_mtime[ tag_file ] = current_mtime
      yield tag_file

  def _AddIdentifiersFromTagFiles( self, tag_files ):
    self._completer.AddIdentifiersToDatabaseFromTagFiles(
      ycm_core.StringVector(
        self._FilterUnchangedTagFiles( tag_files ) ) )

  def _AddIdentifiersFromSyntax( self, keyword_list, filetype ):
    filepath = SYNTAX_FILENAME + filetype
    self._completer.ClearForFileAndAddIdentifiersToDatabase(
      ycm_core.StringVector( keyword_list ),
      filetype,
      filepath )

  def OnFileReadyToParse( self, request_data ):
    self._AddBufferIdentifiers( request_data )
    if 'tag_files' in request_data:
      self._AddIdentifiersFromTagFiles( request_data[ 'tag_files' ] )
    if 'syntax_keywords' in request_data:
      self._AddIdentifiersFromSyntax( request_data[ 'syntax_keywords' ],
                                     request_data[ 'first_filetype' ] )

  def OnInsertLeave( self, request_data ):
    self._AddIdentifierUnderCursor( request_data )

  def OnCurrentIdentifierFinished( self, request_data ):
    self._AddPreviousIdentifier( request_data )

# This looks for the previous identifier and returns it; this might mean looking
# at last identifier on the previous line if a new line has just been created.
def _PreviousIdentifier( min_num_candidate_size_chars,
                         collect_from_comments_and_strings,
                         request_data ):
  def PreviousIdentifierOnLine( line, column, filetype ):
    nearest_ident = ''
    for match in identifier_utils.IdentifierRegexForFiletype(
        filetype ).finditer( line ):
      if match.end() <= column:
        nearest_ident = match.group()
    return nearest_ident

  line_num = request_data[ 'line_num' ] - 1
  column_num = request_data[ 'column_codepoint' ] - 1
  filepath = request_data[ 'filepath' ]
  filetype = request_data[ 'first_filetype' ]

  contents = request_data[ 'file_data' ][ filepath ][ 'contents' ]
  if not collect_from_comments_and_strings:
    contents = identifier_utils.RemoveIdentifierFreeText( contents, filetype )
  contents_per_line = SplitLines( contents )

  ident = PreviousIdentifierOnLine( contents_per_line[ line_num ],
                                    column_num,
                                    filetype )
  if ident:
    if len( ident ) < min_num_candidate_size_chars:
      return ''
    return ident

  line_num = line_num - 1

  if line_num < 0:
    return ''

  prev_line = contents_per_line[ line_num ]
  ident = PreviousIdentifierOnLine( prev_line, len( prev_line ), filetype )
  if len( ident ) < min_num_candidate_size_chars:
    return ''
  return ident

def _RemoveSmallCandidates( candidates, min_num_candidate_size_chars ):
  if min_num_candidate_size_chars == 0:
    return candidates

  return [ x for x in candidates if len( x ) >= min_num_candidate_size_chars ]

def _GetCursorIdentifier( collect_from_comments_and_strings,
                          request_data ):
  filepath = request_data[ 'filepath' ]
  contents = request_data[ 'file_data' ][ filepath ][ 'contents' ]
  filetype = request_data[ 'first_filetype' ]
  if not collect_from_comments_and_strings:
    contents = identifier_utils.RemoveIdentifierFreeText( contents, filetype )
  contents_per_line = SplitLines( contents )
  line = contents_per_line[ request_data[ 'line_num' ] - 1 ]
  return identifier_utils.IdentifierAtIndex(
      line,
      request_data[ 'column_codepoint' ] - 1,
      filetype )

def _IdentifiersFromBuffer( text,
                            filetype,
                            collect_from_comments_and_strings ):
  if not collect_from_comments_and_strings:
    text = identifier_utils.RemoveIdentifierFreeText( text, filetype )
  idents = identifier_utils.ExtractIdentifiersFromText( text, filetype )
  return ycm_core.StringVector( idents )

def _SanitizeQuery( query ):
  return query.strip()


#!/usr/bin/python3
"""Slurmd."""
import json
import logging

from ops.framework import (
    EventBase,
    EventSource,
    Object,
    ObjectEvents,
    StoredState,
)

logger = logging.getLogger()

class SlurmdAvailableEvent(EventBase):
    """Emmited when slurmd is available."""
    def __init__(self, handle, db_info):
        super().__init__(handle)
        self._slurmd_info = db_info

    @property
    def slurmd_info(self):
        return self._slurmd_info

    def snapshot(self):
        return self.slurmd_info.snapshot()

    def restore(self, snapshot):
        self._slurmd_info = SlurmdInfo.restor(snapshot)

class SlurmdRequiresEvents(ObjectEvents):
    """SlurmClusterProviderRelationEvents."""

    slurmd_available = EventSource(SlurmdAvailableEvent)

class Slurmd(Object):
    """Slurmd."""

    on = SlurmdRequiresEvents()
    _state = StoredState()

    def __init__(self, charm, relation_name):
        """Set self._relation_name and self.charm."""
        super().__init__(charm, relation_name)
        self._charm = charm
        self._relation_name = relation_name

        self.framework.observe(
            self._charm.on[self._relation_name].relation_created,
            self._on_relation_created
        )
        self.framework.observe(
            self._charm.on[self._relation_name].relation_changed,
            self._on_relation_changed
        )

    def _on_relation_created(self, event):
        pass

    def _on_relation_joined(self, event):
        pass

    def _on_relation_changed(self, event):
        if not event.relation.data.get(event.unit):
            event.defer()
            return

        inventory = event.relation.data[event.unit].get('inventory')
        if not inventory:
            event.defer()
            return
        partition = event.relation.data[event.unit].get('partition')
        partition = event.relation.data[event.unit].get('state')
        slurmd = SlurmdInfo(inventory, partition, state)
        self.on.slurmd_available.emit(slurmd)

    def _on_relation_broken(self, event):
        pass

class SlurmdInfo:

    def __init__(self, inventory=None, partition=None, state=None):
        self.set_address(partition, port, state)

    def set_address(self, inventory, partition, state):
        self._inventory = inventory
        self._partition = partition
        self._state = state

    @property
    def partition(self):
        return self._partition

    @property
    def inventory(self):
        return self._inventory

    @property
    def state(self):
        return self._state

    @classmethod
    def restore(cls, snapshot):
        return cls(
            inventory=snapshot['slurmd_info.inventory'],
            partition=snapshot['slurmd_info.partition'],
            state=snapshot['slurmd_info.state'],
        )

    def snapshot(self):
        return {
            'slurmd_info.inventory': self.inventory,
            'slurmd_info.partition': self.partition,
            'slurmd_info.state': self.state,
        }


import ast
import fileinput
import re
from math import floor, ceil

def find_exploding_pair(snail_number):
    """
    A pair explodes when it is nested 4 levels deep into the snail number. it's always a pair.

    e.g.:
    [[[[[3, 2], 1]]]]
    [3,2] will explode

    [[[[1, [3, 2]]]]]
    still [3,2] will explode, not 1

    :param snail_number:
    :return: the exploding pair and the index of that pair in the original snailnumber, or None, float('inf') if
        none is found
    """
    chunk_parts = list(snail_number)
    nested_count = 0
    nested_pair = ''
    nested_pair_index = float('inf')
    for index, character in enumerate(chunk_parts):
        if character == '[':
            nested_count += 1
        if nested_count > 4:
            nested_pair_index = index if index < nested_pair_index else nested_pair_index
            nested_pair += character
        if character == ']':
            nested_count -= 1
        if nested_count <= 4 and len(nested_pair) > 0:
            break
    nested_pairs = re.findall(r'\[\d+,\d+\]', nested_pair)

    left_nested_pair = None
    if len(nested_pairs) > 0:
        left_nested_pair = nested_pairs[0]
        nested_pair_index += nested_pair.find(left_nested_pair)  # add index discrepancy to first pair
    print(f"exploding pair: {left_nested_pair}, at index: {nested_pair_index}")
    return left_nested_pair, nested_pair_index

def explode_pair(snail_number, exploding_pair, index_exploding_pair):
    """
    Explode a pair by adding the left side to the first integer left to it in the snailnumber (if any)
    by adding the right side to the first integer to the right in the snailnumber (if any)
    by replacing the original pair [left side, right side]  with a '0'

    :param snail_number:
    :param exploding_pair:
    :param index_exploding_pair:
    :return: snail number after exploding
    """
    lhs, rhs = ast.literal_eval(exploding_pair)

    left_side_string = snail_number[0:index_exploding_pair]
    number_to_left = re.findall(r'\d+', left_side_string)
    if len(number_to_left) > 0:
        number_to_left = number_to_left[-1]
        add_index = left_side_string.rindex(number_to_left)
        new_number = int(number_to_left) + int(lhs)
        left_side_string = left_side_string[0:add_index] + \
                           str(new_number) + \
                           left_side_string[add_index + len(str(number_to_left)): index_exploding_pair]

    right_side_string = snail_number[index_exploding_pair + len(exploding_pair):]
    number_to_right = re.findall(r'\d+', right_side_string)
    if len(number_to_right) > 0:
        number_to_right = number_to_right[0]
        add_index = right_side_string.index(number_to_right)
        new_number = int(number_to_right) + int(rhs)
        right_side_string = right_side_string[0:add_index] + \
                           str(new_number) + \
                           right_side_string[add_index + len(str(number_to_right)):]

    new_snail_number = left_side_string + '0' + right_side_string
    print(f"After explosion: {new_snail_number}")
    return new_snail_number

def requires_split(snail_number):
    """
    Check whether there are any double- or multidigit numbers and return the index of the first occurence and the
    double number as a integer

    :param snail_number:
    :return: tuple of index of first double digit in snailnumber and double digit as int, or None, None
    """
    double_digits = re.findall(r'\d{2,}', snail_number)
    split_index = None
    split_number = None
    if len(double_digits) > 0:
        split_number = int(double_digits[0])
        split_index = snail_number.index(double_digits[0])
    print(f"Double digit {split_number} at index {split_index}")
    return split_index, split_number

def split_snail_number(snail_number, split_index, split_number):
    """
    Replace a double- or multiple-digit digit with a split pair
    [double digit / 2 rounded down, double digit / 2 rounded up]

    :param snail_number:
    :param split_index:
    :param split_number:
    :return: snailnumber with the double digit replaced with a split pair
    """
    insert_pair = f"[{floor(split_number / 2)},{ceil(split_number / 2)}]"
    new_snail_number = snail_number[0:split_index] + insert_pair + snail_number[split_index + len(str(split_number)):]
    print(f"after split: {new_snail_number}")
    return new_snail_number

def reduce(snail_number: str) -> str:
    """
    reduce a single snailnumber by looping through the actions, applying the first that applies:
    - exploding a pair
    - splitting a double digit into a new pair

    :param snail_number:
    :return: reduces snail number
    """
    prev_snail_number = snail_number
    while True:
        action = False
        new_snail_number = prev_snail_number
        exploding_pair, exploding_index = find_exploding_pair(new_snail_number)
        if exploding_pair:
            action = True
            new_snail_number = explode_pair(new_snail_number, exploding_pair, exploding_index)
        else:
            split_index, split_number = requires_split(new_snail_number)
            if split_index:
                action = True
                new_snail_number = split_snail_number(new_snail_number, split_index, split_number)

        if not action:
            break
        prev_snail_number = new_snail_number
    return new_snail_number

def calculate_magnitude(final_number):
    final_numbers_list = ast.literal_eval(final_number)
    total_sum = reduce_sum(final_numbers_list)
    return total_sum

def reduce_sum(sub_list):
    """
    Reduce the pairs to find the magnitude
    :param sub_list:
    :return:
    """
    lhs, rhs = sub_list
    if type(lhs) == list:
        lhs = reduce_sum(lhs)
    if type(rhs) == list:
        rhs = reduce_sum(rhs)
    return (3 * lhs) + (2 * rhs)

def process(input_list: list):
    """
    Find magnitude of the total sum of the snailnumbers input
    :param input_list:
    :return:
    """
    index = 1
    lhs = reduce(input_list[0])
    while index < len(input_list):
        rhs = reduce(input_list[index])
        snail_number = f'[{lhs},{rhs}]'
        print(f"after addition: {snail_number}")
        lhs = reduce(snail_number)
        index += 1
    final_sum = lhs
    print(f"final sum: {lhs}")
    return calculate_magnitude(final_sum)

def find_largest_sum(input_list):
    """
    find pair of snailnumbers with largest magnitude
    :param input_list:
    :return:
    """
    largest_sum = 0
    for lhs_index, lhs_number in enumerate(input_list):
        for rhs_index, rhs_number in enumerate(input_list):
            if rhs_index != lhs_index:
                lhs = reduce(lhs_number)
                rhs = reduce(rhs_number)
                snail_number = f'[{lhs},{rhs}]'
                print(f"after addition: {snail_number}")
                final_sum = reduce(snail_number)
                magnitude = calculate_magnitude(final_sum)
                if magnitude > largest_sum:
                    largest_sum = magnitude
    return largest_sum

if __name__ == '__main__':
    # lines = {i: ast.literal_eval(l.strip('\n')) for i, l in enumerate(fileinput.input())}
    lines = [i.strip('\n') for i in fileinput.input()]
    print(lines)
    output = find_largest_sum(lines)
    print(f'Output: {output}')


from __future__ import print_function

try:
    import time

    import os
    import sys
    import time
    import argparse
    import numpy as np

    import matplotlib as mpl
    import matplotlib.pyplot as plt

    from riconv.model import conv_model
    from riconv.load_data import train_img_generator, test_img_generator
    from riconv.config_utils import ModelConfigurator, DataDirStruct, ModelDirStruct

except ImportError as e:
    print(e)
    raise ImportError

def main():
    global args
    parser = argparse.ArgumentParser(description="Convolutional NN Training Script")
    parser.add_argument("-c", "--config", dest="configfile", default='config.yml', help="Path to yaml configuration file")
    parser.add_argument("-m", "--modelnames", dest="modelnames", nargs="*", default=None, required=False, help="Model name to test")
    parser.add_argument("-s", "--seed", dest="rngseed", default=123, type=int, help="RNG Seed to test different samples")
    args = parser.parse_args()

    # Get configuration file
    hconfig = ModelConfigurator(args.configfile)

    # Extract config parameters
    datapath = hconfig.datapath

    # Get requested models, if None, take config's list
    model_list = args.modelnames
    if model_list is None:
        model_list = hconfig.avail_models

    # Print basic info
    print("\n\n... Starting ...")
    print("\nConfiguration file: {}".format(args.configfile))
    print("\nData set location: {}\n".format(datapath))
    print("About to train {} model(s)\n".format(len(model_list)))

    # Loop over requested models
    for mod_i in model_list:
        mod_i = mod_i.strip()

        # Choose same batch
        np.random.seed(args.rngseed)

        # Set model config parameters
        hconfig.model_config(mod_i)

        # Get config file parameters
        outpath = hconfig.model_outpath
        epochs = hconfig.epochs
        layer_string_list = hconfig.layer_string_list
        # Print out model configuration
        hconfig.print_model(mod_i)

        # Directory structures for data and model saving
        data_dir_struct = DataDirStruct(datapath)
        model_dir_struct = ModelDirStruct(main_dir=outpath, test_model=False)

        # Training and validation generators
        train_gen, valid_gen = train_img_generator(dir_struct=data_dir_struct,
                                                   config_struct=hconfig)

        # Time training
        start_t = time.time()

        # Train the model
        history, trained_model = conv_model(dir_struct=model_dir_struct,
                                            train_gen=train_gen,
                                            valid_gen=valid_gen,
                                            epochs=epochs,
                                            layer_string_list=layer_string_list)

        # Get training time estimate
        elapsed = time.time() - start_t
        print("Estimated time to train {}: {} sec".format(mod_i, elapsed))

        # Test the model on a subset
        print("Running model on the test set...\n")

        # Testing generator
        test_gen = test_img_generator(dir_struct=data_dir_struct,
                                      config_struct=hconfig,
                                      fixed_rotation=False,
                                      rotation_angle=0.)

        # Show scores for a subset
        scores = trained_model.evaluate_generator(test_gen, steps=None, verbose=1)
        print("Testing %s: %.2f%%\n" % (trained_model.metrics_names[1], scores[1]*100))

    print("\nDone training and testing.\n")

if __name__ == "__main__":
    main()


from pathlib import Path
from datasets import load_dataset, concatenate_datasets
from textacy import preprocessing

def get_pipeline():
    preproc = preprocessing.make_pipeline(
        preprocessing.remove.html_tags,
        preprocessing.normalize.unicode,
        preprocessing.normalize.whitespace,
        preprocessing.normalize.bullet_points,
        preprocessing.normalize.quotation_marks,
        preprocessing.replace.hashtags,
        preprocessing.remove.brackets,
        preprocessing.replace.urls
    )
    return preproc

def convert_flatten_image(example, id_col):
    result = dict()
    result['id'] = example[id_col]
    pipe = get_pipeline()
    temp = []
    # filter en
    en_pos = []
    for _, lang_id in enumerate(example['language']):
        if lang_id == 'en':
            en_pos.append(True)
        else:
            en_pos.append(False)

    for key, val in example.items():
        if key == id_col:
            continue
        if key == 'language':
            continue

        content = []
        if isinstance(val, list):
            for item, valid in zip(val, en_pos):
                if valid:
                    clean = pipe(item)
                    content.append(clean)
        else:
            clean = pipe(val)
            content.append(clean)
        text = ' '.join(content)
        result[key] = text
        temp.append(text)
    result['contents'] = ' '.join(temp)
    return result

def convert_flatten_text(example, id_col):
    result = dict()
    result['id'] = example[id_col]
    result['contents'] = ''
    pipe = get_pipeline()
    temp = []
    for key, val in example.items():
        if key == id_col:
            continue

        content = []
        if isinstance(val, list):
            for item in val:
                clean = pipe(item)
                content.append(clean)
        else:
            clean = pipe(val)
            content.append(clean)
        text = ' '.join(content)
        result[key] = text
        temp.append(text)
    result['contents'] = ' '.join(temp)
    return result

def limit_clause(example, limit=1024):
    # truncate the number of 'words' by space
    clauses = example['contents'].split()
    return {'contents': ' '.join(clauses[:limit])}

def augment_image_urls(example, image_id_to_url):
    return {'id': example['id'], 'contents': example['contents'], 'image_url': image_id_to_url[example['id']]}

def maybe_shard_to_save(dataset, output_path, num_lines=1000000):
    output_path.parent.mkdir(parents=True, exist_ok=True)
    if len(dataset) > num_lines:
        n_shards = len(dataset) // num_lines + 1
        for idx in range(n_shards):
            subset = dataset.shard(num_shards=n_shards, index=idx)
            output_file = Path(output_path.parent, output_path.stem + f'.part-{idx:02d}.jsonl')
            subset.to_json(str(output_file))
    else:
        dataset.to_json(str(output_path))

def encode(split, encode_field, qrels_ds, image_ds, text_ds, output_path):
    if split == 'other':
        qrels = load_dataset(qrels_ds)
        qrels = concatenate_datasets(
            [qrels[qrels_split] for qrels_split in ['train', 'validation', 'test']]
        )
    else:
        qrels = load_dataset(qrels_ds, split=split)

    if encode_field == 'image_caption':
        valid_images = set(qrels.unique('image_id'))

        images = load_dataset(image_ds, split='train')
        # remove images for faster processing
        images = images.remove_columns(['image'])
        # save image urls to add on to the data as a separate field later
        image_id_to_url = {}
        for row in images:
            image_id_to_url[row['image_id']] = row['image_url']

        # remove image urls and use the remaining columns as the contents of the image
        images = images.remove_columns(['image_url'])
        old_col = images.column_names

        if split == 'other':
            images = images.filter(lambda example: example['image_id'] not in valid_images, num_proc=32)
        else:
            images = images.filter(lambda example: example['image_id'] in valid_images, num_proc=32)

        images = images.map(convert_flatten_image, fn_kwargs={'id_col': 'image_id'}, num_proc=16)
        images = images.map(limit_clause, num_proc=16)
        images = images.remove_columns(old_col)
        images = images.map(augment_image_urls, fn_kwargs={'image_id_to_url': image_id_to_url}, num_proc=16)
        maybe_shard_to_save(images, output_path / 'image-collection' / f'{split}.image-caption.jsonl')

    elif encode_field == 'text':
        valid_texts = set(qrels.unique('text_id'))

        texts = load_dataset(text_ds, split='train')
        texts = texts.remove_columns(['media', 'category', 'source_id', 'page_url'])
        old_col = texts.column_names

        if split == 'other':
            texts = texts.filter(lambda example: bool(example['text_id'] not in valid_texts), num_proc=32)
        else:
            texts = texts.filter(lambda example: bool(example['text_id'] in valid_texts), num_proc=32)

        texts = texts.map(convert_flatten_text, fn_kwargs={'id_col': 'text_id'}, num_proc=16)
        texts = texts.map(limit_clause, num_proc=16)
        texts = texts.remove_columns(old_col)
        maybe_shard_to_save(texts, output_path / 'text-collection' / f'{split}.text.jsonl')


# Inspired from https://github.com/minimaxir/facebook-page-post-scraper/
# Purposed to scrape images from posts in Dogspotting

import datetime
import time
import re
import json
from settings import *

try:
    from urllib.request import urlopen, Request
except ImportError:
    from urllib2 import urlopen, Request

def request_until_succeed(url):

    req = Request(url)
    success = False
    while not success:
        try:
            res = urlopen(req)
            if res.getcode() == 200: # Success code
                success = True
        except Exception as e:
            print(e)
            time.sleep(3)
            print("ERROR FOR URL {}: {}".format(url, datetime.datetime.now))
            print("Retrying\n")
    print("Success")
    return res.read()

# Convert text to csv friendly format
def unicode_decode(text):
    try:
        return text.encode('utf-8').decode()
    except UnicodeDecodeError:
        return text.encode('utf-8')

def constructFBPageFieldUrl(base_url):
    fields = "&fields=link,updated_time,type,picture,full_picture," + \
        "message,shares,reactions.limit(0).summary(true)"
    url = base_url + fields

    return url

def scrapeFBPageFeedPosts(group_id, access_token):
    has_next_page = True
    num_posts_processed = 0
    start_time = datetime.datetime.now()

    # Unix timestamp or strtotime valuet hat points to the end of the range of time-based data
    until = ''

    # Contains paging token that tells us where we left off during cursor pagination
    paging = ''
    base = "https://graph.facebook.com/v2.11"
    node = "/{}/feed".format(group_id)
    params = "/?limit={}&access_token={}".format(10, access_token)
    since = "&since={}".format(since_date) if since_date \
        is not '' else ''
    until = "&until={}".format(until_date) if until_date \
        is not '' else ''
    print("Begin Scraping Group")

    while has_next_page:
        until = '' if until is '' else "&until={}".format(until)
        paging = '' if until is '' else "&__paging_token={}".format(paging)
        base_url = base + node + params + since + until + paging
        url = constructFBPageFieldUrl(base_url)
        posts = json.loads(request_until_succeed(url))
        for post in posts['data']:
            processFBPageFeedPosts(post)
        # If there are more pages left
        if 'paging' in posts:
            next_url = posts['paging']['next']
            until = re.search('until=([0-9]*?)(&|$)', next_url).group(1)
            paging = re.search('__paging_token=(.*?)(&|$)', next_url).group(1)
        else:
            has_next_page = False
        time.sleep(10)

def processFBPageFeedPosts(post):
    # Processes a single post. Helper for scrapeFBPageFeedPosts
    print(post)
    print("="*30)
    post_id = post['id']
    post_type = post['type']
    post_message = '' if 'message' not in post else post['message']
    post_link = '' if 'link' not in post else post['link']
    post_picture = '' if 'picture' not in post else post['picture']
    post_full_picture = '' if 'full_picture' not in post else post['full_picture']
    num_reactions = 0 if 'reactions' not in post else \
        post['reactions']['summary']['total_count']
    num_comments = 0 if 'comments' not in post else \
        post['comments']['summary']['total_count']
    num_shares = 0 if 'shares' not in post else post['shares']['count']

if __name__ == '__main__':
    scrapeFBPageFeedPosts(group_id, access_token)


# 1359. Count All Valid Pickup and Delivery Options
# Hard

# Larry, https://www.youtube.com/watch?v=Q0dVILwk-dY
class Solution:
    def countOrders(self, N: int) -> int:
        MOD = 10 ** 9 + 7
        # OEIS -> look that up

        # N = 1
        # P1, D1

        # N = 2
        # X X
        # 3 + 2 + 1 = 6 * f(1) = 6

        # N = 3
        # X X X X
        # 5 + 4 + 3 + 2 + 1 = 15 * f(2) = 15 * 6 = 90

        # N = 4
        # P X X X X X X
        # 7 + 6 + 5 + .. + 1 =  28 * f(3) = 28 * 90 = 2520
        ans = 1

        for i in range(2, N + 1):
            previous = (2 * (i - 1))
            pickup = previous + 1
            total = (pickup * (pickup + 1)) // 2
            current = ans * total
            current %= MOD
            ans = current

        return ans % MOD
# 03/06/2022 15:40

larry/1359. Count All Valid Pickup and Delivery Options.py


import easyocr
import time
import pandas as pd
from PIL import Image
import cv2
import numpy as np
import shutil
import os
dataset = "https://github.com/SachaIZADI/Seven-Segment-OCR/tree/master/Datasets_Eleven/0"

start_time = time.time()

pd.set_option('display.max_rows', None)

def create_frames(path):
    frame_counter = 0
    reduced_frames = 0
    capture = cv2.VideoCapture(path)
    name = path.split("/")[-1]
    directory = f'./images/{name}'
    if (os.path.isdir(directory)):
        shutil.rmtree(directory)

    os.makedirs(directory)
    while True:
        success, frame = capture.read()
        if success:
            # Deleting low resolution frame
            if np.mean(frame) < 25:
                print("Removed the frame")
                continue
            if frame_counter % 400 == 0:
                reduced_frames += 1
                resized_frame = cv2.resize(frame, (960, 540))
                cv2.imwrite(
                    f'./images/{name}/frame_{frame_counter}.jpg', resized_frame)
        else:
            break
        frame_counter += 1
    print(f'There were {frame_counter} frames in this video')
    print(f'After reducing frames there are {reduced_frames} in this video. ')
    capture.release()
    return

def enhance_powerlaw(path, file_name, gamma):
    image = cv2.imread(path)
    normalized_image = image / 255.0
    result = cv2.pow(normalized_image, gamma)
    frame_normed = 255 * (result - result.min()) / \
        (result.max() - result.min())
    frame_normed = np.array(frame_normed, np.int64)

    cv2.imwrite(
        f'./enhanced_images/Stable_Video_1.mp4/{file_name}.jpg', frame_normed)
    return

def enhance_inverse(path, file_name, file):
    image = Image.open(path)
    image_array = np.asarray(image)
    image_inverse = 255 - image_array
    fm = './enhanced_images/inverse_law/Stable_Video_1.mp4/'+file_name
    file.write(fm+'\n')
    cv2.imwrite(fm, image_inverse)
    return

def enhance_frames(path, opt, file):
    dirs = os.listdir(path)
    if (opt == 0):
        directory = f'./enhanced_images/power_law/Stable_Video_1.mp4'
        if (os.path.isdir(directory)):
            shutil.rmtree(directory)

        os.makedirs(directory)
        for file_name in dirs:
            enhance_powerlaw(path + '/' + file_name, file_name, 1.6)
    else:
        directory = f'./enhanced_images/inverse_law/Stable_Video_1.mp4'
        if (os.path.isdir(directory)):
            shutil.rmtree(directory)

        os.makedirs(directory)
        for file_name in dirs:
            enhance_inverse(path + '/' + file_name, file_name, file)
            # enhance_powerlaw(path + '/enhanced_images/inverse_law/Stable_Video_1.mp4/' + file_name, file_name, 1.6)

#####################################################################################################
# OPTICAL CHARACTER RECOGNITION (OCR) ON ROI
d = {}
reader = easyocr.Reader(['en'])

def OCR(imgs, mode):
    if mode == 2:
        for img in imgs:
            image = img[1]
            # print(images)
            result = reader.readtext(image)
            # print(result)
            if img[0] not in d:
                d[img[0]] = []
                if (len(result) > 0 and len(result[0]) >= 2):
                    d[img[0]].append(result[0][-2])
                else:
                    # continue
                    d[img[0]].append(None)
            else:
                if (len(result) > 0 and len(result[0]) >= 2):
                    d[img[0]].append(result[0][-2])
                else:
                    # continue
                    d[img[0]].append(None)

#####################################################################################################
####################################################################################################
# for kocr_detection_orientation_check

def order_points(pts):
	# initialzie a list of coordinates that will be ordered
	# such that the first entry in the list is the top-left,
	# the second entry is the top-right, the third is the
	# bottom-right, and the fourth is the bottom-left
	rect = np.zeros((4, 2), dtype="float32")
	# the top-left point will have the smallest sum, whereas
	# the bottom-right point will have the largest sum
	s = pts.sum(axis=1)
	rect[0] = pts[np.argmin(s)]
	rect[2] = pts[np.argmax(s)]
	# now, compute the difference between the points, the
	# top-right point will have the smallest difference,
	# whereas the bottom-left will have the largest difference
	diff = np.diff(pts, axis=1)
	rect[1] = pts[np.argmin(diff)]
	rect[3] = pts[np.argmax(diff)]
	# return the ordered coordinates
	return rect

def four_point_transform(image, pts):
	# obtain a consistent order of the points and unpack them
	# individually
	rect = order_points(pts)
	(tl, tr, br, bl) = rect
	# compute the width of the new image, which will be the
	# maximum distance between bottom-right and bottom-left
	# x-coordiates or the top-right and top-left x-coordinates
	widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
	widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
	maxWidth = max(int(widthA), int(widthB))
	# compute the height of the new image, which will be the
	# maximum distance between the top-right and bottom-right
	# y-coordinates or the top-left and bottom-left y-coordinates
	heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
	heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
	maxHeight = max(int(heightA), int(heightB))
	# now that we have the dimensions of the new image, construct
	# the set of destination points to obtain a "birds eye view",
	# (i.e. top-down view) of the image, again specifying points
	# in the top-left, top-right, bottom-right, and bottom-left
	# order
	dst = np.array([
		[0, 0],
		[maxWidth - 1, 0],
		[maxWidth - 1, maxHeight - 1],
		[0, maxHeight - 1]], dtype="float32")
	# compute the perspective transform matrix and then apply it
	M = cv2.getPerspectiveTransform(rect, dst)
	warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
	# return the warped image
	return warped

#####################################################################################################
# [139, 179, 101, 117]
# [469, 495, 101, 117]
def showROIS(ROIs, img_raw,fp):
    # counter to save image with different name
    crop_number = 0
    imgs = []
    imgp=Image.open(fp)
    # loop over every bounding box save in array "ROIs"
    for rect in ROIs:
        if (isinstance(rect[1][0], np.integer)):
            x1 = rect[1][0]  # tlx
            y1 = rect[1][1]  # brx
            x2 = rect[1][2]  # bry
            y2 = rect[1][3]  # tly
            # crop roi from original image
            if (rect[0].startswith("roi")):
                # img_crop = img_raw[y1:y1+y2, x1:x1+x2]
                img_res = imgp.crop((x1, x2, y1, y2))
                imgs.append((rect[0], "crop"+str(crop_number)+".jpeg"))
                img_res.save("crop"+str(crop_number)+".jpeg")
                crop_number += 1
            else:
                img_crop = img_raw[y1:y1+y2, x1:x1+x2]
                # show cropped image
                # save cropped image
                imgs.append((rect[0], "crop"+str(crop_number)+".jpeg"))
                cv2.imwrite("crop"+str(crop_number)+".jpeg", img_crop)
                crop_number += 1
            # hold window
            # cv2.waitKey(0)
        else:
            coords = [tuple(l) for l in rect[1]]
            pts = np.array(coords, dtype="float32")
            warped = four_point_transform(img_raw, pts)
            imgs.append((rect[0], "crop"+str(crop_number)+".jpeg"))
            cv2.imwrite("crop"+str(crop_number)+".jpeg", warped)
            crop_number += 1

    OCR(imgs, 2)
    # closing all open windows
    cv2.destroyAllWindows()
####################################################################################################

# REGION OF INTEREST (ROI) SELECTIO

reader = easyocr.Reader(['en'])
def createROIS(image_folder, mode):
    files = os.listdir(image_folder)
    if mode == 1:
        for path in image_folder:
            img_raw = cv2.imread(image_folder + "/" + path)
            # select ROIs function
            ROIs = cv2.selectROIs(
                "Select ROIs and press Enter to move further, Press Esc to exit, Press c to clear selection", img_raw)
            # print rectangle points of selected roi
            print(ROIs)
            showROIS(ROIs, img_raw)
    elif mode == 2:
        path = files[0]
        p = image_folder + "/" + path
        print(p)
        img = cv2.imread(p)
        img_raw = cv2.imread(p)
        # image = keras_ocr.tools.read(p)
        img_det = reader.detect(img)
        ctr = 0
        img_tup = []
        for i in img_det:
            for j in i[0]:
                if (isinstance(j[0], np.integer)):
                    print(j)
                    ctr += 1
                    st = 'roi'+str(ctr)
                    img_tup.append((st, np.array(j)))
                if (isinstance(j[0], list)):
                    print(j)
                    ctr += 1
                    st = 'roi'+str(ctr)
                    img_tup.append((st, j))
        for i in img_tup:
            if (isinstance(i[1][0], np.integer)):
                x1 = int(i[1][0])
                y1 = int(i[1][3])
                x2 = int(i[1][1])
                y2 = int(i[1][2])
                cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
                cv2.putText(img, i[0], (x1, y1+5),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 49, 49), 2)
            else:
                pts = i[1]
                pts = np.array(pts)
                x = int(pts[0][0])
                y = int(pts[0][1])
                pts = pts.reshape((-1, 1, 2))
                cv2.polylines(img, np.int32([pts]),
                                    True, (255, 0, 0), 2)
                cv2.putText(img, i[0], (x, y+5),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 20, 147), 2)
        cv2.imshow('window_name', img)
        cv2.waitKey(0)
        r = input("Please select the ROIs on which you want OCR to be done by entering them with comma as a separator:")
        rl = r.split(",")
        rm = list(map(lambda x: "roi"+x, rl))
        rf = tuple(filter(lambda x: x[0] in rm, img_tup))
        print(rf)
        ROIs = cv2.selectROIs(
            "Select ROIs and press Enter to move further, Press Esc to exit, Press c to clear selection", img)
        ROI_tup = []
        for i in ROIs:
            name = input(
                'Please enter the attribute name for the selected ROIS:')
            ROI_tup.append((name, i))
        ROI_tup.extend(rf)
        print(ROI_tup)
        # for name, coords in ROI_tup:
        #     print(f'{name} --- {coords}  {type(coords)} {coords.shape}')

        showROIS(ROI_tup, img_raw, image_folder + "/" + path)
        del files[0]
        for path in files:
            img_raw = cv2.imread(image_folder + "/" + path)
            showROIS(ROI_tup, img_raw, image_folder + "/" + path)
    else:
        for path in files:
            print(image_folder + "/" + path)

            abcd = reader.readtext(image_folder + "/" + path)
            for line in abcd:
                print(f"{line[0]}      {line[1]}")
            print("*****************************************************************")

# [[391, 25], [487, 25], [487, 43], [391, 43]]      DSO-X 3014A
# [[390, 25], [487, 25], [487, 46], [390, 46]]      DSO-X 3014A
# [[391, 27], [487, 27], [487, 45], [391, 45]]      DSO-X 3014A
# [[390, 25], [487, 25], [487, 46], [390, 46]]      DSO-X 3014A

#####################################################################################################

file = open('images.txt', 'w')
# create_frames("./dataset/Stable_Video_1.mp4", 1, file)
create_frames("./dataset/Stable_Video_1.mp4")
enhance_frames("./images/Stable_Video_1.mp4", 1, file)
# image_folder = open("./images.txt", 'r')

createROIS("./enhanced_images/inverse_law/Stable_Video_1.mp4", mode=2)
formated_output = pd.DataFrame(d)

# formated_output.style.set_table_styles([{'selector' : '',
# 'props' : [('border',
# '2px solid white')]}])

print(formated_output)
file.close()
print("Execution time: ", time.time() - start_time)

# print(image_folder[0])
# paths = image_folder.readlines()
# print("***********************************")
# print(paths)
# rotatedl = []
# for path in paths:
#     rotatedl.append(path.strip())
# print(rotatedl)


# Baekjoon_BRONZE2_2386: 도비의 영어 공부

while True:
    temp = input().lower()
    a = list(temp)
    if a[0] != '#':
        cnt = 0
        for i in a[2:]:
            if i == a[0]:
                cnt+=1
        print(a[0], cnt)
    else:
        break


"""
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
"""

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        if len(s) < 2:
            return 0
        max_val = 0
        stack = [-1]

        # Saving the last invalid paranthesis index in stack
        # When a ( comes, store index in stack
        # When a ) come, pop from stack, then check if stack if empty
        # If stack is empty, push index in stack because that's invalid
        # If stack is not empty, check i - top of stack, this will be length of valid substring because top of stack will be index of last invalid paranthesis

        for i in range(len(s)):
            if s[i] == '(':
                stack.append(i)
            else:
                stack.pop()
                if not stack:
                    stack.append(i)
                else:
                    max_val = max(max_val, i-stack[-1])
        return max_val


import csv
import math
from typing import Dict, List, Optional, Tuple

import gym
from stable_baselines3.common.callbacks import EvalCallback

from l5kit.cle.composite_metrics import CompositeMetricAggregator
from l5kit.cle.metric_set import L5MetricSet
from l5kit.cle.scene_type_agg import compute_cle_scene_type_aggregations
from l5kit.cle.validators import ValidationCountingAggregator
from l5kit.environment.gym_metric_set import CLEMetricSet

class L5KitEvalCallback(EvalCallback):
    """Callback for evaluating an agent using L5Kit evaluation metrics.

    :param eval_env: The environment used for initialization
    :param n_eval_episodes: The number of episodes to test the agent
    :param eval_freq: Evaluate the agent every ``eval_freq`` call of the callback.
    :param metric_set: computes a set of metric parametrization for the L5Kit environment
    :param enable_scene_type_aggregation: enable evaluation according to scene type
    :param scene_id_to_type_path: path to the csv file mapping scene id to scene type
    :param prefix: the prefix to save the computed metrics
    :param verbose:
    """

    def __init__(self, eval_env: gym.Env, eval_freq: int = 10000, n_eval_episodes: int = 10,
                 n_eval_envs: int = 4, metric_set: Optional[L5MetricSet] = None,
                 enable_scene_type_aggregation: Optional[bool] = False, scene_id_to_type_path: Optional[str] = None,
                 prefix: str = 'eval', verbose: int = 0) -> None:
        super(L5KitEvalCallback, self).__init__(eval_env)
        self.eval_freq = eval_freq
        self.n_eval_episodes = n_eval_episodes
        self.n_eval_envs = n_eval_envs
        self.verbose = verbose
        self.prefix = prefix
        self.metric_set = metric_set or CLEMetricSet()
        # Assert required metrics exist.
        if 'displacement_error_l2' not in self.metric_set.evaluation_plan.metrics_dict():
            raise RuntimeError('\'displacement_error_l2\' missing in metric set')
        if 'collision_front' not in self.metric_set.evaluation_plan.metrics_dict() or \
            'collision_rear' not in self.metric_set.evaluation_plan.metrics_dict() or \
                'collision_side' not in self.metric_set.evaluation_plan.metrics_dict():
            raise RuntimeError('\'Collision metrics\' missing in metric set')

        # For scene type-based aggregation
        self.enable_scene_type_aggregation = enable_scene_type_aggregation
        if self.enable_scene_type_aggregation:
            assert scene_id_to_type_path is not None
            self.scene_id_to_type_path = scene_id_to_type_path
            self.scene_ids_to_scene_types = self.get_scene_types(self.scene_id_to_type_path)

    def _init_callback(self) -> None:
        pass

    @staticmethod
    def get_scene_types(scene_id_to_type_path: str) -> List[List[str]]:
        """Construct a list mapping scene types to their corresponding types.

        :param scene_id_to_type_path: path to the mapping.
        :return: list of scene type tags per scene
        """
        # Read csv
        scene_type_dict: Dict[int, str]
        with open(scene_id_to_type_path, 'r') as f:
            csv_reader = csv.reader(f)
            scene_type_dict = {int(rows[0]): rows[1] for rows in csv_reader}

        # Convert dict to List[List[str]]
        scene_id_to_type_list: List[List[str]] = []
        for k, v in scene_type_dict.items():
            scene_id_to_type_list.append([v])
        return scene_id_to_type_list

    def _on_step(self) -> bool:
        if self.eval_freq > 0 and self.n_calls % self.eval_freq == 0:
            # Evaluate episode outputs
            self.evaluate_scenes()

            # Start logging metrics, validators and composite metrics
            assert self.logger is not None

            # Aggregate metrics (ADE, FDE)
            ade_error, fde_error = self.compute_ade_fde(self.metric_set)
            self.logger.record(f'{self.prefix}/ade', ade_error)
            self.logger.record(f'{self.prefix}/fde', fde_error)

            # Aggregate validators
            validation_results = self.metric_set.evaluator.validation_results()
            agg = ValidationCountingAggregator().aggregate(validation_results)
            for k, v in agg.items():
                self.logger.record(f'{self.prefix}/{k}', v.item())
            # Add total collisions as well
            tot_collision = agg['collision_front'].item() + agg['collision_side'].item() + agg['collision_rear'].item()
            self.logger.record(f'{self.prefix}/total_collision', tot_collision)

            # Aggregate composite metrics
            composite_metric_results = self.metric_set.evaluator.composite_metric_results()
            comp_agg = CompositeMetricAggregator().aggregate(composite_metric_results)
            for k, v in comp_agg.items():
                self.logger.record(f'{self.prefix}/{k}', v.item())

            # If we should compute the scene-type aggregation metrics
            if self.enable_scene_type_aggregation:
                scene_type_results = \
                    compute_cle_scene_type_aggregations(self.metric_set,
                                                        self.scene_ids_to_scene_types,
                                                        list_validator_table_to_publish=[])
                for k, v in scene_type_results.items():
                    self.logger.record(f'{k}', v)

            # Dump log so the evaluation results are printed with the correct timestep
            self.logger.record("time/total timesteps", self.num_timesteps, exclude="tensorboard")
            self.logger.dump(self.num_timesteps)

            # reset
            self.metric_set.reset()

        return True

    def evaluate_scenes(self) -> None:
        """Evaluate the episode outputs for `n_eval_episodes` episodes.
        """
        assert self.model is not None

        self._set_reset_ids()
        obs = self.eval_env.reset()
        episodes_done = 0
        while True:
            action, _ = self.model.predict(obs, deterministic=True)
            obs, _, done, info = self.eval_env.step(action)

            for idx in range(self.n_eval_envs):
                if done[idx]:
                    if info[idx]["sim_outs"][0].scene_id not in \
                            self.metric_set.evaluator.scene_metric_results.keys():
                        episodes_done += 1
                        self.metric_set.evaluate(info[idx]["sim_outs"])

                    if episodes_done == self.n_eval_episodes:
                        return

    def _set_reset_ids(self) -> None:
        """Reset scene_ids for deterministic unroll"""
        reset_interval = math.ceil(self.n_eval_episodes / self.n_eval_envs)
        reset_indices = [reset_interval * i for i in range(self.n_eval_envs)]
        for idx in range(self.n_eval_envs):
            self.eval_env.env_method("set_reset_id", reset_indices[idx], indices=[idx])
        return

    @staticmethod
    def compute_ade_fde(metric_set: L5MetricSet) -> Tuple[float, float]:
        """Aggregate the Average displacement error (ADE) and Final displacement error (FDE)
        of the simulation outputs.

        :return: Tuple [ADE, FDE]"""
        scenes_result = metric_set.evaluator.metric_results()
        scene_ade_list: List[float] = []
        scene_fde_list: List[float] = []
        for _, scene_result in scenes_result.items():
            scene_ade_list.append(scene_result["displacement_error_l2"][1:].mean().item())
            scene_fde_list.append(scene_result['displacement_error_l2'][-1].item())

        if len(scene_ade_list) == 0:
            return (0, 0)

        average_ade = sum(scene_ade_list) / len(scene_ade_list)
        average_fde = sum(scene_fde_list) / len(scene_fde_list)

        return (average_ade, average_fde)


from Apartment import Apartment
from lab06 import *

def test__getRent():
    a0 = Apartment(1115, 215, "bad")
    assert a0.getRent() == 1115

def test__getMetersFromUCSB():
    a0 = Apartment(1115, 215, "bad")
    assert a0.getMetersFromUCSB() == 215

def test__getCondition():
    a0 = Apartment(1115, 215, "bad")
    assert a0.getCondition() == 'bad'

def test__getApartmentDetails():
    a0 = Apartment(1115, 215, "bad")
    assert a0.getApartmentDetails() == "(Apartment) Rent: $1115, Distance From UCSB: 215m, Condition: bad"

def test__lt__():
    a0 = Apartment(1115, 215, "bad")
    a1 = Apartment(950, 215, "average")
    assert a1.__lt__(a0) == True

def test__gt__():
    a0 = Apartment(1115, 215, "bad")
    a1 = Apartment(950, 215, "average")
    assert a0.__gt__(a1) == True

def test__eq__():
    a0 = Apartment(950, 215, "average")
    a1 = Apartment(950, 215, "average")
    assert a0.__eq__(a1) == True

def test__ensureSortedAscending():
    a0 = Apartment(1115, 215, "bad")
    a1 = Apartment(950, 215, "average")
    a2 = Apartment(950, 215, "excellent")
    a3 = Apartment(950, 190, "excellent")
    a4 = Apartment(900, 190, "excellent")
    a5 = Apartment(500, 250, "bad")
    apartmentList = [a0, a1, a2, a3, a4, a5]
    assert ensureSortedAscending(apartmentList) == False
    mergesort(apartmentList)
    assert ensureSortedAscending(apartmentList) == True

def test__getBestApartment():
    a0 = Apartment(1200, 200, "average")
    a1 = Apartment(1200, 200, "excellent")
    a2 = Apartment(1000, 100, "average")
    a3 = Apartment(1000, 215, "excellent")
    a4 = Apartment(700, 315, "bad")
    a5 = Apartment(800, 250, "excellent")
    apartmentList = [a0, a1, a2, a3, a4, a5]
    assert(getBestApartment(apartmentList)) == "(Apartment) Rent: $700, Distance From UCSB: 315m, Condition: bad"

def test__getWorstApartment():
    a0 = Apartment(1200, 200, "average")
    a1 = Apartment(1200, 200, "excellent")
    a2 = Apartment(1000, 100, "average")
    a3 = Apartment(1000, 215, "excellent")
    a4 = Apartment(700, 315, "bad")
    a5 = Apartment(800, 250, "excellent")
    apartmentList = [a0, a1, a2, a3, a4, a5]
    assert(getWorstApartment(apartmentList)) == "(Apartment) Rent: $1200, Distance From UCSB: 200m, Condition: average"

def test__getAffordableApartments():
    a0 = Apartment(1115, 215, "bad")
    a1 = Apartment(970, 215, "average")
    a2 = Apartment(950, 215, "average")
    a3 = Apartment(950, 190, "excellent")
    a4 = Apartment(900, 190, "excellent")
    a5 = Apartment(500, 250, "bad")
    apartmentList = [a0, a1, a2, a3, a4, a5]
    assert getAffordableApartments(apartmentList, 950) == "(Apartment) Rent: $500, Distance From UCSB: 250m, Condition: bad" + '\n' + "(Apartment) Rent: $900, Distance From UCSB: 190m, Condition: excellent" + '\n' + "(Apartment) Rent: $950, Distance From UCSB: 190m, Condition: excellent" + '\n' + '(Apartment) Rent: $950, Distance From UCSB: 215m, Condition: average'
    assert getAffordableApartments(apartmentList, 450) == ''


import tkinter as tk
from random import randint
from random import seed
import numpy as np

#Alunos: João Vitor Specht Kogut, Nicole Magagnin
#Código de aluno usado: 6462340, soma dos útimos 3 dígitos = 7

def start():

    def XOR(v1,v2):
        if((v1 == 0 and v2 == 0) or (v1 == 1 and v2 == 1)): #Operação XOR
            return 0 #números iguais resultam em 0
        else:
            return 1 #números diferentes em 1

    def gera_hamming(): #Gera a mensagem utilizando codificação hamming

        entrada_direta = i_8_bit.get()
        entrada = list(entrada_direta)

        if( len(entrada) == 8):  #Se detectar 8 bits, utiliza hamming (!2,8)
            print("8 bits!")
            l_saida['text'] = "8 bits detectados!"

            #Faz operação XOR para gerar a palavra
            x0 = XOR( XOR( XOR( XOR( int(entrada[0]) , int(entrada[1]))  , int(entrada[3])) , int(entrada[5])) , int(entrada[7]))
            x1 = XOR( XOR( XOR( XOR( int(entrada[0]) , int(entrada[2]))  , int(entrada[3])) , int(entrada[6])) , int(entrada[7]))
            x3 = XOR( XOR( XOR( int(entrada[1]) , int(entrada[2]))  , int(entrada[3])) , int(entrada[7]))
            x7= XOR( XOR( XOR( int(entrada[4]) , int(entrada[5]))  , int(entrada[6])) , int(entrada[7]))

            entrada.insert(0, x0) #Insere cada bit gerado em sua devida posição na mensagem
            entrada.insert(1,x1)
            entrada.insert(3, x3)
            entrada.insert(7,x7)

            str_saida = ""
            for i in range(len(entrada)):
                str_saida = str_saida + str(entrada[i]) #Gera string para mostrar na tela

            l_resultado['text'] = str_saida

        elif( len(entrada) == 4): #Realiza o mesmo procedimento para o Hamming 7,4
            print("4 bits!")
            l_saida['text'] = "4 bits detectados!"

            x0 = XOR( XOR( int(entrada[0]) , int(entrada[1]))  , int(entrada[3]))
            x1 = XOR( XOR( int(entrada[0]) , int(entrada[2]))  , int(entrada[3]))
            x3 = XOR( XOR( int(entrada[1]) , int(entrada[2]))  , int(entrada[3]))

            entrada.insert(0, x0)
            entrada.insert(1,x1)
            entrada.insert(3, x3)

            str_saida = ""
            for i in range(len(entrada)):
                str_saida = str_saida + str(entrada[i])

            l_resultado['text'] = str_saida

        else:

            l_saida['text'] = "Tamanho errado!" #Caso o tamanho não seja 4 ou 8, mostra a mensagem de tamanho errado

    def transmite_com_erro(): #Função geradora de erro
        ham_correto = list(  l_resultado['text'] )

        posi = randint(0, len(ham_correto)-1)

        if( int(ham_correto[posi]) == 1): # Troca um bit aleatório gerando erro
            ham_correto[posi] = "0"
        else:
            ham_correto[posi] = "1"

        ham_errado =""
        for i in range( len(ham_correto) ):
            ham_errado = ham_errado + str( ham_correto[i] )

        l_resultado_erro['text'] = ham_errado #Imprime na tela a mensagem incorreta

    def detecta_erro(): #Função para detectar o erro

        hem_transmitido = list( l_resultado_erro['text'] )

        if( len(hem_transmitido) == 12):  #Operações XOR caso hamming 12,8
            k0 = XOR( XOR( XOR( XOR(  XOR( int(hem_transmitido[0]) , int(hem_transmitido[2])) , int(hem_transmitido[4])) ,  int(hem_transmitido[6])) , int(hem_transmitido[8])) , int(hem_transmitido[10]))
            k1 = XOR( XOR( XOR( XOR(  XOR( int(hem_transmitido[1]) , int(hem_transmitido[2])) , int(hem_transmitido[5])) ,  int(hem_transmitido[6])) , int(hem_transmitido[9])) , int(hem_transmitido[10]))
            k3 = XOR( XOR( XOR(  XOR( int(hem_transmitido[3]) , int(hem_transmitido[4])) , int(hem_transmitido[5])) ,  int(hem_transmitido[6])) , int(hem_transmitido[11]))
            k7 = XOR( XOR( XOR(  XOR( int(hem_transmitido[7]) , int(hem_transmitido[8])) , int(hem_transmitido[9])) ,  int(hem_transmitido[10])) , int(hem_transmitido[11]))

            posicao_erro_12 = str(k7) + str(k3) + str(k1) + str(k0)
            print(posicao_erro_12)

            posi= np.packbits( [0,0,0,0,k7,k3,k1,k0] , -1)  #Utilizando a biblioteca np.packbits, é impressa na tela a posição do erro

        else: #Caso contrário, realiza operações para o Hamming 7,4
            k2 = XOR( XOR(  XOR( int(hem_transmitido[3]) , int(hem_transmitido[4])) , int(hem_transmitido[5])) ,  int(hem_transmitido[6]))
            k1 = XOR( XOR(  XOR( int(hem_transmitido[1]) , int(hem_transmitido[2])) , int(hem_transmitido[5])) ,  int(hem_transmitido[6]))
            k0 = XOR( XOR(  XOR( int(hem_transmitido[0]) , int(hem_transmitido[2])) , int(hem_transmitido[4])) ,  int(hem_transmitido[6]))

            posicao_erro_7 = str(k2) + str(k1) + str(k0)
            print(posicao_erro_7)

            posi= np.packbits( [0,0,0,0,0,k2,k1,k0] , -1) #Utilizando a biblioteca np.packbits, é impressa na tela a posição do erro

        l_posicao_do_erro['text'] = str( int(posi) )

    def corrigir_erro(): #Função para correção do erro

        errada = list( l_resultado_erro['text'] )
        posicao = int( l_posicao_do_erro['text'] ) - 1 #Posição impressa do erro -1 (para pegar a posição certa do vetor)

        if( errada[posicao] == '1'): #Troca o bit na posição onde foi encontrado o erro
            errada[posicao] = '0' #Se o bit for um vira 0
        else:
            errada[posicao] = '1' #Se o bit for 0 vira 1

        errado_str=""

        for i in range( len( errada) ):
            errado_str = errado_str + str( errada[i] )

        l_m_corrigido['text'] = errado_str #Imprime na tela a mensagem corrigida

    window = tk.Tk()

    window.rowconfigure([0,1,2,3,4,5,6,7,8,9,10,11,12], minsize=20, weight=1)
    window.columnconfigure([0, 1, 2], minsize=20, weight=1)
    window.title("Hamming")
    window.geometry("500x500")

    i_8_bit = tk.Entry(master=window, width=60)
    i_8_bit.grid(row=1, column=1)

    b_about = tk.Button(master=window, text="Gerar Hamming",width=50, command=gera_hamming, bg="grey")
    b_about.grid(row=2,column=1)

    b_erro = tk.Button(master=window, text="Transmitir",width=50, command=transmite_com_erro, bg="red")
    b_erro.grid(row=5,column=1)

    l_saida = tk.Label(master=window, text="" )
    l_saida.grid(row=3, column=1)

    l_intrucao = tk.Label(master=window, text="Insira uma mensagem de 4 ou 8 bits!")
    l_intrucao.grid(row=0,column=1)

    l_resultado = tk.Label(master=window, text="")
    l_resultado.grid(row=4,column=1)

    l_resultado_erro = tk.Label(master=window, text="")
    l_resultado_erro.grid(row=6, column=1)

    b_posicao_erro = tk.Button(master=window, text="Verificar",width=50, command=detecta_erro, bg="green")
    b_posicao_erro.grid(row=7,column=1)
    l_posicao_do_erro = tk.Label(master=window, text= "")
    l_posicao_do_erro.grid(row=8,column=1)

    b_corigir = tk.Button(master=window, text="Corrigir", width=50, command=corrigir_erro, bg="SteelBlue1")
    b_corigir.grid(row=9,column=1)
    l_m_corrigido = tk.Label(master=window, text="")
    l_m_corrigido.grid(row=10, column=1)

    window.mainloop()


def extractShiroritranslationsWordpressCom(item):
	'''
	Parser for 'shiroritranslations.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('okitara 20nen',           'Okitara 20nen nandesukedo! Akuyaku reijo no sono ato no sono ato',                                                                              'translated'),
		('seijo ni narunode',       'Seijo ni Narunode Nidoume no Jinsei wa Katte ni Sasetemoraimasu ~Outaihi wa, Zensei de Watashi wo Futta Koibito Deshita~',                      'translated'),
		('nazeboku',                'Naze Boku no Sekai wo Dare mo Oboeteinainoka?',                                                                                'translated'),
		('mattari',                 'Reijou wa Mattari wo Goshomou',                                                                                'translated'),
		('seijuuban',               'Hikkikomori Reijou wa Hanashi no Wakaru Seijuuban',                                                                                'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


import numpy as np
import matplotlib.pyplot as plt

from analysis.pairs_plotting import pairs_scatter, pairs_density, pairs_lines
from expWorkbench.util import load_results

# load the data
experiments, results = load_results(r"../../../src/analysis/1000 flu cases.cPickle", zipped=False)

# transform the results to the required format
newResults = {}

# get time and remove it from the dict
time = results.pop("TIME")

for key, value in results.items():
    if key == "deceased population region 1":
        newResults[key] = value[:, -1]  # we want the end value
    else:
        # we want the maximum value of the peak
        newResults["max peak"] = np.max(value, axis=1)

        # we want the time at which the maximum occurred
        # the code here is a bit obscure, I don't know why the transpose
        # of value is needed. This however does produce the appropriate results
        logicalIndex = value.T == np.max(value, axis=1)
        newResults["time of max"] = time[logicalIndex.T]

pairs_density((experiments, newResults))
plt.show()


#!/usr/bin/env python3

import sys
import argparse
import pandas
import os

VERSION = '0.1.0'

parser = argparse.ArgumentParser(description= 'Reformat macs2 output format to BED-like')

parser.add_argument('input', help= 'Input *.xls file from macs2')

if __name__ == '__main__':
    args = parser.parse_args()

    with open(args.input) as fin:
        for line in fin:
            line = line.strip()
            if line.startswith('#'):
                line = line.lstrip('#')
                print('##' +  line)
            elif line == '':
                continue
            else:
                print('## Reformatted by %s v%s' % (os.path.basename(__file__), VERSION))
                break

    xls = pandas.read_csv(args.input, sep= '\t', comment= '#', dtype= {0: 'string'})
    xls.rename(columns= {'chr': '#chrom'}, inplace= True)
    xls['start'] = xls['start'] - 1
    xls['abs_summit'] = xls['abs_summit'] - 1

    csv = xls.to_csv(None, sep= '\t', index= False)
    if not csv.endswith('\n'):
        csv += '\n'
    sys.stdout.write(csv)


from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'gettingstarted.views.home', name='home'),
    url(r'^twilio/', include('twilio_app.urls')),

    url(r'^admin/', include(admin.site.urls)),

)


# This Python file uses the following encoding: utf-8

from yapsy.PluginManager import PluginManager
import requests
import sqlite3
import bs4
import datetime
import logging
logging.basicConfig()
log = logging.getLogger('yapsy')

def saveLiborRate(libor3Month, libor6Month):
	today = datetime.date.today().strftime('%d.%m.%Y')
	todayDB = datetime.datetime.strptime(today, '%d.%m.%Y').strftime('%Y-%m-%d')
	con = sqlite3.connect('liborWatch.sqlite')
	with con:
		cur = con.cursor()
		cur.execute("CREATE TABLE IF NOT EXISTS LiborRate(id INTEGER PRIMARY KEY, date TEXT, rate3Month REAL, rate6Month REAL)")
		cur.execute("INSERT INTO LiborRate VALUES(NULL, ?, ?, ?)", (todayDB, libor3Month, libor6Month))

def getLiborRate(libor_url):
	headers = {
		'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36'
		}

	response = requests.get(libor_url, headers=headers)
	soup = bs4.BeautifulSoup(response.text, "html.parser")

	tableCollection = soup.find_all('table')
	liborTable = tableCollection[1]
	liborTableRows = liborTable.find_all('tr')
	liborTableRowData = liborTableRows[1].find_all('td')
	liborRate = liborTableRowData[1].get_text()
	return liborRate

def getBankRates():
    # Load the plugins from the plugin directory.
	manager = PluginManager()
	# Server
	# manager.setPluginPlaces(["./dev/liborWatch/server/plugins"])
	# Dev
	# manager.setPluginPlaces(["./plugins"])
	# Local
	manager.setPluginPlaces(["./dev/NextLevelApps/liborWatch/server/plugins"])

	manager.collectPlugins()
	today = datetime.date.today().strftime('%Y-%m-%d')

    # Loop round the plugins and get the bank rates
	for plugin in manager.getAllPlugins():
		rates = plugin.plugin_object.getRates()
		print(rates);
		if(len(rates) != 10):
			print('Error: We did not get 10 rates from the plugin ' + plugin.name + ' - ' + str(len(rates)))
			return

		newRate = []
		iCnt = 0;
		for rate in rates:
			iCnt = iCnt + 1
			newRate.append((plugin.name, today, iCnt, rate))
#			print('execute insert statement ' + plugin.name, str(today), str(iCnt), str(rate))

		con = sqlite3.connect('liborWatch.sqlite')
		with con:
			cur = con.cursor()
			cur.execute("CREATE TABLE IF NOT EXISTS BankRate(id INTEGER PRIMARY KEY, bankName TEXT, date TEXT, fixedForYears INTEGER, rate REAL)")
			cur.executemany("INSERT INTO BankRate VALUES(NULL, ?, ?, ?, ?)", newRate)

def main():
	libor3Months = getLiborRate("http://www.finanzen.ch/zinsen/Libor-CHF-3-Monate")
	libor6Months = getLiborRate("http://www.finanzen.ch/zinsen/Libor-CHF-6-Monate")
	saveLiborRate(libor3Months, libor6Months)
	getBankRates()

if __name__ == "__main__":
    main()


import os
import tensorflow as tf
import config as config
import model
from utils import readData
import time
import numpy as np
from tensorflow.python.tools import inspect_checkpoint as chkp
import matplotlib.pyplot as plt
import cv2

# config.batch_size = 100
checkpoint_path = os.path.join(config.checkpoint_path, "yolo_last_layer.ckpt")
model_path = "/home/siddharth/Desktop/Adversarial Learning SP/DL/object_detection/yolo.ckpt"
log_file = os.path.join(config.log_file_path ,'status_log.txt')

#Changing parameters to values in yolo.ckpt for loading

model = model.model()
utils = readData(config.dir_path)
label_list = utils.createLabels('train')

sess = tf.InteractiveSession()
saver_pretrained = tf.train.Saver(var_list=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=''))
sess.run(tf.global_variables_initializer())
saver_pretrained.restore(sess, model_path)

prediction = model.yolo(config.dropout)
model.loss()

saver_last_layer = tf.train.Saver(var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope = 'last_layer'))

#Initialize uninitialized variables
uninitialized_vars = []
for var in tf.global_variables():
    try:
        sess.run(var)
    except tf.errors.FailedPreconditionError:
        uninitialized_vars.append(var)

init_new_vars_op = tf.initialize_variables(uninitialized_vars)
sess.run(init_new_vars_op)

#Restoring last layer variables
saver_last_layer.restore(sess, checkpoint_path)

# no_images = len([img for img in os.listdir(utils.testPath) if img.endswith('.jpg')])
no_images = int(config.dataset_ratio * len(label_list))
#Reducing the size of label_list according to dataset size
label_list = label_list[:no_images]

total_loss = 0
loss_test = []
no_batches = 0
for x in range(0, no_images - config.batch_size, config.batch_size):

	print("current batch no: {}".format(no_batches))
	images = np.zeros((config.batch_size, config.image_size, config.image_size, 3))
	label = np.zeros((config.batch_size, config.no_grid, config.no_grid, 5 + config.no_classes))
	batch_id = []

	for batch in range(config.batch_size):

		image_path = label_list[x + batch]['image_path']
		images[batch, :, :, :] = utils.read_img(image_path)
		label[batch, :, :, :] = label_list[x + batch]['label']
		batch_id.append(label_list[x + batch]['id'])

	loss, predict = sess.run([model.total_loss, prediction], feed_dict = {model.images: images, model.labels: label})

	#Plotting images
	utils.display_bounding_box_batch(predict, images, batch_id)

	print ("loss : {}".format(loss))
	loss_test.append(loss)

	total_loss += loss

	no_batches+=1

print ("total_loss = {}".format(total_loss))

fig,ax = plt.subplots()
ax.plot(range(no_batches), loss_test, linewidth =2)
plt.axis('tight')
plt.xlabel('Batch number')
plt.ylabel('Total loss for that batch')
plt.title('Test Loss')
plt.show()