from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import copy
import os
import logging
import random

import torch
import numpy as np
import cv2
from lib.dataset.coco import COCODataset
from lib.dataset.transformations.multi_keypoint_transformation import MultiKeypointTransformation
from lib.dataset.transformations.random_image_transform import RandomImageTransform
from lib.dataset.transformations.targeted_blurring import TargetedBlurring

from lib.dataset.transformations.targeted_cutmix import TargetedCutmix
from lib.dataset.transformations.targeted_cutout import Cutout

from lib.utils.transforms import affine_transform, get_affine_transform, fliplr_joints
from train import get_image_dir_path

logger = logging.getLogger(__name__)

class ContrastiveCOCODataset(COCODataset):
    '''
    "keypoints": {
        0: "nose",
        1: "left_eye",
        2: "right_eye",
        3: "left_ear",
        4: "right_ear",
        5: "left_shoulder",
        6: "right_shoulder",
        7: "left_elbow",
        8: "right_elbow",
        9: "left_wrist",
        10: "right_wrist",
        11: "left_hip",
        12: "right_hip",
        13: "left_knee",
        14: "right_knee",
        15: "left_ankle",
        16: "right_ankle"
    },
	"skeleton": [
        [16,14],[14,12],[17,15],[15,13],[12,13],[6,12],[7,13], [6,7],[6,8],
        [7,9],[8,10],[9,11],[2,3],[1,2],[1,3],[2,4],[3,5],[4,6],[5,7]]
    '''

    def __init__(self, cfg, root, image_set, is_train, transform=None):
        super().__init__(cfg, root, image_set, is_train, transform)
        self.occlusion_transforms_keypoint = []
        self.occlusion_transforms_parts = []
        ## REMEMBER TO NOT USE JITTERING WHEN USING CONTRASTIVE!
        if cfg.CONTRASTIVE.CUTMIX:
            self.occlusion_transforms_parts.append(
                RandomImageTransform(
                    TargetedCutmix(self.get_image_dir_path(cfg), self._get_ann_file_keypoint(), dataset = cfg.DATASET.DATASET), 1.0,
                    "parts", dataset=cfg.DATASET.DATASET))
        if cfg.CONTRASTIVE.CUTOUT.KEYPOINT:
            self.occlusion_transforms_keypoint.append(
                RandomImageTransform(Cutout(cfg.DATASET.DATASET), 1.0, "keypoint", dataset=cfg.DATASET.DATASET))
        if cfg.CONTRASTIVE.CUTOUT.PARTS:
            self.occlusion_transforms_parts.append(
                RandomImageTransform(Cutout(cfg.DATASET.DATASET), 1.0, "parts", dataset=cfg.DATASET.DATASET))
        if cfg.CONTRASTIVE.BLURRING.KEYPOINT:
            self.occlusion_transforms_keypoint.append(
                RandomImageTransform(TargetedBlurring(cfg.DATASET.DATASET), 1.0, "keypoints",
                                     dataset=cfg.DATASET.DATASET))
        if cfg.CONTRASTIVE.BLURRING.PARTS:
            self.occlusion_transforms_parts.append(
                RandomImageTransform(TargetedBlurring(cfg.DATASET.DATASET), 1.0, "parts", dataset=cfg.DATASET.DATASET))
        if cfg.CONTRASTIVE.MULTIKEYPOINT.USE:

            multi_transforms = []
            if cfg.CONTRASTIVE.MULTIKEYPOINT.CUTOUT:
                multi_transforms.append(Cutout(cfg.DATASET.DATASET))
            if cfg.CONTRASTIVE.MULTIKEYPOINT.BLURRING:
                multi_transforms.append(TargetedBlurring(cfg.DATASET.DATASET))
            if len(multi_transforms) > 0:
                self.occlusion_transforms_keypoint.append(
                    MultiKeypointTransformation(multi_transforms, cfg.CONTRASTIVE.MULTIKEYPOINT.MAX_NUM,
                                                1.0, dataset=cfg.DATASET.DATASET))

    def __getitem__(self, idx):
        db_rec = copy.deepcopy(self.db[idx])

        image_file = db_rec['image']
        filename = db_rec['filename'] if 'filename' in db_rec else ''
        imgnum = db_rec['imgnum'] if 'imgnum' in db_rec else ''

        if self.data_format == 'zip':
            from utils import zipreader
            data_numpy = zipreader.imread(
                image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION
            )
        else:
            data_numpy = cv2.imread(
                image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION
            )

        if self.color_rgb:
            data_numpy = cv2.cvtColor(data_numpy, cv2.COLOR_BGR2RGB)

        if data_numpy is None:
            logger.error('=> fail to read {}'.format(image_file))
            raise ValueError('Fail to read {}'.format(image_file))

        joints = db_rec['joints_3d']
        joints_vis = db_rec['joints_3d_vis']

        c = db_rec['center']
        s = db_rec['scale']
        score = db_rec['score'] if 'score' in db_rec else 1
        r = 0

        if self.is_train:
            if (np.sum(joints_vis[:, 0]) > self.num_joints_half_body
                    and np.random.rand() < self.prob_half_body):
                c_half_body, s_half_body = self.half_body_transform(
                    joints, joints_vis
                )

                if c_half_body is not None and s_half_body is not None:
                    c, s = c_half_body, s_half_body

            sf = self.scale_factor
            rf = self.rotation_factor
            s = s * np.clip(np.random.randn() * sf + 1, 1 - sf, 1 + sf)
            r = np.clip(np.random.randn() * rf, -rf * 2, rf * 2) \
                if random.random() <= 0.6 else 0

            if self.flip and random.random() <= 0.5:
                data_numpy = data_numpy[:, ::-1, :]
                joints, joints_vis = fliplr_joints(
                    joints, joints_vis, data_numpy.shape[1], self.flip_pairs)
                c[0] = data_numpy.shape[1] - c[0] - 1

        trans = get_affine_transform(c, s, r, self.image_size)
        input = cv2.warpAffine(
            data_numpy,
            trans,
            (int(self.image_size[0]), int(self.image_size[1])),
            flags=cv2.INTER_LINEAR)

        for i in range(self.num_joints):
            if joints_vis[i, 0] > 0.0:
                joints[i, 0:2] = affine_transform(joints[i, 0:2], trans)

        keypoint_input = copy.deepcopy(input)
        keypoint_joints = copy.deepcopy(joints)
        keypoint_joints_vis = copy.deepcopy(joints_vis)
        parts_input = copy.deepcopy(input)
        parts_joints = copy.deepcopy(joints)
        parts_joints_vis = copy.deepcopy(joints_vis)

        if self.transform:
            if len(self.occlusion_transforms_keypoint) > 0:
                sample = {'image': keypoint_input, 'target': keypoint_joints, 'joints_vis': keypoint_joints_vis}
                choose_transform = random.choice(self.occlusion_transforms_keypoint)
                sample = choose_transform(sample)
                sample = self.transform(sample)
                keypoint_input = sample['image']
                keypoint_joints = sample['target']
                keypoint_joints_vis = sample['joints_vis']

            if len(self.occlusion_transforms_parts) > 0:
                sample = {'image': parts_input, 'target': parts_joints, 'joints_vis': parts_joints_vis}
                choose_transform = random.choice(self.occlusion_transforms_parts)
                sample = choose_transform(sample)
                sample = self.transform(sample)
                parts_input = sample['image']
                parts_joints = sample['target']
                parts_joints_vis = sample['joints_vis']

            # Casual image tranform
            sample = {'image': input, 'target': joints, 'joints_vis': joints_vis}
            sample = self.transform(sample)
            input = sample['image']
            joints = sample['target']
            joints_vis = sample['joints_vis']

        target, target_weight = self.generate_target(joints, joints_vis)
        target = torch.from_numpy(target)
        target_weight = torch.from_numpy(target_weight)

        input_combined = {'normal': input, 'keypoints_occluded': keypoint_input, 'parts_occluded': parts_input}
        meta = {
            'image': image_file,
            'filename': filename,
            'imgnum': imgnum,
            'joints': joints,
            'joints_vis': joints_vis,
            'parts_joints_vis': parts_joints_vis,
            'center': c,
            'scale': s,
            'rotation': r,
            'score': score
        }

        return input_combined, target, target_weight, meta

    def get_image_dir_path(self, cfg):
        prefix = 'test2017' if 'test' in cfg.DATASET.TRAIN_SET else cfg.DATASET.TRAIN_SET
        prefix = 'train2017' if 'train' in cfg.DATASET.TRAIN_SET else prefix
        prefix = 'val2017' if 'val' in cfg.DATASET.TRAIN_SET else prefix

        return os.path.join(cfg.DATASET.ROOT, 'images', prefix)


