Exemplo n.º 1
0
	def __init__(self, schedule_section):
		"""Initialize a Schedule object."""

		# schedule settings
		self.poll_frequency = to_int(schedule_section.poll_frequency)
		self.daily_at = self.format_daily_times(schedule_section.daily_at)
		self.hourly_at = to_int(to_list(schedule_section.hourly_at))

		# skip conditions
		self.skip_hours_of_day = to_int(to_list(schedule_section.hours_of_day))
		self.skip_days_of_week = to_list(schedule_section.days_of_week)
		self.skip_days_of_month = to_int(to_list(schedule_section.days_of_month))
		self.skip_days_of_year = to_list(schedule_section.days_of_year)

		# lowercase skip days of week
		self.skip_days_of_week = [day.lower() for day in self.skip_days_of_week]

		# track state
		self.start_time = None
		self.last_time = None
		self.poll_count = 0
		self.run_count = 0

		# optional poll_message
		self.poll_message = ''
def _parse_2010_or_2014(sheet, num_col, num_col_name,
                        total_name, num_footers):
    # Check header row.
    headers = [
        ['Detailed Years of School', num_col_name],
        ['', 'Number'],
    ]
    type_col = 0
    if not np.all(sheet[4:6, [type_col, num_col]] == headers):
        raise ValueError('Unexpected row headers.')

    schooling_types = sheet[6:, type_col]
    schooling_numbers = sheet[6:, num_col]

    if schooling_types[0] != total_name:
        raise ValueError('Unexpected name for "total"')

    total_people = to_int(schooling_numbers[0])
    schooling_types = schooling_types[1:]
    schooling_numbers = schooling_numbers[1:]

    # Remove footnotes, intentionally leave a blank row.
    if not np.all(schooling_numbers[-num_footers:] == ''):
        raise ValueError('Expected footer rows')
    schooling_numbers = schooling_numbers[:-num_footers]
    schooling_types = schooling_types[:-num_footers]

    result = []

    separator_rows, = np.where(schooling_types == '')
    num_sections = len(separator_rows) - 1
    for section in xrange(num_sections):
        begin_index = separator_rows[section] + 1
        end_index = separator_rows[section + 1] - 1

        # Determine if the section has a category.
        category = None
        if schooling_numbers[begin_index] == '':
            category = schooling_types[begin_index]
            begin_index += 1

        for index in xrange(begin_index, end_index + 1):
            result.append((
                schooling_types[index],
                category,
                to_int(schooling_numbers[index]),
            ))

    if np.abs(sum([val[-1] for val in result]) - total_people) > 5:
        raise ValueError('Total does not match observed.')
    return total_people, result
Exemplo n.º 3
0
def checkAddr(addr):
    ip, port = addr.split(':')
    if not to_int(port):
        return None
    if not checkIp(ip):
        return None
    return True
Exemplo n.º 4
0
def test_to_int():
    assert to_int('012') == 12
    assert to_int('01234.4321') == 1234
    assert to_int("01234.9") == 1234
    assert to_int('-1234') == -1234
    assert to_int('abc', 'FailedToConvert', False) == 'FailedToConvert'
    assert to_int(-32.54e7, 'FailedToConvert', False) == -325400000
    assert to_int(70.2e5, 'FailedToConvert', False) == 7020000
Exemplo n.º 5
0
	def is_mm_dd(mm_dd_value):
		"""
		Return True if mm_dd_value matches a legal month-day value.
		Accepts 02-29 as a leap year day as well.
		"""
		mm_value, separator, dd_value = mm_dd_value.partition('-')
		mm_value = to_int(mm_value, 0)
		dd_value = to_int(dd_value, 0)

		# allow 02-29 (leap year) as legal value
		if mm_value == 2 and dd_value == 29:
			is_valid = True

		else:
			try:
				# year value does not matter; 2000 chosen as an arbitrary year
				# print(f'datetime(2000, {mm_value}, {dd_value}) = {datetime.datetime(2000, mm_value, dd_value)}')
				datetime.datetime(2000, mm_value, dd_value)
				is_valid = True
			except ValueError:
				is_valid = False

		return is_valid
Exemplo n.º 6
0
import common

nums = common.to_int(common.read_file('2021/01/data.txt').splitlines())

# part 1
acc = 0
for i in range(1, len(nums)):
    if nums[i - 1] < nums[i]:
        acc += 1

print(acc)

# part 2
acc = 0
for i in range(3, len(nums)):
    if nums[i - 3] < nums[i]:
        acc += 1

print(acc)
Exemplo n.º 7
0
import common
year_common = common.import_year_common(2017)

data = common.read_file('2017/10/data.txt').strip()
ints = common.to_int(data.split(','))

# NOTE: implementation of knot hash was moved to common

# part 1
result = year_common.knot_hash(ints)
print(result[0] * result[1])