# -*- coding:utf-8 -*-
# Author: 张来吃
# Version: 1.0.0
# Contact: laciechang@163.com

# 感谢 Igor Ridanovic 提供的时间码转换方法
# https://github.com/IgorRidanovic/smpte

# -----------------------------------------------------
# 本工具仅支持在达芬奇内运行
# -----------------------------------------------------
lang = 'en_US'

gui_text = {
    'check': 'Check',
    'threshold': 'Threshold',
    'found': 'Found',
    'results': 'results',
    'title': 'Flash Frame Checker',
}

if lang == 'zh_CN':
    gui_text = {
        'check': '检查',
        'threshold': '阈值',
        'found': '找到',
        'results': '个结果',
        'title': '错帧检查',
    }

RESOLVE_FPS_MAPPING = {             # 虽然很奇怪但是得问问BMD为什么会有这种神奇的帧率表达方式
    '16': 16.0,     '18': 18.0,
    '23': 23.976,   '24': 24.0,   '24.0': 24.0,
    '25.0': 25.0,   '25': 25.0,     '29': 29.97,
    '30': 30.0,     '30.0': 30.0,     '47': 47.952,
    '48': 48.0,     '50': 50.0,
    '59': 59.94,    '60': 60.0,
    '72': 72.0,     '95': 95.904,
    '96': 96.0,     '100': 100.0,
    '119': 119.88,  '120': 120.0
}