# part 2
_, representation = year_common.knot_hash_full(data)
print(representation)
Exemplo n.º 8
0
from collections import deque
import common

deck1 = common.to_int(common.read_file('2020/22/p1.txt').splitlines())
deck2 = common.to_int(common.read_file('2020/22/p2.txt').splitlines())

# part 1
p1 = deque(deck1)
p2 = deque(deck2)

while len(p1) > 0 and len(p2) > 0:
    play1 = p1.popleft()
    play2 = p2.popleft()

    if play1 > play2:
        p1.append(play1)
        p1.append(play2)
    else:
        p2.append(play2)
        p2.append(play1)

winner = p1 if len(p1) > 0 else p2

def calculate_score(cards):
    acc = 0
    for i in range(len(cards)):
        acc += cards[-i-1] * (i+1)
    return acc

print(calculate_score(winner))
Exemplo n.º 9
0
import common

data = common.read_file('2017/6/data.txt')
cells = data.split('\t')

state = common.to_int(cells)
steps = 0
seen = set()
seen_at_step = dict()


def state_to_int():
    acc = 0
    for i in range(0, len(state)):
        acc *= 100
        acc += state[i]
    return acc


while True:
    state_val = state_to_int()
    if state_val in seen:
        break
    seen.add(state_val)
    seen_at_step[state_val] = steps
    steps += 1

    # find max
    max_val = 0
    max_i = 0
Exemplo n.º 10
0
	def is_hh_mm(hh_mm_value):
		"""Return True hh_mm_value matches a legal hour:minute value."""
		hh_value, separator, mm_value = hh_mm_value.partition(':')
		hh_value = to_int(hh_value, -1)
		mm_value = to_int(mm_value, -1)
		return (0 <= hh_value <= 23) and (0 <= mm_value <= 59)
Exemplo n.º 11
0
from collections import defaultdict
import common

nums = common.to_int(common.read_file('2021/06/data.txt').split(','))

fish = defaultdict(lambda: 0)
for num in nums:
    fish[num] += 1

# part 1 and 2

curr_fish = fish
for day in range(256):
    new_fish = defaultdict(lambda: 0)
    for i in range(1, 9):
        if i in curr_fish:
            new_fish[i - 1] = curr_fish[i]
    new_fish[6] += curr_fish[0]
    new_fish[8] += curr_fish[0]
    curr_fish = new_fish

    if day == 79:
        print(sum(curr_fish.values()))

print(sum(curr_fish.values()))
Exemplo n.º 12
0
from collections import defaultdict
import common

lines = common.read_file('2021/13/data.txt').splitlines()
board = defaultdict(lambda: 0)
for i in range(len(lines)):
    line = lines[i]
    if line == '':
        break
    x, y = common.to_int(line.split(','))
    board[(x, y)] = 1

folds = []
for line in lines[i+1:]:
    axis, value = line.split()[2].split('=')
    folds.append((axis, int(value)))

# part 1 and 2

for i in range(len(folds)):
    axis, middle = folds[i]
    new_board = defaultdict(lambda: 0)
    if axis == 'x':
        for x, y in board:
            reflected = 2*middle - x
            if reflected < middle:
                new_board[(reflected, y)] = 1
            else:
                new_board[(x, y)] = 1
    else:
        for x, y in board:
Exemplo n.º 13
0
from collections import deque, defaultdict
from queue import PriorityQueue
import common

lines = common.read_file('2021/15/data.txt').splitlines()
board = [common.to_int(x) for x in lines]
w = len(lines[0])
h = len(lines)

# part 1

def solve(board, w, h):
    distances = {}
    q = PriorityQueue()
    q.put((0, (1, 0)))
    q.put((0, (0, 1)))
    while not q.empty():
        dist, coords = q.get()
        x, y = coords
        if x < 0 or x >= w or y < 0 or y >= h:
            continue
        dist += board[y][x]
        if (x, y) in distances and dist >= distances[(x, y)]:
            continue
        distances[(x, y)] = dist
        if (x, y) == (w-1, h-1):
            break
        q.put((dist, (x-1, y)))
        q.put((dist, (x+1, y)))
        q.put((dist, (x, y-1)))
        q.put((dist, (x, y+1)))
Exemplo n.º 14
0
import common

positions = common.to_int(common.read_file('2021/07/data.txt').split(','))
min_pos = min(positions)
max_pos = max(positions)

# part 1 and 2

fuel_cost = [0] * (max_pos - min_pos + 1)
fuel_cost2 = [0] * (max_pos - min_pos + 1)

for crab in positions:
    for i in range(min_pos, max_pos + 1):
        diff = abs(i - crab)
        fuel_cost[i] += diff
        fuel_cost2[i] += sum(range(diff + 1))

print(min(fuel_cost))
print(min(fuel_cost2))
Exemplo n.º 15
0
import common

data = common.to_int(common.read_file('2019/01/data.txt').splitlines())

# part 1
acc = 0
for num in data:
    acc += (num // 3) - 2

print('part 1: ' + str(acc))

# part 2
acc = 0
for num in data:
    cost = max((num // 3) - 2, 0)
    while cost > 0:
        acc += cost
        cost = max((cost // 3) - 2, 0)

print('part 2: ' + str(acc))
Exemplo n.º 16
0
    def traders_web_D(self):
        # 33333本日の先物取引情報
        table_name = "futures_op"
        UURL = "https://www.traders.co.jp/domestic_stocks/invest_tool/futures/futures_op.asp"
        # テーブル情報取得
        dfs = pd.read_html(common.Chorme_get(UURL), header=1)
        for ii in range(len(dfs)):
            # テーブル番号検索
            if dfs[ii].columns[0] == "証券会社名":  # 証券会社名
                num = ii
                break
        # Webから取得した情報のカラム名をリスト化
        col_list = [i for i in dfs[num].columns]
        # DB追加のカラム作成
        col_tmp = []
        H = ''
        for i in dfs[num].columns:
            if i.count("Unnamed"):
                if 'Unnamed: 2' == i:
                    col_tmp.append('日付')
                    H = 'P'
                else:
                    col_tmp.append('PUT_CALL')
                    H = 'C'
            else:
                col_tmp.append(H + i.replace(".1", ""))
        # カラムのリネームcol_list→col_tmp
#        col = dict(zip(col_list,col_tmp))
        col = {}
        col = {col_list[i]: col_tmp[i] for i in range(len(col_list))}
        dfs[num] = dfs[num].rename(columns=col)

        # DBからカラム情報取得。ない場合は追加する。
        set_new = [i for i in dfs[num].columns]
        res = common.column_check(DB_INFO, table_name, set_new)
        # DBへのインポート
        for idx, row in dfs[num].iterrows():
            dict_w = {}
            for ii in range(len(row)):
                if str(row[ii]) != str(float("nan")):
                    try:
                        dict_w[dfs[num].columns[ii]] = int(row[ii])
                    except:
                        dict_w[dfs[num].columns[ii]] = row[ii]
                else:
                    dict_w[dfs[num].columns[ii]] = 0
            dict_w['日付'] = common.env_time()[0][:8]
            common.insertDB3(DB_INFO, table_name, dict_w)
        # 本日のカラム取得
        sqls = "select * from futures_op where 日付 = %(key1)s" % {'key1': common.env_time()[0][:8]}
        sql_pd = common.select_sql(DB_INFO, sqls)
        set_new = [i for i in sql_pd.columns if i != 'now' and i != '証券会社名' and i != '日付' and i != 'PUT_CALL']
        # 本日のカラムを対象に合計取得
        sqls = "select SUM(" + "),SUM(".join(set_new) + ") from futures_op where 日付 = '%(key1)s'" % {'key1': common.env_time()[0][:8]}
        sql_pd = common.select_sql(DB_INFO, sqls)
        for i, row in sql_pd.iterrows():
            set_val = []
            for ii in range(len(row)):
                if row[ii] is None:
                    set_val.append(0)
                else:
                    set_val.append(row[ii])

        set_val = common.to_int(set_val)
        col = {}
        col = {set_new[i]: set_val[i] for i in range(len(set_new))}
        col['証券会社名'] = '合計'
        col['日付'] = common.env_time()[0][:8]
        col = common.to_int(col)
        common.insertDB3(DB_INFO, table_name, col)
        print(col)

        # 2222222本日の先物取引情報
        table_name = "futures"
        UURL = "https://www.traders.co.jp/domestic_stocks/invest_tool/futures/futures_top.asp"
        dfs = common.read_html2(common.Chorme_get(UURL), 1)  # header=0,skiprows=0(省略可能)
        for ii in range(len(dfs)):
            if dfs[ii].columns[0] == "SELL":
                num = ii
                break
        # カラムの入れ替え
        CC = ['証券会社名', 'SELL_225', 'BUY_225', 'NET_225', '日付',  'SELL_TOPIX','BUY_TOPIX', 'NET_TOPIX', '更新日', 'SELL_225M', 'BUY_225M', 'NET_225M']
        col_name = {}
        col_name = {dfs[num].columns[c]: CC[c] for c in range(len(dfs[num].columns))}
        dfs[num] = dfs[num].rename(columns=col_name)
        # DBへのインポート
        for idx, row in dfs[num].iterrows():
            dict_w = {}
            for ii in range(len(row)):
                dict_w[dfs[num].columns[ii]] = row[ii]
            dict_w['更新日'] = common.env_time()[1]
            dict_w['日付'] = common.env_time()[0][:8]
            common.insertDB3(DB_INFO, table_name, dict_w)