class SMPTE(object):
	'''Frames to SMPTE timecode converter and reverse.'''
	def __init__(self):
		self.fps = 24
		self.df  = False

	def getframes(self, tc):
		'''Converts SMPTE timecode to frame count.'''

		if int(tc[9:]) > self.fps:
			raise ValueError ('SMPTE timecode to frame rate mismatch.', tc, self.fps)

		hours   = int(tc[:2])
		minutes = int(tc[3:5])
		seconds = int(tc[6:8])
		frames  = int(tc[9:])

		totalMinutes = int(60 * hours + minutes)

		# Drop frame calculation using the Duncan/Heidelberger method.
		if self.df:
			dropFrames = int(round(self.fps * 0.066666))
			timeBase   = int(round(self.fps))
			hourFrames   = int(timeBase * 60 * 60)
			minuteFrames = int(timeBase * 60)
			frm = int(((hourFrames * hours) + (minuteFrames * minutes) + (timeBase * seconds) + frames) - (dropFrames * (totalMinutes - (totalMinutes // 10))))
		# Non drop frame calculation.
		else:
			self.fps = int(round(self.fps))
			frm = int((totalMinutes * 60 + seconds) * self.fps + frames)

		return frm

	def gettc(self, frames):
		'''Converts frame count to SMPTE timecode.'''

		frames = abs(frames)

		# Drop frame calculation using the Duncan/Heidelberger method.
		if self.df:

			spacer = ':'
			spacer2 = ';'

			dropFrames         = int(round(self.fps * .066666))
			framesPerHour      = int(round(self.fps * 3600))
			framesPer24Hours   = framesPerHour * 24
			framesPer10Minutes = int(round(self.fps * 600))
			framesPerMinute    = int(round(self.fps) * 60 - dropFrames)

			frames = frames % framesPer24Hours

			d = frames // framesPer10Minutes
			m = frames % framesPer10Minutes

			if m > dropFrames:
				frames = frames + (dropFrames * 9 * d) + dropFrames * ((m - dropFrames) // framesPerMinute)
			else:
				frames = frames + dropFrames * 9 * d

			frRound = int(round(self.fps))
			hr = int(frames // frRound // 60 // 60)
			mn = int((frames // frRound // 60) % 60)
			sc = int((frames // frRound) % 60)
			fr = int(frames % frRound)

		# Non drop frame calculation.
		else:
			self.fps = int(round(self.fps))
			spacer  = ':'
			spacer2 = spacer

			frHour = self.fps * 3600
			frMin  = self.fps * 60

			hr = int(frames // frHour)
			mn = int((frames - hr * frHour) // frMin)
			sc = int((frames - hr * frHour - mn * frMin) // self.fps)
			fr = int(round(frames -  hr * frHour - mn * frMin - sc * self.fps))

		# Return SMPTE timecode string.
		return(
				str(hr).zfill(2) + spacer +
				str(mn).zfill(2) + spacer +
				str(sc).zfill(2) + spacer2 +
				str(fr).zfill(2)
				)

class Resolve():
    def __init__(self) -> None:
        self.resolve = bmd.scriptapp('Resolve')
        self.projectmanager = self.resolve.GetProjectManager()
        self.mediastorage = self.resolve.GetMediaStorage()
        self.currentproject = self.projectmanager.GetCurrentProject()
        self.mediapool = self.currentproject.GetMediaPool()
        self.timeline = self.currentproject.GetCurrentTimeline()

resolve = Resolve()
fu = bmd.scriptapp('Fusion')
ui = fu.UIManager
disp = bmd.UIDispatcher(ui)

fps = str(resolve.timeline.GetSetting('timelineFrameRate'))
smpte = SMPTE()
smpte.fps = RESOLVE_FPS_MAPPING[fps]
smpte.df = bool(int(resolve.timeline.GetSetting('timelineDropFrameTimecode')))

Header = {
    0: {'name': 'Frame', 'width': 100},
    1: {'name': 'Record TC', 'width': 150},
}

def getTracklistbyCount(track_num) -> list:
    return resolve.timeline.GetItemListInTrack('Video', track_num)

def getInlist(tracklist):
    return (int(i.GetStart()) for i in tracklist)

def getOutlist(tracklist):
    return (int(i.GetEnd()) for i in tracklist)

def getAllclipinfo():
    info = {}
    count = int(resolve.timeline.GetTrackCount('Video'))
    for i in range(1, count+1):
        inlist = list(getInlist(getTracklistbyCount(i)))
        inlist = inlist + list(getOutlist(getTracklistbyCount(i)))
        info[i] = inlist
    return info

def markIntimeline(point, treeitem):
    row = treeitem.NewItem()
    row.Text[0] = str(point)
    row.Text[1] = frameToRTC(point)
    treeitem.AddTopLevelItem(row)

def frameToRTC(frame):
    return smpte.gettc(frame)

def compareInpoint(interval, tree):
    info = getAllclipinfo()
    count = int(resolve.timeline.GetTrackCount('Video'))
    result = []
    for i in range(1, count+1):
        inlist = info[i]
        for j in inlist:
            for k in range(1, count+1):
                target = info[k]
                source = j - interval
                if source in target:
                    if j not in result:
                        result.append(j)
                        markIntimeline(j, tree)
    return result

def buildHeader(treeitem):
    header = treeitem.NewItem()
    treeitem.SetHeaderItem(header)
    for i in range(0, len(Header)):
        info = Header[i]
        header.Text[i] = info['name']
        treeitem.ColumnWidth[i] = info['width']

Cliptree = 'Cliptree'
CheckRange = 'CheckRange'
Run = 'Run'
Status = 'Status'

window = [ui.VGroup([
    ui.Label({"Text": "%s"%(gui_text['title']), "Alignment": {"AlignHCenter": True, "AlignVCenter": True}, "Weight": 0.1, "OpenExternalLinks" : True,}),
    ui.Tree({"ID": Cliptree}),
    ui.HGroup({"Weight": 0, "StyleSheet": "max-height:30px"}, [
        ui.Label({"Text": gui_text['threshold'],  "Weight": 0}),
        ui.SpinBox({"ID": CheckRange, "Value": 2, "Minimum": 1, "Maximum": 99, "SingleStep": 1}),
        ui.HGap(),
        ui.Label({"ID": Status,"StyleSheet": "min-width:80px", "Weight": 0 }),
        ui.Button({"ID": Run, "Text": gui_text['check'], "Weight": 0}),
    ]),
])]

dlg = disp.AddWindow({
                        "WindowTitle": "Flash Frame Checker",
                        "ID": "MyWin",
                        "Geometry": [
                                    600, 300, # position when starting
                                    400, 300 #width, height
                         ],
                        "WindowFlags":{
                            "Window": True,
                        }
                        }, window)

itm = dlg.GetItems()
def _closewindow(ev):
    disp.ExitLoop()

def _run(ev):
    itm[Cliptree].Clear()
    checkrange = itm[CheckRange].Value
    totalCount = 0
    for interv in range(1, checkrange+1):
        res = compareInpoint(interv, itm[Cliptree])
        totalCount += len(res)
    itm[Status].Text = gui_text['found'] + " " + str(totalCount) + " " + gui_text['results']

def _jump_to_target_clip(ev):
    timecode = itm[Cliptree].CurrentItem().Text[1]
    resolve.timeline.SetCurrentTimecode(timecode)

buildHeader(itm[Cliptree])

dlg.On['MyWin'].Close = _closewindow
dlg.On[Cliptree].ItemClicked = _jump_to_target_clip
dlg.On[Run].Clicked = _run

if __name__ == '__main__':
    dlg.Show()
    disp.RunLoop()
    dlg.Hide()


import  urllib.request as request
import  urllib
import random

###############获取一条新IP####################
def getIP():
	ip = '';
	rmd = random.randint(1,34);
	print("========================");
	print("访问第"+str(rmd)+"页");
	response = request.urlopen("http://www.66ip.cn/areaindex_"+str(rmd)+"/1.html");
	html = response.read();
	html = html.decode("raw_unicode_escape");
	ip_1 = html.index("
");
	try:
		ip_1 = html.index("
", ip_1+1);
		ip_2 = html.index("	", ip_1+1);
		ip_3 = html.index("	", ip_2+1);
		ip = html[ip_1+8:ip_2] + ':' + html[ip_2+9:ip_3];
		print("获取该页第1条成功");
		print("========================");
	except ValueError:
		print("获取该页失败");
		print("========================");
	return ip;

###############获取若干IP列表####################
def getIPs(size = 20):
	print("获取"+str(size)+"个代理IP");
	iplist = [];
	while len(iplist) < size:
		iplist = list(set(iplist));
		rmd = random.randint(1,34);
		print("========================");
		print("访问第"+str(rmd)+"页");
		response = request.urlopen("http://www.66ip.cn/areaindex_"+str(rmd)+"/1.html");
		html = response.read();
		html = html.decode("raw_unicode_escape");
		ip_1 = html.index("
");
		try:
			while len(iplist) < size:
				ip_1 = html.index("
", ip_1+1);
				ip_2 = html.index("	", ip_1+1);
				ip_3 = html.index("	", ip_2+1);
				ip = html[ip_1+8:ip_2] + ':' + html[ip_2+9:ip_3];
				iplist.append(ip);
			print("已到数量");
			print("========================");
			print("");
		except ValueError:
			print("第"+str(rmd)+"页已获取完毕");
			print("========================");
			print("");
	return iplist;

###############显示当前IP####################
def showIP(ip):
	proxy_support = request.ProxyHandler({'http': ip});
	opener = request.build_opener(proxy_support);
	opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36')];
	request.install_opener(opener);

	try:
		url = "http://www.baidu.com/s?wd=ip%E6%9F%A5%E8%AF%A2";
		print("========================");
		print("正在验证IP:"+ip+"...");
		response = request.urlopen(url);
		html = response.read().decode('utf-8');
		print("验证代理地址成功");
		index1 = html.index('本机IP: ');
		index2 = html.index('',index1);
		index3 = html.index('	    ',index2);
		print("IP:"+html[index1+11:index2]);
		print("地址:"+html[index2+7:index3]);
	except urllib.error.URLError:
		print("验证代理地址出错");
	print("========================");

###############测试函数####################
while True:
	ip = '';
	while (ip == ''):
		ip = getIP();
	print("");
	showIP(ip);
	check = input("是否继续？按Q退出\n\n");
	if (check == 'Q'):
		break;

01-简单爬虫/04自动获取IP并验证/方法2.py


import collections
import functools
import bint

def solution(A,B,C):
    from collections import  deque

    def inner(a, b):
        return a, b, b & a == b, a | b, b | a, a & (a | b), b & (a | b)

    dq = deque([A, B, C])
    dq2 = deque()
    dq3 = deque()
    for l in range(len(dq)):
        a = dq[0]
        b = dq[1]
        print ("<1>",inner(a, b))
        if not (b & a == b):
            dq2.append(a | b)
        dq.rotate()

    for l in range(len(dq2)):
        a = dq2[0]
        b = dq2[1]
        print("<2>",inner(a, b))
        if not (b & a == b):
            dq3.append(a | b)
        dq2.rotate()

    print(dq, dq2, dq3)
    # if B&A == B A is conforming to B
    #return A, B, B&A == B, A|B, B|A, A & (A|B), B & (A|B)

def hash(s: str, mod: int) -> int:
    mult = 997
    return functools.reduce(lambda z, c: (z * mult + ord(c)) % mod, s, 0)

def can_be_palindrome(s:str) -> bool:
    return sum(v % 2 for v in collections.Counter(s).values()) <= 1

if __name__ == '__main__':
    inputs = [

        (1073741727, 1073741631, 1073741679),
        (1,2,3)

    ]

    for i in inputs:
        #print(i, "->", solution(i[0], i[1], i[2]))
        print(hash(str(i[0]), 522))
        print(hash(str(i[1]), 522))
        print(hash(str(i[2]), 522))

    print(can_be_palindrome("abba"))
    print(can_be_palindrome("baba"))


import train
import test
import argparse
import os
import numpy as np
import random

from config import get_params

# parse arguments
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--mode', dest='mode', type=int, default=0,
        help='run mode - (0-train+test, 1-train only, 2-test only, 3-val only)')
parser.add_argument('--nlayers', dest='nlayers', type=int, default=3,
        help='Number of reader layers')
parser.add_argument('--dataset', dest='dataset', type=str, default='wdw',
        help='Dataset - (cnn || dailymail || cbtcn || cbtne || wdw)')
parser.add_argument('--seed', dest='seed', type=int, default=1,
        help='Seed for different experiments with same settings')
parser.add_argument('--gating_fn', dest='gating_fn', type=str, default='T.mul',
        help='Gating function (T.mul || Tsum || Tconcat)')
args = parser.parse_args()
cmd = vars(args)
params = get_params(cmd['dataset'])
params.update(cmd)

np.random.seed(params['seed'])
random.seed(params['seed'])

# save directory
w2v_filename = params['word2vec'].split('/')[-1].split('.')[0] if params['word2vec'] else 'None'
save_path = ('experiments/'+params['dataset'].split('/')[0]+
        '_nhid%d'%params['nhidden']+'_nlayers%d'%params['nlayers']+
        '_dropout%.1f'%params['dropout']+'_%s'%w2v_filename+'_chardim%d'%params['char_dim']+
        '_train%d'%params['train_emb']+
        '_seed%d'%params['seed']+'_use-feat%d'%params['use_feat']+
        '_gf%s'%params['gating_fn']+'/')
if not os.path.exists(save_path): os.makedirs(save_path)

# train
if params['mode']<2:
    train.main(save_path, params)

# test
if params['mode']==0 or params['mode']==2:
    test.main(save_path, params)
elif params['mode']==3:
    test.main(save_path, params, mode='validation')


import logging

from django.core.management.base import BaseCommand

from promgen import prometheus, tasks

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "--reload",
            action="store_true",
            help="Trigger Prometheus Reload",
        )
        parser.add_argument(
            "out",
            nargs="?",
            help="Optionally specify an output file to use an atomic write operation",
        )

    def handle(self, **kwargs):
        if kwargs["out"]:
            tasks.write_rules(
                path=kwargs["out"],
                reload=kwargs["reload"],
            )
        else:
            # Since we're already working with utf8 encoded data, we can skip
            # the newline ending here
            self.stdout.ending = None
            self.stdout.buffer.write(prometheus.render_rules())


import os
import unittest
import time
from appium import webdriver

class AndroidTests(unittest.TestCase):
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '5.1'
        desired_caps['deviceName'] = 'Android Emulator'
        desired_caps['noReset'] = 'True'
        desired_caps['appPackage'] = 'cn.xiaochuankeji.tieba'
        desired_caps['appActivity'] = '.ui.base.SplashActivity'

        self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

    def tearDown(self):
        #self.driver.quit()
        pass

    def test_element_by_id(self):
        self.driver.implicitly_wait(60)
        el = self.driver.find_element_by_id("cn.xiaochuankeji.tieba:id/title")
        print(el.text)
        el.click()

    def test_01(self):
        self.driver.implicitly_wait(60)
        el=self.driver.find_elements_by_id("cn.xiaochuankeji.tieba:id/title")
        print(el)
        el[3].click()

    def test_02(self):
        self.driver.implicitly_wait(60)
        self.driver.find_element_by_xpath("//*[@text='图文']").click()

    def test_03(self):
        self.driver.implicitly_wait(60)
        self.driver.find_element_by_xpath("//*[@text='图文']/../../../android.widget.FrameLayout[3]/android.widget.FrameLayout/android.widget.TextView").click()

    def test_0456789(self):
        self.driver.implicitly_wait(60)
        self.driver.find_element_by_xpath("//*[@resource-id='cn.xiaochuankeji.tieba:id/search_b']/android.widget.ImageView").click()
        self.driver.find_element_by_xpath("//android.widget.EditText").send_keys('666')
        self.driver.find_element_by_xpath("//*[@resource-id='cn.xiaochuankeji.tieba:id/search_input_clear']").click()
        self.driver.find_element_by_xpath('//*[@resource-id="cn.xiaochuankeji.tieba:id/cancel" and @class="android.widget.TextView"]').click()
        el=self.driver.find_elements_by_xpath("//*[@resource-id='cn.xiaochuankeji.tieba:id/textTabItem']")
        el[3].click()
        self.driver.find_element_by_xpath('//*[@text="空间动态"]').click()

    def test_10(self):
        self.driver.implicitly_wait(60)
        el=self.driver.find_elements_by_xpath('//*[@resource-id="cn.xiaochuankeji.tieba:id/iconTabItem"]')
        el[2].click()

    def test_11(self):
        self.driver.implicitly_wait(60)
        el = self.driver.find_elements_by_xpath('//*[@resource-id="cn.xiaochuankeji.tieba:id/iconTabItem"]')
        el[1].click()

    def test_12(self):
        self.driver.implicitly_wait(60)
        self.driver.find_element_by_xpath('//*[@resource-id="cn.xiaochuankeji.tieba:id/home_refresh_view"]').click()

    def test_131415(self):
        self.driver.implicitly_wait(60)
        self.driver.find_element_by_xpath('//*[@resource-id="cn.xiaochuankeji.tieba:id/holder_flow_rmdv"]').click()
        self.driver.find_element_by_xpath('//*[contains(@resource-id,"id/operate_share")]').click()
        self.driver.find_element_by_xpath('//*[@text="收藏"]').click()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(AndroidTests)
    unittest.TextTestRunner(verbosity=2).run(suite)


import os
import re

from math import ceil, floor

FORMULA_FILE = "formulas.txt"

class Reaction:
    """
    A reaction that will process materials/chemicals into another.
    """

    def __init__(self, formula, amount, ingredients):
        self.name = formula
        self.amount = amount
        self.ingredients = ingredients

class NanoFactory:
    """
    NanoFactory class responsible for processing ores into fuel.
    """

    def __init__(self):
        self.formulas = {}
        self.inventory = {}
        self.used_ore = 0
        self.total_ore = 1000000000000

    def input_formulas(self, formulas):
        """
        Input a list of formulas that define individual reactions
        that can be made by the NanoFactory.
        """
        num_digit = re.compile(r"(?:(\d+)\s(\w+))")

        for line in formulas:
            ingredients = {}
            results = num_digit.findall(line)
            formula_amount, formula = results.pop()

            for ingredient in results:
                amount, item = ingredient
                ingredients[item] = int(amount)

            self.formulas[formula] = Reaction(formula, int(formula_amount), ingredients)

    def _add_inventory(self, chemical, amount):
        """
        Add the specified amount of chemical to the inventory.
        """
        if chemical in self.inventory:
            self.inventory[chemical] += amount
        else:
            self.inventory[chemical] = amount

    def _remove_inventory(self, chemical, amount):
        """
        Remove the specified amount of chemical from the inventory.
        """
        self.inventory[chemical] -= amount

    def _needed_inventory(self, chemical, amount):
        """
        Calculate the needed inventory to satisfy the amount of chemical provided..
        """
        if chemical in self.inventory:
            if self.inventory[chemical] > amount:
                return 0
            else:
                return amount - self.inventory[chemical]
        else:
            return amount

    def _get_inventory(self, chemical, amount):
        """
        Recursive function to add the required ingredients for the specified
        chemical to the inventory. Will call itself recursively to add all
        chained sub-ingredients needed to tally the necessary ore. Will only
        add an amount that is a multiple that the formula is for.
        """
        reaction_amount = self.formulas[chemical].amount
        reactions = ceil(amount / reaction_amount)
        ingredients = self.formulas[chemical].ingredients

        for ingredient, subamount in ingredients.items():
            if ingredient == "ORE":
                self.used_ore += subamount * reactions
                self.total_ore -= subamount * reactions
            else:
                needed = self._needed_inventory(ingredient, subamount * reactions)
                if needed > 0:
                    self._get_inventory(ingredient, needed)
                self._remove_inventory(ingredient, subamount * reactions)

        self._add_inventory(chemical, reactions * reaction_amount)

    def calculate_fuel(self, amount):
        """
        Calculate the amount of ore necessary for the required
        amount of fuel.
        """
        self._get_inventory("FUEL", amount)
        return self.used_ore

    def calculate_total_fuel(self):
        """
        Calculate the amount of fuel that can be processed with the limited ore.
        """
        upper = 1000000000000
        lower = 1
        while True:
            target = int(floor((upper + lower) / 2))
            if target == lower:
                return lower

            self.reset()
            self.calculate_fuel(target)

            if self.total_ore < 0:
                upper = target
            else:
                lower = target

    def reset(self):
        """
        Reset the object for another use.
        """
        self.inventory = {}
        self.used_ore = 0
        self.total_ore = 1000000000000

def read_formulas(filename):
    """
    Read in the formulas from a given filename and return as a list.
    List will be formatted as follows: "1 A, 2 B, 3 C => 4 D"
    """
    if os.path.basename(os.getcwd()) == "aoc2019":
        filename = os.path.join("day14", filename)

    with open(filename, "r") as formula_file:
        return formula_file.read().splitlines()

def minecraft(filename, fuel):
    """
    Hello, my name is Peter, and welcome to my Let's Play for Minecraft.
    Today we're going to punch a crapload of trees and magically build
    a house, at least until a creeper comes by and fucks it up.
    """
    formulas = read_formulas(filename)
    creeper = NanoFactory()
    creeper.input_formulas(formulas)
    ore = creeper.calculate_fuel(fuel)

    print(f"The amount of ore required to produce {fuel} fuel: {ore}")
    return ore

def satisfactory(filename):
    """
    Let's mine some ore. Now, let's build a HUB. Now, let's exploit the
    entire planet for its resources, killing off any flora and fauna in
    the process, leaving only acres of factories and smoke! Yay!
    """
    formulas = read_formulas(filename)
    creeper = NanoFactory()
    creeper.input_formulas(formulas)
    fuel = creeper.calculate_total_fuel()

    print(f"The total amount of fuel you can make: {fuel}")
    return fuel

if __name__ == "__main__":
    minecraft(FORMULA_FILE, 1)
    satisfactory(FORMULA_FILE)


import os
import sys
import importlib
import argparse
import csv
import math
import numpy as np
import time
import pickle
import pathlib
import pyscipopt as scip

import tensorflow as tf
import torch
import utilities

class PolicyBranching(scip.Branchrule):

    def __init__(self, policy, device):
        super().__init__()

        self.policy_type = policy['type']
        self.policy_name = policy['name']
        self.device = device

        model = policy['model']
        model.restore_state(policy['parameters'])
        model.to(device)
        model.eval()
        self.policy = model.forward

    def branchinitsol(self):
        self.ndomchgs = 0
        self.ncutoffs = 0
        self.state_buffer = {}
        self.khalil_root_buffer = {}

    def branchexeclp(self, allowaddcons):

        candidate_vars, *_ = self.model.getPseudoBranchCands()
        candidate_mask = [var.getCol().getIndex() for var in candidate_vars]

        state = utilities.extract_state(self.model, self.state_buffer)
        c,e,v = state
        v = v['values'][candidate_mask]

        state_khalil = utilities.extract_khalil_variable_features(self.model, candidate_vars, self.khalil_root_buffer)

        var_feats = np.concatenate([v, state_khalil, np.ones((v.shape[0],1))], axis=1)
        var_feats = utilities._preprocess(var_feats, mode="min-max-2")

        var_feats = torch.as_tensor(var_feats, dtype=torch.float32).to(device)
        with torch.no_grad():
            var_logits = self.policy(var_feats).cpu().numpy()

        best_var = candidate_vars[var_logits.argmax()]
        self.model.branchVar(best_var)
        result = scip.SCIP_RESULT.BRANCHED

        # fair node counting
        if result == scip.SCIP_RESULT.REDUCEDDOM:
            self.ndomchgs += 1
        elif result == scip.SCIP_RESULT.CUTOFF:
            self.ncutoffs += 1

        return {'result': result}

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'problem',
        help='MILP instance type to process.',
        choices=['setcover', 'cauctions', 'facilities', 'indset'],
    )
    parser.add_argument(
        '-g', '--gpu',
        help='CUDA GPU id (-1 for CPU).',
        type=int,
        default=-1,
    )
    parser.add_argument(
        '-s', '--seed',
        help='seed for parallelizing the evaluation. Uses all seeds if not provided.',
        type=int,
        default=-1
    )
    parser.add_argument(
        '-l', '--level',
        help='size of instances to evaluate. Default is all.',
        type=str,
        default='all',
        choices=['all', 'small', 'medium', 'big']
    )
    parser.add_argument(
        '--trained_models',
        help='Directory of trained models.',
        type=str,
        default='trained_models/'
    )
    parser.add_argument(
        '-m', '--model_string',
        help='searches for this string in respective trained_models folder',
        type=str,
        default='',
    )
    parser.add_argument(
        '--model_name',
        help='searches for this model_name in respective trained_models folder',
        type=str,
        default='',
    )
    args = parser.parse_args()

    instances = []
    seeds = [0, 1, 2]
    time_limit = 2700

    ### OUTPUT DIRECTORY
    result_dir = f"eval_results/{args.problem}"
    os.makedirs(result_dir, exist_ok=True)
    device = "CPU" if args.gpu == -1 else "GPU"
    result_file = f"{result_dir}/mlp_{device}_{time.strftime('%Y%m%d-%H%M%S')}.csv"

    ### MODELS TO EVALUATE ###
    basedir = f"{args.trained_models}/{args.problem}"
    if args.model_string != "":
        models_to_evaluate = [y for y in pathlib.Path(basedir).iterdir() if args.model_string in y.name and 'mlp_' in y.name]
        assert len(models_to_evaluate) > 0, f"no model matched the model_string: {args.model_string}"
    elif args.model_name != "":
        model_path = pathlib.Path(f"{basedir}/{args.model_name}")
        assert model_path.exists(), f"path: {model_path} doesn't exist"
        assert 'mlp_' in model_path.name, f"only tests mlp models. model_path doesn't look like its mlp: {model_path}"
        models_to_evaluate = [model_path]
    else:
        models_to_evaluate = [y for y in pathlib.Path(f"{basedir}").iterdir() if 'mlp_' in y.name]
        assert len(models_to_evaluate) > 0, f"no model found in {basedir}"

    if args.problem == 'setcover':
        instances += [{'type': 'small', 'path': f"data/instances/setcover/transfer_500r_1000c_0.05d/instance_{i+1}.lp"} for i in range(20)]
        instances += [{'type': 'medium', 'path': f"data/instances/setcover/transfer_1000r_1000c_0.05d/instance_{i+1}.lp"} for i in range(20)]
        instances += [{'type': 'big', 'path': f"data/instances/setcover/transfer_2000r_1000c_0.05d/instance_{i+1}.lp"} for i in range(20)]

    elif args.problem == 'cauctions':
        instances += [{'type': 'small', 'path': f"data/instances/cauctions/transfer_100_500/instance_{i+1}.lp"} for i in range(20)]
        instances += [{'type': 'medium', 'path': f"data/instances/cauctions/transfer_200_1000/instance_{i+1}.lp"} for i in range(20)]
        instances += [{'type': 'big', 'path': f"data/instances/cauctions/transfer_300_1500/instance_{i+1}.lp"} for i in range(20)]

    elif args.problem == 'facilities':
        instances += [{'type': 'small', 'path': f"data/instances/facilities/transfer_100_100_5/instance_{i+1}.lp"} for i in range(20)]
        instances += [{'type': 'medium', 'path': f"data/instances/facilities/transfer_200_100_5/instance_{i+1}.lp"} for i in range(20)]
        instances += [{'type': 'big', 'path': f"data/instances/facilities/transfer_400_100_5/instance_{i+1}.lp"} for i in range(20)]

    elif args.problem == 'indset':
        instances += [{'type': 'small', 'path': f"data/instances/indset/transfer_750_4/instance_{i+1}.lp"} for i in range(20)]
        instances += [{'type': 'medium', 'path': f"data/instances/indset/transfer_1000_4/instance_{i+1}.lp"} for i in range(20)]
        instances += [{'type': 'big', 'path': f"data/instances/indset/transfer_1500_4/instance_{i+1}.lp"} for i in range(20)]

    else:
        raise NotImplementedError

    ### SEEDS TO EVALUATE ###
    if args.seed != -1:
        seeds = [args.seed]

    ### PROBLEM SIZES TO EVALUATE ###
    if args.level != "all":
        instances = [x for x in instances if x['type'] == args.level]

    branching_policies = []

    # GCNN models
    for model_path in models_to_evaluate:
        for seed in seeds:
            branching_policies.append({
                'type': 'mlp',
                'name': model_path.name,
                'seed': seed,
                'parameters': str(model_path / f"{seed}/best_params.pkl")
            })

    print(f"problem: {args.problem}")
    print(f"gpu: {args.gpu}")
    print(f"time limit: {time_limit} s")

    ### NUMPY / TORCH SETUP ###
    if args.gpu == -1:
        os.environ['CUDA_VISIBLE_DEVICES'] = ''
        device = torch.device("cpu")
    else:
        os.environ['CUDA_VISIBLE_DEVICES'] = f'{args.gpu}'
        device = torch.device(f"cuda" if torch.cuda.is_available() else "cpu")

    # load and assign tensorflow models to policies (share models and update parameters)
    loaded_models = {}
    for policy in branching_policies:
        if policy['type'] not in loaded_models:
            sys.path.insert(0, os.path.abspath(f"models/{policy['type']}"))
            import model
            importlib.reload(model)
            loaded_models[policy['type']] = model.Policy()
            del sys.path[0]
            loaded_models[policy['type']].to(device)
            loaded_models[policy['type']].eval()
        policy['model'] = loaded_models[policy['type']]

    print("running SCIP...")

    fieldnames = [
        'problem',
        'device',
        'policy',
        'seed',
        'type',
        'instance',
        'nnodes',
        'nlps',
        'stime',
        'gap',
        'status',
        'ndomchgs',
        'ncutoffs',
        'walltime',
        'proctime',
    ]

    with open(result_file, 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

        for instance in instances:
            print(f"{instance['type']}: {instance['path']}...")

            for policy in branching_policies:
                torch.manual_seed(policy['seed'])

                m = scip.Model()
                m.setIntParam('display/verblevel', 0)
                m.readProblem(f"{instance['path']}")
                utilities.init_scip_params(m, seed=policy['seed'])
                m.setIntParam('timing/clocktype', 1)  # 1: CPU user seconds, 2: wall clock time
                m.setRealParam('limits/time', time_limit)

                brancher = PolicyBranching(policy, device)
                m.includeBranchrule(
                    branchrule=brancher,
                    name=f"{policy['type']}:{policy['name']}",
                    desc=f"Custom MLPOpt branching policy.",
                    priority=666666, maxdepth=-1, maxbounddist=1)

                walltime = time.perf_counter()
                proctime = time.process_time()

                m.optimize()

                walltime = time.perf_counter() - walltime
                proctime = time.process_time() - proctime

                stime = m.getSolvingTime()
                nnodes = m.getNNodes()
                nlps = m.getNLPs()
                gap = m.getGap()
                status = m.getStatus()
                ndomchgs = brancher.ndomchgs
                ncutoffs = brancher.ncutoffs

                writer.writerow({
                    'policy': f"{policy['type']}:{policy['name']}",
                    'seed': policy['seed'],
                    'type': instance['type'],
                    'instance': instance['path'],
                    'nnodes': nnodes,
                    'nlps': nlps,
                    'stime': stime,
                    'gap': gap,
                    'status': status,
                    'ndomchgs': ndomchgs,
                    'ncutoffs': ncutoffs,
                    'walltime': walltime,
                    'proctime': proctime,
                    'problem':args.problem,
                    'device': device
                })

                csvfile.flush()
                m.freeProb()

                print(f"  {policy['type']}:{policy['name']} {policy['seed']} - {nnodes} ({nnodes+2*(ndomchgs+ncutoffs)}) nodes {nlps} lps {stime:.2f} ({walltime:.2f} wall {proctime:.2f} proc) s. {status}")


"""

문제 유형 : DP

1,4,9.19,16,25

26 루트 5.1

7 루트 2.6

answer = 0
while n >= 1 :
    sq = sqrt(n)
    sq = int(sq)
    n = n - sq**2
    answer += 1
print(answer)

DP를 활용해보자

"""
import sys
from math import sqrt

input = sys.stdin.readline

n = int(input())

dp = [i for i in range(n+1)]

for i in range(1, n+1) :
    for j in range(1,i) :
        if j*j > i :
            break
        if dp[i] > dp[i-j*j] + 1 :
            dp[i] = dp[i-j*j] + 1

print(dp[n])

AlgorithmStudy/백준/7 Dynamic Programming/1699 제곱수의 합(9.8).py